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
25569cd765a53d6a042967ef201706635b267674
Swift
venkatesh-791/fourth-demo
/for loop .playground/Contents.swift
UTF-8
148
3.171875
3
[]
no_license
//: Playground - noun: a place where people can play import UIKit var counter = "Hello, playground" for counter in 1...5 { print(counter) }
true
0d5be03cb8be362e36f53c864cf41009876df981
Swift
IonutPopovici1992/Swift3
/Swift-4.2/3_Strings_and_Characters/StringMutability.playground/Contents.swift
UTF-8
416
3.859375
4
[]
no_license
//: Playground - noun: a place where people can play //// String Mutability import UIKit var str = "Hello, playground!!!" var variableString = "Horse" variableString += " and carriage." // variableString is now "Horse and carriage" print(variableString) let constantString = "Highlander" // constantString += " and another Highlander" // this reports a compile-time error - a constant string cannot be modified
true
d39e3363bf5261e7691f762a45ab211655439fcc
Swift
win-design/FbAlbums
/Fbalbums/Services/FirebaseServices.swift
UTF-8
1,182
2.671875
3
[]
no_license
// // FirebaseServices.swift // Fbalbums // // Created by Gms on 12/30/17. // Copyright © 2017 win-deisgn. All rights reserved. // import Firebase struct FirebaseServices { func uploadPhotos(_ photos: [Photo], uploadCompletion: ((Bool) -> ())?) { var uploadedPhotosCount = 0 for photo in photos { let data = try? Data(contentsOf: photo.imageUrl) guard let photoData = data else { return } let storageRef = Storage.storage().reference().child("images/\(photo.id).jpg") storageRef.putData(photoData, metadata: nil, completion: { metadata, error in if error != nil { uploadCompletion?(false) return } else { uploadedPhotosCount += 1 if photos.count == uploadedPhotosCount { uploadCompletion?(true) return } } }) } } }
true
1e5c166608f6a9b77cec69afebfc75bab3cf1cfc
Swift
lijoraju/On-The-Map
/On The Map/Browser.swift
UTF-8
1,193
3.125
3
[]
no_license
// // Browser.swift // On The Map // // Created by LIJO RAJU on 16/11/16. // Copyright © 2016 LIJORAJU. All rights reserved. // import UIKit class Browser: UIViewController { static let sharedInstance = Browser() // MARK: Open URL in browser func Open(Scheme: String) { if let url = URL(string: Scheme) { // Opening a URL with iOS 10 if #available(iOS 10, *) { UIApplication.shared.open(url, options: [:], completionHandler: { (sucess) in print("Open \(url):\(sucess)") }) } // Opening a URL with iOS 9 or earlier else { let sucess = UIApplication.shared.openURL(url) print("Open \(url):\(sucess)") } } } // Escaping URL func cleanURL(url:String)-> String { var testURL = url if testURL.characters.first != "h" && testURL.characters.first != "H" { testURL = "http://" + testURL } return String(testURL.characters.filter{!"".characters.contains($0)}) } }
true
c2e10360ff16b65cbd91bc0f3be3f3b0798d9dcf
Swift
GerardoTC/MeLiChallenge
/MeLi/Sections/PredictiveSearch/Interactor/PredictiveSearchInteractor.swift
UTF-8
1,813
2.6875
3
[]
no_license
// // PredictiveSearchInteractor.swift // MeLi // // Created by Gerardo Tarazona Caceres on 16/09/20. // Copyright © 2020 Gerardo Tarazona Caceres. All rights reserved. // import Foundation import CoreData class PredictiveSearchInteractor: PredictiveSearchInteractorProtocol { var network: MeLiAPIProtocol var dataController: LocalSuggestionDataControllerProtocol init(network: MeLiAPIProtocol = MeLiAPI(), dataController: LocalSuggestionDataControllerProtocol = LocalSuggestionDataController()) { self.network = network self.dataController = dataController } func searchText(_ text: String, completion: @escaping (Result<[String], Error>) -> Void) { let url = MeLiNetworkConstants.Endpoints.autoSuggest(query: text).url let parser: (Data) throws -> PredictiveSearchEntity = { data in return try JSONDecoder().decode(PredictiveSearchEntity.self, from: data) } let resource = NetworkResource(url: url, parse: parser) network.getRequest(resource: resource) { (result) in switch result { case .success(let result): let suggestions = result.suggestions.map { (predictiveSuggestion) -> String in predictiveSuggestion.suggestion } completion(.success(suggestions)) case .failure(let error): completion(.failure(error)) } } } func searchTextLocally(_ text: String) -> Result<[String], Error> { dataController.searchTextLocally(text) } func saveSuggestion(text: String) { dataController.saveSuggestion(text) } func bringAllSuggestions() -> Result<[String], Error> { dataController.bringAllLocalSuggestions() } }
true
ea3f677b15607cb6ded455ccd02d6fadc3d8eb66
Swift
rbruinier/SwiftRaytracer
/SwiftRaytracer/Raytracer/Ray.swift
UTF-8
203
2.734375
3
[ "CC0-1.0" ]
permissive
// Created by Robert Bruinier public struct Ray { public var origin: Point3 public var direction: Vector3 public func point(at t: Double) -> Point3 { return origin + (t * direction) } }
true
50aa86ca58210d78f1a47302c803bbb624bb4527
Swift
resh-surendran/CorkTouristSpots-iOS
/Cork Tourist Spots/WebViewController.swift
UTF-8
2,014
2.625
3
[]
no_license
// // WebViewController.swift // Cork Tourist Spots // // Created by Reshma Surendran on 21/02/2019. // Copyright © 2019 UCC. All rights reserved. // import UIKit import WebKit class WebViewController: UIViewController, WKNavigationDelegate { @IBOutlet weak var webView: WKWebView! @IBOutlet weak var backButton: UIButton! @IBOutlet weak var forwardButton: UIButton! @IBOutlet weak var navigationToolbar: UINavigationItem! @IBAction func backAction(_ sender: Any) { if webView.canGoBack { webView.goBack() } } @IBAction func forwardAction(_ sender: Any) { if webView.canGoForward { webView.goForward() } } var webData : String! override func viewDidLoad() { super.viewDidLoad() webView.navigationDelegate = self webView.addObserver(self, forKeyPath: #keyPath(WKWebView.title), options: .new, context: nil) // Do any additional setup after loading the view. let url = URL(string: webData) let request = URLRequest(url: url!) webView.load(request) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { backButton.isEnabled = webView.canGoBack forwardButton.isEnabled = webView.canGoForward } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "title" { if let title = webView.title { print(title) self.title = title } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
true
d1ae95cb54896e9f0c19181ca423ec36c7d489db
Swift
aorellano/Tasks-Today
/Tasks Today/Model/MockData.swift
UTF-8
1,471
2.84375
3
[]
no_license
// // MockData.swift // Tasks Today // // Created by Alexis Orellano on 6/24/19. // Copyright © 2019 Alexis Orellano. All rights reserved. // import Foundation class MockData { static func createMockTaskData() -> [TaskModel] { var mockTasks = [TaskModel]() mockTasks.append(TaskModel(title: "Project", itemNumbers: 5, todoModels: createMockTodoData())) mockTasks.append(TaskModel(title: "School", itemNumbers: 0)) mockTasks.append(TaskModel(title: "Blog", itemNumbers: 2)) return mockTasks } static func createMockTodoData() -> [TodoModel] { var mockTodos = [TodoModel]() mockTodos.append(TodoModel(title: "Create wireframe for app", date: Date(), notes: "", isChecked: false, isExpanded: true)) mockTodos.append(TodoModel(title: "Create home screen", date: Date(), notes: "", isChecked: false, isExpanded: true)) mockTodos.append(TodoModel(title: "Create theme for app", date: Date(), notes: "", isChecked: false, isExpanded: true)) mockTodos.append(TodoModel(title: "Choose font", date: Date().add(days: 1), notes: "", isChecked: false, isExpanded: true)) mockTodos.append(TodoModel(title: "Choose color scheme", date: Date().add(days: 2), notes: "", isChecked: false, isExpanded: true)) mockTodos.append(TodoModel(title: "Add additional features", date: Date().add(days: 3), notes: "", isChecked: false, isExpanded: true)) return mockTodos } }
true
2f8ee585041bcfcf9ee1d7c06c705c1ea85c2c02
Swift
SamLau888/VLVAlgorithms
/VLVAlgorithms/LeetcodeProblems/Queue/SQueue.swift
UTF-8
923
3.5625
4
[]
no_license
// // SQueue.swift // LeetcodeProblems // // Created by sam on 2021/1/9. // class SQueue { private var inArray = [Int]() private var outArray = [Int]() /** Initialize your data structure here. */ init() { } /** Push element x to the back of queue. */ func push(_ x: Int) { inArray.append(x) } /** Removes the element from in front of queue and returns that element. */ func pop() -> Int { if outArray.isEmpty { while let i = inArray.popLast() { outArray.append(i) } } return outArray.removeLast() } /** Get the front element. */ func peek() -> Int { return inArray.isEmpty ? outArray.last! : inArray.first! } /** Returns whether the queue is empty. */ func empty() -> Bool { inArray.isEmpty && outArray.isEmpty } }
true
2fa0b07352f3d4caaa86fe4c80cf1b2e3b5dfee7
Swift
lvh1g15/TinderLikeAnimation
/TinderAnimation/TinderAnimation/animation.swift
UTF-8
2,642
2.65625
3
[]
no_license
// // animation.swift // TinderAnimation // // Created by Landon Vago-Hughes on 25/08/2017. // Copyright © 2017 Landon Vago-Hughes. All rights reserved. import Foundation import UIKit import Darwin class TinderAnimate { var superView: UIView? func setup(view: UIView, options: UIViewAnimationOptions) { var constant: CGFloat = 0.0 let circularAnimation = UIView() view.insertSubview(circularAnimation, at: 1) self.superView = view circularAnimation.tag = 1 circularAnimation.translatesAutoresizingMaskIntoConstraints = false circularAnimation.layer.borderWidth = 0.5 circularAnimation.layer.borderColor = UIColor(red: 254/255, green: 63/255, blue: 68/255, alpha: 1.0).cgColor circularAnimation.layer.backgroundColor = UIColor(red: 254/255, green: 130/255, blue: 130/255, alpha: 1.0).cgColor circularAnimation.layer.opacity = 1.0 circularAnimation.layer.cornerRadius = 0.0 circularAnimation.centerXAnchor.constraint(equalTo: view.layoutMarginsGuide.centerXAnchor, constant: 0.0).isActive = true circularAnimation.centerYAnchor.constraint(equalTo: view.layoutMarginsGuide.centerYAnchor, constant: 0.0).isActive = true constant = 100 circularAnimation.widthAnchor.constraint(equalToConstant: constant/2).isActive = true circularAnimation.heightAnchor.constraint(equalToConstant: constant/2).isActive = true circularAnimation.layer.cornerRadius = 25.0 view.layoutIfNeeded() UIView.animate(withDuration: 2.5, delay: 0.1, options: options, animations: { view.layoutIfNeeded() circularAnimation.layer.opacity = 0.0 circularAnimation.transform = CGAffineTransform(scaleX: 7, y: 7) }, completion: { stop in if options == .curveEaseOut { circularAnimation.removeFromSuperview() } }) } func profileAnimateTouchBegin(profileView: UIImageView, bool: Bool, view: UIView) { if bool == true { UIView.animate(withDuration: 0.1, delay: 0, options: .curveLinear, animations: { profileView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) }, completion: nil) setup(view: view, options: .curveEaseOut) } else { UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 6.0, options: .curveLinear, animations: { profileView.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: nil) } } }
true
2159d24b83893961e72825939238ad11f436008f
Swift
RockyFung/TimeMovieSwift3
/TimeMovieSwift3/Main/Home/View/PosterView/PosterView.swift
UTF-8
5,758
2.546875
3
[]
no_license
// // PosterView.swift // TimeMovieSwift3 // // Created by rocky on 16/11/24. // Copyright © 2016年 rocky. All rights reserved. // import UIKit class PosterView: UIView { var posterCollectionView:PosterCollectionView? var headerView:UIImageView? // 黄色箭头的背景图 var indexCollectionView:IndexCollectionView? // 小海报collectionView var coverView:UIView? // 半透明遮罩 // 赋值时调用 var dataList:[HomeModel]?{ didSet{ posterCollectionView?.dataList = dataList indexCollectionView?.dataList = dataList } } //复写初始化方法 override init(frame: CGRect) { super.init(frame: frame) layoutIfNeeded() loadSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // 加载子视图 func loadSubviews(){ // 大海报 createCollectionView() // 小海报 creatHeaderView() // 遮罩 createCoverView() // 灯光 createLight() // 滑动监听 addObserver() } // 大海报 func createCollectionView(){ posterCollectionView = PosterCollectionView(frame:CGRect.init(x:0, y:0, width:KScreen_W, height:frame.size.height), itemwidth: KScreen_W - 150) addSubview(posterCollectionView!) } // 小海报 func creatHeaderView(){ headerView = UIImageView(frame: CGRect(x: 0, y: -135, width: KScreen_W, height: 155)) headerView?.image = UIImage(named: "indexBG_home")?.stretchableImage(withLeftCapWidth: 0, topCapHeight: 5) headerView?.isUserInteractionEnabled = true addSubview(headerView!) //按钮 let btn = UIButton(type: UIButtonType.custom) btn.frame = CGRect(x: KScreen_W/2.0-100.0/2.0+3.5, y: 130, width: 100, height: 30) btn.addTarget(self, action: #selector(btnAction(btn:)), for: UIControlEvents.touchUpInside) btn.setImage(UIImage.init(named: "down_home"), for: UIControlState.normal) headerView?.addSubview(btn) // 小海报collectionView indexCollectionView = IndexCollectionView(frame:CGRect(x: 0, y: 0, width: KScreen_W, height: 135),itemwidth:100) headerView?.addSubview(indexCollectionView!) } func btnAction(btn:UIButton){ if btn.isSelected == false { // 动画 //动画 weak var weakSelf = self UIView.animate(withDuration: 0.3, animations: { weakSelf!.coverView?.isHidden = false weakSelf!.headerView?.transform = CGAffineTransform(translationX: 0, y: 135) //按钮旋转 btn.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI)) }) }else{ //还原 weak var weakSelf = self UIView.animate(withDuration: 0.3, animations: { weakSelf!.coverView?.isHidden = true weakSelf!.headerView?.transform = CGAffineTransform.identity // 还原 btn.transform = CGAffineTransform.identity }) } btn.isSelected = !btn.isSelected } //灯光 func createLight() -> Void { let lightView = UIImageView(frame: CGRect(x: 0, y: 10, width: 124, height: 240)) lightView.image = UIImage(named: "light") addSubview(lightView) let lightView2 = UIImageView(frame: CGRect(x: KScreen_W-124.0, y: 10, width: 124, height: 240)) lightView2.image = UIImage(named: "light") addSubview(lightView2) } // 遮罩 func createCoverView() -> Void { coverView = UIView(frame: bounds) coverView?.backgroundColor = UIColor.black coverView?.alpha = 0.5 coverView?.isHidden = true insertSubview(coverView!, belowSubview: headerView!) } //添加监听,监听滑动 func addObserver() -> Void { //添加indexCollectionView的监听 indexCollectionView?.addObserver(self, forKeyPath: "currentIndex", options: NSKeyValueObservingOptions.new, context: nil) //添加posterCollectionView的监听 posterCollectionView?.addObserver(self, forKeyPath: "currentIndex", options: NSKeyValueObservingOptions.new, context: nil) } // 观察者方法 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // 变化后的值 let index = change?[NSKeyValueChangeKey.newKey] as! Int // 创建indexPath let indexPath = IndexPath(item:index, section:0) // 判断是否是currenIndex属性 guard keyPath == "currentIndex" else { return } // 判断对象的类型 if object is PosterCollectionView { //滑动到指定单元格 indexCollectionView?.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.centeredHorizontally, animated: true) }else if object is IndexCollectionView{ //滑动到指定单元格 posterCollectionView?.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.centeredHorizontally, animated: true) } } // 销毁 deinit { //移除观察者 indexCollectionView?.removeObserver(self, forKeyPath: "currentIndex") posterCollectionView?.removeObserver(self, forKeyPath: "currentIndex") } }
true
292eb4e49b950a3066225261871b9f6ba95afd6d
Swift
stefanomartina/Disaster-Monitor
/Disaster Monitor/UI/Settings/Message Editor Page/MessageEditorView.swift
UTF-8
6,958
2.765625
3
[]
no_license
// // MessageEditorView.swift // Disaster Monitor // // Created by Francesco Peressini on 28/02/2020. // Copyright © 2020 Stefano Martina. All rights reserved. // import Tempura // MARK: - ViewModel struct MessageEditorViewModel: ViewModelWithState { var state: AppState init?(state: AppState) { self.state = state } } // MARK: - View class MessageEditorView: UIView, ViewControllerModellableView { var messageTextView = UITextView() var bodyLabel = UILabel() var currentMessage: String = "" var didTapCloseButton: (() -> ())? @objc func didTapCloseButtonFunc() { didTapCloseButton?() } var didTapDoneButton: ((String) -> ())? @objc func didTapDoneButtonFunc() { didTapDoneButton?(messageTextView.text!.trimmingCharacters(in: .whitespacesAndNewlines)) } func setup() { addSubview(messageTextView) setupMessageTextField() addSubview(bodyLabel) setupBodyLabel() let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) addGestureRecognizer(tap) } @objc func dismissKeyboard() { self.endEditing(true) } func style() { backgroundColor = .systemGroupedBackground navigationItem?.title = "Message Editor" navigationItem?.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(didTapCloseButtonFunc)) navigationItem?.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(didTapDoneButtonFunc)) navigationItem?.rightBarButtonItem?.isEnabled = false if #available(iOS 13.0, *) { let navBarAppearance = UINavigationBarAppearance() navBarAppearance.configureWithOpaqueBackground() navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.label] // cambia aspetto del titolo navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.label] // cambia aspetto del titolo (con prefersLargeTitles = true) // navigationBar?.tintColor = .systemBlue // tintColor changes the color of the UIBarButtonItem navBarAppearance.backgroundColor = .secondarySystemBackground // cambia il colore dello sfondo della navigation bar // navigationBar?.isTranslucent = false // da provare la differenza tra true/false solo con colori vivi navigationBar?.standardAppearance = navBarAppearance navigationBar?.scrollEdgeAppearance = navBarAppearance } else { // navigationBar?.tintColor = .systemBlue navigationBar?.barTintColor = .secondarySystemBackground // navigationBar?.isTranslucent = false } } func update(oldModel: MessageEditorViewModel?) { guard let model = self.model else { return } currentMessage = model.state.message if messageTextView.text.isEmpty { messageTextView.text = currentMessage } let prepared = "This is the message that you can share on the Map Page to let your parents and friends know that you are safe!\n\n" bodyLabel.text = prepared + "Current message:\n\(currentMessage)" navigationBar?.tintColor = model.state.customColor.getColor() } override func layoutSubviews() { super.layoutSubviews() messageTextView.translatesAutoresizingMaskIntoConstraints = false messageTextView.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 50).isActive = true messageTextView.centerXAnchor.constraint(equalTo: self.safeAreaLayoutGuide.centerXAnchor).isActive = true messageTextView.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor).isActive = true messageTextView.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor).isActive = true bodyLabel.translatesAutoresizingMaskIntoConstraints = false bodyLabel.topAnchor.constraint(equalTo: messageTextView.safeAreaLayoutGuide.bottomAnchor, constant: 20).isActive = true bodyLabel.centerXAnchor.constraint(equalTo: self.safeAreaLayoutGuide.centerXAnchor).isActive = true bodyLabel.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 15).isActive = true bodyLabel.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: -15).isActive = true } private func setupMessageTextField() { messageTextView.isSelectable = true messageTextView.isScrollEnabled = false messageTextView.textContainer.maximumNumberOfLines = 7 messageTextView.textContainer.lineBreakMode = .byTruncatingTail messageTextView.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) messageTextView.textAlignment = .left messageTextView.font = UIFont.systemFont(ofSize: 18) messageTextView.layer.borderWidth = 0.2 messageTextView.layer.borderColor = UIColor.separator.cgColor messageTextView.backgroundColor = .secondarySystemGroupedBackground messageTextView.autocorrectionType = UITextAutocorrectionType.default messageTextView.keyboardType = UIKeyboardType.default messageTextView.delegate = self } private func setupBodyLabel() { bodyLabel.numberOfLines = 0 bodyLabel.textColor = .secondaryLabel bodyLabel.font = UIFont.systemFont(ofSize: 15) bodyLabel.textAlignment = .left } } extension MessageEditorView: UITextViewDelegate { func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { let textMessage = (messageTextView.text! as NSString).replacingCharacters(in: range, with: text) if textMessage.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { navigationItem?.rightBarButtonItem?.isEnabled = false } else { navigationItem?.rightBarButtonItem?.isEnabled = true } let existingLines = textView.text.components(separatedBy: CharacterSet.newlines) let newLines = text.components(separatedBy: CharacterSet.newlines) let linesAfterChange = existingLines.count + newLines.count - 1 return linesAfterChange <= textView.textContainer.maximumNumberOfLines } /* func textViewDidBeginEditing(_ textView: UITextView) { if messageTextView.textColor == .tertiaryLabel { messageTextView.text = nil messageTextView.textColor = .label } } func textViewDidEndEditing(_ textView: UITextView) { if messageTextView.text.isEmpty { messageTextView.text = currentMessage messageTextView.textColor = .tertiaryLabel } } */ }
true
def7c1102c294efc713211595774f64d97ecbb0d
Swift
ze230123/EGKit
/Sources/EGKit/Extensions/UICollectionView+DataEmptyable.swift
UTF-8
739
2.78125
3
[]
no_license
// // UICollectionView+DataEmptyable.swift // // // Created by youzy01 on 2020/9/28. // import UIKit extension UICollectionView { public func reloadDataIfEmpty(_ type: CheckType = .row) { reloadData() let isEmpty = dataIsEmpty(type: type) if isEmpty { eg.showEmpty() } else { eg.hideEmpty() } } /// 判断是否没有数据 /// - Parameter type: `CheckType`判断条件 /// - Returns: `Bool` private func dataIsEmpty(type: CheckType) -> Bool { switch type { case .section: return numberOfSections == 0 case .row: return numberOfSections == 1 && numberOfItems(inSection: 0) == 0 } } }
true
ca1f44c539c31ba98c290636cfe43cf5f1921e69
Swift
blazierkyle/AuthenticationApp
/AuthenticationApp/Utilities/Supporting Files/UIViewController+Extensions.swift
UTF-8
2,082
2.890625
3
[]
no_license
// // UIViewController+Extensions.swift // AuthenticationApp // // Created by Kyle Blazier on 1/31/17. // Copyright © 2017 Kyle Blazier. All rights reserved. // import Foundation import UIKit extension UIViewController { func delay(delay : Double, closure: @escaping () -> ()) { let when = DispatchTime.now() + delay DispatchQueue.main.asyncAfter(deadline: when) { closure() } } // MARK: - Utility function to present actionable alerts and popups func presentAlert(alertTitle : String?, alertMessage : String, cancelButtonTitle : String = "OK", cancelButtonAction : (()->())? = nil, okButtonTitle : String? = nil, okButtonAction : (()->())? = nil, thirdButtonTitle : String? = nil, thirdButtonAction : (()->())? = nil) { let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.alert) if let okAction = okButtonTitle { alert.addAction(UIAlertAction(title: okAction, style: .default, handler: { (action) in okButtonAction?() })) if let thirdButton = thirdButtonTitle { alert.addAction(UIAlertAction(title: thirdButton, style: .default, handler: { (action) in thirdButtonAction?() })) } } alert.addAction(UIAlertAction(title: cancelButtonTitle, style: UIAlertActionStyle.cancel, handler: { (action) in cancelButtonAction?() })) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } func showPopup(message : String) { let popup = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.actionSheet) self.present(popup, animated: true, completion: { }) self.perform(#selector(hidePopup), with: nil, afterDelay: 1.0) } func hidePopup() { self.dismiss(animated: true, completion: { }) } }
true
6e2ed6a1ddfe3a0aa6e676a22c559b151a96d3a5
Swift
rugoli/AVSwift
/AVSwift/AVSwift/Models/AVStockResults.swift
UTF-8
897
2.640625
3
[ "Apache-2.0" ]
permissive
// // AVStockResults.swift // AVSwift // // Created by Roshan Goli on 3/4/18. // Copyright © 2018 Roshan. All rights reserved. // import UIKit public final class AVStockResultsMetadata { public let earliestDate: Date? public let latestDate: Date? // let lastRefreshedDate: Date public let numberOfParsingErrors: Int init(earliestDate: Date?, latestDate: Date?, // lastRefreshedDate: Date, numberOfParsingErrors: Int) { self.earliestDate = earliestDate self.latestDate = latestDate // self.lastRefreshedDate = lastRefreshedDate self.numberOfParsingErrors = numberOfParsingErrors } } public final class AVStockResults<Model>{ public let timeSeries: [Model] public let metadata: AVStockResultsMetadata init(timeSeries: [Model], metadata: AVStockResultsMetadata) { self.timeSeries = timeSeries self.metadata = metadata } }
true
48ef230b1e87d9bb7a0577975c44b08217a7b7fc
Swift
vatsanp/wordsearch
/WordSearch/ModalViewController.swift
UTF-8
655
2.515625
3
[]
no_license
// // ModalViewController.swift // WordSearch // // Created by Vatsan Prabhu on 2019-05-14. // Copyright © 2019 vatsan. All rights reserved. // import UIKit //View Controller for 'About Me' screen class ModalViewController: UIViewController { //–––––VARIABLES AND OUTLETS––––– @IBOutlet weak var modalView: UIView! //–––––FUNCTIONS––––– override func viewDidLoad() { super.viewDidLoad() modalView.layer.cornerRadius = 10 //Round the corners of modalView modalView.layer.masksToBounds = true } //Dismiss Modal Segue @IBAction func dismiss(_ sender: UIButton) { dismiss(animated: true) {} } }
true
16aefafc5f120b3d5c6334649b330080c86a4264
Swift
Sarghm/Beaconator
/Beaconator/TableViewDelegate.swift
UTF-8
888
2.828125
3
[]
no_license
// // TableViewDelegate.swift // Beaconator // // Created by Sam Piggott on 07/08/2014. // Copyright (c) 2014 Sam Piggott. All rights reserved. // import UIKit class TableViewDelegate: NSObject, UITableViewDelegate, UITableViewDataSource { // TODO: Move to a more concise data source // Data source for debugging purposes will be a simple array of dictionaries let uuidArray = [["uuid":"dank", "name":"Name of ID"], ["uuid":"dank-2", "name":"Another iBeacon"]] func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return uuidArray.count } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { var cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") return cell } }
true
502ee6ac89b08cbaa6f6aacd999ed77d56c0bb02
Swift
marcounderscore/yorha-client-ios
/yorha-client-ios/DataManager/CoreData/WeaponStore.swift
UTF-8
1,565
2.828125
3
[]
no_license
// // WeaponStore.swift // yorha-client-ios // // Created by Marco Vazquez on 5/11/19. // Copyright © 2019 Marco Vazquez. All rights reserved. // import CoreData class WeaponStore: WeaponLocalDataProtocol { func retrieveWeapons() throws -> [WeaponCD] { guard let managedOC = CoreDataStore.managedObjectContext else { throw PersistenceError.managedObjectContextNotFound } let request: NSFetchRequest<WeaponCD> = NSFetchRequest(entityName: String(describing: WeaponCD.self)) return try managedOC.fetch(request) } func storeWeapon( id: Int32, name: String, minAttack: Int32, maxAttack: Int32, ability: String, photo: String, classID: Int32, className: String ) throws { guard let managedOC = CoreDataStore.managedObjectContext else { throw PersistenceError.managedObjectContextNotFound } if let newWeapon = NSEntityDescription.entity(forEntityName: String(describing: WeaponCD.self), in: managedOC) { let Weapon = WeaponCD(entity: newWeapon, insertInto: managedOC) Weapon.id = id Weapon.name = name Weapon.minAttack = minAttack Weapon.maxAttack = maxAttack Weapon.ability = ability Weapon.photo = photo Weapon.classID = classID Weapon.weaponClass?.id = classID Weapon.weaponClass?.name = className try managedOC.save() } throw PersistenceError.couldNotSaveObject } }
true
3cef6700921c6bdd928d6f578f4a65d927ff9607
Swift
babak51/CIS55Lab1_MohammadAmiraslani
/CIS55Lab1_MohammadAmiraslani/ViewController.swift
UTF-8
860
2.515625
3
[]
no_license
// // ViewController.swift // CIS55Lab1_MohammadAmiraslani // // Created by Mohammad Amiraslani on 9/28/17. // Copyright © 2017 Mohammad and Avi team CIS55. All rights reserved. // GitHub: https//github.com/babak51/CIS55Lab1_MohammadAmiraslani.git // import UIKit class ViewController: UIViewController { //MARK: Properties @IBOutlet weak var myText: UITextField! @IBOutlet weak var myLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Actions @IBAction func moveTextToLabel(_ sender: UIButton) { myLabel.text = myText.text myText.text = "" } }
true
467e8df5bc916e8173b536ca35cc7ba385c7e4e6
Swift
uv2706/truckit-ios-user
/TruckIt/Extension/UILabel+Extension.swift
UTF-8
1,638
2.6875
3
[]
no_license
// // UILabel+Extension.swift // PickUpUser // // Created by hb on 06/06/19. // Copyright © 2019 hb. All rights reserved. // import Foundation import UIKit extension UILabel { func calculateMaxLines() -> Int { let maxSize = CGSize(width: frame.size.width, height: CGFloat(Float.infinity)) let charSize = font.lineHeight let text = (self.text ?? "") as NSString let textSize = text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil) let linesRoundedUp = Int(ceil(textSize.height/charSize)) return linesRoundedUp } public func addAttributeString(mainString: String, subString: String, subStringFont: UIFont, subStringColor: UIColor) { let attributeString = NSMutableAttributedString(string: mainString) let attributes = [NSAttributedString.Key.font: subStringFont, NSAttributedString.Key.foregroundColor: subStringColor] attributeString.addAttributes(attributes, range: (mainString as NSString).range(of: subString)) self.attributedText = attributeString } public func addAttributeAgain(mainString: NSAttributedString, subString: String, subStringFont: UIFont, subStringColor: UIColor) { let attributeString = NSMutableAttributedString(attributedString: mainString) let attributes = [NSAttributedString.Key.font: subStringFont, NSAttributedString.Key.foregroundColor: subStringColor] attributeString.addAttributes(attributes, range: (mainString.string as NSString).range(of: subString)) self.attributedText = attributeString } }
true
1b975d12221f979d2294195ce6e89453f804ea36
Swift
v57/swift-nio-apns
/Sources/NIOAPNS/APNSRequest.swift
UTF-8
2,796
2.546875
3
[ "Apache-2.0" ]
permissive
// // APNSRequest.swift // CNIOAtomics // // Created by Kyle Browning on 2/1/19. // import NIO import NIOHTTP1 import NIOHTTP2 import Foundation public protocol APNSNotification { // var aps: APSPayload { get } func request() throws -> [String: Any] func encode() throws -> Data } extension APNSNotification { func encode() throws -> Data { return try JSONSerialization.data(withJSONObject: request(), options: []) } } /** APNS Payload [https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html#]: Payload Key Reference */ public struct APSPayload: Codable { public let alert: Alert? public let badge: Int? public let sound: String? public let contentAvailable: Int? public let category: String? public let threadID: String? public init (alert: Alert? = nil, badge: Int? = nil, sound: String? = nil, contentAvailable: Int? = nil, category: String? = nil, threadID: String? = nil) { self.alert = alert self.badge = badge self.sound = sound self.contentAvailable = contentAvailable self.category = category self.threadID = threadID } enum CodingKeys: String, CodingKey { case alert case badge case sound case contentAvailable = "content-available" case category case threadID = "thread-id" } } /** APNS Alert - SeeAlso: `struct APSPayload: Codable` */ public struct Alert: Codable { public let title: String? public let subtitle: String? public let body: String? public let titleLocKey: String? public let titleLocArgs: [String]? public let actionLocKey: String? public let locKey: String? public let locArgs: [String]? public let launchImage: String? public init(title: String? = nil, subtitle: String? = nil, body: String? = nil, titleLocKey: String? = nil, titleLocArgs: [String]? = nil, actionLocKey: String? = nil, locKey: String? = nil, locArgs: [String]? = nil, launchImage: String? = nil) { self.title = title self.subtitle = subtitle self.body = body self.titleLocKey = titleLocKey self.titleLocArgs = titleLocArgs self.actionLocKey = actionLocKey self.locKey = locKey self.locArgs = locArgs self.launchImage = launchImage } enum CodingKeys: String, CodingKey { case title case subtitle case body case titleLocKey = "title-loc-key" case titleLocArgs = "title-loc-args" case actionLocKey = "action-loc-key" case locKey = "loc-key" case locArgs = "loc-args" case launchImage = "launch-image" } }
true
a831e47248e83b5c7dab47fed822a592643723bd
Swift
Yasser-Aboibrahim/TO-DO-LIST-MVC-Demo
/TODO-MVC-Demo/ViewModel/Authentication/SignInViewModel.swift
UTF-8
3,475
3.046875
3
[]
no_license
// // SignInPresenter.swift // TODO-MVC-Demo // // Created by yasser on 11/11/20. // Copyright © 2020 Yasser Aboibrahim. All rights reserved. // import Foundation protocol SignInViewModelProtocol: class{ func logInUser(email: String, password: String) } class SignInViewModel{ //MARK:- Properties private weak var view: SignInVCProtocol! init(view: SignInVCProtocol){ self.view = view } // MARK:- Private Methods private func userDataValidator(userEmail: String, Password: String)-> Bool{ guard ValidationManager.shared().isValidEmail(email: userEmail) else{ return false } guard ValidationManager.shared().isValidPassword(password: Password) else{ return false } return true } private func isDataEntered(userEmail: String, Password: String)-> Bool{ guard ValidationManager.shared().isEmptyEmail(email: userEmail) else{ view.showAlert(alertTitle: "Incompleted Data Entry",message: "Please Enter Email",actionTitle: "Dismiss") return false } guard ValidationManager.shared().isEmptyPassword(password: Password) else{ view.showAlert(alertTitle: "Incompleted Data Entry",message: "Please Enter Password",actionTitle: "Dismiss") return false } return true } private func isValidRegex(userEmail: String, Password: String)-> Bool{ guard ValidationManager.shared().isValidEmail(email: userEmail) else{ view.showAlert(alertTitle: "Wrong Email Form",message: "Please Enter Valid email(a@a.com)",actionTitle: "Dismiss") return false } guard ValidationManager.shared().isValidPassword(password: Password) else{ view.showAlert(alertTitle: "Wrong Password Form",message: "Password need to be : \n at least one uppercase \n at least one digit \n at leat one lowercase \n characters total",actionTitle: "Dismiss") return false } return true } private func signInWithEnteredData(email: String, password: String){ view.showLoader() APIManager.loginAPIRouter(email: email, password: password){ response in switch response{ case .failure(let error): if error.localizedDescription == "The data couldn’t be read because it isn’t in the correct format." { self.view.showAlert(alertTitle: "Error",message: "Incorrect Email and Password",actionTitle: "Dismiss") }else{ self.view.showAlert(alertTitle: "Error",message: "Please try again",actionTitle: "Dismiss") print(error.localizedDescription) } case .success(let result): print(result.token) UserDefaultsManager.shared().token = result.token UserDefaultsManager.shared().userId = result.user.id self.view.goToTodoListVC() } self.view.hideLoader() } } } // MARK:- Extension SignInViewModel protocol Funcs extension SignInViewModel: SignInViewModelProtocol{ func logInUser(email: String, password: String){ if isDataEntered(userEmail: email, Password: password){ if isValidRegex(userEmail: email, Password: password){ signInWithEnteredData(email: email, password: password) } } } }
true
7e0c64ed0ff4d983c8c03712e3c327d34cc0aee5
Swift
hintoz/marvel-test-task
/marvel-test-task/DTOs/Characters/CharactersResponse.swift
UTF-8
1,643
2.96875
3
[]
no_license
// // CharactersResponse.swift // // Created by Евгений Дац on 30/10/2017 // Copyright (c) Evgeny Dats. All rights reserved. // import Foundation import ObjectMapper public class CharactersResponse: Mappable { // MARK: Declaration for string constants to be used to decode and also serialize. private struct SerializationKeys { static let copyright = "copyright" static let status = "status" static let data = "data" static let attributionText = "attributionText" static let code = "code" static let etag = "etag" static let attributionHTML = "attributionHTML" } // MARK: Properties public var copyright: String? public var status: String? public var data: Data? public var attributionText: String? public var code: Int? public var etag: String? public var attributionHTML: String? // MARK: ObjectMapper Initializers /// Map a JSON object to this class using ObjectMapper. /// /// - parameter map: A mapping from ObjectMapper. public required init?(map: Map){ } /// Map a JSON object to this class using ObjectMapper. /// /// - parameter map: A mapping from ObjectMapper. public func mapping(map: Map) { copyright <- map[SerializationKeys.copyright] status <- map[SerializationKeys.status] data <- map[SerializationKeys.data] attributionText <- map[SerializationKeys.attributionText] code <- map[SerializationKeys.code] etag <- map[SerializationKeys.etag] attributionHTML <- map[SerializationKeys.attributionHTML] } }
true
e4187f035164916a3ed2a738238a919d5027180f
Swift
sabarics/ChatViewController
/Source/Core/ChatStackView.swift
UTF-8
1,062
2.65625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // ChatStackView.swift // ChatViewController // // Created by Hoangtaiki on 5/18/18. // Copyright © 2018 toprating. All rights reserved. // import UIKit open class ChatStackView: UIStackView { /// The stack view position in the InputBarAccessoryView /// /// - left: Left Stack View /// - right: Bottom Stack View /// - bottom: Left Stack View /// - top: Top Stack View public enum Position { case left, right, bottom, top } // MARK: Initialization convenience init(axis: NSLayoutConstraint.Axis, spacing: CGFloat) { self.init(frame: .zero) self.axis = axis self.spacing = spacing } public override init(frame: CGRect) { super.init(frame: frame) setup() } required public init(coder: NSCoder) { super.init(coder: coder) } // MARK: - Setup /// Sets up the default properties open func setup() { translatesAutoresizingMaskIntoConstraints = false distribution = .fill alignment = .bottom } }
true
dd8e981e3251a8bd9486c1c3c52f2cebf564399d
Swift
jeanfdq/Instagram-MVVM
/Instagram-MVVM/ViewModel/ProfileHeaderViewModel.swift
UTF-8
1,206
2.609375
3
[]
no_license
// // ProfileHeaderViewModel.swift // Instagram-MVVM // // Created by Jean Paul Borges Manzini on 09/02/21. // import UIKit class ProfileHeaderViewModel: NSObject { fileprivate var user:User init(_ user:User) { self.user = user } var userId:String { return user.id } var profileImage:String { return user.profileImage } var fullName:String { return user.fullName } var isCurrentUser:Bool { return AuthService.shared.getCurrentUserId() == user.id } var isFollowed:Bool { return user.followed ?? false } var numberOfFollowers:Int { return user.stats?.followers ?? 0 } var numberOfFollowing:Int { return user.stats?.following ?? 0 } var numberOfPosts:Int { return user.stats?.posts ?? 0 } var profileBtnTitle:String { return isCurrentUser ? "Edit Profile" : isFollowed ? "Unfollow" : "Follow" } var profileBtnBackground:UIColor { return isCurrentUser ? .clear : .systemBlue } var profileBtnTextColor:UIColor { return isCurrentUser ? .darkGray : .white } }
true
7fc47981f99d0db4d8efd4d328034a03d7ad7cd3
Swift
cihanbas/Swift_MVVM_Sample
/1News/AppDelegate.swift
UTF-8
973
2.546875
3
[]
no_license
// // AppDelegate.swift // AutoLayoutTest // // Created by cihan bas on 7.10.2020. // // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var coordinator: AppCoordinator? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow() coordinator = AppCoordinator(window: window!) coordinator?.start() UINavigationBar.appearance().barTintColor = UIColor(displayP3Red: 47/255, green: 54/255, blue: 64/255, alpha: 1.0) UINavigationBar.appearance().largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.systemPink] UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white] return true } }
true
c7cef376e6cb71c9a99c35d033f7e39f8f9afc0d
Swift
yariksmirnov/aerial
/shared/LogMessage.swift
UTF-8
1,988
3.046875
3
[ "MIT" ]
permissive
// // LogMessage.swift // // Created by Yaroslav Smirnov on 05/12/2016. // Copyright © 2016 Yaroslav Smirnov. All rights reserved. // import ObjectMapper enum LogLevel: Int, CustomStringConvertible { case off case fatal case error case warning case info case debug case verbose var description: String { switch self { case .fatal: return "Fatal" case .error: return "Error" case .warning: return "Warning" case .info: return "Info" case .debug: return "Debug" case .verbose: return "Verbose" case .off: return "Off" } } init(string: String) { switch string { case "Fatal": self = .fatal case "Error": self = .error case "Warning": self = .warning case "Info": self = .info case "Debug": self = .debug case "Verbose": self = .verbose default: self = .off } } func contains(_ level: LogLevel) -> Bool { return level.rawValue >= self.rawValue } static func allLevels() -> [LogLevel] { return [.fatal, .error, .warning, .info, .debug, .verbose] } } public class LogMessage: NSObject, Mappable { var message: String = "" var level: LogLevel = .off var file: String = "" var function: String = "" var line: Int = 0 var timestamp: Date = Date() override init() { super.init() } required public init?(map: Map) { } public func mapping(map: Map) { message <- map["message"] level <- map["level"] file <- map["file"] function <- map["function"] line <- map["line"] timestamp <- (map["timestamp"], DateTransform()) } } extension Packet { convenience init(_ logMessage: LogMessage) { self.init() self.data = logMessage.toJSON() } func logMessages() -> [LogMessage] { return [] } }
true
11354be6d33392764c50db61ed2ff224ac842f21
Swift
aatish-rajkarnikar/starship
/starships/utils/FavouriteManager.swift
UTF-8
754
2.875
3
[]
no_license
// // FavouriteManager.swift // starships // // Created by Aatish Rajkarnikar on 30/9/21. // import Foundation class FavouriteManager: ObservableObject { static let shared: FavouriteManager = FavouriteManager() @Published var favourites: Set<Starship> private init() { favourites = [] } func addToFavourite(starship: Starship) { objectWillChange.send() favourites.insert(starship) } func removeFavourite(starship: Starship) { objectWillChange.send() favourites.remove(starship) } func contains(startship: Starship) -> Bool { return favourites.contains(startship) } func save() { } func load() { } }
true
6b9bdfbb8d28ff676cf6dee8a586fe9443ced84b
Swift
Haileyyyyyyyy/Swift_Study
/MyApp/MyApp/ViewController.swift
UTF-8
608
2.609375
3
[]
no_license
import UIKit class ViewController: UIViewController { @IBOutlet weak var midLabel: UILabel! var countDown = 100 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func onButtonClick(_ sender: Any) { countDown = countDown - 5; midLabel.text = String(countDown); if countDown <= 10{ midLabel.textColor = .blue; } else if countDown <= 50 { midLabel.textColor = .red; } } }
true
8e0bd6c10965c1480b8169717fc7a72d9d0a39d1
Swift
BatmanInGotham2/CupertinoInstantAlert
/iOS/CupertinoInstantAlert/CupertinoInstantAlert/MapsViewController.swift
UTF-8
6,172
2.578125
3
[]
no_license
// // MapsViewController.swift // CupertinoInstantAlert // // Created by Gautam Ajjarapu on 4/7/17. // Copyright © 2017 Gautam Ajjarapu. All rights reserved. // import UIKit import Firebase import GoogleMaps import SwiftyJSON import Alamofire struct mapItem { var lat: Double! var lon: Double! var notif: String var address: String // Initialize from arbitrary data init(lat: Double, lon: Double, notif: String, address: String) { self.lat = lat self.lon = lon self.notif = notif self.address = address } } var coords = [mapItem]() let camera = GMSCameraPosition.camera(withLatitude: 37.3230, longitude: -122.0322, zoom: 12.0) let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) class MapsViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //GMSPlacesClient.provideAPIKey("AIzaSyD5m07TQPJqftIfgTcUJpZpGiMxgPKKG9g") // Do any additional setup after loading the view. //mapView.clear() let currentmarker = GMSMarker() currentmarker.position = CLLocationCoordinate2D(latitude: 37.3258, longitude: -122.0424) currentmarker.title = "Current Location" currentmarker.snippet = "Quinlan Community Center" currentmarker.icon = GMSMarker.markerImage(with: .black) currentmarker.map = mapView self.view = mapView rootRef.observe(.childAdded, with: { snapshot in let object = JSON(snapshot.value!) //mapView.clear() print(object) if(object["type"].string! == "message") { //print(subJson) var latitude = 0.0 var longitude = 0.0 var message = "" var add = "" if object["latitude"] != JSON.null { latitude = object["latitude"].double! } if object["longitude"] != JSON.null { longitude = object["longitude"].double! } if object["message"] != JSON.null { message = object["message"].string! } if object["location"] != JSON.null { add = object["location"].string! } if latitude != 0.0 { print("if") var currentLoc = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=37.3258,-122.0424&destinations=\(latitude),\(longitude)&key=AIzaSyBAe1D2F75M4aKbFI8Vu61no_SLBhm8yaA"; //print(longitude) Alamofire.request(currentLoc).responseJSON { response in // print(response.request) // original URL request //print(response.response) // HTTP URL response print(response) // server data //print(response.result) // result of response serialization var miles = JSON(response.value!)["rows"][0]["elements"][0]["distance"]["text"].string! //print(miles) let index1 = miles.index(miles.endIndex, offsetBy: -2) print(miles.substring(from: index1)) if(miles.substring(from: index1) == "ft") { print("here") let alert = UIAlertController(title: "Alert", message: "Nearby: \(message)", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } else { let index = miles.index(miles.startIndex, offsetBy: 3) print(miles.substring(to: index)) if Double(miles.substring(to: index))! < 1.0 { let alert = UIAlertController(title: "Alert", message: "Nearby: \(message)", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) //print("here") } } } } let myItem = mapItem(lat: latitude, lon: longitude, notif: message, address: add) coords.insert(myItem, at: 0) //print(coords) self.updateMarkers() } }) rootRef.observe(.childRemoved, with: { snapshot in let object = JSON(snapshot.value!) mapView.clear() if object["type"] == "message" { var place = 0; for i in 0...list.count-1{ if(list[i].info == object["message"].string && list[i].loc == object["location"].string && list[i].time == object["timestamp"].string) { place = i } } coords.remove(at: place) self.updateMarkers() } }) // Creates a marker in the center of the map. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateMarkers() { //print(coords.count) for i in 0...coords.count-1{ let marker = GMSMarker() //print(coords[i]) marker.position = CLLocationCoordinate2D(latitude: coords[i].lat, longitude: coords[i].lon) marker.title = coords[i].address marker.snippet = coords[i].notif marker.map = mapView } //print(coords) } }
true
0fbacee1e3730b0f43185f327b29855b678bf3b0
Swift
gonecd/Serie-A
/iPhone Seriez/Sources/TheTVdb.swift
UTF-8
9,523
2.546875
3
[]
no_license
// // TheTVdb.swift // Seriez // // Created by Cyril Delamare on 03/01/2017. // Copyright © 2017 Home. All rights reserved. // import Foundation import SeriesCommon class TheTVdb : NSObject { var chrono : TimeInterval = 0 var TokenPath : String = String() let TheTVdbAPIkey : String = "8168E8621729A50F" var Token : String = "" override init() { super.init() } func loadAPI(reqAPI: String) -> NSObject { let startChrono : Date = Date() var ended : Bool = false var result : NSObject = NSObject() var request = URLRequest(url: URL(string: reqAPI)!) request.httpMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("en", forHTTPHeaderField: "Accept-Language") request.addValue("Bearer \(self.Token)", forHTTPHeaderField: "Authorization") let task = URLSession.shared.dataTask(with: request) { data, response, error in if let data = data, let response = response as? HTTPURLResponse { do { if (response.statusCode != 200) { print("TheTVdb::error \(response.statusCode) received for req=\(reqAPI) "); ended = true; return; } result = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSObject ended = true } catch let error as NSError { print("TheTVdb::failed \(error.localizedDescription) for req=\(reqAPI)"); ended = true; } } else { print(error as Any); ended = true; } } task.resume() while (!ended) { usleep(1000) } chrono = chrono + Date().timeIntervalSince(startChrono) return result } func initializeToken() { // Première connection pour récupérer un token valable ??? temps ( = 24h ? ) et le dumper dans un fichier /tmp/TheTVdbToken var request = URLRequest(url: URL(string: "https://api.thetvdb.com/login")!) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("Bearer \(self.TheTVdbAPIkey)", forHTTPHeaderField: "Authorization") request.httpBody = "{\n \"apikey\": \"\(self.TheTVdbAPIkey)\"\n}".data(using: String.Encoding.utf8); let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in if let data = data, let response = response as? HTTPURLResponse { if response.statusCode == 200 { do { let jsonToken : NSDictionary = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary self.Token = jsonToken.object(forKey: "token") as? String ?? "" print("Token = \(self.Token)") } catch let error as NSError { print("TheTVdb::getToken failed: \(error.localizedDescription)") } } else { print("TheTVdb::getToken error code \(response.statusCode)") } } else { print("TheTVdb::getToken failed: \(error!.localizedDescription)") } }) task.resume() while (task.state != URLSessionTask.State.completed) { sleep(1) } } func getEpisodesDetailsAndRating(uneSerie: Serie) { var pageToLoad : Int = 1 var continuer : Bool = true if (uneSerie.idTVdb == "") { return } while ( continuer ) { let reqResult : NSDictionary = loadAPI(reqAPI: "https://api.thetvdb.com/series/\(uneSerie.idTVdb)/episodes?page=\(pageToLoad)") as? NSDictionary ?? NSDictionary() if (reqResult.object(forKey: "links") != nil) { let nextPage : Int = ((reqResult.object(forKey: "links") as AnyObject).object(forKey: "next") as? Int ?? 0) if (nextPage == 0) { continuer = false } } if (reqResult.object(forKey: "data") != nil) { for fiche in reqResult.object(forKey: "data")! as! NSArray { let laSaison : Int = ((fiche as AnyObject).object(forKey: "airedSeason") as? Int ?? 0) if (laSaison != 0) { if (laSaison > uneSerie.saisons.count) { // Il manque une (ou des) saison(s), on crée toutes les saisons manquantes var uneSaison : Saison for i:Int in uneSerie.saisons.count ..< laSaison { uneSaison = Saison(serie: uneSerie.serie, saison: i+1) uneSerie.saisons.append(uneSaison) } } let lEpisode : Int = ((fiche as AnyObject).object(forKey: "airedEpisodeNumber") as! Int) if (lEpisode > uneSerie.saisons[laSaison - 1].episodes.count) { // Il manque un (ou des) épisode(s), on crée tous les épisodes manquants var unEpisode : Episode for i:Int in uneSerie.saisons[laSaison - 1].episodes.count ..< lEpisode { unEpisode = Episode(serie: uneSerie.serie, fichier: "", saison: laSaison, episode: i+1) uneSerie.saisons[laSaison - 1].episodes.append(unEpisode) } } if (lEpisode != 0) { uneSerie.saisons[laSaison - 1].episodes[lEpisode - 1].titre = (fiche as AnyObject).object(forKey: "episodeName") as? String ?? "" uneSerie.saisons[laSaison - 1].episodes[lEpisode - 1].resume = (fiche as AnyObject).object(forKey: "overview") as? String ?? "" uneSerie.saisons[laSaison - 1].episodes[lEpisode - 1].ratingTVdb = Int(10 * ((fiche as AnyObject).object(forKey: "siteRating") as? Double ?? 0.0)) uneSerie.saisons[laSaison - 1].episodes[lEpisode - 1].ratersTVdb = (fiche as AnyObject).object(forKey: "siteRatingCount") as? Int ?? 0 uneSerie.saisons[laSaison - 1].episodes[lEpisode - 1].idIMdb = (fiche as AnyObject).object(forKey: "imdbId") as? String ?? "" uneSerie.saisons[laSaison - 1].episodes[lEpisode - 1].idTVdb = (fiche as AnyObject).object(forKey: "id") as? Int ?? 0 let stringDate : String = (fiche as AnyObject).object(forKey: "firstAired") as? String ?? "" if (stringDate == "") { uneSerie.saisons[laSaison - 1].episodes[lEpisode - 1].date = ZeroDate } else { uneSerie.saisons[laSaison - 1].episodes[lEpisode - 1].date = dateFormSource.date(from: stringDate)! } } else { print ("TheTVdb::getEpisodesDetailsAndRating failed on episode = 0 \(uneSerie.serie) saison \(laSaison)") } } } } pageToLoad = pageToLoad + 1 } } func getSerieGlobalInfos(idTVdb : String) -> Serie { let uneSerie : Serie = Serie(serie: "") if (idTVdb == "") { return uneSerie } let reqResult : NSDictionary = loadAPI(reqAPI: "https://api.thetvdb.com/series/\(idTVdb)") as? NSDictionary ?? NSDictionary() if (reqResult.object(forKey: "data") != nil) { uneSerie.serie = (reqResult.object(forKey: "data")! as AnyObject).object(forKey: "seriesName") as? String ?? "" uneSerie.idTVdb = String((reqResult.object(forKey: "data")! as AnyObject).object(forKey: "id") as? Int ?? 0) uneSerie.idIMdb = (reqResult.object(forKey: "data")! as AnyObject).object(forKey: "imdbId") as? String ?? "" uneSerie.status = (reqResult.object(forKey: "data")! as AnyObject).object(forKey: "status") as? String ?? "" uneSerie.network = (reqResult.object(forKey: "data")! as AnyObject).object(forKey: "network") as? String ?? "" uneSerie.resume = (reqResult.object(forKey: "data")! as AnyObject).object(forKey: "overview") as? String ?? "" uneSerie.genres = (reqResult.object(forKey: "data")! as AnyObject).object(forKey: "genre") as? [String] ?? [] uneSerie.certification = (reqResult.object(forKey: "data")! as AnyObject).object(forKey: "rating") as? String ?? "" let bannerFile : String = (reqResult.object(forKey: "data")! as AnyObject).object(forKey: "banner") as? String ?? "" if (bannerFile != "") { uneSerie.banner = "https://www.thetvdb.com/banners/" + bannerFile } let textRuntime : String = (reqResult.object(forKey: "data")! as AnyObject).object(forKey: "runtime") as? String ?? "0" if (textRuntime != "" ) { uneSerie.runtime = Int(textRuntime)! } } return uneSerie } }
true
9e0c0e35374f0477b4b1a494bb12ec0765e50cc9
Swift
MYliuxiang/TaoZ
/TaoZ/Tools/YMKTools/YMKDataTool.swift
UTF-8
2,809
2.703125
3
[]
no_license
// // YMKDataTool.swift // YiMeiKa // // Created by ykm on 2018/12/29. // Copyright © 2018 joyshops. All rights reserved. // import UIKit class YMKDataTool: NSObject { static var defaultIAPHelper :YMKDataTool{ struct Single{ static let defaultIAPHelper = YMKDataTool() } return Single.defaultIAPHelper } //数据类型装换 func getString(resurt:Any) -> String { if resurt as? String != nil { let resurtString = resurt as? String ?? "" return resurtString } else if resurt as? Int != nil { let resurtInt = resurt as? Int ?? 0 let resurtString = "\(resurtInt)" return resurtString } else if resurt as? Double != nil { let resurtDouble = resurt as? Double ?? 0 let resurtString = "\(resurtDouble)" return resurtString } else if resurt as? Float != nil { let resurtFloat = resurt as? Float ?? 0 let resurtString = "\(resurtFloat)" return resurtString } return "" } /** * 获取图片的大小 */ func getDataFromWith(_ hdImage: Any) -> Data { var data: Data? if hdImage is String { var hdImageStr = "\(hdImage)" if hdImageStr.hasPrefix("http://") || hdImageStr.hasPrefix("https://") { // 网络图片 do { let imageData = try Data.init(contentsOf: URL.init(string: hdImageStr)!) let image = UIImage.init(data: imageData as Data) data = image?.jpegData(compressionQuality: 0.8) let data_size = (data?.count ?? 0)/1024 if data_size > 125 { data = image?.jpegData(compressionQuality: 0.1) } // print("***** 压缩图片大小\((data?.count ?? 0)/1024)kb") }catch { } } else { // 本地图片 if hdImageStr.count == 0 { hdImageStr = "shareIcon" } var image = UIImage.init(named: hdImageStr) if image == nil { image = UIImage.init(named: "shareIcon") } data = image?.jpegData(compressionQuality: 0.5) } } else if hdImage is UIImage { // 本地图片 data = (hdImage as! UIImage).jpegData(compressionQuality: 0.3) } return data! } }
true
c8fa0c56eee47e7499571d66edadbc99c7c7d94b
Swift
komal2006/Day1sample
/Day1sample/Contents.swift
UTF-8
762
3.75
4
[]
no_license
import UIKit /*var str = "Hello, playground" //str=100 print(str) var s: Int = 100 print(s) let a = 200 //a = 300 print(a)*/ var a = 30 var b = 10 var sum = a+b print("sum of \(a) and \(b) is \(sum)") print(sum) print("sum : \(sum)") //read line() var p = "😝" print(p) var 😻 = "Cat" print(😻) var x1 = (1, "Komaldeep", "kaur") print(x1) print(x1,0) print(x1,1) print(x1,2) var x2 = (collegeId : 10, collegeName : "Lambton College", cityName : "Toronto") print(x2) print(x2.collegeId) print(x2.collegeName) print(x2.cityName) var (_,collegeName,cityName) = x2 var _ = 1000 print(collegeName, cityName) var c = 1...10 print(c) for i in -10..<10 { print("Komal \(i)") } for i in stride(from: 10, to: 1, by: -1) { print("Komal \(i)") }
true
ab9b66a3c279f942e194d23da4f47d3a0f33501f
Swift
Apophis-AppJam/ApophisiOS
/Apophis/Apophis_AppJam/Source/ViewControllers/Intro/IntroNewsViewController.swift
UTF-8
32,989
2.59375
3
[]
no_license
// // IntroNewsViewController.swift // Apophis_AppJam // // Created by 송지훈 on 2020/12/29. // import Foundation import UIKit import AVFoundation import AVKit class IntroNewsViewController: UIViewController { //MARK:- IBOutlet Part @IBOutlet weak var tempTitle1: UILabel! @IBOutlet weak var tempTitle2: UILabel! @IBOutlet weak var tempTitle3: UILabel! @IBOutlet weak var sampleView: UIView! @IBOutlet weak var chatTableView: UITableView! //MARK:- Variable Part let avPlayerViewController = AVPlayerViewController() var avPlayer : AVPlayer? var newsCommentList : [NewsCommentDataModel] = [] var newsCommentTempList : [NewsCommentDataModel] = [] // 실제 배열에 넣기 전에 임시 저장하는 곳 var commentCount = 0 // 100개 되면 종료하기 //MARK:- Constraint Part //MARK:- Life Cycle Part /// 앱의 Life Cycle 부분을 선언합니다 /// ex) override func viewWillAppear() { } override func viewDidLoad() { super.viewDidLoad() setDummyComment() playVideo() defaultViewSetting() defaultTableViewSetting() let time = DispatchTime.now() + .seconds(40) DispatchQueue.main.asyncAfter(deadline: time) { self.avPlayerViewController.player?.pause() guard let phoneVC = self.storyboard?.instantiateViewController(identifier: "IntroPhoneRingViewController") as? IntroPhoneRingViewController else {return} phoneVC.modalTransitionStyle = .crossDissolve phoneVC.modalPresentationStyle = .fullScreen self.present(phoneVC, animated: true, completion: nil) } } func playVideo(){ let filepath: String? = Bundle.main.path(forResource: "onBoardingNews", ofType: "mp4") let fileURL = URL.init(fileURLWithPath: filepath!) self.avPlayer = AVPlayer(url: fileURL) self.avPlayerViewController.player = self.avPlayer self.avPlayerViewController.view.frame = sampleView.bounds avPlayerViewController.showsPlaybackControls = false sampleView.addSubview(avPlayerViewController.view) self.avPlayerViewController.player?.play() } //MARK:- IBAction Part //MARK:- default Setting Function Part func defaultViewSetting() { self.navigationController?.navigationBar.isHidden = true tempTitle1.font = UIFont.gmarketFont(weight: .Medium, size: 16) tempTitle2.font = UIFont.gmarketFont(weight: .Medium, size: 12) tempTitle3.font = UIFont.gmarketFont(weight: .Medium, size: 12) } func defaultTableViewSetting() { chatTableView.delegate = self chatTableView.dataSource = self chatTableView.backgroundColor = .clear chatTableView.separatorStyle = .none chatTableView.allowsSelection = false } func setDummyComment() { newsCommentTempList.append(contentsOf: [ NewsCommentDataModel(message: "커퓌한잔할래요?", time: "오후 2:56", nickname: "콩이"), NewsCommentDataModel(message: "제주도 방어회는 먹고 죽고 싶어", time: "오후 2:56", nickname: "틱톡수연"), NewsCommentDataModel(message: "바다 한번 못보고 이렇게 가는구나", time: "오후 2:56", nickname: "버디"), NewsCommentDataModel(message: "죽을 때는 버건디 옷을 입어야겠다", time: "오후 2:56", nickname: "버건디두"), NewsCommentDataModel(message: "아포피스 맞이 라이브 컨텐츠 구독과 좋아요~", time: "오후 2:56", nickname: "진수"), NewsCommentDataModel(message: "지구의 삶은 짧아도 예술은 영원해!", time: "오후 2:57", nickname: "쥬똄 킴"), NewsCommentDataModel(message: "앞머리 어제 잘랐는데 길기도 전에 죽네!", time: "오후 2:57", nickname: "세화"), NewsCommentDataModel(message: "헉 죽기 전에 얼른 자퇴해야지", time: "오후 2:57", nickname: "봉쥬르 안"), NewsCommentDataModel(message: "마지막에 사람이 변한다고 하지... 오이를 아삭아삭..", time: "오후 2:57", nickname: "오이영재"), NewsCommentDataModel(message: "죽기전에 흑발을 할까 말까", time: "오후 2:57", nickname: "성림성"), NewsCommentDataModel(message: "에브리 바디 루프탑 파리~~~", time: "오후 2:57", nickname: "연수정수연"), NewsCommentDataModel(message: "우물쭈물 살다가 이럴 줄 알았지", time: "오후 2:57", nickname: "다니엘 최"), NewsCommentDataModel(message: "나는 죽어도 아름다운 나의 사랑은 계속될거야", time: "오후 2:57", nickname: "레고가좋아현"), NewsCommentDataModel(message: "나긋나긋 asmr (지구멸망.ver)", time: "오후 2:57", nickname: "서나선아"), NewsCommentDataModel(message: "아직 해리포터 다 못 봤는데 ㅠㅠㅠ", time: "오후 2:57", nickname: "혜니포터"), NewsCommentDataModel(message: "나는 사과나무를 한그루 심겠어", time: "오후 2:57", nickname: "럭키디두"), NewsCommentDataModel(message: "최준은 내꺼야 다 건들지마", time: "오후 2:57", nickname: "최준♥유경"), NewsCommentDataModel(message: "아직 틱톡 못찍었는데 망했다ㅜ", time: "오후 2:57", nickname: "가토수연"), NewsCommentDataModel(message: "거짓말이겠지..", time: "오후 2:57", nickname: "폭풍영재"), NewsCommentDataModel(message: "5252~다들 호들갑 떨지 말라구~", time: "오후 2:57", nickname: "52영재"), NewsCommentDataModel(message: "커퓌한잔할래요?", time: "오후 2:58", nickname: "콩이"), NewsCommentDataModel(message: "제주도 방어회는 먹고 죽고 싶어", time: "오후 2:58", nickname: "틱톡수연"), NewsCommentDataModel(message: "바다 한번 못보고 이렇게 가는구나", time: "오후 2:58", nickname: "버디"), NewsCommentDataModel(message: "죽을 때는 버건디 옷을 입어야겠다", time: "오후 2:58", nickname: "버건디두"), NewsCommentDataModel(message: "아포피스 맞이 라이브 컨텐츠 구독과 좋아요~", time: "오후 2:58", nickname: "진수"), NewsCommentDataModel(message: "지구의 삶은 짧아도 예술은 영원해!", time: "오후 2:58", nickname: "쥬똄 킴"), NewsCommentDataModel(message: "앞머리 어제 잘랐는데 길기도 전에 죽네!", time: "오후 2:58", nickname: "세화"), NewsCommentDataModel(message: "헉 죽기 전에 얼른 자퇴해야지", time: "오후 2:58", nickname: "봉쥬르 안"), NewsCommentDataModel(message: "마지막에 사람이 변한다고 하지... 오이를 아삭아삭..", time: "오후 2:58", nickname: "오이영재"), NewsCommentDataModel(message: "죽기전에 흑발을 할까 말까", time: "오후 2:58", nickname: "성림성"), NewsCommentDataModel(message: "에브리 바디 루프탑 파리~~~", time: "오후 2:58", nickname: "연수정수연"), NewsCommentDataModel(message: "우물쭈물 살다가 이럴 줄 알았지", time: "오후 2:58", nickname: "다니엘 최"), NewsCommentDataModel(message: "나는 죽어도 아름다운 나의 사랑은 계속될거야", time: "오후 2:58", nickname: "레고가좋아현"), NewsCommentDataModel(message: "나긋나긋 asmr (지구멸망.ver)", time: "오후 2:58", nickname: "서나선아"), NewsCommentDataModel(message: "아직 해리포터 다 못 봤는데 ㅠㅠㅠ", time: "오후 2:58", nickname: "혜니포터"), NewsCommentDataModel(message: "나는 사과나무를 한그루 심겠어", time: "오후 2:58", nickname: "럭키디두"), NewsCommentDataModel(message: "최준은 내꺼야 다 건들지마", time: "오후 2:58", nickname: "최준♥유경"), NewsCommentDataModel(message: "아직 틱톡 못찍었는데 망했다ㅜ", time: "오후 2:58", nickname: "가토수연"), NewsCommentDataModel(message: "거짓말이겠지..", time: "오후 2:58", nickname: "폭풍영재"), NewsCommentDataModel(message: "5252~다들 호들갑 떨지 말라구~", time: "오후 2:58", nickname: "52영재"), NewsCommentDataModel(message: "커퓌한잔할래요?", time: "오후 2:58", nickname: "콩이"), NewsCommentDataModel(message: "제주도 방어회는 먹고 죽고 싶어", time: "오후 2:58", nickname: "틱톡수연"), NewsCommentDataModel(message: "바다 한번 못보고 이렇게 가는구나", time: "오후 2:58", nickname: "버디"), NewsCommentDataModel(message: "죽을 때는 버건디 옷을 입어야겠다", time: "오후 2:58", nickname: "버건디두"), NewsCommentDataModel(message: "아포피스 맞이 라이브 컨텐츠 구독과 좋아요~", time: "오후 2:58", nickname: "진수"), NewsCommentDataModel(message: "지구의 삶은 짧아도 예술은 영원해!", time: "오후 2:58", nickname: "쥬똄 킴"), NewsCommentDataModel(message: "앞머리 어제 잘랐는데 길기도 전에 죽네!", time: "오후 2:58", nickname: "세화"), NewsCommentDataModel(message: "헉 죽기 전에 얼른 자퇴해야지", time: "오후 2:58", nickname: "봉쥬르 안"), NewsCommentDataModel(message: "마지막에 사람이 변한다고 하지... 오이를 아삭아삭..", time: "오후 2:58", nickname: "오이영재"), NewsCommentDataModel(message: "죽기전에 흑발을 할까 말까", time: "오후 2:58", nickname: "성림성"), NewsCommentDataModel(message: "에브리 바디 루프탑 파리~~~", time: "오후 2:58", nickname: "연수정수연"), NewsCommentDataModel(message: "우물쭈물 살다가 이럴 줄 알았지", time: "오후 2:58", nickname: "다니엘 최"), NewsCommentDataModel(message: "나는 죽어도 아름다운 나의 사랑은 계속될거야", time: "오후 2:58", nickname: "레고가좋아현"), NewsCommentDataModel(message: "나긋나긋 asmr (지구멸망.ver)", time: "오후 2:58", nickname: "서나선아"), NewsCommentDataModel(message: "아직 해리포터 다 못 봤는데 ㅠㅠㅠ", time: "오후 2:58", nickname: "혜니포터"), NewsCommentDataModel(message: "나는 사과나무를 한그루 심겠어", time: "오후 2:58", nickname: "럭키디두"), NewsCommentDataModel(message: "최준은 내꺼야 다 건들지마", time: "오후 2:58", nickname: "최준♥유경"), NewsCommentDataModel(message: "아직 틱톡 못찍었는데 망했다ㅜ", time: "오후 2:58", nickname: "가토수연"), NewsCommentDataModel(message: "거짓말이겠지..", time: "오후 2:58", nickname: "폭풍영재"), NewsCommentDataModel(message: "5252~다들 호들갑 떨지 말라구~", time: "오후 2:58", nickname: "52영재"), NewsCommentDataModel(message: "커퓌한잔할래요?", time: "오후 2:58", nickname: "콩이"), NewsCommentDataModel(message: "제주도 방어회는 먹고 죽고 싶어", time: "오후 2:58", nickname: "틱톡수연"), NewsCommentDataModel(message: "바다 한번 못보고 이렇게 가는구나", time: "오후 2:58", nickname: "버디"), NewsCommentDataModel(message: "죽을 때는 버건디 옷을 입어야겠다", time: "오후 2:58", nickname: "버건디두"), NewsCommentDataModel(message: "아포피스 맞이 라이브 컨텐츠 구독과 좋아요~", time: "오후 2:58", nickname: "진수"), NewsCommentDataModel(message: "지구의 삶은 짧아도 예술은 영원해!", time: "오후 2:58", nickname: "쥬똄 킴"), NewsCommentDataModel(message: "앞머리 어제 잘랐는데 길기도 전에 죽네!", time: "오후 2:58", nickname: "세화"), NewsCommentDataModel(message: "헉 죽기 전에 얼른 자퇴해야지", time: "오후 2:58", nickname: "봉쥬르 안"), NewsCommentDataModel(message: "마지막에 사람이 변한다고 하지... 오이를 아삭아삭..", time: "오후 2:58", nickname: "오이영재"), NewsCommentDataModel(message: "죽기전에 흑발을 할까 말까", time: "오후 2:58", nickname: "성림성"), NewsCommentDataModel(message: "에브리 바디 루프탑 파리~~~", time: "오후 2:58", nickname: "연수정수연"), NewsCommentDataModel(message: "우물쭈물 살다가 이럴 줄 알았지", time: "오후 2:58", nickname: "다니엘 최"), NewsCommentDataModel(message: "나는 죽어도 아름다운 나의 사랑은 계속될거야", time: "오후 2:58", nickname: "레고가좋아현"), NewsCommentDataModel(message: "나긋나긋 asmr (지구멸망.ver)", time: "오후 2:58", nickname: "서나선아"), NewsCommentDataModel(message: "아직 해리포터 다 못 봤는데 ㅠㅠㅠ", time: "오후 2:58", nickname: "혜니포터"), NewsCommentDataModel(message: "나는 사과나무를 한그루 심겠어", time: "오후 2:58", nickname: "럭키디두"), NewsCommentDataModel(message: "최준은 내꺼야 다 건들지마", time: "오후 2:58", nickname: "최준♥유경"), NewsCommentDataModel(message: "아직 틱톡 못찍었는데 망했다ㅜ", time: "오후 2:58", nickname: "가토수연"), NewsCommentDataModel(message: "거짓말이겠지..", time: "오후 2:58", nickname: "폭풍영재"), NewsCommentDataModel(message: "5252~다들 호들갑 떨지 말라구~", time: "오후 2:58", nickname: "52영재"), NewsCommentDataModel(message: "커퓌한잔할래요?", time: "오후 2:58", nickname: "콩이"), NewsCommentDataModel(message: "제주도 방어회는 먹고 죽고 싶어", time: "오후 2:58", nickname: "틱톡수연"), NewsCommentDataModel(message: "바다 한번 못보고 이렇게 가는구나", time: "오후 2:58", nickname: "버디"), NewsCommentDataModel(message: "죽을 때는 버건디 옷을 입어야겠다", time: "오후 2:58", nickname: "버건디두"), NewsCommentDataModel(message: "아포피스 맞이 라이브 컨텐츠 구독과 좋아요~", time: "오후 2:58", nickname: "진수"), NewsCommentDataModel(message: "지구의 삶은 짧아도 예술은 영원해!", time: "오후 2:58", nickname: "쥬똄 킴"), NewsCommentDataModel(message: "앞머리 어제 잘랐는데 길기도 전에 죽네!", time: "오후 2:58", nickname: "세화"), NewsCommentDataModel(message: "헉 죽기 전에 얼른 자퇴해야지", time: "오후 2:58", nickname: "봉쥬르 안"), NewsCommentDataModel(message: "마지막에 사람이 변한다고 하지... 오이를 아삭아삭..", time: "오후 2:58", nickname: "오이영재"), NewsCommentDataModel(message: "죽기전에 흑발을 할까 말까", time: "오후 2:58", nickname: "성림성"), NewsCommentDataModel(message: "에브리 바디 루프탑 파리~~~", time: "오후 2:58", nickname: "연수정수연"), NewsCommentDataModel(message: "우물쭈물 살다가 이럴 줄 알았지", time: "오후 2:58", nickname: "다니엘 최"), NewsCommentDataModel(message: "나는 죽어도 아름다운 나의 사랑은 계속될거야", time: "오후 2:58", nickname: "레고가좋아현"), NewsCommentDataModel(message: "나긋나긋 asmr (지구멸망.ver)", time: "오후 2:58", nickname: "서나선아"), NewsCommentDataModel(message: "아직 해리포터 다 못 봤는데 ㅠㅠㅠ", time: "오후 2:58", nickname: "혜니포터"), NewsCommentDataModel(message: "나는 사과나무를 한그루 심겠어", time: "오후 2:58", nickname: "럭키디두"), NewsCommentDataModel(message: "최준은 내꺼야 다 건들지마", time: "오후 2:58", nickname: "최준♥유경"), NewsCommentDataModel(message: "아직 틱톡 못찍었는데 망했다ㅜ", time: "오후 2:58", nickname: "가토수연"), NewsCommentDataModel(message: "거짓말이겠지..", time: "오후 2:58", nickname: "폭풍영재"), NewsCommentDataModel(message: "5252~다들 호들갑 떨지 말라구~", time: "오후 2:58", nickname: "52영재"), NewsCommentDataModel(message: "아직 해리포터 다 못 봤는데 ㅠㅠㅠ", time: "오후 2:58", nickname: "혜니포터"), NewsCommentDataModel(message: "나는 사과나무를 한그루 심겠어", time: "오후 2:58", nickname: "럭키디두"), NewsCommentDataModel(message: "최준은 내꺼야 다 건들지마", time: "오후 2:58", nickname: "최준♥유경"), NewsCommentDataModel(message: "아직 틱톡 못찍었는데 망했다ㅜ", time: "오후 2:58", nickname: "가토수연"), NewsCommentDataModel(message: "거짓말이겠지..", time: "오후 2:58", nickname: "폭풍영재"), NewsCommentDataModel(message: "5252~다들 호들갑 떨지 말라구~", time: "오후 2:58", nickname: "52영재"), NewsCommentDataModel(message: "커퓌한잔할래요?", time: "오후 2:58", nickname: "콩이"), NewsCommentDataModel(message: "제주도 방어회는 먹고 죽고 싶어", time: "오후 2:58", nickname: "틱톡수연"), NewsCommentDataModel(message: "바다 한번 못보고 이렇게 가는구나", time: "오후 2:58", nickname: "버디"), NewsCommentDataModel(message: "죽을 때는 버건디 옷을 입어야겠다", time: "오후 2:58", nickname: "버건디두"), NewsCommentDataModel(message: "아포피스 맞이 라이브 컨텐츠 구독과 좋아요~", time: "오후 2:58", nickname: "진수"), NewsCommentDataModel(message: "지구의 삶은 짧아도 예술은 영원해!", time: "오후 2:58", nickname: "쥬똄 킴"), NewsCommentDataModel(message: "앞머리 어제 잘랐는데 길기도 전에 죽네!", time: "오후 2:58", nickname: "세화"), NewsCommentDataModel(message: "헉 죽기 전에 얼른 자퇴해야지", time: "오후 2:58", nickname: "봉쥬르 안"), NewsCommentDataModel(message: "마지막에 사람이 변한다고 하지... 오이를 아삭아삭..", time: "오후 2:58", nickname: "오이영재"), NewsCommentDataModel(message: "죽기전에 흑발을 할까 말까", time: "오후 2:58", nickname: "성림성"), NewsCommentDataModel(message: "에브리 바디 루프탑 파리~~~", time: "오후 2:58", nickname: "연수정수연"), NewsCommentDataModel(message: "우물쭈물 살다가 이럴 줄 알았지", time: "오후 2:58", nickname: "다니엘 최"), NewsCommentDataModel(message: "나는 죽어도 아름다운 나의 사랑은 계속될거야", time: "오후 2:58", nickname: "레고가좋아현"), NewsCommentDataModel(message: "나긋나긋 asmr (지구멸망.ver)", time: "오후 2:58", nickname: "서나선아"), NewsCommentDataModel(message: "아직 해리포터 다 못 봤는데 ㅠㅠㅠ", time: "오후 2:58", nickname: "혜니포터"), NewsCommentDataModel(message: "나는 사과나무를 한그루 심겠어", time: "오후 2:58", nickname: "럭키디두"), NewsCommentDataModel(message: "최준은 내꺼야 다 건들지마", time: "오후 2:58", nickname: "최준♥유경"), NewsCommentDataModel(message: "아직 틱톡 못찍었는데 망했다ㅜ", time: "오후 2:58", nickname: "가토수연"), NewsCommentDataModel(message: "거짓말이겠지..", time: "오후 2:58", nickname: "폭풍영재"), NewsCommentDataModel(message: "5252~다들 호들갑 떨지 말라구~", time: "오후 2:58", nickname: "52영재"), NewsCommentDataModel(message: "아직 해리포터 다 못 봤는데 ㅠㅠㅠ", time: "오후 2:58", nickname: "혜니포터"), NewsCommentDataModel(message: "나는 사과나무를 한그루 심겠어", time: "오후 2:58", nickname: "럭키디두"), NewsCommentDataModel(message: "최준은 내꺼야 다 건들지마", time: "오후 2:58", nickname: "최준♥유경"), NewsCommentDataModel(message: "아직 틱톡 못찍었는데 망했다ㅜ", time: "오후 2:58", nickname: "가토수연"), NewsCommentDataModel(message: "거짓말이겠지..", time: "오후 2:58", nickname: "폭풍영재"), NewsCommentDataModel(message: "5252~다들 호들갑 떨지 말라구~", time: "오후 2:58", nickname: "52영재"), NewsCommentDataModel(message: "커퓌한잔할래요?", time: "오후 2:58", nickname: "콩이"), NewsCommentDataModel(message: "제주도 방어회는 먹고 죽고 싶어", time: "오후 2:58", nickname: "틱톡수연"), NewsCommentDataModel(message: "바다 한번 못보고 이렇게 가는구나", time: "오후 2:58", nickname: "버디"), NewsCommentDataModel(message: "죽을 때는 버건디 옷을 입어야겠다", time: "오후 2:58", nickname: "버건디두"), NewsCommentDataModel(message: "아포피스 맞이 라이브 컨텐츠 구독과 좋아요~", time: "오후 2:58", nickname: "진수"), NewsCommentDataModel(message: "지구의 삶은 짧아도 예술은 영원해!", time: "오후 2:58", nickname: "쥬똄 킴"), NewsCommentDataModel(message: "앞머리 어제 잘랐는데 길기도 전에 죽네!", time: "오후 2:58", nickname: "세화"), NewsCommentDataModel(message: "헉 죽기 전에 얼른 자퇴해야지", time: "오후 2:58", nickname: "봉쥬르 안"), NewsCommentDataModel(message: "마지막에 사람이 변한다고 하지... 오이를 아삭아삭..", time: "오후 2:58", nickname: "오이영재"), NewsCommentDataModel(message: "죽기전에 흑발을 할까 말까", time: "오후 2:58", nickname: "성림성"), NewsCommentDataModel(message: "에브리 바디 루프탑 파리~~~", time: "오후 2:58", nickname: "연수정수연"), NewsCommentDataModel(message: "우물쭈물 살다가 이럴 줄 알았지", time: "오후 2:58", nickname: "다니엘 최"), NewsCommentDataModel(message: "나는 죽어도 아름다운 나의 사랑은 계속될거야", time: "오후 2:58", nickname: "레고가좋아현"), NewsCommentDataModel(message: "나긋나긋 asmr (지구멸망.ver)", time: "오후 2:58", nickname: "서나선아"), NewsCommentDataModel(message: "아직 해리포터 다 못 봤는데 ㅠㅠㅠ", time: "오후 2:58", nickname: "혜니포터"), NewsCommentDataModel(message: "나는 사과나무를 한그루 심겠어", time: "오후 2:58", nickname: "럭키디두"), NewsCommentDataModel(message: "최준은 내꺼야 다 건들지마", time: "오후 2:58", nickname: "최준♥유경"), NewsCommentDataModel(message: "아직 틱톡 못찍었는데 망했다ㅜ", time: "오후 2:58", nickname: "가토수연"), NewsCommentDataModel(message: "거짓말이겠지..", time: "오후 2:58", nickname: "폭풍영재"), NewsCommentDataModel(message: "5252~다들 호들갑 떨지 말라구~", time: "오후 2:58", nickname: "52영재"), NewsCommentDataModel(message: "아직 해리포터 다 못 봤는데 ㅠㅠㅠ", time: "오후 2:58", nickname: "혜니포터"), NewsCommentDataModel(message: "나는 사과나무를 한그루 심겠어", time: "오후 2:58", nickname: "럭키디두"), NewsCommentDataModel(message: "최준은 내꺼야 다 건들지마", time: "오후 2:58", nickname: "최준♥유경"), NewsCommentDataModel(message: "아직 틱톡 못찍었는데 망했다ㅜ", time: "오후 2:58", nickname: "가토수연"), NewsCommentDataModel(message: "거짓말이겠지..", time: "오후 2:58", nickname: "폭풍영재"), NewsCommentDataModel(message: "5252~다들 호들갑 떨지 말라구~", time: "오후 2:58", nickname: "52영재"), NewsCommentDataModel(message: "커퓌한잔할래요?", time: "오후 2:58", nickname: "콩이"), NewsCommentDataModel(message: "제주도 방어회는 먹고 죽고 싶어", time: "오후 2:58", nickname: "틱톡수연"), NewsCommentDataModel(message: "바다 한번 못보고 이렇게 가는구나", time: "오후 2:58", nickname: "버디"), NewsCommentDataModel(message: "죽을 때는 버건디 옷을 입어야겠다", time: "오후 2:58", nickname: "버건디두"), NewsCommentDataModel(message: "아포피스 맞이 라이브 컨텐츠 구독과 좋아요~", time: "오후 2:58", nickname: "진수"), NewsCommentDataModel(message: "지구의 삶은 짧아도 예술은 영원해!", time: "오후 2:58", nickname: "쥬똄 킴"), NewsCommentDataModel(message: "앞머리 어제 잘랐는데 길기도 전에 죽네!", time: "오후 2:58", nickname: "세화"), NewsCommentDataModel(message: "헉 죽기 전에 얼른 자퇴해야지", time: "오후 2:58", nickname: "봉쥬르 안"), NewsCommentDataModel(message: "마지막에 사람이 변한다고 하지... 오이를 아삭아삭..", time: "오후 2:58", nickname: "오이영재"), NewsCommentDataModel(message: "죽기전에 흑발을 할까 말까", time: "오후 2:58", nickname: "성림성"), NewsCommentDataModel(message: "에브리 바디 루프탑 파리~~~", time: "오후 2:58", nickname: "연수정수연"), NewsCommentDataModel(message: "우물쭈물 살다가 이럴 줄 알았지", time: "오후 2:58", nickname: "다니엘 최"), NewsCommentDataModel(message: "나는 죽어도 아름다운 나의 사랑은 계속될거야", time: "오후 2:58", nickname: "레고가좋아현"), NewsCommentDataModel(message: "나긋나긋 asmr (지구멸망.ver)", time: "오후 2:58", nickname: "서나선아"), NewsCommentDataModel(message: "아직 해리포터 다 못 봤는데 ㅠㅠㅠ", time: "오후 2:58", nickname: "혜니포터"), NewsCommentDataModel(message: "나는 사과나무를 한그루 심겠어", time: "오후 2:58", nickname: "럭키디두"), NewsCommentDataModel(message: "최준은 내꺼야 다 건들지마", time: "오후 2:58", nickname: "최준♥유경"), NewsCommentDataModel(message: "아직 틱톡 못찍었는데 망했다ㅜ", time: "오후 2:58", nickname: "가토수연"), NewsCommentDataModel(message: "거짓말이겠지..", time: "오후 2:58", nickname: "폭풍영재"), NewsCommentDataModel(message: "5252~다들 호들갑 떨지 말라구~", time: "오후 2:58", nickname: "52영재"), NewsCommentDataModel(message: "아직 해리포터 다 못 봤는데 ㅠㅠㅠ", time: "오후 2:58", nickname: "혜니포터"), NewsCommentDataModel(message: "나는 사과나무를 한그루 심겠어", time: "오후 2:58", nickname: "럭키디두"), NewsCommentDataModel(message: "최준은 내꺼야 다 건들지마", time: "오후 2:58", nickname: "최준♥유경"), NewsCommentDataModel(message: "아직 틱톡 못찍었는데 망했다ㅜ", time: "오후 2:58", nickname: "가토수연"), NewsCommentDataModel(message: "거짓말이겠지..", time: "오후 2:58", nickname: "폭풍영재"), NewsCommentDataModel(message: "5252~다들 호들갑 떨지 말라구~", time: "오후 2:58", nickname: "52영재"), NewsCommentDataModel(message: "커퓌한잔할래요?", time: "오후 2:58", nickname: "콩이"), NewsCommentDataModel(message: "제주도 방어회는 먹고 죽고 싶어", time: "오후 2:58", nickname: "틱톡수연"), NewsCommentDataModel(message: "바다 한번 못보고 이렇게 가는구나", time: "오후 2:58", nickname: "버디"), NewsCommentDataModel(message: "죽을 때는 버건디 옷을 입어야겠다", time: "오후 2:58", nickname: "버건디두"), NewsCommentDataModel(message: "아포피스 맞이 라이브 컨텐츠 구독과 좋아요~", time: "오후 2:58", nickname: "진수"), NewsCommentDataModel(message: "지구의 삶은 짧아도 예술은 영원해!", time: "오후 2:58", nickname: "쥬똄 킴"), NewsCommentDataModel(message: "앞머리 어제 잘랐는데 길기도 전에 죽네!", time: "오후 2:58", nickname: "세화"), NewsCommentDataModel(message: "헉 죽기 전에 얼른 자퇴해야지", time: "오후 2:58", nickname: "봉쥬르 안"), NewsCommentDataModel(message: "마지막에 사람이 변한다고 하지... 오이를 아삭아삭..", time: "오후 2:58", nickname: "오이영재"), NewsCommentDataModel(message: "죽기전에 흑발을 할까 말까", time: "오후 2:58", nickname: "성림성"), NewsCommentDataModel(message: "에브리 바디 루프탑 파리~~~", time: "오후 2:58", nickname: "연수정수연"), NewsCommentDataModel(message: "우물쭈물 살다가 이럴 줄 알았지", time: "오후 2:58", nickname: "다니엘 최"), NewsCommentDataModel(message: "나는 죽어도 아름다운 나의 사랑은 계속될거야", time: "오후 2:58", nickname: "레고가좋아현"), NewsCommentDataModel(message: "나긋나긋 asmr (지구멸망.ver)", time: "오후 2:58", nickname: "서나선아"), NewsCommentDataModel(message: "아직 해리포터 다 못 봤는데 ㅠㅠㅠ", time: "오후 2:58", nickname: "혜니포터"), NewsCommentDataModel(message: "나는 사과나무를 한그루 심겠어", time: "오후 2:58", nickname: "럭키디두"), NewsCommentDataModel(message: "최준은 내꺼야 다 건들지마", time: "오후 2:58", nickname: "최준♥유경"), NewsCommentDataModel(message: "아직 틱톡 못찍었는데 망했다ㅜ", time: "오후 2:58", nickname: "가토수연"), NewsCommentDataModel(message: "거짓말이겠지..", time: "오후 2:58", nickname: "폭풍영재"), NewsCommentDataModel(message: "5252~다들 호들갑 떨지 말라구~", time: "오후 2:58", nickname: "52영재") ]) chatTableView.reloadData() Timer.scheduledTimer(withTimeInterval: 0.8, repeats: true) { timer in self.newsCommentList.append(self.newsCommentTempList[self.commentCount]) self.chatTableView.reloadData() self.chatTableView.scrollToBottom() self.commentCount += 1 if self.commentCount == self.newsCommentTempList.count // temp 배열 떨어질때까지 하나씩 추가해봅시다 { timer.invalidate() } } } //MARK:- Function Part } //MARK:- extension 부분 extension IntroNewsViewController : UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 28 } } extension IntroNewsViewController : UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return newsCommentList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let commentCell = tableView.dequeueReusableCell(withIdentifier: "IntroNewsCommentCell") as? IntroNewsCommentCell else {return UITableViewCell() } commentCell.setMessage(time: newsCommentList[indexPath.row].time, name: newsCommentList[indexPath.row].nickname, message: newsCommentList[indexPath.row].message, imageIndex: indexPath.row % 5) commentCell.backgroundColor = .clear return commentCell } }
true
dac0dca1f0de3325292f51dd1a925debb929e0da
Swift
sdoylelambda/ios-sprint3-challenge
/Pokedex Sprint 3 2.1/Pokedex Sprint 3 2.1/Model/Pokemon.swift
UTF-8
391
2.90625
3
[]
no_license
import Foundation struct Pokemon: Codable { let name: String let id: Int let types: [TypeElement] let abilities: [Ability] let sprites: Sprites } struct TypeElement: Codable { let type: Species } struct Ability: Codable { let ability: Species } struct Species: Codable { let name: String } struct Sprites: Codable { let frontDefault: String }
true
2b82cc97d38798dc3da51db4ab61863b7401be27
Swift
zs40x/PersonalProductivityAssistant
/PersonalProductivityAssistant/Model/Data/PickableDate.swift
UTF-8
842
3.203125
3
[ "MIT" ]
permissive
// // PickableDate.swift // PersonalProductivityAssistant // // Created by Stefan Mehnert on 25/12/2016. // Copyright © 2016 Stefan Mehnert. All rights reserved. // import Foundation class PickableDate: Equatable { fileprivate(set) var date: Date fileprivate(set) var title: String fileprivate(set) var field: DatePickTargetField init(title: String, field: DatePickTargetField, date: Date) { self.date = date self.title = title self.field = field } convenience init(title: String, field: DatePickTargetField) { self.init(title: title, field: field,date: Date()) } static func ==(lhs: PickableDate, rhs: PickableDate) -> Bool { return lhs.date == rhs.date && lhs.title == rhs.title && lhs.field == rhs.field } }
true
b7f7d03e515ad9c83569cb7992d125286e66f8f6
Swift
Nikitaxub/GameSet
/GameSet/Card.swift
UTF-8
938
3
3
[]
no_license
// // Card.swift // GameSet // // Created by Ivanych Puy on 17.05.2020. // Copyright © 2020 xubuntus. All rights reserved. // import Foundation struct Card: Hashable { // static func == (lhs: Card, rhs: Card) -> Bool { // return lhs.identifier == rhs.identifier // } // func hash(into hasher: inout Hasher) { hasher.combine(figure) hasher.combine(color) hasher.combine(qty) hasher.combine(filling) } var isPassed = false var isChoosed = false var setID: Int? var placeID: Int? let figure: Int let color: Int let qty: Int let filling: Int // private var identifier: Int // // private static var identifierFactory = 0 // // private static func getUniqueIdentifier() -> Int { // identifierFactory += 1 // return identifierFactory // } // // init() { // self.identifier = Card.getUniqueIdentifier() // } }
true
94b624ee5dd58a6c13897d8e046fd1ace174e8f2
Swift
hung070996/ios_training
/DemoMVVM/DemoMVVM/Repository/SearchRepository.swift
UTF-8
669
2.515625
3
[]
no_license
// // SearchRepository.swift // DemoMVVM // // Created by Do Hung on 8/22/18. // Copyright © 2018 Do Hung. All rights reserved. // import Foundation import ObjectMapper import RxSwift protocol SearchRepository { func getSearch(input: SearchRequest) -> Observable<[TrackSearch]> } class SearchRepositoryImp: SearchRepository { func getSearch(input: SearchRequest) -> Observable<[TrackSearch]> { return api.request(input: input).map({ (response: SearchResponse) -> [TrackSearch] in return response.collection }) } private var api: APIManager! required init(api: APIManager) { self.api = api } }
true
2eef5982f9fe282a6591187cdd6c2d9fae72cb13
Swift
jiaowochunge/Fake2048
/Fake2048/GameScene.swift
UTF-8
24,840
2.765625
3
[]
no_license
// // GameScene.swift // Fake2048 // // Created by john on 16/5/10. // Copyright (c) 2016年 BOLO. All rights reserved. // import SpriteKit let showTinyMap = false let LowTile: CGFloat = 10 let MidTile: CGFloat = 20 let HighTile: CGFloat = 30 /** * 游戏进程代理 */ protocol GameDelegateProtocol { func saveGameDelegate() func loadGameDelegate() } /// 游戏状态 enum GameStatus { /// 还没开始 case gameNotStart /// 游戏中 case gameProcess /// 完蛋了 case gameOver } /// 游戏配置上下文 struct GameContext { /// 地图 var tileMap: [[Int]] /// 地图维度 var dimension: Int /// 游戏状态 var status: GameStatus = .gameNotStart /// 已进行步数 var stepCount: Int = 0 /// 分数 var score: Int = 0 init(dimension: Int = 4) { self.dimension = dimension tileMap = Array<[Int]>(repeating: Array<Int>(repeating: 0, count: dimension), count: dimension) } init(record: History) { self.dimension = record.dimension!.intValue // 根据 "," 分割字符串,将分隔后的字符串强转 Int let tileMap1 = record.tile_map!.characters.split(separator: ",").map { Int(String($0))! } // [Int] -> [[Int]] var tileMap2: [[Int]] = [] for i in 0..<dimension { let s = i * dimension, e = i * dimension + dimension let t = tileMap1[s..<e] tileMap2.append(Array<Int>(t)) } self.tileMap = tileMap2 } } class GameScene: SKScene { var gameDelegate: GameDelegateProtocol! var context: GameContext /// 是否正在动画过程中 var inAnimation = false /// 同步动画组序列 lazy var animationGroup = DispatchGroup() // TODO: 使用 GameStatus 代替 var hasStartGame: Bool = false var gameOver = false /// 方块容器 var tileBoard: SKShapeNode! /// 方块之间的间距 let tileMargin: CGFloat = 10 /// 方块长度 var tileLength: CGFloat! var startMenu: SKShapeNode! var loadMenu: SKShapeNode! var saveMenu: SKShapeNode! // 小地图 var tinyMap: SKLabelNode! override init(size: CGSize) { context = GameContext() super.init(size: size) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMove(to view: SKView) { addDecorateNode() initGame() } override func update(_ currentTime: TimeInterval) { /* Called before each frame is rendered */ } /** 添加节点 */ func addDecorateNode() { self.backgroundColor = SKColor(white: 247 / 255.0, alpha: 1) // 屏幕尺寸 let screenSize = UIScreen.main.bounds.size // 游戏区域划分:正方形主要游戏区域在中间,剩下高度,2/3在上,1/3在下 var boardRect = CGRect(x: -screenSize.width / 2, y: -screenSize.width / 2, width: screenSize.width, height: screenSize.width) // 缩进 boardRect = boardRect.insetBy(dx: 15, dy: 15) tileBoard = SKShapeNode(rect: boardRect, cornerRadius: 5) tileBoard.fillColor = SKColor(red: 174 / 255.0, green: 159 / 255.0, blue: 143 / 255.0, alpha: 1) tileBoard.position = CGPoint(x: screenSize.width / 2, y: (screenSize.height - screenSize.width) / 3 + screenSize.width / 2) self.addChild(tileBoard) // 文字提示 let gameNameLabel = SKLabelNode(text: "2048") gameNameLabel.fontSize = 35 gameNameLabel.fontName = "Arial-BoldMT" gameNameLabel.fontColor = SKColor(red: 99 / 255.0, green: 91 / 255.0, blue: 82 / 255.0, alpha: 1) gameNameLabel.verticalAlignmentMode = .center gameNameLabel.horizontalAlignmentMode = .left gameNameLabel.position = CGPoint(x: 15, y: screenSize.height - (screenSize.height - screenSize.width) / 3) self.addChild(gameNameLabel) let gameBrief = SKLabelNode(text: "获得 2048,你就赢了!") gameBrief.fontSize = 12 gameBrief.fontName = "ArialMT" gameBrief.fontColor = SKColor(red: 99 / 255.0, green: 91 / 255.0, blue: 82 / 255.0, alpha: 1) gameBrief.verticalAlignmentMode = .center gameBrief.horizontalAlignmentMode = .left gameBrief.position = CGPoint(x: gameNameLabel.position.x, y: screenSize.height - (screenSize.height - screenSize.width) / 2) self.addChild(gameBrief) // 开始游戏 startMenu = SKShapeNode(rect: CGRect(x: -37.5, y: -10, width: 75, height: 20), cornerRadius: 2) startMenu.strokeColor = SKColor(red: 124 / 255.0, green: 103 / 255.0, blue: 83 / 255.0, alpha: 1) startMenu.fillColor = startMenu.strokeColor startMenu.position = CGPoint(x: screenSize.width - 37.5 - gameBrief.position.x, y: gameBrief.position.y) self.addChild(startMenu) let startLabel = SKLabelNode(text: "Start Game") startLabel.fontSize = 12 startLabel.fontName = "Arial-BoldMT" startLabel.fontColor = SKColor.white startLabel.verticalAlignmentMode = .center startLabel.position = CGPoint.zero startMenu.addChild(startLabel) if showTinyMap { tinyMap = SKLabelNode(text: nil) tinyMap.fontSize = 10 tinyMap.fontName = "ArialMT" tinyMap.fontColor = SKColor.black tinyMap.verticalAlignmentMode = .center tinyMap.horizontalAlignmentMode = .left tinyMap.position = CGPoint(x: gameNameLabel.position.x, y: (screenSize.height - screenSize.width) / 6) self.addChild(tinyMap) } // 装载游戏 loadMenu = SKShapeNode(rect: CGRect(x: -37.5, y: -10, width: 75, height: 20), cornerRadius: 2) loadMenu.strokeColor = SKColor(red: 124 / 255.0, green: 103 / 255.0, blue: 83 / 255.0, alpha: 1) loadMenu.fillColor = loadMenu.strokeColor loadMenu.position = CGPoint(x: 15 + loadMenu.frame.width * 0.5, y: (screenSize.height - screenSize.width) / 3 - 20) self.addChild(loadMenu) let loadLabel = SKLabelNode(text: "Load Game") loadLabel.fontSize = 12 loadLabel.fontName = "Arial-BoldMT" loadLabel.fontColor = SKColor.white loadLabel.verticalAlignmentMode = .center loadLabel.position = CGPoint.zero loadMenu.addChild(loadLabel) // 保存游戏 saveMenu = SKShapeNode(rect: CGRect(x: -37.5, y: -10, width: 75, height: 20), cornerRadius: 2) saveMenu.strokeColor = SKColor(red: 124 / 255.0, green: 103 / 255.0, blue: 83 / 255.0, alpha: 1) saveMenu.fillColor = saveMenu.strokeColor saveMenu.position = CGPoint(x: screenSize.width - 15 - saveMenu.frame.width * 0.5, y: loadMenu.position.y) self.addChild(saveMenu) let saveLabel = SKLabelNode(text: "Save Game") saveLabel.fontSize = 12 saveLabel.fontName = "Arial-BoldMT" saveLabel.fontColor = SKColor.white saveLabel.verticalAlignmentMode = .center saveLabel.position = CGPoint.zero saveMenu.addChild(saveLabel) } func initGame() { tileLength = (tileBoard.frame.size.width - CGFloat(context.dimension + 1) * tileMargin) / CGFloat(context.dimension) for i in (0..<context.dimension) { for j in (0..<context.dimension) { // 添加背景小方块 let tile = NumTile(length: tileLength) tile.position = tilePosition(i, j) tile.zPosition = LowTile tileBoard.addChild(tile) } } } func startGame() { // 重新开始 if hasStartGame || gameOver { if gameOver { self.childNode(withName: "gameover")?.removeFromParent() } tileBoard.removeAllChildren() context = GameContext() initGame() self.view?.undoManager?.removeAllActions() } gameOver = false hasStartGame = true let l = startMenu.children.first as! SKLabelNode l.text = "New Game" // 由两个方块起手 for _ in (0..<2) { addNewTile() } } /** 返回一个随机空白位置 - returns: 该位置的坐标 */ func randomPosition() -> (Int, Int) { var remainRoom: Array<(Int, Int)> = [] for i in (0..<context.dimension) { for j in (0..<context.dimension) { if context.tileMap[i][j] == 0 { remainRoom.append((i, j)) } } } return remainRoom[Int(arc4random()) % remainRoom.count] } func tilePosition(_ x: Int, _ y: Int) -> CGPoint { /*** 数组方向是行列式方向 | 11 12 13 14 | | 21 22 23 24 | | 31 32 33 34 | | 41 42 43 44 | */ // 计算坐标 var x1 = (CGFloat(y) + 1) * tileMargin + (CGFloat(y) + 0.5) * tileLength var y1 = (CGFloat(context.dimension - 1 - x) + 1) * tileMargin + (CGFloat(context.dimension - 1 - x) + 0.5) * tileLength // 由于父坐标系的锚点在中心,需要偏移 x1 -= tileBoard.frame.size.width / 2 y1 -= tileBoard.frame.size.width / 2 return CGPoint(x: x1, y: y1) } func addNewTile() { let p = randomPosition() let t = NumTile(length: tileLength) t.position = tilePosition(p.0, p.1) t.name = "\(p.0),\(p.1)" t.zPosition = HighTile tileBoard.addChild(t) t.levelUp() // 标记方块 context.tileMap[p.0][p.1] = t.level.rawValue logStatus() } func detectGameOver() -> Bool { // 还有0就还能玩 var hasSpace = false for i in 0..<context.dimension { for j in 0..<context.dimension { if context.tileMap[i][j] == 0 { hasSpace = true break } } } if hasSpace { return false } else { // 已经没有空间了,检测是否有相邻的两个方块相同 var alive = false for i in 0..<context.dimension { for j in 0..<context.dimension { // 左侧 if j > 0 && context.tileMap[i][j] == context.tileMap[i][j - 1] { alive = true break } // 右侧 if j < context.dimension - 2 && context.tileMap[i][j] == context.tileMap[i][j + 1] { alive = true break } // 上边 if i > 0 && context.tileMap[i][j] == context.tileMap[i - 1][j] { alive = true break } // 下边 if i < context.dimension - 2 && context.tileMap[i][j] == context.tileMap[i + 1][j] { alive = true break } } } return !alive } } /** 打印游戏日志 */ func logStatus() { if showTinyMap { var s: String = "" NSLog("=============================") for i in 0..<context.dimension { var vs: String = "|" s += "|" for j in 0..<context.dimension { s += " \(context.tileMap[i][j]) " vs += " \(context.tileMap[i][j]) " } s += "|" vs += "|" NSLog(vs) s += "\n" } NSLog("=============================") tinyMap.text = s } } } extension GameScene { override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { // 反正不支持多点触控,直接取第一个触摸点 guard let touch = touches.first else { return } // 找到触摸点 let touchPoint = touch.location(in: self) // 是开始按钮 if startMenu.contains(touchPoint) { startGame() } else if saveMenu.contains(touchPoint) { if !hasStartGame || gameOver { return } let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.modelController.saveGame(context) // 数据源是由自己管理的,外层controller不好处理。姑且通知下 gameDelegate.saveGameDelegate() } else if loadMenu.contains(touchPoint) { // 什么都不做,由外层controller处理 gameDelegate.loadGameDelegate() } } // 后退一步 func restoreLastStep(_ state: [[Int]]) { let snapShot = context.tileMap self.view?.undoManager?.registerUndo(withTarget: self, selector: #selector(GameScene.restoreLastStep(_:)), object: snapShot); tileBoard.removeAllChildren() context.tileMap = state for i in 0..<context.dimension { for j in 0..<context.dimension { // 添加背景小方块 let tile = NumTile(length: tileLength) tile.position = tilePosition(i, j) tile.zPosition = LowTile tileBoard.addChild(tile) if context.tileMap[i][j] != 0 { let t = NumTile(length: tileLength) t.level = TileLevel(rawValue: context.tileMap[i][j])! t.position = tilePosition(i, j) t.name = "\(i),\(j)" t.zPosition = HighTile tileBoard.addChild(t) } } } logStatus() } } extension GameScene: GameActionProtocol { func swipeGesture(_ direction: UISwipeGestureRecognizerDirection) { // 变换坐标。这个变换是可逆的,变过去或变回来是同一个变换 let transformPosition = { [unowned self] (x: Int, y: Int) -> (Int, Int) in if direction == .left { // 无需变换 return (x, y) } else if direction == .right { // 子数组倒序 return (x, self.context.dimension - 1 - y) } else if direction == .up { // 旋转 return (self.context.dimension - 1 - y, x) } else { // 旋转 return (y, self.context.dimension - 1 - x) } } let transformPositionReverse = { [unowned self] (x: Int, y: Int) -> (Int, Int) in if direction == .left { // 无需变换 return (x, y) } else if direction == .right { // 子数组倒序 return (x, self.context.dimension - 1 - y) } else if direction == .up { // 旋转 return (y, self.context.dimension - 1 - x) } else { // 旋转 return (self.context.dimension - 1 - y, x) } } if !hasStartGame || gameOver || inAnimation { return } // 当前快照,用来支持undo操作 let snapShot = context.tileMap // 方向向左时,二重循环访问的元素是正确的坐标,其他方向时访问坐标不对。我们对数组做对应变换 var transformMap = context.tileMap // 方向向左时,不需要变换 if direction != .left { for i in 0..<context.dimension { for j in 0..<context.dimension { let tp = transformPosition(i, j) transformMap[tp.0][tp.1] = context.tileMap[i][j] } } } // 方块移动速度。0.1s移动一格 let moveSpeed: CGFloat = tileLength * 10 // 是否有动作执行 var hasAction = false // 算法:对每行依次执行算法,如果能移动,设置hasAction标识位,执行动作,随机空白位生成一个新的方块,判断是否game over。 // 每行算法:对每列依次执行判断。如果位置是空白,下一个;否则从前一个位置直到开头位置的方块依次检测,如果是空白,说明可以移动,如果和本方块一样,说明可以升级,终止判断,必然不能移动到更前面了。 // 采用两个数组辅助,statusMap是当前方块状态,levelUpMap代表判断过程中哪些方块要升级。status只负责移动方块判断,并不升级。因为如果前面遇到升级了,后面本不能升级的方块就能升级了。 for i in 0..<context.dimension { // 行状态表 var statusMap = transformMap[i] // 升级表 var levelUpMap: [Bool] = Array<Bool>(repeating: false, count: context.dimension) var hasRowAction = false for j in 0..<context.dimension { // 第一个方块不会移动,没有方块不用理会 if j == 0 || statusMap[j] == 0 { continue } // 移动目的地 var moveDst = j // 是否能升级 var canLevelUp = false // 倒序计算 for k in 0...j-1 { // 前一格是空格,可以前移 if statusMap[j - 1 - k] == 0 { moveDst -= 1 } else { // 前一格和当前格数字相同,且没有升过级,可以升级,可以移动。终止判断,不可能再前移了 if statusMap[j - 1 - k] == statusMap[j] && !levelUpMap[j - 1 - k] { moveDst -= 1 canLevelUp = true } break } } // 没有移动 if moveDst == j { continue } hasRowAction = true hasAction = true self.animationGroup.enter() // 当前方块。地图数组已经经过变换,但元素名没有经过变换,要定位回去 let transformP = transformPositionReverse(i, j) // 目标地点 let transformDstP = transformPositionReverse(i, moveDst) let transformDstPos = tilePosition(transformDstP.0, transformDstP.1) // 移动方块 let t = tileBoard.childNode(withName: "\(transformP.0),\(transformP.1)") as! NumTile // 移动时间。保持所有动作速度相同 let moveDuration: TimeInterval = TimeInterval((fabs(t.position.x - transformDstPos.x) + fabs(t.position.y - transformDstPos.y)) / moveSpeed) // 能升级时,移动的方块是要在升级方块之下的,升级的动作由不动的方块执行 if canLevelUp { // 待升级方块 let lt = tileBoard.childNode(withName: "\(transformDstP.0),\(transformDstP.1)") as! NumTile // 更改层次结构 t.zPosition = MidTile // 移动到目的地后直接移除掉。然后升级 t.run(SKAction.move(to: tilePosition(transformDstP.0, transformDstP.1), duration: moveDuration), completion: { () -> Void in lt.levelUp() t.removeFromParent() self.animationGroup.leave() }) /** 修改名字。这里总算明白这个bug了。假设有某串数字是这样的"2, 2, 1, 1",如果这里不修改名字,会产生这样一个bug: 1、第二个2与第一个2合并,忘了修改名字,第二个2名字序号依然是1 2、第一个1移动到`1`位,修改名字后序号是1,第二个1与第一个1合并,这时,第二个2与第一个1的名字是一样的,取错元素了,所以第二个升级动画失败 3、为了修复上述的bug,将这个即将remove的元素,名字改成一个特殊的索引,驱逐之。 */ t.name = "-1,-1" } else { // 移动到目的地 t.run(SKAction.move(to: tilePosition(transformDstP.0, transformDstP.1), duration: moveDuration), completion: { () -> Void in self.animationGroup.leave() }) // 修改名字。这个是立即执行的 t.name = "\(transformDstP.0),\(transformDstP.1)" } // 修改临时状态 if canLevelUp { levelUpMap[moveDst] = true } else { statusMap[moveDst] = statusMap[j] } statusMap[j] = 0 } if hasRowAction { // 修改地图状态 var finalRow: [Int] = Array<Int>(repeating: 0, count: context.dimension) for l in 0..<context.dimension { finalRow[l] = levelUpMap[l] ? statusMap[l] + 1 : statusMap[l] } transformMap[i] = finalRow } } if hasAction { // 注册undo操作 self.view?.undoManager?.registerUndo(withTarget: self, selector: #selector(GameScene.restoreLastStep(_:)), object: snapShot) // 恢复变换 if direction == .left { context.tileMap = transformMap } else { for i in 0..<context.dimension { for j in 0..<context.dimension { let tp = transformPositionReverse(i, j) context.tileMap[tp.0][tp.1] = transformMap[i][j] } } } self.inAnimation = true // 所有动作结束后添加新方块 self.animationGroup.notify(queue: DispatchQueue.main, execute: { self.inAnimation = false self.addNewTile() if self.detectGameOver() { let gameOver = SKLabelNode(text: "GAME OVER") gameOver.fontSize = 35 gameOver.name = "gameover" gameOver.fontName = "Arial-BoldMT" gameOver.fontColor = SKColor.red gameOver.verticalAlignmentMode = .center gameOver.horizontalAlignmentMode = .center gameOver.position = CGPoint(x: self.size.width / 2, y: (self.size.height - self.size.width) / 6) self.addChild(gameOver) self.gameOver = true } }) } } func loadGame(_ c: GameContext) { // 清理后退栈 self.view?.undoManager?.removeAllActions() // 重新开始 self.gameOver = false self.hasStartGame = true self.context = c tileBoard.removeAllChildren() for i in 0..<context.dimension { for j in 0..<context.dimension { // 添加背景小方块 let tile = NumTile(length: tileLength) tile.position = tilePosition(i, j) tile.zPosition = LowTile tileBoard.addChild(tile) if context.tileMap[i][j] != 0 { let t = NumTile(length: tileLength) t.level = TileLevel(rawValue: context.tileMap[i][j])! t.position = tilePosition(i, j) t.name = "\(i),\(j)" t.zPosition = HighTile tileBoard.addChild(t) } } } logStatus() } }
true
59645c9625dc5d6a8b2b14ec34a08f4faddc8b6f
Swift
RomanTheBaby/DesignLenses
/DesignLenses/Library/Models/LensCategory.swift
UTF-8
540
3.1875
3
[ "MIT" ]
permissive
// // LensCategory.swift // DesignLenses // // Created by Baby on 3/4/19. // Copyright © 2019 baby. All rights reserved. // import Foundation enum LensCategory: Int, Equatable { case experience = 0 case designer = 1 case process = 2 case player = 3 case game = 4 } extension LensCategory { var description: String { switch self { case .experience: return "Experience" case .designer: return "Designer" case .process: return "Process" case .player: return "Player" case .game: return "Game" } } }
true
ee0f06b9eaa4a5f112db6bccc4466c9bbaba4bf7
Swift
gkkit/100-days-of-swiftui
/M3 - AnimalTables/AnimalTables/ContentView.swift
UTF-8
1,069
2.9375
3
[]
no_license
// // ContentView.swift // AnimalTables // // Created by Emilio Schepis on 28/10/2019. // Copyright © 2019 Emilio Schepis. All rights reserved. // import SwiftUI struct ContentView: View { @State private var settingUp = true @State private var tables = 2 @State private var quizzesCount = 0 private let quizzesValues = [5, 10, 20, .max] var body: some View { NavigationView { Group { if (settingUp) { SetupView(tables: $tables, quizzesCount: $quizzesCount, settingUp: $settingUp) } if (!settingUp) { QuizView(tables: $tables, settingUp: $settingUp, quizzesCount: quizzesValues[quizzesCount]) } } .navigationBarTitle("AnimalTables") } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
true
4530b7d689701b71a10a9201746f205742c17be2
Swift
Anthony-R-G/ForSquaresOnly
/FourSquare/Views/CreatedCollectionViewCell.swift
UTF-8
1,260
2.6875
3
[]
no_license
// // CreatedCollectionViewCell.swift // FourSquare // // Created by Anthony Gonzalez on 11/19/19. // Copyright © 2019 Antnee. All rights reserved. // import UIKit class CreatedCollectionViewCell: UICollectionViewCell { lazy var imageView: UIImageView = { let iv = UIImageView() iv.backgroundColor = .purple return iv }() lazy var nameLabel: UILabel = { let label = UILabel() label.textColor = .black label.textAlignment = .center return label }() private func setConstraints(){ NSLayoutConstraint.activate([ imageView.centerXAnchor.constraint(equalTo: centerXAnchor), imageView.centerYAnchor.constraint(equalTo: centerYAnchor), imageView.widthAnchor.constraint(equalToConstant: 150), imageView.heightAnchor.constraint(equalToConstant: 150), nameLabel.centerXAnchor.constraint(equalTo: centerXAnchor), ]) } override init(frame: CGRect) { super.init(frame: frame) setConstraints() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
cd4622644411b38404f12289b9896fcd4cf87efc
Swift
MSalaah/Swenson-He-Challenge
/ioschallenge/CurrenciesList/Model/Converter.swift
UTF-8
365
2.578125
3
[]
no_license
// // Converter.swift // ioschallenge // // Created by Mohamed Salah on 4/23/21. // Copyright © 2021 SWENSON HE. All rights reserved. // import Foundation struct Converter: Codable { let base : String let date : String let rates : [CurrencyRate] } struct ConverterResponse: Codable { let success : Bool let rates : Dictionary<String, Double> }
true
fc3e0ff8071d099ecaf76c1a5cd6e0cb28d6db16
Swift
rohitjindal1184/SwiftPasscodeLock
/PasscodeLockTests/Fakes/FakePasscodeLockConfiguration.swift
UTF-8
547
2.546875
3
[ "MIT" ]
permissive
// // FakePasscodeLockConfiguration.swift // PasscodeLock // // Created by Yanko Dimitrov on 8/28/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import Foundation class FakePasscodeLockConfiguration: PasscodeLockConfigurationType { let repository: PasscodeRepositoryType let passcodeLength = 4 var isTouchIDAllowed = false let maximumInccorectPasscodeAttempts = 3 let shouldRequestTouchIDImmediately = false init(repository: PasscodeRepositoryType) { self.repository = repository } }
true
5889c941f2f806d14cd71ba487cda57095856d3c
Swift
LYM-mg/MGDS_Swift
/MGDS_Swift/MGDS_Swift/Class/Home/Liveky/emmitParticles.swift
UTF-8
3,101
2.71875
3
[ "MIT" ]
permissive
// // emmitParticles.swift // Liveyktest1 // // Created by yons on 16/9/21. // Copyright © 2016年 xiaobo. All rights reserved. // func emmitParticles(from point: CGPoint, emitter: CAEmitterLayer , in rootView:UIView) { let originPoint = CGPoint(x: rootView.bounds.maxX, y: rootView.bounds.maxY) let newOriginPoint = CGPoint(x: originPoint.x / 2, y: originPoint.y / 2) let pos = CGPoint(x: newOriginPoint.x + point.x, y: point.y) let image = #imageLiteral(resourceName: "tspark") emitter.emitterPosition = pos emitter.renderMode = CAEmitterLayerRenderMode.backToFront let rocket = CAEmitterCell() rocket.emissionLongitude = CGFloat(M_PI_2) rocket.emissionLatitude = 0 rocket.lifetime = 1.6 rocket.birthRate = 1 rocket.velocity = 40 rocket.velocityRange = 100 rocket.yAcceleration = -250 rocket.emissionRange = CGFloat(M_PI_4) rocket.color = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.8).cgColor rocket.redRange = 0.5 rocket.greenRange = 0.5 rocket.blueRange = 0.5 rocket.name = "rocket" let flare = CAEmitterCell() flare.contents = image.cgImage flare.emissionLongitude = 4 * CGFloat(M_PI_2) flare.scale = 0.4 flare.velocity = 100; flare.birthRate = 45; flare.lifetime = 1.5; flare.yAcceleration = -350; flare.emissionRange = CGFloat(M_PI / 7) flare.alphaSpeed = -0.7; flare.scaleSpeed = -0.1; flare.scaleRange = 0.1; flare.beginTime = 0.01; flare.duration = 0.7; //The particles that make up the explosion let firework = CAEmitterCell() firework.contents = image.cgImage; firework.birthRate = 9999; firework.scale = 0.6; firework.velocity = 130; firework.lifetime = 2; firework.alphaSpeed = -0.2; firework.yAcceleration = -80; firework.beginTime = 1.5; firework.duration = 0.1; firework.emissionRange = CGFloat(M_PI * 2) firework.scaleSpeed = -0.1 firework.spin = 2; //Name the cell so that it can be animated later using keypath firework.name = "firework" //preSpark is an invisible particle used to later emit the spark let preSpark = CAEmitterCell() preSpark.birthRate = 80 preSpark.velocity = firework.velocity * 0.70 preSpark.lifetime = 1.7 preSpark.yAcceleration = firework.yAcceleration * 0.85 preSpark.beginTime = firework.beginTime - 0.2 preSpark.emissionRange = firework.emissionRange preSpark.greenSpeed = 100 preSpark.blueSpeed = 100 preSpark.redSpeed = 100 //Name the cell so that it can be animated later using keypath preSpark.name = "preSpark" //The 'sparkle' at the end of a firework let spark = CAEmitterCell() spark.contents = image.cgImage spark.lifetime = 0.05; spark.yAcceleration = -250; spark.beginTime = 0.8; spark.scale = 0.4; spark.birthRate = 10; preSpark.emitterCells = [spark] rocket.emitterCells = [flare, firework, preSpark] emitter.emitterCells = [rocket] rootView.setNeedsDisplay() }
true
e3aabef594742bf8c272b43c776cb0f9527575e7
Swift
it-muslim/muslim-quiz-ios
/Muslim Quiz/Models/Round/Round.swift
UTF-8
2,559
2.875
3
[ "MIT" ]
permissive
// // Round.swift // Muslim Quiz // // Created by Amin Benarieb on 23/12/2018. // Copyright © 2018 Amin Benarieb. All rights reserved. // import ObjectMapper struct Round: Equatable { let identifier: String let topicId: String let userInfos : [RoundUserInfo] let startDate: Date? let endDate: Date? let status: RoundStatus func roundSummary(roundIndex :Int, questionIndex: Int) -> RoundSummary { let userNames = { () -> String in return self.userInfos .filter { $0.user != self.currentUser } .map { $0.user?.fullName ?? $0.userId }.joined(separator: ",") }() return RoundSummary(identifier: self.identifier, title: "Раунд \(roundIndex) против \(userNames)", questionCount: self.topic?.questions.count ?? 0, questionIndex: questionIndex) } /// Required join var topic: Topic? /// Required join var currentUser: User? var index : Int? } // MARK: JSON Decoding extension Round: ImmutableMappable { init(map: Map) throws { let identifier: String = try map.value("identifier") let topicId : String = try map.value("topic") let userInfos: [RoundUserInfo] = { guard let userJSONs = map.JSON["userInfos"] as? [String : [String : Any]] else { return [RoundUserInfo]() } return userJSONs.compactMap { let key = $0.key var value = $0.value value["identifier"] = key return RoundUserInfo(JSON: value) } }() let startDate: Date? = try? map.value("startDate", using: DateTransform()) let endDate: Date? = try? map.value("endDate", using: DateTransform()) let statusRaw: String = try map.value("status") let status: RoundStatus = try { return try RoundStatus(JSON: ["identifier": identifier, "status": statusRaw]) }() self.identifier = identifier self.topicId = topicId self.userInfos = userInfos self.startDate = startDate self.endDate = endDate self.status = status } } // MARK: Diffable extension Round: Diffable { var diffIdentifier: String { return self.identifier } func isEqual(toDiffableObject object: Diffable?) -> Bool { guard let object = object as? Round else { return false } return self == object } }
true
b449276a653ff45511d6c7893476f1f0366d56d1
Swift
sumittiwari2508/TriviaApp
/TriviaApp/SourceControllers/CricketerNameViewController.swift
UTF-8
3,099
2.75
3
[]
no_license
// // CricketerNameViewController.swift // TriviaApp // // Created by Kasun on 10/29/1399 AP. // import UIKit class CricketerNameViewController: UIViewController, UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var nextBtn: UIButton! @IBOutlet weak var cricketerNameTableView: UITableView! var cricketerName = String() var cricketernameArr = ["Sachin Tendulkar","Virat Kohli","Adam Gilchirst","Jacques Kallis"] var index = [Int]() var userName = String() override func viewDidLoad() { super.viewDidLoad() cricketerNameTableView.delegate = self cricketerNameTableView.dataSource = self cricketerNameTableView.register(UINib(nibName: "CricketerNameTableViewCell", bundle: nil), forCellReuseIdentifier: "cricketer") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cricketernameArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = "cricketer" let cell = (tableView.dequeueReusableCell(withIdentifier: identifier) as? CricketerNameTableViewCell)! let dict = cricketernameArr[indexPath.row] cell.cricketerName.text = dict if index.contains(indexPath.row){ // if index value == indexPath.row then it will display selected value cell.checkbox.image = UIImage(named: "Select") }else{ cell.checkbox.image = UIImage(named: "Deselect") } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if index.count != 0{ // if selected index != 0 then it will remove previous value and add next selected value index.removeAll() index.append(indexPath.row) self.cricketerNameTableView.reloadData() }else{ index.append(indexPath.row) self.cricketerNameTableView.reloadData() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "colors" { if index.count == 0{ let alert = UIAlertController(title: "", message: "Please select cricketer name", preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)) self.present(alert, animated: true, completion: nil) }else{ cricketerName = String() let Detailedview = segue.destination as! FlagColorsViewController Detailedview.Name = userName for (index, element) in cricketernameArr.enumerated() { // using enumerated() to get name and position if [index] == self.index{ cricketerName = element } } Detailedview.cricketerName = cricketerName Detailedview.modalPresentationStyle = .fullScreen } } } }
true
3e211be4851ddd2dac701576a3739e99a1b588ca
Swift
marian19/TwitterClient
/TwitterClient/TwitterClient/Data/Models/Tweet.swift
UTF-8
2,955
2.71875
3
[]
no_license
// // Tweet+CoreDataClass.swift // // // Created by Marian on 9/9/17. // // import Foundation import CoreData import SwiftyJSON @objc(Tweet) public class Tweet: NSManagedObject { static func getTweetWith(id:String) -> Tweet? { let context = CoreDataManager.sharedInstance.managedObjectContext var tweet: Tweet? do { let fetchRequest : NSFetchRequest<Tweet> = Tweet.fetchRequest() fetchRequest.predicate = NSPredicate(format: "id LIKE[cd] %@", id) let fetchedResults = try context.fetch(fetchRequest) if fetchedResults.first != nil { tweet = fetchedResults.first } } catch { print ("fetch task failed", error) } return tweet } static func deleteAllTweets() { let context = CoreDataManager.sharedInstance.managedObjectContext let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Tweet") let request = NSBatchDeleteRequest(fetchRequest: fetch) do { _ = try context.execute(request) } catch { print("delete error") } } static func addTweet(json: JSON) -> Tweet? { let context = CoreDataManager.sharedInstance.managedObjectContext let id = json[DataConstants.TimelineData.id].stringValue var tweet = Tweet.getTweetWith(id: id) let userID = json[DataConstants.TimelineData.user][DataConstants.TimelineData.id].stringValue let follower = Follower.getFollowerWith(id: userID) if tweet == nil{ tweet = NSEntityDescription.insertNewObject(forEntityName: "Tweet", into: context) as? Tweet } tweet?.id = json[DataConstants.TimelineData.id].stringValue tweet?.text = json[DataConstants.TimelineData.text].stringValue tweet?.retweetCount = json[DataConstants.TimelineData.retweetCount].stringValue tweet?.favoriteCount = json[DataConstants.TimelineData.favoriteCount].stringValue tweet?.user = follower do { try context.save() print("Saved") } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } return tweet } static func getTweetsFor(userId:String) -> [Tweet]? { let context = CoreDataManager.sharedInstance.managedObjectContext var tweets = [Tweet]() do { let fetchRequest : NSFetchRequest<Tweet> = Tweet.fetchRequest() fetchRequest.predicate = NSPredicate(format: "user.id LIKE[cd] %@", userId) let fetchedResults = try context.fetch(fetchRequest) tweets = fetchedResults } catch { print ("fetch task failed", error) } return tweets } }
true
2b1cd5b92cd61f8ee68e11ee4e1f137192823c15
Swift
tim03021995/todolistURLPlus
/todolistURLPlus/Custom/CustomBtn.swift
UTF-8
2,541
3.046875
3
[]
no_license
// // CustomUI.swift // todolistURLPlus // // Created by Ray Hsu on 2020/9/2. // Copyright © 2020 Alvin Tseng. All rights reserved. // import UIKit class CustomButton: UIButton { override init(frame: CGRect) { super.init(frame:frame) // setUpBtn() } //for storyboard required init?(coder: NSCoder) { super.init(coder:coder) setUpBtn() } convenience init(title:String){ self.init(frame:.zero) self.setTitle(title, for: .normal) } private func setUpBtn(){ //TODO 設置按鈕 backgroundColor = .glassColor layer.cornerRadius = frame.size.height/3 tintColor = .white } } class ButtonFactory{ static func makeButton(type:ButtonType,text:String) -> UIButton { let button = UIButton(frame: CGRect( x: 0, y: 0, width: ScreenSize.width.value * 0.35, height: ScreenSize.height.value * 0.075)) button.setTitle(text, for: .normal) button.layer.cornerRadius = button.frame.size.height/4 switch type { case .normal: button.backgroundColor = .gray button.setTitleColor(.white, for: .normal) case .cancel: button.backgroundColor = .darkGray button.setTitleColor(.red, for: .normal) } return button } enum ButtonType{ case normal,cancel } } class ColorButtonFactory{ enum ButtonType:CaseIterable{ case red,orange,yellow,green,blue,darkBlue,purple } } enum ColorsButtonType:String,CaseIterable{ case red,orange,yellow,green,blue,darkBlue,purple var color:UIColor{ switch self{ case .red: return UIColor.buttonRed case .orange: return UIColor.buttonOrange case .yellow: return UIColor.buttonYellow case .green: return UIColor.buttonGreen case .blue: return UIColor.buttonBlue case .darkBlue: return UIColor.button2u04 case .purple: return UIColor.buttonPurple } } } class ConerRadiusButton: UIButton { override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = self.frame.height / 2 } } class ConerRadiusButtonBackground: UIVisualEffectView{ override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = self.frame.height / 2 } }
true
8925e24ffc8d096fe1442095872a9178d946c3a6
Swift
annika2210/SiriDemo
/Shared/CalendarAccess.swift
UTF-8
3,871
2.90625
3
[]
no_license
// // CalendarAccess.swift // SiriDemo // // Created by Annika Pfosch on 26.10.20. // import Foundation import EventKit class CalendarAccess { public static var sharedInstance = CalendarAccess() var eventStore = EKEventStore() var calendar : EKCalendar? @Published var accessGranted = false var showAlert : Bool = false let calendarTitle = "Hochschule Hof Stundenplan App" func checkCalendarAuthorizationStatus() { let status = EKEventStore.authorizationStatus(for: EKEntityType.event) switch (status) { case EKAuthorizationStatus.notDetermined: // This happens on first-run requestAccess() case EKAuthorizationStatus.authorized: // All good accessGranted = true showAlert = false case EKAuthorizationStatus.restricted, EKAuthorizationStatus.denied: // We need to help them give us permission print("please give app permission to access calendar") showAlert = true @unknown default: print("this should not happen") } } //Kalender sollen erst geladen werden, wenn Nutzer zugriff erlaubt func getCalendars() -> [Calendar] { var calendars : [Calendar] = [] //if allDone { let ekCalendars = self.eventStore.calendars(for: .event) for c in ekCalendars { calendars.append(Calendar(calendar: c)) print("Titel:", c.title) } //} return calendars } //Kalender sollen erst geladen werden, wenn Nutzer zugriff erlaubt func getLectureCalendar() -> Calendar? { let calendars = getCalendars() for c in calendars { if c.calendar.title == calendarTitle { calendar = c.calendar return c } } //TO-DO: Error Handling, falls es diesen Kalender nicht gibt, weil der Nutzer die Kalender-Sync der Stundenplan-App nicht aktiviert hat //return Calendar(calendar: calendars[0].calendar) return nil } func returnCalendarCount() -> Int { let calendars = getCalendars() let count = calendars.count return count } func getLectureEvents() -> [Event]{ var events : [Event] = [] var ekEvents : [EKEvent] = [] let calendar = getLectureCalendar() //calendar = getLectureCalendar()?.calendar //wenn calendar nicht null, dann sollen events aus diesem kalender gelden und zurückgegeben werden //if(calendar != nil) { if(accessGranted == true) { let oneDayAfter = Date(timeIntervalSinceNow: +1*24*3600) let predicate = self.eventStore.predicateForEvents(withStart: Date(), end: oneDayAfter, calendars: [calendar!.calendar]) ekEvents = eventStore.events(matching: predicate) for event in ekEvents { events.append(Event(event: event)) } } //} return events } func requestAccess() { self.eventStore.requestAccess(to: .event, completion: {[weak self] (granted: Bool, error: Error?) -> Void in if granted { print("Access granted") self?.accessGranted = true } else { print("Access denied") self?.accessGranted = false } }) print("Not Determined") } } struct Calendar : Identifiable { var id = UUID() var calendar : EKCalendar } struct Event : Identifiable { var id = UUID() var event : EKEvent }
true
fb1a946c5b203cd5325ae22cf45425097c43e1ea
Swift
wudi890520/SSUIKit
/SSUIKit/Classes/Extensions/View.swift
UTF-8
10,258
2.609375
3
[ "MIT" ]
permissive
// // SSUIView.swift // SSHuitouche // // Created by 吴頔 on 2019/3/24. // Copyright © 2019 DDC. All rights reserved. // import UIKit import QMUIKit public typealias View = UIView public protocol SSUIViewCompatible {} extension UIView: SSUIViewCompatible {} public extension SSUIViewCompatible where Self: UIView { /// 用CGRect约束Frame /// /// - Parameter rect: CGRect /// - Returns: UIView泛型 @discardableResult func ss_frame(rect: CGRect) -> Self { self.frame = rect return self } /// 用x, y, width, height分别约束Frame /// /// - Parameters: /// - x: 横坐标 /// - y: 纵坐标 /// - width: 视图宽度 /// - height: 视图高度 /// - Returns: UIView泛型 @discardableResult func ss_frame(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) -> Self { return ss_frame(rect: CGRect(x: x, y: y, width: width, height: height)) } /// 用CGSize约束视图大小(此方法要求Point为0,即CGPoint = .zero) /// /// - Parameter size: CGSize /// - Returns: UIView泛型 @discardableResult func ss_frame(size: CGSize) -> Self { return ss_frame(rect: CGRect(origin: .zero, size: size)) } /// 设置视图背景颜色 /// /// - Parameter color: UIColor /// - Returns: UIView泛型 @discardableResult func ss_backgroundColor(_ color: UIColor?) -> Self { self.backgroundColor = color return self } /// 设置是否隐藏 /// /// - Parameter isHidden: Bool类型。 true = 隐藏,false = 显示 /// - Returns: UIView泛型 @discardableResult func ss_isHidden(_ isHidden: Bool) -> Self { self.isHidden = isHidden return self } /// 设置透明度 /// /// - Parameter alpha: CGFloat类型。范围0-1 /// - Returns: UIView泛型 @discardableResult func ss_alpha(_ alpha: CGFloat = 0) -> Self { self.alpha = alpha return self } /// 设置用户是否可点击 /// /// - Parameter isEnable: Bool类型。 true = 可点击,false = 不可点击 /// - Returns: UIView泛型 @discardableResult func ss_isEnable(_ isEnable: Bool) -> Self { self.isUserInteractionEnabled = isEnable return self } /// 设置标签 /// /// - Parameter tag: Int类型 /// - Returns: UIView泛型 @discardableResult func ss_tag(_ tag: Int) -> Self { self.tag = tag return self } /// 设置边界风格 /// /// - Parameters: /// - color: 边界线颜色 /// - width: 边界线宽度 /// - Returns: UIView泛型 @discardableResult func ss_layerBorder(color: UIColor?, width: CGFloat) -> Self { self.layer.borderColor = color?.cgColor self.layer.borderWidth = width return self } /// 设置阴影 /// /// - Parameters: /// - cornerRadius: 阴影半径 /// - shadowColor: 阴影颜色 /// - shadowOpacity: 阴影透明度 /// - shadowOffset: 阴影方向 /// - shadowRadius: 阴影长度 /// - Returns: UIView泛型 @discardableResult func ss_shadow( shadowColor: UIColor? = .hex("#e0e0e0"), shadowOpacity: Float = 1, shadowOffset: CGSize = .zero, shadowRadius: CGFloat = 3) -> Self { if backgroundColor == nil || backgroundColor == .clear { backgroundColor = .white } layer.shadowColor = shadowColor?.cgColor layer.shadowOpacity = shadowOpacity layer.shadowOffset = shadowOffset layer.shadowRadius = shadowRadius layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale return self } /// 设置圆角风格 /// /// - Parameter cornerRadius: 圆角半径 /// - Returns: UIView泛型 @discardableResult func ss_layerCornerRadius(_ cornerRadius: CGFloat = 4, isOnShadow: Bool = false) -> Self { self.layer.cornerRadius = cornerRadius self.layer.masksToBounds = !isOnShadow return self } /// 设置部分圆角 /// /// - Parameters: /// - rectCorner: 分为左上,右上,左下,右下,可随意组合。示例:[UIRectCorner.topLeft, UIRectCorner.bottomRight] /// - cornerRadius: 圆角半径 /// - borderColor: 边界线颜色 /// - borderWidth: 边界线宽度 /// - Returns: UIView泛型 @discardableResult func ss_partLayerCornerRadius(rectCorner: UIRectCorner, cornerRadius: CGFloat, borderColor: UIColor = .clear, borderWidth: CGFloat = 1.0/UIScreen.main.scale) -> Self { let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: rectCorner, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)) let mask = CAShapeLayer() mask.frame = bounds mask.path = path.cgPath mask.borderColor = borderColor.cgColor mask.borderWidth = borderWidth self.layer.mask = mask return self } /// 添加手势 /// /// - Parameter gesture: 手势实例 /// - Returns: UIView泛型 @discardableResult func ss_addGesture(_ gesture: UIGestureRecognizer) -> Self { isUserInteractionEnabled = true addGestureRecognizer(gesture) return self } } public protocol SSUIViewAddChild {} extension UIView: SSUIViewAddChild {} public extension SSUIViewAddChild where Self: UIView { /// 添加子视图 /// /// - Parameter subview: 子视图实例 /// - Returns: UIView泛型 @discardableResult func ss_add(_ subview: UIView) -> Self { addSubview(subview) return self } /// 添加一条线(利用border) /// /// - Parameter position: QMUIViewBorderPosition /// - Returns: UIView泛型 @discardableResult func ss_border(at position: QMUIViewBorderPosition = .top, color: UIColor? = .ss_line, lineWidth: CGFloat = CGFloat.line, insets: UIEdgeInsets? = nil) -> Self { if let insets = insets { let borderView = UIView().ss_backgroundColor(color) self.addSubview(borderView) switch position { case .top: borderView.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(insets.left) make.right.equalToSuperview().offset(-insets.right) make.top.equalTo(0).offset(insets.top) make.height.equalTo(lineWidth) } case .bottom: borderView.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(insets.left) make.right.equalToSuperview().offset(-insets.right) make.bottom.equalToSuperview().offset(-insets.bottom) make.height.equalTo(lineWidth) } case .left: borderView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(insets.top) make.bottom.equalToSuperview().offset(-insets.bottom) make.left.equalToSuperview().offset(insets.left) make.width.equalTo(lineWidth) } case .right: borderView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(insets.top) make.bottom.equalToSuperview().offset(-insets.bottom) make.right.equalToSuperview().offset(-insets.right) make.width.equalTo(lineWidth) } default: break } }else{ qmui_borderPosition = position qmui_borderColor = color qmui_borderWidth = lineWidth } return self } } let SSViewTopLineTag = 250001 let SSViewBottomLineTag = 250002 let SSViewLeftLineTag = 250003 public extension UIView { /// 初始化一条线 /// /// - Parameter isHidden: 是否需要隐藏 默认不隐藏 /// - Returns: UIView static func line(_ isHidden: Bool = false, tag: Int? = nil) -> UIView { return UIView() .ss_frame(x: 0, y: 0, width: CGFloat.screenWidth, height: CGFloat.line) .ss_backgroundColor(.ss_line) .ss_isHidden(isHidden) .ss_tag(tag.orEmpty) } } public extension UIView { /// 开始无限旋转动画 func infinityRotate() { let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.toValue = Float.pi * 2 animation.duration = 1 animation.isCumulative = true animation.repeatCount = Float.infinity layer.add(animation, forKey: "rotationAnimation") } /// 停止旋转 func stopRotate() { layer.removeAllAnimations() } } public extension UIView { func ss_update(_ animated: Bool = true, duration: TimeInterval = 0.25, delay: TimeInterval = 0, completion: (() -> Void)? = nil) { needsUpdateConstraints() updateConstraintsIfNeeded() if animated { UIView.animate(withDuration: duration, delay: delay, options: .curveEaseOut, animations: { self.layoutIfNeeded() }) { (finished) in if let completion = completion { completion() } } }else{ layoutIfNeeded() } } } public extension UIView { /// 开启调试模式,所有的subviews随机设置背景颜色 @discardableResult func ss_debug() -> Self { qmui_shouldShowDebugColor = true qmui_needsDifferentDebugColor = true return self } /// 对当前视图截图 func ss_snapshotImage(_ afterScreenUpdates: Bool) -> UIImage? { if afterScreenUpdates { return qmui_snapshotImage(afterScreenUpdates: afterScreenUpdates) }else{ return qmui_snapshotLayerImage() } } /// 获取当前 view 所在的 UIViewController func ss_superViewController() -> UIViewController? { return qmui_viewController } }
true
5fb6345d0965eba663e12a6fc914c3ea95331066
Swift
AiRcTRL2/HerbalEncyclopedia
/Herbal Encyclopedia/View Controllers & View Models/Recipes/RecipesViewController.swift
UTF-8
1,730
2.609375
3
[]
no_license
// // RecipesViewController.swift // Herbal Encyclopedia // // Created by Karim Elgendy on 08/07/2020. // Copyright © 2020 Rebellion Media. All rights reserved. // import Foundation import UIKit class RecipesViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var appContainer = AppDelegate.appContainer var recipeCategories: RecipesViewModel? let cell = UINib(nibName: "ImageAndTitleTableViewCell", bundle: nil) override func viewDidLoad() { super.viewDidLoad() recipeCategories = appContainer.buildRecipesViewModel() tableView.delegate = self tableView.dataSource = self tableView.register(cell, forCellReuseIdentifier: "imageAndTitleTableViewCell") } } extension RecipesViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { recipeCategories?.categories?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "imageAndTitleTableViewCell") as! ImageAndTitleTableViewCell guard let model = recipeCategories?.categories?[indexPath.row] else { return UITableViewCell() } cell.configure(for: model) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { forwardNavigationPressed(indexPath: indexPath) } } extension RecipesViewController { func forwardNavigationPressed(indexPath: IndexPath) { print("presed") } }
true
a13db214fcdd7f116f996c0b690765d6fdcdde47
Swift
peteratseneca/dps923winter2015
/Week_09/Scroll/Classes/Launch.swift
UTF-8
9,243
2.765625
3
[ "MIT" ]
permissive
// // Launch.swift // Toronto 2015 // // Created by Peter McIntyre on 2015-03-03. // Copyright (c) 2015 School of ICT, Seneca College. All rights reserved. // import UIKit import CoreData class Launch: UIViewController { // MARK: - Properties var model: Model! // These will be filled by the results of the web service requests var sports = [AnyObject]() var venues = [AnyObject]() // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() let frc = model.frc_sport // This controller will be the frc delegate frc.delegate = nil // No predicate (which means the results will NOT be filtered) frc.fetchRequest.predicate = nil // Create an error object var error: NSError? = nil // Perform fetch, and if there's an error, log it if !frc.performFetch(&error) { println(error?.description) } // Finally, check for data on the device, and if not, load the data checkForDataOnDevice() } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "toSportList" { let vc = segue.destinationViewController as SportList vc.model = model } if segue.identifier == "toVenueList" { let vc = segue.destinationViewController as VenueList vc.model = model } } // MARK: - On first launch, fetch initial data from the web service func checkForDataOnDevice() { if model.frc_sport.fetchedObjects?.count == 0 { print("Device does not have data.\nWill fetch data from the network.\n") // First, listen for the notification (from the WebServiceRequest instance) // that indicates that the download is complete NSNotificationCenter.defaultCenter().addObserver(self, selector: "fetchCompletedSports", name: "Scroll.Launch_sports_fetch_completed", object: nil) // Next, cause the request to run // Create, configure, and execute a web service request // When complete, the runtime will save the results in the 'sports' array variable, // and call the 'fetchCompletedSports' method let request = WebServiceRequest() request.sendRequestToUrlPath("/sports", forDataKeyName: "Collection", from: self, propertyNamed: "sports") print("Request for sports has been sent.\nWaiting for results.\n\n") } } func fetchCompletedSports() { // This method is called when there's new/updated data from the network // It's the 'listener' method print("Results have returned.\n") print("\(sports.count) sport objects were fetched.\n") print("Next, the venues will be fetched.\n") // First, listen for the notification (from the WebServiceRequest instance) // that indicates that the download is complete NSNotificationCenter.defaultCenter().addObserver(self, selector: "fetchCompletedVenues", name: "Scroll.Launch_venues_fetch_completed", object: nil) // Next, cause the request to run // Create, configure, and execute a web service request // When complete, the runtime will save the results in the 'venues' array variable, // and call the 'fetchCompletedVenues' method let request = WebServiceRequest() request.sendRequestToUrlPath("/venues/withsports", forDataKeyName: "Collection", from: self, propertyNamed: "venues") print("Request for venues has been sent.\nWaiting for results.\n\n") } func fetchCompletedVenues() { // This method is called when there's new/updated data from the network // It's the 'listener' method print("Results have returned.\n") print("\(venues.count) venue objects were fetched.\n") print("Data will be saved on this device.\n") // At this point in time, we have all the sports and venues // Process the sports first... // For each web service sport, create and configure a local sport object for s in sports { // Here, we use 'd' for the name of the new device-stored object let d = model.addNewSport() // The data type of the web service 'sport' is AnyObject // When reading a value from this AnyObject, // we will use its key-value accessor, 'valueForKey' // The data type of the local 'sport' is Sport // When writing (setting) a value to this Sport, // we will use its property name d.sportName = s.valueForKey("Name") as String print("Adding \(d.sportName)...\n") d.sportDescription = s.valueForKey("Description") as String d.history = s.valueForKey("History") as String d.howItWorks = s.valueForKey("HowItWorks") as String d.hostId = s.valueForKey("Id") as Int // Get logo and photo // let urlLogo = s.valueForKey("LogoUrl") as String // if let logo = UIImage(data: NSData(contentsOfURL: NSURL(string: urlLogo)!)!) { // d.logo = UIImagePNGRepresentation(logo) // } // // let urlPhoto = s.valueForKey("PhotoUrl") as String // if let photo = UIImage(data: NSData(contentsOfURL: NSURL(string: urlPhoto)!)!) { // d.photo = UIImagePNGRepresentation(photo) // } // // print("- logo and photo fetched.\n") } print("All sports have been added.\n\n") model.saveChanges() // Create and configure a fetch request object // We will need this to set the sport-venue relation let f = NSFetchRequest(entityName: "Sport") // Process the venues next... // For each web service venue, create and configure a local venue object // While doing this, use the fetch request object to get a local sport object, // so that it can be set in the 'sports' relation collection // This task uses an Venue 'extension', which you can find in the // 'Extensions.swift' source code file // Use this 'best practice' technique to configure a many-to-many relationship for v in venues { // Here, we use 'd' for the name of the new device-stored object let d = model.addNewVenue() d.venueName = v.valueForKey("Name") as String print("Adding \(d.venueName)...\n") d.venueDescription = v.valueForKey("Description") as String d.location = v.valueForKey("Location") as String // // Get photo and map // // let urlPhoto = v.valueForKey("PhotoUrl") as String // if let photo = UIImage(data: NSData(contentsOfURL: NSURL(string: urlPhoto)!)!) { // d.photo = UIImagePNGRepresentation(photo) // } // // let urlMap = v.valueForKey("MapUrl") as String // if let map = NSData(contentsOfURL: NSURL(string: urlMap)!) { // d.map = map // } // // print("- photo and map fetched.\n") model.saveChanges() // This code block will check if the web service 'venue' // has anything in its "Sports" collection // If yes, the code will fetch the 'sport' object from the device data store, // and use it to set the sport-venue relationship if let sportsInVenue = (v.valueForKey("Sports") as? [AnyObject]) { for s in sportsInVenue { // We need a unique identifier, and the web service 'Id' value is unique let sportId = s.valueForKey("Id") as Int // We will use that value in the (lookup/search) predicate f.predicate = NSPredicate(format: "hostId == %@", argumentArray: [sportId]) // Attempt to fetch the matching sport object from the device store // The results from the 'executeFetchRequest' call is an array of AnyObject // However, the array will contain exactly one object (if successful) // That's why we get and use the first object found in the array if let relatedSport = (model.executeFetchRequest(fetchRequest: f))[0] as? Sport { d.addSport(relatedSport) print("- \(relatedSport.sportName) added to this venue\n") } } } model.saveChanges() } print("All venues have been added.\n\n") } }
true
0934c21e8e0eb29b68aedd1ed235ec666bb770c0
Swift
Parvfect/Scientific-Programming
/CompPhy/Sources/CompPhy/series.swift
UTF-8
2,263
3.390625
3
[]
no_license
import Foundation public struct ArithmeticProgression:CustomStringConvertible{ var a:Double var d:Double var n:Double init(a:Double, d:Double, n:Double){ self.a = a self.d = d self.n = n } func getLastTerm()-> Double{ return (self.a + (self.n-1)*self.d) } func sum() -> Double{ return (self.n/2)*(2*self.a + (self.n-1)*self.d) } func sum_to_k(k:Double) -> Double{ return (k/2)*(2*self.a + (k-1)*self.d) } public var description: String{ return "\(self.a) + \(self.sum_to_k(k:2.0)) + \(self.sum_to_k(k:3.0)) + \(self.sum_to_k(k:4.0)) + ... + \(self.getLastTerm())" } } public struct GeometricProgression:CustomStringConvertible{ var a:Double var r:Double var n:Double init(a:Double, r:Double, n:Double){ self.a = a self.r = r self.n = n } func getLastTerm()-> Double{ return (self.a * pow(self.r,(self.n-1))) } func sum() -> Double{ return (self.a*(1 - pow(self.r, (self.n-1))))/(1-self.r) } func sum_to_k(k:Double) -> Double{ return (self.a*(1 - pow(self.r, (k-1))))/(1-self.r) } public var description: String{ return "\(self.a) + \(self.sum_to_k(k:2.0)) + \(self.sum_to_k(k:3.0)) + \(self.sum_to_k(k:4.0)) + ... + \(self.getLastTerm())" } } public struct ArithoGeometricProgression:CustomStringConvertible{ var a:Double var r:Double var n:Double var d:Double init(a:Double, r:Double, n:Double, d:Double){ self.a = a self.r = r self.n = n self.d = d } func getLastTerm()-> Double{ return ((self.a + (n-1)*self.d) * pow(self.r,(self.n-1))) } func sum() -> Double{ return ((self.a - self.getLastTerm()*self.r) / (1-r)) + ((self.r*self.d*(1 - pow(self.r,(self.n-1))))/pow((1-self.r),2)) } func sum_to_k(k:Double) -> Double{ return ((self.a - self.getLastTerm()*self.r) / (1-r)) + ((self.r*self.d*(1 - pow(self.r,(k-1))))/pow((1-self.r),2)) } public var description: String{ return "\(self.a) + \(self.sum_to_k(k:2.0)) + \(self.sum_to_k(k:3.0)) + \(self.sum_to_k(k:4.0)) + ... + \(self.getLastTerm())" } }
true
a444abfebcba88fb269f43cc04dd19dfd9e3010a
Swift
raghavbobal1/RenterProjectW2020MAD3004
/RenterProjectW2020MAD3004/Util/PasswordUtil.swift
UTF-8
757
2.96875
3
[]
no_license
// // PasswordUtil.swift // RenterProjectW2020MAD3004 // // Created by Raghav Bobal on 2020-02-20. // Copyright © 2020 com.lambton. All rights reserved. // import Foundation struct PasswordUtil { static private let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" static func getSalt() -> String{ return String((0..<10).map{ _ in PasswordUtil.letters.randomElement()! }) } static func getHashedPassword(salt: String, plainPassword: String) -> String{ return salt + plainPassword } static func validate(salt: String, hashedPassword: String, userInputPassword: String) -> Bool{ return getHashedPassword(salt: salt, plainPassword: userInputPassword) == hashedPassword } }
true
f6333bddc4a43649cdca0d5fb456bada24fb552b
Swift
BarredEwe/WaterStates
/WaterStates/Classes/WaterStates/WaterStates+StateDispalyble.swift
UTF-8
854
2.640625
3
[ "MIT" ]
permissive
import UIKit public extension WaterStates where Self: UIViewController { func showState(_ state: State<ContentType>) { if stateMachine == nil { stateMachine = StateMachine(displayable: self) } stateMachine?.setState(state) } func showError(_ info: StateInfo) { guard info.type == .default else { return } defaultShowError(info) } func hideError() { defaulthideError() } func showLoading(_ info: StateInfo) { guard info.type == .default else { return } defaultShowLoading(info) } func hideLoading() { defaultHideLoading() } func showEmpty(_ info: StateInfo) { guard info.type == .default else { return } defaultShowEmpty(info) } func hideEmpty() { defaultHideEmpty() } func showContent(_: Any) {} }
true
5c6b20f6b482054b82ab4bef6f52601ab7572edd
Swift
taymasoff/VKApp
/VKApp/Services/GroupsSearchingService.swift
UTF-8
1,503
2.640625
3
[]
no_license
// // GroupsSearchService.swift // VKApp // // Created by Тимур Таймасов on 29.03.2018. // Copyright © 2018 Timur Taymasov. All rights reserved. // import Alamofire import SwiftyJSON struct GroupsSearchService { // MARK: Find Groups by Name Get Request static func find(scale count: String, searchBy userSearchInput: String, completion: @escaping (_ groupData: [Group])->Void) { var components = URLComponents() components.scheme = "https" components.host = "api.vk.com" components.path = "/method/groups.search" components.queryItems = [ URLQueryItem(name: "fields", value: "members_count"), URLQueryItem(name: "q", value: "\(userSearchInput)"), URLQueryItem(name: "count", value: "\(count)"), URLQueryItem(name: "access_token", value: "\(VKApi.access_token)"), URLQueryItem(name: "v", value: "5.73") ] Alamofire.request(components.url!, method: .get).validate().responseJSON(queue: DispatchQueue.global()) { response in switch response.result { case .success(let value): let json = JSON(value) let group = json["response"]["items"].compactMap { Group(json: $0.1)} completion(group) case .failure(let error): print(error, "\nSearch progress failed.") } } } }
true
723acf19ff1202587d75571d2f30f54a52af571a
Swift
BoshiLee/CloudInteractive
/CloudInteractive/FlowCollectionView/WebImageView.swift
UTF-8
1,700
2.71875
3
[]
no_license
// // Created by Boshi Li on 2018-01-09. // Copyright (c) 2018 Boshi Li. All rights reserved. // import UIKit private let imageCache = NSCache<NSURL, UIImage>() final class WebImageView: UIImageView { struct Configuration { var placeholderImage: UIImage? = nil var animationDuration: TimeInterval = 0.3 var animationOptions: UIView.AnimationOptions = .transitionCrossDissolve } fileprivate var currentTask: URLSessionDataTaskProtocol? { didSet { oldValue?.cancel() currentTask?.resume() } } fileprivate var originRequsetURL: URL? var responseURL: URL? public var configuration = Configuration() } // Web Request extension WebImageView { public func load(url: URL) { self.originRequsetURL = url let configuration = self.configuration image = configuration.placeholderImage if let image = CacheHelper.shared.loadImage(imageURL: url) { setup(image: image, of: configuration) } else { currentTask = UIImageAPIManager(session: URLSession.shared).downloadImage(of: url, isCompression: true, completionHandler: { [weak self] (image) in guard let weakSelf = self else { return } weakSelf.setup(image: image, of: configuration) }) } } private func setup(image: UIImage?, of configuration: Configuration) { DispatchQueue.main.async { UIView.transition(with: self, duration: configuration.animationDuration, options: configuration.animationOptions, animations: { self.image = image }, completion: nil) } } }
true
9ee3076c70ffb70f252b26d8bf8d5412852dac99
Swift
lawchihon/Swiftris
/Swiftris/GameScene.swift
UTF-8
10,322
3.359375
3
[]
no_license
// // GameScene.swift // Swiftris // // Created by John Law on 10/11/15. // Copyright (c) 2015 Chi Hon Law. All rights reserved. // import SpriteKit // we simply define the point size of each block sprite - in our case 20.0 x 20.0 - the lower of the available resolution options for each block image. We also declare a layer position which will give us an offset from the edge of the screen. let BlockSize:CGFloat = 20.0 // we define a new constant TickLengthLevelOne. This variable will represent the slowest speed at which our shapes will travel. We've set it to 600 milliseconds, which means that every 6/10ths of a second, our shape should descend by one row. let TickLengthLevelOne = NSTimeInterval(600) class GameScene: SKScene { // we've introduced a couple of SKNodes which can be thought of as superimposed layers of activity within our scene. The gameLayer sits above the background visuals and the shapeLayer sits atop that. let gameLayer = SKNode() let shapeLayer = SKNode() let LayerPosition = CGPoint(x: 6, y: -6) // tickLengthMillis and lastTick look similar to declarations we've seen before: one being the GameScene's current tick length – set to TickLengthLevelOne by default – and the other will track the last time we experienced a tick, an NSDate object. // // However, tick:(() -> ())? looks horrifying… tick is what's known as a closure in Swift. A closure is essentially a block of code that performs a function, and Swift refers to functions as closures. In defining tick, its type is (() -> ())? which means that it's a closure which takes no parameters and returns nothing. Its question mark indicates that it is optional and therefore may be nil. var tick:(() -> ())? var tickLengthMillis = TickLengthLevelOne var lastTick:NSDate? var textureCache = Dictionary<String, SKTexture>() override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ // we'll put our new member variables to work. If lastTick is missing, we are in a paused state, not reporting elapsed ticks to anyone, therefore we simply return. However, if lastTick is present we recover the time passed since the last execution of update by invoking timeIntervalSinceNow on our lastTick object. Functions on objects are invoked using dot syntax in Swift. if lastTick == nil { return } let timePassed = lastTick!.timeIntervalSinceNow * -1000.0 if timePassed > tickLengthMillis { lastTick = NSDate() tick?() } } required init(coder aDecoder: NSCoder) { fatalError("NSCoder not supported") } override init(size: CGSize) { super.init(size: size) anchorPoint = CGPoint(x: 0, y: 1.0) let background = SKSpriteNode(imageNamed: "background") background.position = CGPoint(x: 0, y: 0) background.anchorPoint = CGPoint(x: 0, y: 1.0) addChild(background) addChild(gameLayer) let gameBoardTexture = SKTexture(imageNamed: "gameboard") let gameBoard = SKSpriteNode(texture: gameBoardTexture, size: CGSizeMake(BlockSize * CGFloat(NumColumns), BlockSize * CGFloat(NumRows))) gameBoard.anchorPoint = CGPoint(x:0, y:1.0) gameBoard.position = LayerPosition shapeLayer.position = LayerPosition shapeLayer.addChild(gameBoard) gameLayer.addChild(shapeLayer) // set up a looping sound playback action of our theme song runAction(SKAction.repeatActionForever(SKAction.playSoundFileNamed("theme.mp3", waitForCompletion: true))) } // play any sound file on demand func playSound(sound:String) { runAction(SKAction.playSoundFileNamed(sound, waitForCompletion: false)) } // we provide accessor methods to let external classes stop and start the ticking process, something we'll make use of later in order to keep pieces from falling at key moments. func startTicking() { lastTick = NSDate() } func stopTicking() { lastTick = nil } // we've written GameScene's most important function, pointForColumn(Int, Int). This function returns the precise coordinate on the screen for where a block sprite belongs based on its row and column position. The math here looks funky but just know that each sprite will be anchored at its center, therefore we need to find its center coordinate before placing it in our shapeLayer object. func pointForColumn(column: Int, row: Int) -> CGPoint { let x: CGFloat = LayerPosition.x + (CGFloat(column) * BlockSize) + (BlockSize / 2) let y: CGFloat = LayerPosition.y - ((CGFloat(row) * BlockSize) + (BlockSize / 2)) return CGPointMake(x, y) } func addPreviewShapeToScene(shape:Shape, completion:() -> ()) { for (_, block) in shape.blocks.enumerate() { // we've created a method which will add a shape for the first time to the scene as a preview shape. We use a dictionary to store copies of re-usable SKTexture objects since each shape will require multiple copies of the same image. var texture = textureCache[block.spriteName] if texture == nil { texture = SKTexture(imageNamed: block.spriteName) textureCache[block.spriteName] = texture } let sprite = SKSpriteNode(texture: texture) // #5 sprite.position = pointForColumn(block.column, row:block.row - 2) shapeLayer.addChild(sprite) block.sprite = sprite // Animation sprite.alpha = 0 // #6 let moveAction = SKAction.moveTo(pointForColumn(block.column, row: block.row), duration: NSTimeInterval(0.2)) moveAction.timingMode = .EaseOut let fadeInAction = SKAction.fadeAlphaTo(0.7, duration: 0.4) fadeInAction.timingMode = .EaseOut sprite.runAction(SKAction.group([moveAction, fadeInAction])) } runAction(SKAction.waitForDuration(0.4), completion: completion) } func movePreviewShape(shape:Shape, completion:() -> ()) { for (_, block) in shape.blocks.enumerate() { let sprite = block.sprite! let moveTo = pointForColumn(block.column, row:block.row) let moveToAction:SKAction = SKAction.moveTo(moveTo, duration: 0.2) moveToAction.timingMode = .EaseOut sprite.runAction( SKAction.group([moveToAction, SKAction.fadeAlphaTo(1.0, duration: 0.2)])) } runAction(SKAction.waitForDuration(0.2), completion: completion) } func redrawShape(shape:Shape, completion:() -> ()) { for (_, block) in shape.blocks.enumerate() { let sprite = block.sprite! let moveTo = pointForColumn(block.column, row:block.row) let moveToAction:SKAction = SKAction.moveTo(moveTo, duration: 0.05) moveToAction.timingMode = .EaseOut sprite.runAction(moveToAction) } runAction(SKAction.waitForDuration(0.05), completion: completion) } // ensure that GameViewController need only pass those elements to GameScene in order for them to animate properly func animateCollapsingLines(linesToRemove: Array<Array<Block>>, fallenBlocks: Array<Array<Block>>, completion:() -> ()) { var longestDuration: NSTimeInterval = 0 // iterating column by column, block by block for (columnIdx, column) in fallenBlocks.enumerate() { for (blockIdx, block) in column.enumerate() { let newPosition = pointForColumn(block.column, row: block.row) let sprite = block.sprite! // produce the pleasing effect for eye balls let delay = (NSTimeInterval(columnIdx) * 0.05) + (NSTimeInterval(blockIdx) * 0.05) let duration = NSTimeInterval(((sprite.position.y - newPosition.y) / BlockSize) * 0.1) let moveAction = SKAction.moveTo(newPosition, duration: duration) moveAction.timingMode = .EaseOut sprite.runAction( SKAction.sequence([ SKAction.waitForDuration(delay), moveAction])) longestDuration = max(longestDuration, duration + delay) } } for (_, row) in linesToRemove.enumerate() { for (_, block) in row.enumerate() { // make their blocks shoot off the screen like explosive debris let randomRadius = CGFloat(UInt(arc4random_uniform(400) + 100)) let goLeft = arc4random_uniform(100) % 2 == 0 var point = pointForColumn(block.column, row: block.row) point = CGPointMake(point.x + (goLeft ? -randomRadius : randomRadius), point.y) let randomDuration = NSTimeInterval(arc4random_uniform(2)) + 0.5 // choose beginning and starting angles var startAngle = CGFloat(M_PI) var endAngle = startAngle * 2 if goLeft { endAngle = startAngle startAngle = 0 } let archPath = UIBezierPath(arcCenter: point, radius: randomRadius, startAngle: startAngle, endAngle: endAngle, clockwise: goLeft) let archAction = SKAction.followPath(archPath.CGPath, asOffset: false, orientToPath: true, duration: randomDuration) archAction.timingMode = .EaseIn let sprite = block.sprite! // blocks animate above the other blocks and begin the sequence of actions sprite.zPosition = 100 sprite.runAction( SKAction.sequence( [SKAction.group([archAction, SKAction.fadeOutWithDuration(NSTimeInterval(randomDuration))]), SKAction.removeFromParent()])) } } // drop the last block to its new resting place runAction(SKAction.waitForDuration(longestDuration), completion:completion) } }
true
f8394a6ec65b3bd7a77fdb85dd24d72b333d529d
Swift
InMotionSoft/IMSCircleProgress
/CircleProgress/Code/CircleProgressView/IMSCircleDoubleDragProgressView.swift
UTF-8
8,065
2.515625
3
[]
no_license
// // IMSCircleDoubleProgressView.swift // CircleProgress // // Created by Max on 20.01.16. // Copyright © 2016 InMotion Soft. All rights reserved. // import Foundation import UIKit @objc public protocol IMSCircleDoubleDragProgressViewDelegate: NSObjectProtocol { func circleDoubleProgressView(_ view: IMSCircleProgressView, didChangeSecondProgress progress: CGFloat) } @objc open class IMSCircleDoubleDragProgressView: IMSCircleDragProgressView { var secondProgressLayer: CAShapeLayer! open var secondProgressDelegate: IMSCircleDoubleDragProgressViewDelegate? fileprivate var currentProgressIsSecond: Bool = false open var secondProgressStrokeColor = UIColor.white { didSet { self.setupCircleViewLineWidth(self.lineWidth, radius: self.radius) } } open var firstProgress: CGFloat { get { return self.progress } set { self.progress = newValue } } var currentProgress: CGFloat { get { return (self.currentProgressIsSecond) ? self.secondProgress : self.firstProgress } } open var secondProgress: CGFloat = 0.0 { willSet { if secondProgress == 0 { let startAngle = (self.progressClockwiseDirection) ? self.startAngle : self.endAngle let anglePoint = self.pointForAngle(startAngle) let startPoint = CGPoint(x: CGFloat(NSInteger(anglePoint.x)), y: CGFloat(NSInteger(anglePoint.y))) let buttonPoint = CGPoint(x: CGFloat(NSInteger(self.progressButton.center.x)), y: CGFloat(NSInteger(self.progressButton.center.y))) if startPoint.equalTo(buttonPoint) { let angle: Float = self.angleForProgress(newValue) self.progressButton.center = self.pointForAngle(angle) } self.currentProgressIsSecond = true } } didSet { let finalProgress = self.endlessProgress(secondProgress) if progressDuration > 0 && self.animatedProgress { let progressDif = abs(oldValue - secondProgress) if progressDif > 0 { let time: TimeInterval = TimeInterval(progressDuration * progressDif) let endAnimation = CABasicAnimation.createMoveAnimation(fromValue: oldValue, toValue: finalProgress, withDuration: time) self.secondProgressLayer.add(endAnimation, forKey: nil) } } else { self.secondProgressLayer.strokeEnd = finalProgress self.secondProgressLayer.removeAllAnimations() } self.secondProgressDelegate?.circleDoubleProgressView(self, didChangeSecondProgress: secondProgress) } } override func setupCircleViewLineWidth(_ lineWidth: CGFloat, radius circleRadius: CGFloat) { super.setupCircleViewLineWidth(lineWidth, radius: radius) let circlePath = self.pathForRadius(circleRadius) if self.secondProgressLayer == nil { self.secondProgressLayer = CAShapeLayer() self.secondProgressLayer.fillColor = UIColor.clear.cgColor self.layer.addSublayer(self.secondProgressLayer) } self.secondProgressLayer.path = circlePath.cgPath self.secondProgressLayer.strokeColor = self.secondProgressStrokeColor.cgColor self.secondProgressLayer.lineWidth = lineWidth self.secondProgressLayer.strokeEnd = self.secondProgress let layer = self.secondProgressLayer layer?.removeAllAnimations() } func progressForAngle(_ angle: Float, currentProgress: Float) -> Float { let angleForProgress = angle - self.startAngle let fullCircleAngle = fabsf(self.startAngle) + fabsf(self.endAngle); var progress = angleForProgress / fullCircleAngle if progress < 0 && currentProgress > 0.5 { progress = (kFullCircleAngle + angleForProgress)/fullCircleAngle } progress = min(Float(1), Float(progress)) progress = max(Float(0), Float(progress)) return progress } // MARK: Events override func buttonDrag(_ button: UIButton, withEvent event:UIEvent) { guard let touch: UITouch = event.allTouches?.first else { return } let previousLocation = touch.previousLocation(in: button) let location = touch.location(in: button) let deltaX: CGFloat = location.x - previousLocation.x let deltaY: CGFloat = location.y - previousLocation.y var newButtonCenter = CGPoint(x: button.center.x + deltaX, y: button.center.y + deltaY) var angle: Float = self.angleBetweenCenterAndPoint(newButtonCenter) newButtonCenter = self.pointForAngle(angle) if self.progressClockwiseDirection == false { if angle < 0 && self.progress < 0.5 { angle += kFullCircleAngle } } let fullAngle = fabsf(self.startAngle) + fabsf(self.endAngle) if fullAngle != kFullCircleAngle { if ((startAngle > 0 && angle > startAngle) || (startAngle < 0 && angle < startAngle)) { angle = self.startAngle newButtonCenter = self.pointForAngle(angle) } else if ((endAngle > 0 && angle > endAngle) || (endAngle < 0 && angle < endAngle)) { angle = self.endAngle newButtonCenter = self.pointForAngle(angle) } } var progress = self.progressForAngle(angle, currentProgress: Float(self.currentProgress)) if self.progressClockwiseDirection == false && progress <= 1 { progress = 1 - progress } if CGFloat(progress) == self.progress { if self.shouldCrossStartPosition == false { return } else { if progress > 0.5 { progress = 0 if fullAngle != kFullCircleAngle { newButtonCenter = self.pointForAngle(self.startAngle) } } else { progress = 1 self.firstProgress = 1 self.currentProgressIsSecond = true if fullAngle != kFullCircleAngle { newButtonCenter = self.pointForAngle(self.endAngle) } } } } if progress >= 0 && progress < 0.1 { if self.currentProgressIsSecond == false { if self.firstProgress >= 0.9 { self.firstProgress = 1 self.currentProgressIsSecond = true } } else if self.firstProgress == 1 && self.secondProgress >= 0.9 { if self.shouldCrossStartPosition { self.currentProgressIsSecond = false self.firstProgress = 0 self.secondProgress = 0 } else { self.firstProgress = 1 self.secondProgress = 1 newButtonCenter = self.pointForAngle(self.endAngle) button.center = newButtonCenter return } } else if progress == 0 && self.currentProgressIsSecond { self.secondProgress = 0 self.currentProgressIsSecond = false progress = 1 } } button.center = newButtonCenter if self.currentProgressIsSecond { self.secondProgress = CGFloat(progress) } else { self.firstProgress = CGFloat(progress) } } }
true
1a0d95c20ef47904d93fe64e6c6365e30b332ef2
Swift
AlexanderLevinQU/AlexLevinPersonal
/boomerangSwift-2/finalBoomerangSwift/emailMessage.swift
UTF-8
586
2.703125
3
[]
no_license
// // emailMessage.swift // finalBoomerangSwift // // Created by Levin, Alexander J. on 4/26/18. // Copyright © 2018 Levin, Alexander J. All rights reserved. // import UIKit class emailMessage: NSObject{ //Variables for emailMessage var message:String = "" var subject:String = "" var timeSent:String = "" var emailSendingToo:String = "" var numberSendingToo:String = "" //Calculate difference in time for counter to start public func calcTimeDiff(currentTime: String, endTime: String) -> String{ return "Counter of time left" } }
true
3b04d646f5605fbc092b09453ec2bb08e8fcaa09
Swift
RafalSwat/PlayingWithGestures
/PlayingWithGestures/SpinningWheel/SpinningWheelViewController.swift
UTF-8
2,887
3.03125
3
[ "MIT" ]
permissive
// // SpinningWheelViewController.swift // PlayingWithGestures // // Created by Rafał Swat on 13/05/2021. // import UIKit import SpinWheelControl enum SpinWheelState { case Spins case Stands } class SpinningWheelViewController: UIViewController { @IBOutlet weak var wheelContainer: UIView! @IBOutlet weak var poiterView : UIImageView! @IBOutlet weak var resultLabel : UILabel! var spinWheelControl: SpinWheelControl! private let spinningWheelModelView = SpinningWheelModelView() private var state: SpinWheelState = .Stands override func viewDidLoad() { super.viewDidLoad() setupSpinWheel() setupSpinWheelDelegateAndDataSorce() changePoiterImage() } func setupSpinWheel() { let frame = CGRect(x: 0, y: 0, width: self.wheelContainer.frame.size.width, height: self.wheelContainer.frame.size.width) spinWheelControl = SpinWheelControl(frame: frame, snapOrientation: SpinWheelDirection.up, wedgeLabelOrientation: WedgeLabelOrientation.inOut) spinWheelControl.addTarget(self, action: #selector(spinWheelDidChangeValue), for: UIControl.Event.valueChanged) self.wheelContainer.addSubview(spinWheelControl) self.wheelContainer.bringSubviewToFront(poiterView) } func setupSpinWheelDelegateAndDataSorce() { spinWheelControl.dataSource = self spinWheelControl.reloadData() spinWheelControl.delegate = self } @IBAction func spinWheelDidChangeValue(sender: AnyObject) { self.resultLabel.text = spinningWheelModelView.slices[self.spinWheelControl.selectedIndex].description } func wedgeForSliceAtIndex(index: UInt) -> SpinWheelWedge { let wedge = SpinWheelWedge() wedge.shape.fillColor = spinningWheelModelView.slices[Int(index)].color.cgColor wedge.label.text = spinningWheelModelView.slices[Int(index)].text return wedge } func changePoiterImage() { Animations.simpleAnimate(actions: { if self.state == .Stands { self.poiterView.transform = .identity } else { self.poiterView.transform = self.poiterView.transform.rotated(by: -.pi / 2) } }) } } extension SpinningWheelViewController: SpinWheelControlDelegate { func spinWheelDidEndDecelerating(spinWheel: SpinWheelControl) { self.state = .Stands changePoiterImage() } func spinWheelDidRotateByRadians(radians: Radians) { if self.state == .Stands { self.state = .Spins changePoiterImage() } } } extension SpinningWheelViewController: SpinWheelControlDataSource { func numberOfWedgesInSpinWheel(spinWheel: SpinWheelControl) -> UInt { return UInt(spinningWheelModelView.slices.count) } }
true
afdea778f1dfe374c777cccb5563d41c8b6b3f6f
Swift
GrzegorzKwasniewski/iOSMVVMDemo
/CoinsCap_MVVM/Helpers/Colors.swift
UTF-8
549
2.78125
3
[]
no_license
import UIKit private enum BaseColors { static let darkGray = #colorLiteral(red: 0.1764705882, green: 0.1764705882, blue: 0.1764705882, alpha: 1) static let white = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) static let purple = #colorLiteral(red: 0.6787353158, green: 0.1848334074, blue: 0.4715739489, alpha: 1) } enum Colors { static let whiteBackground = BaseColors.white static let whiteText = BaseColors.white static let darkGreyText = BaseColors.darkGray static let purpleBackground = BaseColors.purple }
true
902f0ddc18e85d1838a66029ff4769b9703875f8
Swift
guseulalio/UltimatePortfolio
/UltimatePortfolio/Activities/Awards/Award.swift
UTF-8
464
2.859375
3
[]
no_license
// // Award.swift // UltimatePortfolio // // Created by Gustavo E M Cabral on 13/3/21. // import Foundation /// An Award represents an achievement reached by the user. struct Award : Decodable, Identifiable { var id: String { name } let name: String let description: String let color: String let criterion: String let value: Int let image: String static let allAwards = Bundle.main.decode([Award].self, from: "Awards.json") static let example = allAwards[0] }
true
56a7450ec1b053f98d077817253a6e69b896f974
Swift
LukaszLik/Vapor
/Sources/App/Models/Book.swift
UTF-8
704
2.671875
3
[]
no_license
import Vapor import Fluent final class Book: Model, Content { static let schema = "books" @ID(key: .id) var id: UUID? @Field(key: "title") var title: String @Field(key: "numPages") var numPages: Int @Field(key: "placeOfPublication") var placeOfPublication: String @Parent(key: "authorId") var authorId: Author init() { // Intentionally unimplemented... } init(id: UUID? = nil, title: String, numPages: Int, placeOfPublication: String, authorId: UUID) { self.id = id self.title = title self.numPages = numPages self.placeOfPublication = placeOfPublication self.$authorId.id = authorId } }
true
532cd3c130649aad0cd94de1d2d7348316de7195
Swift
chadarutherford/ios-sprint-challenge-pokedex-objc
/CARPokedex-Objc/CARPokedex-Objc/Controller/View Controllers/Detail View/PokemonDetailViewController.swift
UTF-8
2,774
2.890625
3
[]
no_license
// // PokemonDetailViewController.swift // CARPokedex-Objc // // Created by Chad Rutherford on 2/28/20. // Copyright © 2020 Chad Rutherford. All rights reserved. // import UIKit class PokemonDetailViewController: UIViewController { @IBOutlet weak var spriteImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var pokemonIdLabel: UILabel! @IBOutlet weak var abilitiesLabel: UILabel! @objc dynamic var pokemon: Pokemon? var idObservation: NSKeyValueObservation? var abilitiesObservation: NSKeyValueObservation? var spriteObservation: NSKeyValueObservation? override func viewDidLoad() { super.viewDidLoad() setupObservers() fillInDetails() } private func fillInDetails() { guard let pokemon = pokemon else { return } PokemonAPI.shared.fillInDetails(for: pokemon) } private func setupObservers() { guard let pokemon = pokemon else { return } idObservation = observe(\.pokemon?.pokemonId) { [weak self] object, change in guard let self = self, let pokemonId = pokemon.pokemonId else { return } self.pokemonIdLabel.text = "\(pokemonId)" } abilitiesObservation = observe(\.pokemon?.abilities) { [weak self] object, change in guard let self = self, let abilities = pokemon.abilities else { return } var abilityString = "" for ability in abilities { abilityString = "\(abilityString)\(ability.capitalized)\n" } self.abilitiesLabel.text = abilityString } spriteObservation = observe(\.pokemon?.spriteURL) { [weak self] object, change in guard let self = self else { return } self.fetchSpriteImage(for: pokemon.spriteURL) } nameLabel.text = pokemon.name.capitalized title = pokemon.name.capitalized } deinit { idObservation?.invalidate() idObservation = nil abilitiesObservation?.invalidate() abilitiesObservation = nil spriteObservation?.invalidate() spriteObservation = nil } private func fetchSpriteImage(for pokemonURL: String) { guard let url = URL(string: pokemonURL) else { return } URLSession.shared.dataTask(with: url) { data, response, error in guard error == nil else { return } guard let response = response as? HTTPURLResponse, response.statusCode == 200 else { return } guard let data = data else { return } guard let image = UIImage(data: data) else { return } DispatchQueue.main.async { self.spriteImageView.image = image } }.resume() } }
true
c79f68dd21e9319838da03afcf6283e7811b7101
Swift
LazzaFisio/Lazzarin_S_sportApp
/Lazzarin_S_sportApp/Lazzarin_S_sportApp/Classi/Dati.swift
UTF-8
10,338
2.671875
3
[]
no_license
// // Info.swift // sport app // // Created by Leonardo Lazzarin on 15/01/2019. // Copyright © 2019 Leonardo Lazzarin. All rights reserved. // import Foundation import UIKit class Dati{ static var errore : String = "" static var preferiti : Array<NSMutableDictionary> = [] static var selezionato = NSDictionary() static var informazioni = NSDictionary() static var viewAttesa : ViewAttesa! //--------------------------------------------------------------- // Gestione json //--------------------------------------------------------------- public static func richiestraWeb(query : String) -> [NSDictionary]{ let url = URL(string: query) var condizione = false var elementi = [NSDictionary]() let session = URLSession.shared if(query != ""){ session.dataTask(with: url!) { (data, response, error) in if error == nil{ do{ if let risposta = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String : Array<NSDictionary>]{ for item in risposta{ elementi = item.value } }else{ errore = "nessun dato trovato" elementi.removeAll() } }catch{ errore = "errore" } }else{ errore = "Errore di connessione" } condizione = true }.resume() while !condizione {} errore = "" } return elementi } public static func esenzialiRicerca(condizioni : [String], lista : [NSDictionary]) -> [NSMutableDictionary]{ var dizionario = [NSMutableDictionary]() for item in lista{ let appoggio = NSMutableDictionary() for item2 in condizioni{ appoggio.setValue(item.value(forKey: item2) as? String ?? "", forKey: item2) } dizionario.append(appoggio) } return dizionario } public static func tutteLeghe(sport : String, restrizioni : Bool) -> [NSDictionary]{ let richiesta = "https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?s=" + sport if restrizioni{ return esenzialiRicerca(condizioni: ["strLeague", "idLeague", "strBadge"], lista: richiestraWeb(query: richiesta)) }else{ return richiestraWeb(query: richiesta) } } public static func tuttiTeam(sport : String, restrizioni : Bool) -> [NSDictionary]{ let leghe = tutteLeghe(sport: sport, restrizioni: restrizioni) var dizionario = [NSDictionary]() let query = "https://www.thesportsdb.com/api/v1/json/1/lookup_all_teams.php?id=" for item in leghe{ if Cerca.ricerca != ""{ let appoggio = richiestraWeb(query: query + (item.value(forKey: "idLeague") as! String)) for item2 in appoggio{ dizionario.append(item2) } } } if restrizioni && Cerca.ricerca != ""{ return esenzialiRicerca(condizioni: ["strTeam", "idTeam", "strTeamBadge"], lista: dizionario) } return dizionario } public static func tuttiPlayer(sport : String, restrizioni : Bool) -> [NSDictionary]{ let team = tuttiTeam(sport: sport, restrizioni: restrizioni) var dizionario = [NSDictionary]() let query = "https://www.thesportsdb.com/api/v1/json/1/lookup_all_players.php?id=" for item in team{ if Cerca.ricerca != ""{ let appoggio = richiestraWeb(query: query + (item.value(forKey: "idTeam") as! String)) for item2 in appoggio{ dizionario.append(item2) } } } if restrizioni && Cerca.ricerca != ""{ return esenzialiRicerca(condizioni: ["strPlayer", "idPlayer", "strCutout"], lista: dizionario) } return dizionario } //--------------------------------------------------------------- // Gestione immagini //--------------------------------------------------------------- public static func scaricaImmagine(stringa : String, chiave : String){ let url = URL(string: stringa) var condizione = false let session = URLSession.shared var immagine = UIImage() if stringa != ""{ session.dataTask(with: url!) { (data, res, error) in guard let data = data, error == nil else { errore = "erorre si connessione" return } immagine = UIImage(data: data) ?? UIImage() condizione = true }.resume() while !condizione {} errore = "" } let imm = immagine.pngData() as NSData? ?? NSData() UserDefaults.standard.set(imm, forKey: chiave) } public static func immagine(chiave : String, url : String) -> UIImage{ var data = UserDefaults.standard.value(forKey: chiave) var immagine = UIImage() if data != nil{ let appoggio = data as! NSData immagine = UIImage(data: appoggio as Data) ?? UIImage() }else if url != ""{ scaricaImmagine(stringa: url, chiave: chiave) data = UserDefaults.standard.value(forKey: chiave) immagine = UIImage(data: (data as! NSData) as Data)! } return immagine } public static func codImm(ricerca : String) -> String{ switch ricerca { case "Player": return "strBadge" case "Team": return "strTeamBadge" default: return "strBadge" } } public static func immBandiera(stato : String) -> UIImage{ let dizionario = esenzialiRicerca(condizioni: ["Response"], lista: richiestraWeb(query: "http://countryapi.gear.host/v1/Country/getCountries?pName=" + nomeCorrettoStato(stato: stato)))[0] return immagine(chiave: stato, url: (dizionario[0] as! NSDictionary).value(forKey: "FlagPng") as? String ?? "") } private static func nomeCorrettoStato(stato : String) -> String{ if stato == "USA"{ return "United States of America" } return stato } //--------------------------------------------------------------- // Gestione preferiti //--------------------------------------------------------------- public static func caricaPreferiti(){ let cercare = ["numLeague", "numTeam"] let nomi = ["League", "Team"] for i in 0...cercare.count - 1{ let daAggiungere = NSMutableDictionary() daAggiungere.setValue(nomi[i], forKey: "nome") let dimensione = UserDefaults.standard.value(forKey: cercare[i]) as? Int ?? 0 daAggiungere.setValue(dimensione, forKey: "dimensione") if dimensione > 0{ for y in 1...dimensione{ let inserire = String(y) + nomi[i] daAggiungere.setValue(UserDefaults.standard.value(forKey: inserire), forKey: inserire) } } preferiti.append(daAggiungere) } } public static func aggiungiPreferiti(valore : String, opzione: String) { for item in preferiti{ if item.value(forKey: "nome") as! String == opzione{ var dimensione = item.value(forKey: "dimensione") as! Int dimensione += 1 item.setValue(valore, forKey: String(dimensione) + (item.value(forKey: "nome") as! String)) item.setValue(dimensione, forKey: "dimensione") } } salvaPreferiti() } public static func cancellaPreferiti(valore : String, opzione : String){ for item in preferiti{ if item.value(forKey: "nome") as! String == opzione{ var dimensione = item.value(forKey: "dimensione") as! Int var dizionario : [String] = [] for i in 1...dimensione{ UserDefaults.standard.removeObject(forKey: String(i) + opzione) let appoggio = item.value(forKey: String(i) + opzione) as! String if appoggio != valore{ dizionario.append(appoggio) } item.removeObject(forKey: appoggio) } dimensione -= 1 if dimensione > 0{ for i in 1...dimensione{ item.setValue(dizionario[i - 1], forKey: String(i) + opzione) } } item.setValue(dimensione, forKey: "dimensione") } } salvaPreferiti() } public static func preferito(valore : String, opzione : String) -> Bool{ for item in preferiti{ if item.value(forKey: "nome") as! String == opzione{ let dimensione = item.value(forKey: "dimensione") as! Int if dimensione > 0{ for i in 1...dimensione{ if item.value(forKey: String(i) + opzione) as! String == valore{ return true } } } } } return false } private static func salvaPreferiti(){ for item in preferiti{ let nome = item.value(forKey: "nome") as! String UserDefaults.standard.removeObject(forKey: "num" + nome) UserDefaults.standard.setValue(item.value(forKey: "dimensione"), forKey: "num" + nome) let dimensione = item.value(forKey: "dimensione") as! Int if dimensione > 0{ for i in 1...dimensione{ let inserire = String(i) + nome UserDefaults.standard.removeObject(forKey: inserire) UserDefaults.standard.setValue(item.value(forKey: inserire), forKey: inserire) } } } } }
true
2978027dd6698483232b434f3177dbe3d73057c6
Swift
Abdulloh-swiftdev/Magna_Sport
/MgnaSport/View/Raiting/RaitingsView.swift
UTF-8
2,800
2.9375
3
[]
no_license
// // RatingsDetailView.swift // Touch down // // Created by Abdulloh Bahromjonov on 7/19/21. // import SwiftUI struct RatingsView: View { @EnvironmentObject var shop: Shop var body: some View { VStack(alignment: .leading, spacing: 3, content: { Text("Ratings") .fontWeight(.semibold) .foregroundColor(.gray) HStack(alignment: .center, spacing: 5, content: { ForEach(starsData) { star in RaitingItemView(star: star) .onTapGesture { shop.selectedStar = star if shop.selectedStar.id >= starsData[0].id { starsData[0].color = "yellow1" starsData[1].color = "white-1" starsData[2].color = "white-1" starsData[3].color = "white-1" starsData[4].color = "white-1" } if shop.selectedStar.id >= starsData[1].id { starsData[1].color = "yellow1" starsData[2].color = "white-1" starsData[3].color = "white-1" starsData[4].color = "white-1" } if shop.selectedStar.id >= starsData[2].id { starsData[2].color = "yellow1" starsData[3].color = "white-1" starsData[4].color = "white-1" } if shop.selectedStar.id >= starsData[3].id { starsData[3].color = "yellow1" starsData[4].color = "white-1" } if shop.selectedStar.id >= starsData[4].id { starsData[4].color = "yellow1" } } } }) }) } } struct RatingsDetailView_Previews: PreviewProvider { static var previews: some View { RatingsView() .previewLayout(.sizeThatFits) .padding() .environmentObject(Shop()) } }
true
38d5541c02fefbb54563bd6950331b11bf54355c
Swift
YuSiangTseng/Recipes
/SmoothiesAndMilkshake/SmoothiesAPI.swift
UTF-8
2,405
3.0625
3
[]
no_license
// // SmoothiesAPI.swift // SmoothiesAndMilkshake // // Created by Chris Tseng on 16/01/2017. // Copyright © 2017 Tseng Yu Siang. All rights reserved. // import Foundation enum SmoothiesResult { case Success([Smoothie]) case Failure(Error) } enum SmoothiesAPIError: Error { case InvalidJSONData } struct SmoothiesAPI { let smoothiesURLString = "https://api.edamam.com/search?q=smoothies&app_id=c1f22483&app_key=945f948f7024a5bc7f1b053cbd21e477&from=0&to=200" let session = URLSession.shared func fetchSmoothies(completion: @escaping (SmoothiesResult) -> Void) { guard let url = URL(string: smoothiesURLString) else { return; } session.dataTask(with: url) { (data, response, error) in OperationQueue.main.addOperation({ let result = self.smoothiesResultWithData(data: data) completion(result) }) }.resume() } private func smoothiesResultWithData(data: Data?) -> SmoothiesResult { guard data != nil, let jsonObject = try? JSONSerialization.jsonObject(with: data!, options: []) as? [String : AnyObject], let smoothiesArray = jsonObject?["hits"] as? [[String : AnyObject]] else { return .Failure(SmoothiesAPIError.InvalidJSONData) } var finalSmoothies = [Smoothie]() for smoothiesJSON in smoothiesArray { if let smoothie = smoothieWithArray(json: smoothiesJSON) { finalSmoothies.append(smoothie) } } return .Success(finalSmoothies) } private func smoothieWithArray(json: [String : AnyObject]) -> Smoothie? { guard let recipe = json["recipe"] as? [String : AnyObject], let label = recipe["label"] as? String, let sourceURL = recipe["url"] as? String, let imageURL = recipe["image"] as? String, let ingredientLines = recipe["ingredientLines"] as? [String], let dietLabels = recipe["dietLabels"] as? [String] else { return nil } if sourceURL == "http://www.myrecipes.com/recipe/fruity-breakfast-smoothie-197243/" { return nil } return Smoothie(label: label, sourceURL: sourceURL, imageURL: imageURL, ingredientLines: ingredientLines, dietLabels: dietLabels) } }
true
f699114cd25b8f3780d834e240eafa364c6c91e3
Swift
euanmac/PDDemo
/PDDemo/ContentfulDataManager.swift
UTF-8
11,676
2.953125
3
[]
no_license
// // ContentfulData.swift // PocketDoctor // // Created by Euan Macfarlane on 29/10/2018. // Copyright © 2018 None. All rights reserved. // import Foundation import Contentful import UIKit enum CodingTypes: String, CodingKey { case contentTypeId } protocol EntryMappable { init (from: Entry) } protocol ContentfulDataObserver { func headersLoaded(result: (Result<[Header]>)) } final class ContentfulDataManager { public let SPACE_ID = "4hscjhj185vb" public let ACCESS_TOKEN = "b4ab36dc9ea14f8e8e4a3ece38115c907302591186e836d0cdfc659144b75e85" private let SYNC_TOKEN = "synctoken.json" private let HEADER_CACHE = "headercache.json" private let NOTES_FILE = "notes.json" //Array of listeners var observers = [ContentfulDataObserver]() //Image cache //var imageCache: [AssetID: UIImage] = [:] //Headers var headers = [Header]() //Notes- provide access through property so Notes can be loaded only when needed private var notes = ArticleNotes() //Hide initialiser to make singleton private init() {} static let shared = ContentfulDataManager() //Property for notes - will load notes when first requested public var articleNotes : ArticleNotes { get { if notes.state == .empty { //Load notes notes = fetchNotesFromFile() ?? ArticleNotes() } return notes } set { notes = newValue notes.state = .changed } } //Initialises the processes of populating the headers object model //Will attempt to load from cached json file if available and not changed //If not will attempt to download from the contentful website //Once loaded will let any registered listeners know outcome of load public func fetchHeaders(useCache: Bool = true) { //Try loading from cache, if successful call listeners //Errors here are suppressed as not fatal //TODO: Add logging if useCache, let cacheHeaders = fetchHeadersFromFileCache() { headers = cacheHeaders observers.forEach() {$0.headersLoaded(result: Result.success(cacheHeaders))} print("Successfully loaded \(cacheHeaders.count) headers from cache") return } //No file cached headers so will get contentful space and initialise model from there fetchHeadersFromSyncSpace() {(result: Result<[Header]>) in switch result { case .success(let syncHeaders): self.headers = syncHeaders self.writeHeadersToFileCache() self.observers.forEach() {$0.headersLoaded(result: Result.success(syncHeaders))} case .error(let err): //TODO: Log this properly print(err.localizedDescription) } } return } //Retrieve image for a given URL string using the Contentful client. //Will call a completion handler on succesful fetch of image and pass the UIImage to it otherwise will pass nil public func fetchImage(for imageUrl: String, _ completion: @escaping ((UIImage?) -> Void)) { //Check we have a valid URL, if not exit and call completion with nil guard let url = URL(string: imageUrl) else { completion(nil) //Todo : Log this print("Invalid URL string") return } //Otherwise use client to get image let client:Client = Client(spaceId: SPACE_ID, accessToken: ACCESS_TOKEN) let _ = client.fetch(url: url) { result in switch result { case .success(let imageData): let image = UIImage(data: imageData) completion(image) case .error(let error): print(error.localizedDescription) } } } //Download object model from Contentful Space private func fetchHeadersFromSyncSpace(then completion: @escaping ResultsHandler<[Header]>) { let client: Client = Client(spaceId: SPACE_ID, accessToken: ACCESS_TOKEN) client.sync() { (result: Result<SyncSpace>) in switch result { case .success(let syncSpace): let syncHeaders = self.initHeaders(from: syncSpace) completion(Result.success(syncHeaders)) case .error(let err): print("Oh no something went wrong: \(err)") completion(Result.error(err)) } } } //Initialies the object model from contentful space entries private func initHeaders(from space: SyncSpace) -> [Header] { return space.entries.filter({$0.sys.contentTypeId == "header"}).map() {entry in return Header(from: entry) } } //Encode headers to JSON and write to file //Errors here can be suppressed for now unless trying to write file which will throw fatal error private func writeHeadersToFileCache() { let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let data = try! encoder.encode(headers) let cachesDir = FileManager().urls(for: .cachesDirectory, in: .allDomainsMask).first! let cacheFile = cachesDir.appendingPathComponent(HEADER_CACHE) print (cacheFile.absoluteURL) do { try data.write(to: cacheFile) } catch { //TODO: Log this fatalError("Couldnt write to cache " + cacheFile.absoluteString) } return } //Load the object model from json cache //Errors here can be suppressed for now as will fall back to using contenful data private func fetchHeadersFromFileCache() -> [Header]? { //let decoder = JSONDecoder() let cachesDir = FileManager().urls(for: .cachesDirectory, in: .allDomainsMask).first! let cacheFile = cachesDir.appendingPathComponent(HEADER_CACHE) print(cacheFile.absoluteURL) do { let jsonData = try Data(contentsOf: cacheFile) let cachHeaders = try JSONDecoder().decode([Header].self, from: jsonData) return cachHeaders } catch { // contents could not be loaded print (error) return nil } } //Load the article notes from json //Errors here can be suppressed for now as will fall back to using contenful data private func fetchNotesFromFile() -> ArticleNotes? { let fileManager = FileManager() let docsDir = fileManager.urls(for: .documentDirectory, in: .allDomainsMask).first! let notesFile = docsDir.appendingPathComponent(NOTES_FILE) print(notesFile.path) //check file exists guard fileManager.fileExists(atPath: notesFile.path) else { return nil } do { let jsonData = try Data(contentsOf: notesFile) var notes = try JSONDecoder().decode(ArticleNotes.self, from: jsonData) notes.state = .clean return notes } catch { // contents could not be loaded print (error) return nil } } //Encode notes to JSON and write to file //Errors here can be suppressed for now unless trying to write file which will throw fatal error public func writeNotesToFile() { let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let data = try! encoder.encode(notes) let docsDir = FileManager().urls(for: .documentDirectory, in: .allDomainsMask).first! let notesFile = docsDir.appendingPathComponent(NOTES_FILE) print (notesFile.absoluteURL) do { try data.write(to: notesFile) notes.state = .clean } catch { fatalError("Couldnt write notes to " + notesFile.absoluteString) } return } } extension Entry { /// A set of convenience subscript operators to access the fields dictionary directly and return a value /// for a given Coding Key subscript(key: CodingKey) -> Int? { return fields[key.stringValue] as? Int } subscript(key: CodingKey) -> String? { return fields[key.stringValue] as? String } subscript(key: CodingKey) -> Bool? { return fields[key.stringValue] as? Bool } subscript(entryKey key: CodingKey) -> Entry? { return fields.linkedEntry(at: key.stringValue) } subscript(key: CodingKey) -> [Entry]? { return fields.linkedEntries(at: key.stringValue) } subscript(key: CodingKey) -> Asset? { return fields.linkedAsset(at: key.stringValue) } subscript(key: CodingKey) -> [Asset]? { return fields.linkedAssets(at: key.stringValue) } //Maps an entry to one of a defined set of types //Returns nil if type on Entry is not known - makes //T should be an enum that describes set of concrete classes that could be mapped to func mapTo <T: ContentTypes>(types: T.Type) -> EntryMappable? { if let contentType = types.init(rawValue: self.sys.contentTypeId!) { let mappedObject = contentType.getType().init(from: self) return mappedObject } else { //TODO: Log print("Type of entry not known, skipping") return nil } } } // Extension to decodable to allow decoded initialisation of object from it's type internal extension Decodable where Self: Decodable { // This is a magic workaround for the fact that dynamic metatypes cannot be passed into // initializers such as UnkeyedDecodingContainer.decode(Decodable.Type), yet static methods CAN // be called on metatypes. static func popEntryDecodable(from container: inout UnkeyedDecodingContainer) throws -> Self { let entryDecodable = try container.decode(self) return entryDecodable } } //Extension to decode an array of types internal extension KeyedDecodingContainer { //Specfic extennsion to decoder to allow decoding of heterogenous array //i.e. decode different concrete article types but coalesce into single array of [Article] //protocol instances. Requires set of possible types to be defined in ContentTypes enum func decode<T: ContentTypes> (types: T.Type, forKey key: K) throws -> [Decodable] { var container = try self.nestedUnkeyedContainer(forKey: key) var list = [Decodable]() var tmpContainer = container while !container.isAtEnd { let typeContainer = try container.nestedContainer(keyedBy: CodingTypes.self) let jSONtype = try typeContainer.decode(String.self, forKey: CodingTypes.contentTypeId) if let decodableType = types.init(rawValue: jSONtype)?.getType() as? Decodable.Type { list.append(try decodableType.popEntryDecodable(from: &tmpContainer)) } else { //TODO: Log print("Type of entry not known, skipping") } } return list } } //Struct to hold sync token //struct SyncToken { // let token: String //}
true
9bd1ab3a6b05e89f2482a9a5baccde5d816bc2ea
Swift
mkuegeler/swiftplaygrounds
/MyPlayground-2018-2.playground/Contents.swift
UTF-8
1,361
3.46875
3
[]
no_license
//: Playground - noun: a place where people can play // see here: https://medium.com/@vhart/read-write-and-delete-file-handling-from-xcode-playground-abf57e445b4 import UIKit import Foundation import CoreGraphics import PlaygroundSupport // var str = "Hello, playground" // Create a FileHandle instance // func readFile (file: String) { let testFileUrl = playgroundSharedDataDirectory.appendingPathComponent("mytest.txt") var fileContents: String? do { fileContents = try String(contentsOf:testFileUrl ) } catch { print ("Error reading content\(error)") } // } // write file let newFileUrl = playgroundSharedDataDirectory.appendingPathComponent("newfile.txt") let textToWrite = """ This is just a test text written to a file """ do { try textToWrite.write(to: newFileUrl, atomically: true, encoding: .utf8) } catch { print ("Error writing: \(error)") } let proofOfWrite = try? String(contentsOf: newFileUrl) // MARK: Updating a file in a much more efficient way let monkeyLine = "\nAdding a 🐵 to the end of the file via FileHandle" if let fileUpdater = try? FileHandle(forUpdating: newFileUrl) { fileUpdater.seekToEndOfFile() fileUpdater.write(monkeyLine.data(using: .utf8)!) fileUpdater.closeFile() } let contentsAfterUpdatingViaFileHandle = try? String(contentsOf: newFileUrl)
true
9293e123395fb10741e1391cb20c3a065b470f7b
Swift
urazov-s/Avia
/avia.test/Utilities/Resources/Images.swift
UTF-8
1,584
2.828125
3
[]
no_license
// // Images.swift // avia.test // // Created by Sergey Urazov on 24/02/2019. // Copyright © 2019 Sergey Urazov. All rights reserved. // import Foundation import UIKit extension UIImage { static let xPlane = UIImage(named: "plane") } extension UIImage { static func airportAnnotation(withText text: String) -> UIImage? { let textLayer = CATextLayer() textLayer.contentsScale = UIScreen.main.scale textLayer.font = UIFont.xMedium(16) textLayer.fontSize = 16 textLayer.foregroundColor = UIColor.xShakespeare.cgColor textLayer.string = text textLayer.alignmentMode = .center let hMargin: CGFloat = 8 let vMargin: CGFloat = 4 let layerSize = textLayer.preferredFrameSize() let size = CGSize(width: layerSize.width + 2 * hMargin, height: layerSize.height + 2 * vMargin) return UIImage.draw(withSize: size, { context, rect in context.setFillColor(UIColor.xWhite.withAlphaComponent(0.7).cgColor) context.setStrokeColor(UIColor.xShakespeare.cgColor) let lineWidth: CGFloat = 3.0 context.setLineWidth(lineWidth) let path = UIBezierPath( roundedRect: rect.insetBy(dx: lineWidth / 2, dy: lineWidth / 2), cornerRadius: rect.size.height / 2 ).cgPath context.addPath(path) context.fillPath() context.addPath(path) context.strokePath() context.render(layer: textLayer, centeredAt: CGPoint(x: rect.midX, y: rect.midY)) }) } }
true
94cd5446098a1dc9498cd2f60f3686367a2f55b9
Swift
sametytmz/The-Guide-to-JSON-Parsing-Using-Swift-5
/Advance JSON Parsing.playground/Contents.swift
UTF-8
812
3.515625
4
[]
no_license
import UIKit struct AnyDecodable: Decodable { let value: Any init<T>(_ value:T?) { self.value = value ?? () } init(from decoder: Decoder)throws { let container = try decoder.singleValueContainer() if let string = try? container.decode(String.self) { self.init(string) } else if let int = try? container.decode(Int.self) { self.init(int) } else if let bool = try? container.decode(Bool.self) { self.init(bool) } else { self.init(()) } } } let json = """ { "foo" : "Hello", "bar" : 123, "isCheck" : true } """.data(using: .utf8)! let dictionary = try! JSONDecoder().decode([String: AnyDecodable].self, from: json) print(dictionary) print(dictionary["isCheck"])
true
94d17919a86757c8c742482fff9942b04d61895c
Swift
drothfeld/Cipher-Stats
/Cipher Stats/Services/FirebaseService.swift
UTF-8
9,649
2.875
3
[]
no_license
// // FirebaseService.swift // Cipher Stats // // Created by Dylan Rothfeld on 7/10/19. // Copyright © 2019 Dylan Rothfeld. All rights reserved. // import Foundation import Firebase // ================================================== // Singleton service to manage Firebase API calls // ================================================== class FirebaseService { static let shared = FirebaseService() private init(){} // // GET: Retrieve all TCG-Portal player profiles // func getPlayerProfiles(completion: @escaping (Result<[Player], Error>) -> Void) { let ref = Database.database().reference(withPath: "users/") ref.observe(.value, with: { snapshot in var playerProfiles = [Player]() // Build new player profile list from data snapshot for item in snapshot.children { let playerProfile = Player(snapshot: item as! DataSnapshot) playerProfiles.append(playerProfile) } // Return the list of player profiles playerProfiles.sort(by: <) DispatchQueue.main.async { completion(.success(playerProfiles)) } // An error occurred during the Firebase API call }) { error in DispatchQueue.main.async { completion(.failure(error)) } } } // // GET: Retrieve overall cipher game stats for a single player // func getPlayerStats(ref: DatabaseReference, completion: @escaping (Result<PlayerGameStat, Error>) -> Void) { ref.child("playerStats/fireEmblemCipher").observeSingleEvent(of: .value, with: { (snapshot) in let playerStats = PlayerGameStat(snapshot: snapshot) // Return the player game stats DispatchQueue.main.async { completion(.success(playerStats)) } // An error occurred during the Firebase API call }) { error in DispatchQueue.main.async { completion(.failure(error)) } } } // // GET: Retrieves all recorded cipher game matches // func getCipherGameMatches(completion: @escaping (Result<[CipherGame], Error>) -> Void) { let ref = Database.database().reference(withPath: "recorded-games") ref.observe(.value, with: { snapshot in var cipherMatches = [CipherGame]() // Build recorded cipher game match list for item in snapshot.children { let cipherGame = CipherGame(snapshot: item as! DataSnapshot) cipherMatches.append(cipherGame) } // Return the list of recorded cipher game matches sorted by date cipherMatches = cipherMatches.sorted { $0.date > $1.date } DispatchQueue.main.async { completion(.success(cipherMatches)) } // An error occurred during the Firebase API call }) { error in DispatchQueue.main.async { completion(.failure(error)) } } } // // GET: Returns a CipherDeckStat object that contains win/loss // data for a given lord/MC deck name (i.e. "Corrin (M)") // func getCipherDeckStats(deckName: String, completion: @escaping (Result<CipherDeckStat, Error>) -> Void) { let ref = Database.database().reference(withPath: "recorded-games") ref.observe(.value, with: { snapshot in var cipherDeckStats = CipherDeckStat(name: deckName) // Go through all retrieved cipher game matches and count // the wins/losses for the given deck/lord/MC name for item in snapshot.children { let cipherGame = CipherGame(snapshot: item as! DataSnapshot) if cipherGame.winningDeckOrCharacterName == cipherDeckStats.name { cipherDeckStats.addWin(); cipherDeckStats.relevantCipherGames.append(cipherGame) } else if cipherGame.losingDecksOrCharacterName == cipherDeckStats.name { cipherDeckStats.addLoss(); cipherDeckStats.relevantCipherGames.append(cipherGame) } } // Calculate winrate and return CipherDeckStat object cipherDeckStats.calculateWinRate() DispatchQueue.main.async { completion(.success(cipherDeckStats)) } // An error occurred during the Firebase API call }) { error in DispatchQueue.main.async { completion(.failure(error)) } } } // // GET: Returns a CipherDeckStat object that contains win/loss // data when comparing one decks performance against another // func getDeckMatchupStats(deckNameA: String, deckNameB: String, completion: @escaping (Result<CipherDeckStat, Error>) -> Void) { let ref = Database.database().reference(withPath: "recorded-games") ref.observe(.value, with: { snapshot in var cipherDeckStats = CipherDeckStat(name: deckNameA, opponent: deckNameB) // Go through all retrieved cipher game matches and count // the wins/losses for deckNameA's performance against deckNameB for item in snapshot.children { let cipherGame = CipherGame(snapshot: item as! DataSnapshot) if cipherGame.winningDeckOrCharacterName == cipherDeckStats.name && cipherGame.losingDecksOrCharacterName == cipherDeckStats.opponent { cipherDeckStats.addWin(); cipherDeckStats.relevantCipherGames.append(cipherGame) } else if cipherGame.winningDeckOrCharacterName == cipherDeckStats.opponent && cipherGame.losingDecksOrCharacterName == cipherDeckStats.name { cipherDeckStats.addLoss(); cipherDeckStats.relevantCipherGames.append(cipherGame) } } // Calculate winrate and return CipherDeckStat object cipherDeckStats.calculateWinRate() DispatchQueue.main.async { completion(.success(cipherDeckStats)) } // An error occurred during the Firebase API call }) { error in DispatchQueue.main.async { completion(.failure(error)) } } } // // GET: Returns an array containing the win/loss count and // overall win-rate of Player-A and Player-B's cipher matches // func getPlayerMatchupStats(selectedPlayer: Player, selectedOpponent: Player, completion: @escaping (Result<[Int], Error>) -> Void) { let ref = Database.database().reference(withPath: "recorded-games") ref.observe(.value, with: { snapshot in var playerMatchupStats = [0, 0, 0] // Build win/loss/winrate array from recorded cipher matches for item in snapshot.children { let cipherGame = CipherGame(snapshot: item as! DataSnapshot) if (cipherGame.winningPlayer == selectedPlayer.username && cipherGame.losingPlayer == selectedOpponent.username) { playerMatchupStats[0] += 1 } else if (cipherGame.winningPlayer == selectedOpponent.username && cipherGame.losingPlayer == selectedPlayer.username) { playerMatchupStats[1] += 1 } } playerMatchupStats[2] = (Double(playerMatchupStats[0]) / (Double(playerMatchupStats[0]) + Double(playerMatchupStats[1]))).roundToPercentage(2) DispatchQueue.main.async { completion(.success(playerMatchupStats)) } // An error occurred during the Firebase API call }) { error in DispatchQueue.main.async { completion(.failure(error)) } } } // // GET: Returns an array of CipherInsigniaStat objects that // contain all matchup statistics for all combinations // of CipherInsignia matchups // func getInsigniaMatchupStats(completion: @escaping (Result<[CipherInsigniaStat], Error>) -> Void) { let ref = Database.database().reference(withPath: "game-statistics/fireEmblemCipher") ref.observe(.value, with: { snapshot in var insigniaMatchupStats = [CipherInsigniaStat]() var insigniaMatchup: CipherInsigniaStat for (index, color) in snapshot.children.enumerated() { switch index { case 0: insigniaMatchup = CipherInsigniaStat(cipherInsignia: CipherInsignia.nohr, snapshot: color as! DataSnapshot) case 1: insigniaMatchup = CipherInsigniaStat(cipherInsignia: CipherInsignia.mark_of_naga, snapshot: color as! DataSnapshot) case 2: insigniaMatchup = CipherInsigniaStat(cipherInsignia: CipherInsignia.medallion, snapshot: color as! DataSnapshot) case 12: insigniaMatchup = CipherInsigniaStat(cipherInsignia: CipherInsignia.divine_weapons, snapshot: color as! DataSnapshot) case 13: insigniaMatchup = CipherInsigniaStat(cipherInsignia: CipherInsignia.blade_of_light, snapshot: color as! DataSnapshot) case 15: insigniaMatchup = CipherInsigniaStat(cipherInsignia: CipherInsignia.hoshido, snapshot: color as! DataSnapshot) case 16: insigniaMatchup = CipherInsigniaStat(cipherInsignia: CipherInsignia.holy_war_flag, snapshot: color as! DataSnapshot) default: continue } insigniaMatchupStats.append(insigniaMatchup) } DispatchQueue.main.async { completion(.success(insigniaMatchupStats)) } // An error occurred during the Firebase API call }) { error in DispatchQueue.main.async { completion(.failure(error)) } } } }
true
79bdd7d7ae5a039ed8872b0b9392f7e252e72115
Swift
leejend/StudentMgmtApp
/StudentMgmtApp/AddExamController.swift
UTF-8
2,604
2.796875
3
[]
no_license
// // AddExamController.swift // StudentMgmtApp // // Created by Jeanette Lee on 10/25/18. // Copyright © 2018 Jeanette Lee. All rights reserved. // import UIKit class AddExamController: UIViewController { @IBOutlet weak var unitName: UITextField! @IBOutlet weak var location: UITextField! @IBOutlet weak var dateTime: UILabel! @IBOutlet weak var datePicker: UIDatePicker! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func addExam(_ sender: Any) { //Referencing date let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy HH:mm" let strDate = dateFormatter.string(from: datePicker.date) dateTime.text = strDate //Ref date // let dateFormatter = NSDateFormatter() // dateFormatter.dateFormat = "MM/dd/yyyy" // let someDate = dateFormatter.dateFromString("03/10/2015") // //Get calendar // let calendar = NSCalendar.currentCalendar() // // //Get just MM/dd/yyyy from current date // let flags = NSCalendar.Unit.CalendarUnitDay | NSCalendar.Unit.CalendarUnitMonth | NSCalendar.Unit.CalendarUnitYear // let components = calendar.components(flags, fromDate: NSDate()) // // //Convert to NSDate // let today = calendar.dateFromComponents(components) // // if strDate!.timeIntervalSinceDate(today!).isSignMinus { // //someDate is berofe than today // } else { // //someDate is equal or after than today // } // get the AppDelegate object let appDelegate = UIApplication.shared.delegate as! AppDelegate do { showAlert(msg: "Exam details saved") } catch { showAlert(msg: "Error when saving to details") } // call the function storeExamInfo from AppDelegate appDelegate.storeExamInfo(unitName: unitName.text!, location: location.text!, dateTime: dateTime.text!) unitName.text = "" location.text = "" dateTime.text! = "" } func showAlert(msg: String) { let alert = UIAlertController(title: "Successful", message: msg, preferredStyle: UIAlertController.Style.alert) let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alert.addAction(cancelAction) self.present(alert, animated: true, completion:nil) } }
true
be57e7b7693eb73367157f93babf98e692c37617
Swift
2bjake/GyroHub
/GyroPad/Map/LevelReader.swift
UTF-8
3,868
2.9375
3
[]
no_license
// // LevelReader.swift // GyroPad // // Created by Jake Foster on 6/27/19. // Copyright © 2019 Jake Foster. All rights reserved. // import SpriteKit class LevelReader { func mapConfigFor(_ levelAssetName: String) -> MapConfig { guard let levelAsset = NSDataAsset(name: levelAssetName, bundle: Bundle(for: type(of: self))), let levelString = String(data: levelAsset.data, encoding: .utf8) else { fatalError("could not retrieve level data with name \(levelAssetName)") } var characterCoords: MapCoordinates? var elements = [MapCoordinates: MapElement]() let lines = levelString.split(separator: "\n") lines.enumerated().forEach { lineIndex, line in guard lines[lineIndex].count == lines[0].count else { fatalError("line \(lineIndex) length (\(lines[lineIndex].count)) does not match line 0 length (\(lines[0].count))") } line.enumerated().forEach { charIndex, char in let row = lines.count - lineIndex - 1 let column = charIndex let coords = MapCoordinates(column: column, row: row) let mapElement = MapElement(char) if case .character = mapElement { characterCoords = coords elements[coords] = .empty } else { elements[coords] = mapElement } } } let numberOfColumns = lines[0].count let numberOfRows = lines.count let pipeConfigs = findPipesIn(elements, numberOfColumns: numberOfColumns, numberOfRows: numberOfRows) if let characterCoords = characterCoords { return MapConfig(numberOfColumns: numberOfColumns, numberOfRows: numberOfRows, elements: elements, characterLocation: characterCoords, pipeConfigs: pipeConfigs) } else { fatalError("no character position defined in the level data") //TODO: handle this gracefully } } private func findPipesIn(_ elements: [MapCoordinates: MapElement], numberOfColumns: Int, numberOfRows: Int) -> [PipeConfig] { //iterate through elements by column (bottom to top) to find pipes var pipeConfigs = [PipeConfig]() var currentPipe: (bottomCoords: MapCoordinates, color: UIColor)? for column in 0..<numberOfColumns { currentPipe = nil for row in 0..<numberOfRows { let currentCoords = MapCoordinates(column: column, row: row) let currentElement = elements[currentCoords]! // if we're missing a coord at this point, we've already screwed up pretty badly if let pipe = currentPipe, currentElement.pipeColor != pipe.color { // left the top of the pipe, save coordinate pipeConfigs.append((top: currentCoords.down, bottom: pipe.bottomCoords, color: pipe.color)) if let newColor = currentElement.pipeColor { currentPipe = (currentCoords, newColor) } else { currentPipe = nil } } else if case let .pipe(color) = currentElement, currentPipe == nil { // found a new bottom pipe, set currentPipe currentPipe = (currentCoords, color) } } // about to loop around to the next column, record the current pipe (if there is one) if let pipe = currentPipe { pipeConfigs.append((top: MapCoordinates(column: column, row: numberOfRows - 1), bottom: pipe.bottomCoords, color: pipe.color)) } } return pipeConfigs } }
true
0f1fa376f7ec1ce13a5fe236f932cd5d4eac4bc9
Swift
buptwsg/SwiftyGitClient
/GitBucket/App/SGFoundation/AppData/AppData.swift
UTF-8
2,672
2.515625
3
[ "MIT" ]
permissive
// // AppData.swift // GitBucket // // Created by sulirong on 2018/1/29. // Copyright © 2018年 CleanAirGames. All rights reserved. // import Foundation import ObjectMapper class AppData: Mappable { var user: SGUser? = nil var countryDataOfPopularUsers: SGExploreData? = nil var languageDataOfPopularUsers: SGExploreData? = nil var languageDataOfPopularRepos: SGExploreData? = nil var languageDataOfTrendingRepos: SGExploreData? = nil var languageDataOfSearch: SGExploreData? = nil private static let archivePath: String = { let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] return docURL.appendingPathComponent("appdata.bin").path }() static let `default`: AppData = { let path = archivePath if FileManager.default.fileExists(atPath: path) { do { let jsonString = try String(contentsOfFile: path) if let instance = AppData(JSONString: jsonString) { return instance } else { return AppData() } } catch { return AppData() } } else { return AppData() } }() init() { countryDataOfPopularUsers = SGExploreData(name: "All Countries", slug: "") languageDataOfPopularUsers = SGExploreData(name: "All Languages", slug: "") languageDataOfPopularRepos = SGExploreData(name: "All Languages", slug: "") languageDataOfTrendingRepos = SGExploreData(name: "All Languages", slug: "") languageDataOfSearch = SGExploreData(name: "All Languages", slug: "") } required init?(map: Map) { } func mapping(map: Map) { user <- map["user"] countryDataOfPopularUsers <- map["countryDataOfPopularUsers"] languageDataOfPopularUsers <- map["languageDataOfPopularUsers"] languageDataOfPopularRepos <- map["languageDataOfPopularRepos"] languageDataOfTrendingRepos <- map["languageDataOfTrendingRepos"] languageDataOfSearch <- map["languageDataOfSearch"] } func save() { let path = type(of: self).archivePath let jsonString = self.toJSONString(prettyPrint: true) do { try jsonString?.write(toFile: path, atomically: true, encoding: .utf8) } catch (let error) { print("save app data error: \(error.localizedDescription)") } } func isLoggedUser(_ anotherEntity: SGEntity) -> Bool { return user?.login == anotherEntity.login } }
true
ec18f0027973438aebcd3a111d4a83993c116da7
Swift
LUSHDigital/lush-player-iOS
/Lush Player iOS/UIDevice+Versions.swift
UTF-8
1,829
2.921875
3
[]
no_license
// // UIDevice+Versions.swift // LUSH // // Created by Daniela on 11/4/14. // Copyright (c) 2014 Lush. All rights reserved. // import UIKit extension UIDevice { class func displayType() -> DisplayType { return Display.displayType } } // Based on https://gist.github.com/hfossli/bc93d924649de881ee2882457f14e346 // public enum DisplayType { case unknown case iphone4 case iphone5 case iphone6and7 case iphone6and7plus case iphoneX } private final class Display { class var width:CGFloat { return UIScreen.main.bounds.size.width } class var height:CGFloat { return UIScreen.main.bounds.size.height } class var maxLength:CGFloat { return max(width, height) } class var minLength:CGFloat { return min(width, height) } class var zoomed:Bool { return UIScreen.main.nativeScale >= UIScreen.main.scale } class var retina:Bool { return UIScreen.main.scale >= 2.0 } class var phone:Bool { return UIDevice.current.userInterfaceIdiom == .phone } class var pad:Bool { return UIDevice.current.userInterfaceIdiom == .pad } @available(iOS 9.0, *) class var carplay:Bool { return UIDevice.current.userInterfaceIdiom == .carPlay } @available(iOS 9.0, *) class var tv:Bool { return UIDevice.current.userInterfaceIdiom == .tv } class var displayType: DisplayType { if phone && maxLength < 568 { return .iphone4 } else if phone && maxLength == 568 { return .iphone5 } else if phone && maxLength == 667 { return .iphone6and7 } else if phone && maxLength == 736 { return .iphone6and7plus } else if phone && maxLength == 812 { return .iphoneX } return .unknown } }
true
f019c4a9e60ccd60acedd0190cea3d280da4c925
Swift
jotape26/Splashify
/Splashify/Data Model/CoreDataController.swift
UTF-8
698
2.53125
3
[]
no_license
// // CoreDataController.swift // Splashify // // Created by João Leite on 25/03/19. // Copyright © 2019 João Leite. All rights reserved. // import Foundation import CoreData class CoreDataController { let container: NSPersistentContainer var viewContext: NSManagedObjectContext { return container.viewContext } init(modelName: String) { container = NSPersistentContainer(name: modelName) } func load(completion: (() -> Void)? = nil){ container.loadPersistentStores { storeDescription, err in guard err == nil else { fatalError(err!.localizedDescription) } completion?() } } }
true
48099cbc9250e9da70c98a7579b21f84b72c522e
Swift
carabina/BeyovaJSON
/Source/JCodable.swift
UTF-8
3,532
2.984375
3
[ "MIT" ]
permissive
// // JTokenCodable.swift // BeyovaJSON // // Copyright © 2017 Beyova. All rights reserved. // import Foundation extension JToken: Codable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if container.decodeNil() { self = .null } else if let array = try? container.decode([JToken].self) { self = .array(.init(array)) } else if let dict = try? container.decode([String: JToken].self) { self = .object(.init(dict)) } else if let val = try? container.decode(JValue.self) { self = .simple(val) } else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "")) } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .null: try container.encodeNil() case let .simple(value): try container.encode(value) case let .object(value): try container.encode(value.item) case let .array(value): try container.encode(value.item) } } } extension JValue: Codable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let value = try? container.decode(Date.self) { self.init(value) } else if let value = try? container.decode(Data.self) { self.init(value) } else if let value = try? container.decode(String.self) { self.init(value) } else if let value = try? container.decode(Bool.self) { self.init(value) } else if let value = try? container.decode(Int.self) { self.init(value) } else if let value = try? container.decode(Double.self) { self.init(value) } else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "")) } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch value { case let val as String: try container.encode(val) case let val as Int: try container.encode(val) case let val as Bool: try container.encode(val) case let val as Date: try container.encode(val) case let val as Data: try container.encode(val) case let val as Float: try container.encode(val) case let val as Double: try container.encode(val) case let val as Decimal: try container.encode(val) case let val as Int8: try container.encode(val) case let val as Int16: try container.encode(val) case let val as Int32: try container.encode(val) case let val as Int64: try container.encode(val) case let val as UInt8: try container.encode(val) case let val as UInt16: try container.encode(val) case let val as UInt32: try container.encode(val) case let val as UInt64: try container.encode(val) default: throw EncodingError.invalidValue(value, .init(codingPath: container.codingPath, debugDescription: "")) } } }
true
88661f22f354af3415d0b5d4efe87d2eb643b1f8
Swift
shin1412-zz/study
/DBDemo/DBDemo/Controller/ViewController.swift
UTF-8
1,479
3.171875
3
[]
no_license
// // ViewController.swift // DBDemo // // Created by Huong Nguyen on 26/05/2021. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let cellReuIfentifier = "cell" let database: Database = Database() var persons: [Person] = [] override func viewDidLoad() { super.viewDidLoad() initComponent() } fileprivate func initComponent() { tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuIfentifier) tableView.delegate = self tableView.dataSource = self database.insert(id: 0, name: "Naruto", age: 14) database.insert(id: 0, name: "Hinata", age: 13) database.insert(id: 0, name: "Sasuke", age: 14) database.insert(id: 0, name: "Sakura", age: 13) persons = database.read() } } extension ViewController: UITableViewDelegate, UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return persons.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellReuIfentifier)! cell.textLabel?.text = "\(persons[indexPath.row].id ?? 0). Name: \(persons[indexPath.row].name ?? "") - Age: \(persons[indexPath.row].age ?? 0)" return cell } }
true
428be9e4cd885644c7c30d16f783e032640e818c
Swift
dottydaily/ShabuMaiJa-IOSClass
/ShabuMaiJa-IOSClass/ShabuMaiJa-IOSClass/Model/DataJSON.swift
UTF-8
1,870
2.71875
3
[]
no_license
// // DataJSON.swift // ShabuMaiJa-IOSClass // // Created by DottyPurkt on 19/12/2561 BE. // Copyright © 2561 iOS Dev. All rights reserved. // import Foundation class DataJSON: Decodable { struct Place: Decodable { struct Geometry: Decodable { struct Location: Decodable { var lat: Double? var lng: Double? } struct Viewport: Decodable { var northeast: Location var southwest: Location } var location: Location var viewport: Viewport } struct OpeningHours: Decodable { var open_now: Bool? } struct Photo: Decodable { var height: Int var html_attributions: [String?] var photo_reference: String? var width: Int } struct PlusCode: Decodable { var compound_code: String var global_code: String } var geometry: Geometry var icon: String? var id: String var name: String? var opening_hours: OpeningHours? var photos: [Photo?]? var place_id: String? var plus_code: PlusCode? var rating: Float var reference: String var scope: String var types: [String?] var vicinity: String? } init() { html_attributions = [] results = [] status = "empty" } func printResults() { for result in results! { print("place id : \(result?.place_id!)") print("place name : \(result?.name!)") print("place address : \(result?.vicinity!)") } } var html_attributions: [String?] var results: [Place?]? var status: String }
true
71c305c4ce0218da8f045d8890d7cfab392327a3
Swift
AsmaaHassenIbrahem/ShareImages-iOS
/ShareImage/ShareImage/viewmodel/ViewModel.swift
UTF-8
2,471
2.640625
3
[]
no_license
// // ViewModel.swift // ShareImage // // Created by Asmaa on 2/29/20. // Copyright © 2020 Asmaa. All rights reserved. // import UIKit import Moya class ViewModel: NSObject { var apiProvider : MoyaProvider<APIServices> init(apiProvider: MoyaProvider<APIServices> = MoyaProvider<APIServices>()) { self.apiProvider = apiProvider } func login(username :String ,completion: @escaping(Int?, Error?)->()){ apiProvider.request(.loginUser(username: username), completion: {(Result) in switch Result { case .success(let response): do { let user = try response.map(LoginResponse.self) print(user.result.userId) completion(user.result.userId , nil) } catch let error { print(error) } case .failure(let error): print(error) } }) } func upload(image :UIImage ,userId :Int , isPublic:Bool , completion: @escaping(Bool)->()){ apiProvider.request(.uploadImage(image: image, userId: userId, isPublic: isPublic), completion: {(Result) in switch Result { case .success(let response): do { let result = try response.map(BaseResponse.self) completion(result.isSuccess) print(result.isSuccess) } catch let error { print(error) } case .failure(let error): print(error.errorDescription) } }) } func getImagesVal(userId :Int , completion: @escaping(ImageListResponse)->()){ apiProvider.request(.readData(userId: userId), completion: {(Result) in switch Result { case .success(let response): do { let images = try response.map(ImageListResponse.self) print(images.result[0].picture) completion(images) } catch let error { print(error) } case .failure(let error): print(error) } }) } }
true
abb10ea75dd7a155411ce16b88e1d133bce56a0a
Swift
okhanokbay/CleanSwiftSample
/CleanSwiftSample/Shared/General/Strings.swift
UTF-8
392
2.765625
3
[]
no_license
// // Strings.swift // CleanSwiftSample // // Created by Okhan Okbay on 24.10.2020. // import Foundation enum Strings { static let error = "Error" static let confirm = "OK" static let usernamePlaceholder = "Username" static var usernameCharacterLength: String { "Username must be longer than \(ValidationRules.usernameMinCharLength) characters" } static let leave = "Leave" }
true
80042c0a6680f0f2753e0116e10f2de2071078df
Swift
nmandica/DirectedGraph
/Sources/Graph/SimpleNode.swift
UTF-8
188
2.6875
3
[ "MIT" ]
permissive
public struct SimpleNode: Node { public var id: String public var group: Int public init(id: String, group: Int) { self.id = id self.group = group } }
true
b9d4ddb9e18a5a8ee833d831d7a353f72714a05a
Swift
vhosune/IPDataDotCo
/IPDataDotCo/ResponseObjects/IPDataDotCo+Carrier.swift
UTF-8
688
2.796875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
// // Created by Vincent HO-SUNE. // Copyright © 2019 HO-SUNE Vincent. All rights reserved. // import Foundation extension IPDataDotCo { public struct Carrier: Codable { enum CodingKeys: String, CodingKey { case name case mobileCountryCode = "mmc" case mobileNetworkCode = "mnc" } /// The name of the carrier that owns the IP Address. public let name: String? /// The Mobile Country Code of the carrier. public let mobileCountryCode: String? /// The Mobile Network Code that identifies the carrier public let mobileNetworkCode: String? } }
true
b1cabe0a27219986932168d073705ab8fade35e6
Swift
kumabook/MusicFav
/MusicFav/MusicFavError.swift
UTF-8
996
2.90625
3
[ "MIT" ]
permissive
// // Error.swift // MusicFav // // Created by KumamotoHiroki on 10/12/15. // Copyright © 2015 Hiroki Kumamoto. All rights reserved. // import Foundation enum MusicFavError: Int { case entryAlreadyExists = 0 var domain: String { return "io.kumabook.MusicFav" } var code: Int { return rawValue } var title: String { switch self { case .entryAlreadyExists: return "Notice" } } var message: String { switch self { case .entryAlreadyExists: return "This entry already saved as favorite" } } func alertController(_ handler: @escaping (UIAlertAction!) -> Void) -> UIAlertController { let ac = UIAlertController(title: title.localize(), message: message.localize(), preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "OK".localize(), style: UIAlertActionStyle.default, handler: handler) ac.addAction(okAction) return ac } }
true
fdd1020d2d6a57b86eef3c386208a517f481c6e7
Swift
olimdzhon/task345
/Task/repository/GuideRepository.swift
UTF-8
1,161
2.78125
3
[]
no_license
// // GuideRepository.swift // Task // // Created by developer on 9/1/20. // Copyright © 2020 developer. All rights reserved. // import Foundation import Alamofire import PromiseKit class GuideRepository { func load() -> Promise<LoadedData> { let url = "https://guidebook.com/service/v2/upcomingGuides/" return Promise {seal in var request = URLRequest(url: URL(string: url)!) request.timeoutInterval = 30.0 AF.request(request).validate().responseData { response in switch response.result { case .success(let data): debugPrint("alamofire request data \(data)") do { let decoder = JSONDecoder() let guides = try decoder.decode(LoadedData.self, from: data) seal.fulfill(guides) } catch let error { seal.reject(error) } case .failure(let error): seal.reject(error) } } } } }
true
b7f059a1857c394879e0f293f6202d975a1f6f77
Swift
mrasyidhaikal/iCol
/iCol/ReusableCells/ChallengeCell.swift
UTF-8
2,205
2.625
3
[]
no_license
// // ChallengeCell.swift // iCol // // Created by Wendy Kurniawan on 13/10/20. // import UIKit class ChallengeCell: UICollectionViewCell { static let reuseIdentifier = "ChallengeCell" let containerView = UIView() let challengeLabel = UILabel() let challengeImageView = UIImageView() override init(frame: CGRect) { super.init(frame: .zero) // TODO: - Initialize View containerView.layer.cornerRadius = 8 containerView.clipsToBounds = false containerView.backgroundColor = .white containerView.addShadow(color: .black, opacity: 0.1, radius: 10, offset: CGSize(width: 0, height: 4)) challengeImageView.frame = CGRect(x: 0, y: 0, width: containerView.bounds.width / 2, height: 10) challengeImageView.contentMode = .scaleAspectFit challengeLabel.textAlignment = .center challengeLabel.numberOfLines = 0 challengeLabel.font = .preferredFont(forTextStyle: .title3) // TODO: - Adding Subview addSubview(containerView) containerView.addSubview(challengeImageView) containerView.addSubview(challengeLabel) // TODO: - Setting Auto Layout containerView.setConstraint( topAnchor: topAnchor, topAnchorConstant: 8, bottomAnchor: bottomAnchor, bottomAnchorConstant: 0, leadingAnchor: layoutMarginsGuide.leadingAnchor, leadingAnchorConstant: 0, trailingAnchor: layoutMarginsGuide.trailingAnchor, trailingAnchorConstant: 0 ) challengeImageView.setConstraint( topAnchor: topAnchor, topAnchorConstant: 32, centerXAnchor: containerView.centerXAnchor, centerXAnchorConstant: 0, heighAnchorConstant: 80, widthAnchorConstant: 80) challengeLabel.setConstraint( bottomAnchor: containerView.bottomAnchor, bottomAnchorConstant: -20, leadingAnchor: containerView.leadingAnchor, leadingAnchorConstant: 14, centerXAnchor: containerView.centerXAnchor ) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
01ff0474492fa134d64f7d00b3194c32e4476298
Swift
Koronaa/YTS-Mobile
/YTS/UI/Main/MovieList/MovieListViewModel.swift
UTF-8
3,419
2.671875
3
[ "MIT" ]
permissive
// // MovieListViewModel.swift // YTS // // Created by Sajith Konara on 4/27/20. // Copyright © 2020 Sajith Konara. All rights reserved. // import Foundation import RxSwift class MovieListViewModel{ fileprivate var commonViewModel:CommonViewModel? fileprivate let bag = DisposeBag() var searchViewModel:SearchViewModel! var movieListType:MovieListType init(commonViewModel:CommonViewModel?,movieListType:MovieListType) { self.commonViewModel = commonViewModel self.movieListType = movieListType } var movies:[Movie] = [] var data:ResultData? var limit:Int {data?.limit ?? 0} var totalNoOfPages:Int { return (data?.movieCount) ?? 0/limit} var currentPage:Int {return data?.pageNo ?? 0} var totalMovies:Int {return movies.count} func addMovies(moviesData:DataClass){ if self.movies.count == 0{ self.movies = moviesData.movies ?? [Movie]() self.data = ResultData(limit: moviesData.limit, pageNo: moviesData.pageNumber, movieCount: moviesData.movieCount) }else{ self.movies += moviesData.movies ?? [Movie]() } } func loadData(onCompleted:@escaping(Observable<Error?>)->Void){ switch movieListType { case .LATEST: commonViewModel!.loadLatestMovies(limit: 50, pageNo: currentPage) { (moviesDataObservable) in moviesDataObservable.subscribe(onNext: { moviesData,error in if let data = moviesData{ self.addMovies(moviesData: data) onCompleted(Observable.just(nil)) }else{ onCompleted(Observable.just(error)) } }).disposed(by: self.bag) } case .POPULAR: commonViewModel!.loadPopularMovies(limit: 50, pageNo: currentPage) { (moviesDataObservable) in moviesDataObservable.subscribe(onNext: { moviesData,error in if let data = moviesData{ self.addMovies(moviesData: data) onCompleted(Observable.just(nil)) }else{ onCompleted(Observable.just(error)) } }).disposed(by: self.bag) } case .RATED: commonViewModel!.loadMostRatedMovies(limit: 50, pageNo: currentPage) { (moviesDataObservable) in moviesDataObservable.subscribe(onNext: { moviesData,error in if let data = moviesData{ self.addMovies(moviesData: data) onCompleted(Observable.just(nil)) }else{ onCompleted(Observable.just(error)) } }).disposed(by: self.bag) } case .SEARCH: searchViewModel!.search(pageNo: currentPage, limit: 50){ (moviesDataObservable) in moviesDataObservable.subscribe(onNext: { moviesData,error in if let data = moviesData{ self.addMovies(moviesData: data) onCompleted(Observable.just(nil)) }else{ onCompleted(Observable.just(error)) } }).disposed(by: self.bag) } } } }
true
20c84c36111809b55ec377707515304b43be52e8
Swift
sengeiou/SchoolPlus
/SchoolPlus/Model/Organization.swift
UTF-8
955
2.625
3
[]
no_license
// // Organization.swift // SchoolPlus // // Created by 金含霖 on 2020/7/18. // Copyright © 2020 金含霖. All rights reserved. // import Foundation import SwiftyJSON class Organization { var organizationId:Int? var organizationName:String? var logo:String? var slogan:String? var intro:String? var founderId:Int? var founder:String? var auditor:String? var hasCheck:Bool? var hasSubscribed:Bool? init() { } init(_ json:JSON){ organizationId = json["organizationId"].int organizationName = json["organizationName"].string logo = json["logo"].string slogan = json["slogan"].string intro = json["intro"].string founder = json["founder"].string founderId = json["founderId"].int auditor = json["auditor"].string hasCheck = json["hasCheck"].bool hasSubscribed = json["hasSubscribed"].bool } }
true
301c00e2aad3b4b26e5a520ea946c9b4c473eaab
Swift
texyz/Payoneer
/Payoneer/View/BaseViewController.swift
UTF-8
1,301
2.75
3
[]
no_license
// // BaseViewController.swift // Payoneer // // Created by Rotimi Joshua on 06/05/2021. // import Foundation import UIKit class BaseViewController: ViewController { func simpleAlert(alertType:UIAlertController.Style?, message:String){ let actionSheet = UIAlertController(title: "Error", message: message, preferredStyle: alertType ?? .alert) actionSheet.addAction(UIAlertAction(title: "OKAY", style: .cancel, handler: nil)) present(actionSheet, animated: true, completion: nil) DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { actionSheet.dismiss(animated: true, completion: nil) } } func showLoader(){ let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert) let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50)) loadingIndicator.hidesWhenStopped = true loadingIndicator.style = UIActivityIndicatorView.Style.medium loadingIndicator.startAnimating(); alert.view.addSubview(loadingIndicator) present(alert, animated: true, completion: nil) } func dismissLoader(){ dismiss(animated: false, completion: nil) } }
true
14efa06c093e3d80ee622dc71d8e12104f6f2f4a
Swift
beallej/iOS
/RestExample/HelloRest/HelloRestSpecs/PeopleServiceTests.swift
UTF-8
3,060
2.625
3
[ "MIT" ]
permissive
import Foundation import Quick import Nimble import OHHTTPStubs import SwiftyJSON @testable import HelloRest class PeopleServiceTests: QuickSpec { override func spec() { beforeEach { stub(condition: isHost("localhost") && isPath("/list") && isMethodGET()) { request in let obj = [[ "id": 7, "name": "Ballard Craig", ], [ "id": 8, "name": "Brown Holt", ]] return OHHTTPStubsResponse(jsonObject: obj, statusCode: 200, headers: nil).responseTime(OHHTTPStubsDownloadSpeed3G) } stub(condition: isHost("localhost") && isPath("/listAll") && isMethodGET()) { request in let obj = [[ "id": 7, "name": "Ballard Craig", "phone":"Craig Cell" ], [ "id": 8, "name": "Brown Holt", "phone": "Brown Cell" ]] return OHHTTPStubsResponse(jsonObject: obj, statusCode: 200, headers: nil).responseTime(OHHTTPStubsDownloadSpeed3G) } } afterEach { OHHTTPStubs.removeAllStubs() } describe(".getAllPeople") { it("should get people with limited detail from list endpoint") { let peopleService = PeopleService() var completionCalled = false var actualPeople:[Person] = [] peopleService.getAllPeople { people in completionCalled = true actualPeople = people } expect(completionCalled).toEventually(beTrue()) expect(actualPeople).toEventually(haveCount(2)) let firstPerson = actualPeople.first expect(firstPerson?.id).toNot(beNil()) expect(firstPerson?.name).toNot(beNil()) expect(firstPerson?.phone).to(beNil()) } } describe(".getAllPeopleWithCell") { it("should get people with cell detail from cell endpoint") { let peopleService = PeopleService() var completionCalled = false var actualPeople:[Person] = [] peopleService.getAllPeopleWithCell { people in completionCalled = true actualPeople = people } expect(completionCalled).toEventually(beTrue()) expect(actualPeople).toEventually(haveCount(2)) let firstPerson = actualPeople.first expect(firstPerson?.id).toNot(beNil()) expect(firstPerson?.name).toNot(beNil()) expect(firstPerson?.phone).toNot(beNil()) } } } }
true
826f8d89adc21fc82c809ff552b2b73f7621155e
Swift
JustTerr0r/CurrensyAPP
/CurrensyAPP/Extensions.swift
UTF-8
1,716
3
3
[]
no_license
// // Extensions.swift // CurrensyAPP // // Created by Stanislav Frolov on 07.04.2021. // import UIKit extension ViewController: UIPickerViewDataSource { public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if apiClient.currensyName.isEmpty == false{ return apiClient.currensyName.count as Int } else { print("Something wrong with API") ; return 3 } } } extension ViewController: UIPickerViewDelegate, UITextFieldDelegate { public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return apiClient.currensyName[row] } public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let currentCurrensy = pickerView.selectedRow(inComponent: 0) let resultCurrensy = pickerView.selectedRow(inComponent: 1) if let key = apiClient.latestCurrensy.key(from: apiClient.currensyName[resultCurrensy]) { self.resultMultiplier = apiClient.latestRates[key] ?? 0.0 } if let key = apiClient.latestCurrensy.key(from: apiClient.currensyName[currentCurrensy]) { self.baseMultiplier = apiClient.latestRates[key] ?? 0.0 } calculate(userValue: Double(self.textField1.text!) ?? 0.0) } } // Extension for search in Dictionary extension Dictionary where Value: Equatable { public func key(from value: Value) -> Key? { return self.first(where: { $0.value == value })?.key } }
true
881516a5da2f8daf8cfffae11c19385945743656
Swift
MedLaunch/Myotera_GitHub
/myotera/MovesenseApi/MovesenseApi/MovesenseBleController.swift
UTF-8
3,646
2.65625
3
[]
no_license
// // MovesenseBleController.swift // MovesenseApi // // Copyright © 2018 Suunto. All rights reserved. // import CoreBluetooth protocol MovesenseBleControllerDelegate: class { func deviceFound(uuid: UUID, localName: String, serialNumber: String, rssi: Int) } protocol MovesenseBleController: class { var delegate: MovesenseBleControllerDelegate? { get set } var mdsCentralManager: CBCentralManager? { get } func startScan() func stopScan() } final class MovesenseBleControllerConcrete: NSObject, MovesenseBleController { weak var delegate: MovesenseBleControllerDelegate? // Keep this one here to use the same queue with our own central private(set) var mdsCentralManager: CBCentralManager? private let bleQueue: DispatchQueue private var centralManager: CBCentralManager? override init() { self.bleQueue = DispatchQueue(label: "com.movesense.ble") super.init() centralManager = CBCentralManager(delegate: self, queue: bleQueue, options: nil) mdsCentralManager = CBCentralManager(delegate: self, queue: bleQueue, options: nil) } func startScan() { guard let centralManager = centralManager else { NSLog("MovesenseBleController::stopScan integrity error.") return } if centralManager.state != .poweredOn { NSLog("MovesenseBleController::startScan Bluetooth not on.") return } centralManager.scanForPeripherals(withServices: Movesense.MOVESENSE_SERVICES, options: [CBCentralManagerScanOptionAllowDuplicatesKey: false]) } func stopScan() { guard let centralManager = centralManager else { NSLog("MovesenseBleController::stopScan integrity error.") return } if centralManager.state != .poweredOn { NSLog("MovesenseBleController::stopScan Bluetooth not on.") return } if centralManager.isScanning == false { return } centralManager.stopScan() } private func isMovesense(_ localName: String) -> Bool { let index = localName.firstIndex(of: " ") ?? localName.endIndex return localName[localName.startIndex..<index] == "Movesense" } private func parseSerial(_ localName: String) -> String? { guard isMovesense(localName), let idx = localName.range(of: " ", options: .backwards)?.lowerBound else { return nil } return String(localName[localName.index(after: idx)...]) } } extension MovesenseBleControllerConcrete: CBCentralManagerDelegate { func centralManagerDidUpdateState(_ central: CBCentralManager) { switch central.state { case CBManagerState.poweredOff: NSLog("centralManagerDidUpdateState: poweredOff") case CBManagerState.poweredOn: NSLog("centralManagerDidUpdateState: poweredOn") default: NSLog("centralManagerDidUpdateState: \(central.state.rawValue)") } } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) { guard let localName = peripheral.name, let serialNumber = parseSerial(localName) else { return } delegate?.deviceFound(uuid: peripheral.identifier, localName: localName, serialNumber: serialNumber, rssi: RSSI.intValue) } }
true
17a00ec46f13efb38b54ae6181d0bad31b99d9be
Swift
JCFlores93/iosArea51Training
/Modulo_3/Clase04/Clase04_Tests/Casos/CalculadoraViewControllerTests.swift
UTF-8
572
2.65625
3
[]
no_license
// // CalculadoraViewControllerTests.swift // C22_0412_M03_C4_Tests // // Created by Alumno on 12/4/17. // Copyright © 2017 Area51. All rights reserved. // import XCTest @testable import C22_0412_M03_C4_ //Clase5 class CalculadoraViewControllerTests: XCTestCase { func testSumar(){ //let calculadora = Calculadora() //Calculadora.hacer(operacion: .suma, value1) let number = Calculadora.hacer(operacion: .suma,value1: "hsh", value2: "d") //XCTAssert(number == nil, "Fallo") XCTAseerNil(number, "fallo") } }
true
e8a64f27f0eb70a5b3f0beaf4f5524c2f074fe50
Swift
microsoft/soundscape
/apps/ios/GuideDogs/Code/Visual UI/Views/Helpers/CustomScaledMetric.swift
UTF-8
3,546
2.6875
3
[ "MIT" ]
permissive
// // CustomScaledMetric.swift // Soundscape // // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // NOTE: This is a temporary replacement for the @ScaledMetric property wrapper // that is only available in iOS 14.0 and later. Remove this property wrapper when // the minimum supported iOS version increases to 14.0. // import SwiftUI @propertyWrapper struct CustomScaledMetric<Value>: DynamicProperty where Value: BinaryFloatingPoint { @Environment(\.horizontalSizeClass) var horizontalSizeClass @Environment(\.verticalSizeClass) var verticalSizeClass @Environment(\.sizeCategory) var contentSize let textStyle: UIFont.TextStyle let baseValue: Value let maxValue: Value? // Creates the scaled metric with an unscaled value and a text style to scale relative to. init(wrappedValue: Value, maxValue: Value? = nil, relativeTo textStyle: Font.TextStyle = .body) { self.textStyle = textStyle.uiKit self.baseValue = wrappedValue self.maxValue = maxValue } private var traitCollection: UITraitCollection { UITraitCollection(traitsFrom: [ UITraitCollection(horizontalSizeClass: horizontalSizeClass?.uiKit ?? .unspecified), UITraitCollection(verticalSizeClass: verticalSizeClass?.uiKit ?? .unspecified), UITraitCollection(preferredContentSizeCategory: contentSize.uiKit) ]) } // The value scaled based on the current environment. var wrappedValue: Value { let scaled = Value(UIFontMetrics(forTextStyle: textStyle).scaledValue(for: CGFloat(baseValue), compatibleWith: traitCollection)) return maxValue.map { min($0, scaled) } ?? scaled } } fileprivate extension UserInterfaceSizeClass { var uiKit: UIUserInterfaceSizeClass { switch self { case .compact: return .compact case .regular: return .regular @unknown default: return .unspecified } } } fileprivate extension ContentSizeCategory { var uiKit: UIContentSizeCategory { switch self { case .accessibilityExtraExtraExtraLarge: return .accessibilityExtraExtraExtraLarge case .accessibilityExtraExtraLarge: return .accessibilityExtraExtraLarge case .accessibilityExtraLarge: return .accessibilityExtraLarge case .accessibilityLarge: return .accessibilityLarge case .accessibilityMedium: return .accessibilityMedium case .extraExtraExtraLarge: return .extraExtraExtraLarge case .extraExtraLarge: return .extraExtraLarge case .extraLarge: return .extraLarge case .extraSmall: return .extraSmall case .large: return .large case .medium: return .medium case .small: return .small @unknown default: return .unspecified } } } extension Font.TextStyle { fileprivate var uiKit: UIFont.TextStyle { switch self { case .body: return .body case .callout: return .callout case .caption: return .caption1 case .caption2: return .caption2 case .footnote: return .footnote case .headline: return .headline case .largeTitle: return .largeTitle case .subheadline: return .subheadline case .title: return .title1 case .title2: return .title2 case .title3: return .title3 @unknown default: return .body } } var pointSize: CGFloat { return UIFont.preferredFont(forTextStyle: self.uiKit).pointSize } }
true
8b889b4f238310ffdabf9572ce731c3697bf9328
Swift
MostafaBelihi/iOS-iOS_App_Development__Design_Patterns_for_Mobile_Architecture-LinkedInCourse
/Ch03/Ch03_All_Diff/KnownSpys/SecretDetailsViewController.swift
UTF-8
1,393
2.765625
3
[]
no_license
import UIKit protocol SecretDetailsDelegate: class { func passwordCrackingFinished() } class SecretDetailsViewController: UIViewController { @IBOutlet var activityIndicator: UIActivityIndicatorView! @IBOutlet var passwordLabel: UILabel! fileprivate var presenter: SecretDetailsPresenter weak var delegate: SecretDetailsDelegate? init(with presenter: SecretDetailsPresenter, and delegate: SecretDetailsDelegate?) { self.presenter = presenter self.delegate = delegate super.init(nibName: "SecretDetailsViewController", bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() activityIndicator.startAnimating() activityIndicator.isHidden = false DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in self?.showPassword() } } func showPassword() { activityIndicator.stopAnimating() activityIndicator.isHidden = true passwordLabel.text = presenter.password } @IBAction func finishedButtonTapped(_ button: UIButton) { navigationController?.popViewController(animated: true) delegate?.passwordCrackingFinished() } }
true
f7a57d32b944152e3e6239fe23333142b086bfcf
Swift
Kishan-Kalburgi/Airlines-iOS-App
/NavyM/TheModel.swift
UTF-8
1,748
3.046875
3
[]
no_license
// // TheModel.swift // NavyM // // Created by Agrawal,Abhijeet P on 2/27/18. // Copyright © 2018 Agrawal,Abhijeet P. All rights reserved. // import Foundation struct Airline { var name:String var profits:Double var homebase:String var numEmployees:Int var citiesFlown:[String] init(name:String, profits:Double, homebase:String, numEmployees:Int, citiesFlown:[String]){ self.name = name self.profits = profits self.homebase = homebase self.numEmployees = numEmployees self.citiesFlown = citiesFlown } } struct FAA { static var airlines:[Airline] = [ Airline(name: "United", profits: 25.0, homebase: "Chicago", numEmployees: 2500, citiesFlown:["New York", "Toronto", "London", "Paris"]), Airline(name: "Delta", profits: 50.0, homebase: "Atlanta", numEmployees: 3500, citiesFlown:["Cairo", "Tel Aviv", "Ankara", "Tokyo", "Beijing"]), Airline(name: "Jet Airways", profits: 87.50, homebase: "Mumbai", numEmployees: 3000, citiesFlown: ["Bangalore", "Colombo", "Chennai", "Budapest", "London"]), Airline(name: "Lufthansa", profits:75.0,homebase: "London",numEmployees:1000, citiesFlown:["Rome", "Munich", "Johannesburg"]), Airline(name: "Air Canada", profits: 315.0, homebase: "Ottawa", numEmployees: 500, citiesFlown: ["Toronto", "Vancouver", "Tokyo"]) ] static func numAirlines()->Int { return airlines.count } static func airlineNum(_ index:Int) -> Airline { return airlines[index] } static func addNewAirline(_ airline:Airline){ airlines.append(airline) } }
true
88a6b90caad10e35e2a204b281a0d641f79ff0a6
Swift
tongminhnguyet2020/TheCoffeeHouse
/AppTheCoffeeHouse/Model/menu/Category.swift
UTF-8
2,602
2.734375
3
[]
no_license
// // Category.swift // AppTheCoffeeHouse // // Created by Tong Minh Nguyet on 4/21/20. // Copyright © 2020 Tong Minh Nguyet. All rights reserved. // import Foundation class Categ { var name: String? var type: String? var dataCateg: [Category]? init(data: [String: Any]) { name = data["name"] as? String type = data["type"] as? String if let categArray = data["data"] as? [[String: Any]] { self.dataCateg = categArray.compactMap({ Category(data: $0)}) } } } // [categ_sp, fo, dik] -> [data_sp1, sp2, sp3] -> category_id1, id2, id3 // ->[cf7 ngay-data,.... ] ->[(espsua-id1,....] -> lay id1 ra them vao nhom [id special] =[int] // -> [fo1, fo2, fo3, fo4, fo5] -> id1, id2, id3, id4, id5 // -> class Category { var id: Int? var name: String? var branch: String? var image: String? var type: String? var sectionStyle: SectionStyle? var idDrink: String? var description: String? var updatedAt: DateNumberLong? var locale: Localize? var localize: Localize? var createdAt: DateNumberLong? // server khong tra ve, phai tu tao bang code var menuDatas = [Data]() init(data: [String: Any]) { id = data["id"] as? Int name = data["name"] as? String branch = data["branch"] as? String image = data["image"] as? String type = data["type"] as? String if let sectionStyleX = data["header"] as? [String: Any] { self.sectionStyle = SectionStyle(data: sectionStyleX) } idDrink = data["type"] as? String description = data["type"] as? String if let dateOfUpX = data["updated_at"] as? [String: Any] { self.updatedAt = DateNumberLong(data: dateOfUpX) } if let loca = data["locale"] as? [String: Any] { self.locale = Localize(data: loca) } if let loca = data["locale"] as? [String: Any] { self.localize = Localize(data: loca) } if let dateOfUpX = data["created_at"] as? [String: Any] { self.createdAt = DateNumberLong(data: dateOfUpX) } } } class DateNumberLong { var dateOfUp: NumberLong? init(data: [String: Any]) { if let dateOfUpX = data["$date"] as? [String: Any] { self.dateOfUp = NumberLong(data: dateOfUpX) } } } class NumberLong { var numberLong: String? init(data: [String: Any]) { numberLong = data["$numberLong"] as? String } }
true