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
ec8bfa3abccd4a9057fe8a22ea59046437a21605
Swift
ignasiperez/SWIFT-Swift_org-The_Swift_programming_language-Language_guide
/SW-01-Swift_Language_Guide -Swift5.4/Swift_language_Guide -Swift5_4.playground/Pages/08-ENUMERATIONS-Sec05 Ex02c - Accessing the raw value of an enum case with rawValue.xcplaygroundpage/Contents.swift
UTF-8
808
4.0625
4
[]
no_license
//: # [ 􀄪 ](@previous) [ 􀙋 ](_Cover%20page) [ 􀄫](@next) /*: ### 08 - Section 5 - Example 02c # ENUMERATIONS # Raw Values ## Accessing the raw value of an enum case with rawValue --- */ import Foundation // ******************** 08-Sec05-Ex02c ******************** enum Planet: Int { case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune } enum CompassPoint: String { case north, south, east, west } print("\n--- 08-Sec05-Ex02c ---") let earthsOrder = Planet.earth.rawValue // earthsOrder is 3 print("earthsOrder: \(earthsOrder)") let sunsetDirection = CompassPoint.west.rawValue // sunsetDirection is "west" print("sunsetDirection: \(sunsetDirection)") //: # [ 􀄪 ](@previous) [ 􀙋 ](_Cover%20page) [ 􀄫](@next)
true
93d9b6db086870ca725aad3dee8babbbbacc3bd4
Swift
Abdullah8888/Quran247
/Quran247/NetworkService/NetworkService.swift
UTF-8
2,490
2.71875
3
[]
no_license
// // NetworkService.swift // Quran247 // // Created by Jimoh Babatunde on 13/05/2020. // Copyright © 2020 Dawah Nigeria. All rights reserved. // import Foundation import UIKit import SwiftyJSON public class NetworkService: NSObject { //A singleton object public static let sharedManager = NetworkService() public func getAllReciters(completion: @escaping (_ success: Bool, _ object: SwiftyJSON.JSON?, _ response: URLResponse) -> ()) { let urlString = "https://dawahnigeria.com/dn_qs.json" let request = self.createRequest(urlString: urlString) post(request: request) { (success, object, response) in completion(success, object, response) } } //MARK: Convenience Methods private func dataTask(request: NSMutableURLRequest, method: String, completion: @escaping (_ success: Bool, _ object: SwiftyJSON.JSON?, _ response: URLResponse) -> ()) { request.httpMethod = method let session = URLSession(configuration: URLSessionConfiguration.default); session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in if let error = error { print("the error now is \(error.localizedDescription)") } if let data = data { let obj = try? JSON(data: data) if let response = response as? HTTPURLResponse, 200...299 ~= response.statusCode { completion(true, obj, response) } else { completion(false, obj, response!) } } }.resume(); } private func createRequest(urlString: String) -> NSMutableURLRequest { let request = NSMutableURLRequest(url: NSURL(string: urlString)! as URL) request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("", forHTTPHeaderField: "User-Agent") return request } private func post(request: NSMutableURLRequest, completion: @escaping (_ success: Bool, _ object: SwiftyJSON.JSON?, _ response: URLResponse) -> ()) { dataTask(request: request, method: "POST", completion: completion) } private func get(request: NSMutableURLRequest, completion: @escaping (_ success: Bool, _ object: SwiftyJSON.JSON?, _ response: URLResponse) -> ()) { dataTask(request: request, method: "GET", completion: completion) } }
true
abb0aa9bc6ceca8dba84f66ae9190e3d006b21cb
Swift
dabestswag25/functionalswift
/Playground.playground/Pages/Untitled Page 6.xcplaygroundpage/Contents.swift
UTF-8
1,389
3.96875
4
[]
no_license
//: [Previous](@previous) import Foundation class Graph { var vertices : [Vertex] var edges : [Edge] init() { vertices = [] edges = [] } } class Vertex { var value : String init(_ value: String) { self.value = value } } class Edge { var a : Vertex var b : Vertex var weight : Double init(a: Vertex, b: Vertex, weight: Double) { self.a = a self.b = b self.weight = weight } } let graph = Graph() let a = Vertex("A") let b = Vertex("B") let c = Vertex("C") let d = Vertex("D") let e = Vertex("E") let z = Vertex("Z") graph.vertices = [a, b, c, d, e, z] graph.edges = [ Edge(a: a, b: b, weight: 1.0), Edge(a: a, b: c, weight: 2.0), Edge(a: b, b: c, weight: 3.0), Edge(a: b, b: d, weight: 1.0), Edge(a: c, b: d, weight: 2.0), Edge(a: c, b: e, weight: 3.0), Edge(a: d, b: e, weight: 1.0), Edge(a: e, b: z, weight: 2.0), Edge(a: d, b: z, weight: 3.0) ] func neighbors(vertex: Vertex, graph: Graph) -> [Vertex] { var neighbors: [Vertex] = [] for edge in graph.edges { if vertex === edge.a { neighbors.append(edge.b) } else if vertex === edge.b { neighbors.append(edge.a) } } return neighbors } neighbors(vertex: e, graph: graph) //: [Next](@next)
true
8952e49ecb6264b36249519fa267b4e49af31431
Swift
ineelam899/SwiftVIPERCitiesDemo
/SwiftVIPERCitiesDemo/CityList/CityListPresenter.swift
UTF-8
1,241
2.953125
3
[ "MIT" ]
permissive
// // CityListPresenter.swift // SwiftVIPERCitiesDemo // // Created by Neelam on 12/20/19. // Copyright © 2019 Neelam. All rights reserved. // import Foundation protocol CityListPresentation { func viewDidLoad() -> Void } class CityListPresenter: CityListPresentation { weak var view: CityListView? var interactor: CityListUseCase? var router: CityListRouting? init(view: CityListView, interactor: CityListUseCase, router: CityListRouting) { self.view = view self.interactor = interactor self.router = router } } extension CityListPresenter { func viewDidLoad() { DispatchQueue.global(qos: .background).async { [weak self] in self?.interactor?.getCities(completion: { result in let cityList = result.cities.compactMap({ CityItemViewModel(using: $0) }) DispatchQueue.main.async { [weak self] in self?.view?.updateCities(cityList: cityList) } }) } } } struct CityItemViewModel { let country: String let name: String init(using cityModel: City) { self.country = cityModel.country ?? "" self.name = cityModel.name ?? "" } }
true
207560651f208a4483dad2da8ad1a0543add7b41
Swift
rdscoo1/ChatApp
/ChatApp/Presentation Layer/Modules/Conversation/Model/Message.swift
UTF-8
923
3.203125
3
[]
no_license
// // Message.swift // ChatApp // // Created by Roman Khodukin on 3/26/21. // import Foundation import Firebase struct Message { let identifier: String let content: String let created: Date let senderId: String let senderName: String } extension Message { var isMyMessage: Bool { return senderId == UserDataManager.shared.identifier } init?(identifier: String, firestoreData: [String: Any]) { guard let content = firestoreData["content"] as? String, let senderId = firestoreData["senderId"] as? String, let senderName = firestoreData["senderName"] as? String, let created = firestoreData["created"] as? Timestamp else { return nil } self.identifier = identifier self.content = content self.senderId = senderId self.senderName = senderName self.created = created.dateValue() } }
true
4e6573acac74e8cfe244d7f94906cfe8d2d75395
Swift
Robihamanto/theatre
/Theatre/Utils/Enums/Collection.swift
UTF-8
470
2.984375
3
[]
no_license
// // Collection.swift // Theatre // // Created by Robihamanto on 09/11/18. // Copyright © 2018 Robihamanto. All rights reserved. // import Foundation enum Collection { case nowPlaying case topRated case upcoming var string: String { switch self { case .nowPlaying: return "now_playing" case .topRated: return "top_rated" case .upcoming: return "upcoming" } } }
true
6bc9c1b09b22caf96c213e747ded52a6c389805c
Swift
c4arl0s/PlaygroundsSwift421
/Playgrounds/TypeCastingForAnyAndAnyObject.playground/Contents.swift
UTF-8
2,360
4.90625
5
[ "MIT" ]
permissive
// Swift provides two special types for working with nonspecific types: // Any : can represent an instance of any type at all, including function types. // AnyObject : can represent an instance of any class type. // Use Any and AnyObject only when you explicitly need the behavior and capabilities they provide. It is always better to be specific about the types you expect to work with in your code. class MediaItem { var name: String init(name: String) { self.name = name } } class Movie: MediaItem { var director: String init(name: String, director: String) { self.director = director super.init(name: name) // you have to ask about this, september 1st. 2018. } } class Song: MediaItem { var artist: String init(name: String, artist: String) { self.artist = artist super.init(name: name) } } // Here’s an example of using Any to work with a mix of different types, including function types and nonclass types. The example creates an array called things, which can store values of type Any: var things = [Any]() things.append(0) things.append(0.0) things.append(42) things.append(3.14159) things.append("hello") things.append((3.0, 5.0)) things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman")) // things.append({ (name: String) -> String in "Hello, \(name)" }) // Closure // lets pass all members of thea array into for statement to check what kind of type are them: // notice that after case word is doing the casting for thing in things { switch thing { case 0 as Int: print("zero as an Int") case 0 as Double: print("zero as a Double") case let someInt as Int: print("an integer value of \(someInt)") case let someDouble as Double where someDouble > 0: print("a positive double value of \(someDouble)") case is Double: print("some other double value that I don't want to print") case let someString as String: print("a string value of \"\(someString)\"") case let (x, y) as (Double, Double): print("an (x, y) point at \(x), \(y)") case let movie as Movie: print("a movie called \(movie.name), dir. \(movie.director)") case let stringConverter as (String) -> String: print(stringConverter("Michael")) default: print("something else") } }
true
954e15d88b258a22e38db6c2bf8707437e5a560b
Swift
agon94/Swift-Exercises-2
/BakeryDelegate.swift
UTF-8
690
4.1875
4
[]
no_license
// Bakery Class struct Cookie: { var size = 5 var hasCocolate = true } protocol: bakeryDelegate { func cookieMade(_ cookie: Cookie) } // Bakery class - Boss class Bakery: { var storeWorker = bakeryDelegate? func makeCookie(_ size: Int, _ hasCocolate: Bool) { var newCookie = Cookie() newCookie.size = size newCookie.hasCocolate = hasCocolate storeWorker?.cookieMade(newCookie) } } // cookieStore class - Worker class CookieStore: bakeryDelegate { func cookieMade(_ cookie: Cookie) { print("Cookie of size \(cookie.size) was made!") } } // Main var bakery = Bakery() var cookieStore = CookieStore() bakery.storeWorker = cookieStore bakery.makeCookie(10, true)
true
f863960223e86630f4b30ef1933182f05de11b65
Swift
ASV44/Game-Of-Shapes-iOS
/Game_Of_Shapes_iOS/Shape.swift
UTF-8
7,219
2.78125
3
[]
no_license
// // Shape.swift // Game_Of_Shapes_iOS // // Created by Hackintosh on 6/5/17. // Copyright © 2017 Hackintosh. All rights reserved. // import Foundation import SpriteKit class Shape: SKSpriteNode { let width: CGFloat let height: CGFloat var location: Int var animated: CGFloat var animation: CGFloat let id: Int let connect: String let opacity: SKSpriteNode let cloned: Bool enum shapeOrientation: String {case NONE, HORIZONTAL, VERTICAL, PIVOT} var orientation: shapeOrientation init(orientation: shapeOrientation, location: Int, shapeName: String) { let texture = SKTexture(imageNamed: shapeName) let displaySize: CGRect = UIScreen.main.bounds width = 0.1694 * displaySize.width height = 0.0973 * displaySize.height self.location = location animated = 0 switch orientation { case .VERTICAL: animation = 0.1077 * displaySize.height break case .HORIZONTAL: animation = 0.1925 * displaySize.width break default: animation = 0 break } let startIndex = shapeName.characters.distance(from: shapeName.startIndex, to: shapeName.characters.index(of: "_")!) var start = shapeName.index(shapeName.startIndex, offsetBy: startIndex) id = Int(shapeName.substring(to: start))! start = shapeName.index(shapeName.startIndex, offsetBy: startIndex + 1) let endIndex = shapeName.characters.distance(from: shapeName.startIndex, to: shapeName.characters.index(of: ".")!) let end = shapeName.index(shapeName.startIndex, offsetBy: endIndex) let range = start..<end connect = shapeName.substring(with: range) // print("Id",id) // print("Connect",connect) opacity = SKSpriteNode(imageNamed: "opacity") cloned = false self.orientation = orientation if(location == 2) { self.orientation = .PIVOT } super.init(texture: texture, color: UIColor.clear, size: texture.size()) anchorPoint = CGPoint(x: 0, y: 0) name = shapeName switch orientation { case .VERTICAL: position.x = 0.413 * displaySize.width let gap = CGFloat(location) * CGFloat(0.0104) * displaySize.height position.y = 0.210 * displaySize.height + CGFloat(location) * CGFloat(height) + gap break case .HORIZONTAL: let gap = CGFloat(location) * CGFloat(0.0221) * displaySize.width position.x = 0.0304 * displaySize.width + CGFloat(location) * CGFloat(width) + gap position.y = 0.426 * displaySize.height break default: break } size = CGSize(width: width, height: height) opacity.size = CGSize(width: width, height: height) opacity.anchorPoint = CGPoint(x: 0, y: 0) opacity.zPosition = -1 self.addChild(self.opacity) zPosition = 2 } init(shape: Shape) { width = shape.width height = shape.height self.location = shape.location animated = 0 animation = shape.animation id = shape.id connect = shape.connect opacity = SKSpriteNode(imageNamed: "opacity") cloned = true orientation = shape.orientation super.init(texture: shape.texture, color: UIColor.clear, size: (shape.texture?.size())!) anchorPoint = CGPoint(x: 0, y: 0) name = shape.name position = shape.position size = CGSize(width: width, height: height) opacity.size = CGSize(width: width, height: height) opacity.anchorPoint = CGPoint(x: 0, y: 0) opacity.zPosition = -1 self.addChild(self.opacity) zPosition = 2 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateCoordinates(orientation: GameItemsMoves.moveDirection) { let displaySize: CGRect = UIScreen.main.bounds switch orientation { case .VERTICAL: position.x = 0.413 * displaySize.width let gap = CGFloat(location) * CGFloat(0.0104) * displaySize.height position.y = 0.210 * displaySize.height + CGFloat(location) * CGFloat(height) + gap animation = 0.1077 * displaySize.height break case .HORIZONTAL: let gap = CGFloat(location) * CGFloat(0.0221) * displaySize.width position.x = 0.0304 * displaySize.width + CGFloat(location) * CGFloat(width) + gap position.y = 0.426 * displaySize.height animation = 0.1925 * displaySize.width break default: break } } func move(direction: GameItemsMoves.moveDirection ,increment: CGPoint) { switch direction { case .UP: position.y += increment.y animated += increment.y break case .DOWN: position.y -= increment.y animated += increment.y break case .RIGHT: position.x += increment.x animated += increment.x break case .LEFT: position.x -= increment.x animated += increment.x break default: break } } func increaseLocation(orientation: GameItemsMoves.moveDirection) { print("animation",animation) print("animated",animated) animated = 0 location += 1 checkPivot(orientation: changeConstant(constant: orientation)) updateCoordinates(orientation: orientation) } func decreaseLocation(orientation: GameItemsMoves.moveDirection, bound: Int) { print("animation",animation) print("animated",animated) animated = 0 location -= 1 if location < 0 { location = bound - 1 } checkPivot(orientation: changeConstant(constant: orientation)) updateCoordinates(orientation: orientation) } func changeLocation(direction: GameItemsMoves.Direction, bound: Int) { if(direction.moveDirection == .UP || direction.moveDirection == .RIGHT) { increaseLocation(orientation: direction.orientation) } else { decreaseLocation(orientation: direction.orientation, bound: bound) } } func checkPivot(orientation: shapeOrientation) { if(location == 2) { self.orientation = .PIVOT } else if self.orientation == .PIVOT { self.orientation = orientation } } func changeConstant(constant: GameItemsMoves.moveDirection) -> shapeOrientation { var newConstant: shapeOrientation = .NONE switch constant { case GameItemsMoves.moveDirection.HORIZONTAL: newConstant = .HORIZONTAL break case GameItemsMoves.moveDirection.VERTICAL: newConstant = .VERTICAL break default: break } return newConstant } }
true
cf89f18000df435be6b8987b5f15a1331ca15ea7
Swift
cmriboldi/NPC-Generator
/NPCGenerator/Flaw.swift
UTF-8
537
3.21875
3
[]
no_license
// // Flaw.swift // NPCGenerator // // Created by Christian Riboldi on 9/16/17. // Copyright © 2017 Christian Riboldi. All rights reserved. // import Foundation enum Flaw : String { case love, arrogance, phobia, none func description() -> String { switch self { case .love: return "Has a forbidden love." case .arrogance: return "Arrogance." case .phobia: return "Has a specific phobia." default: return String(self.rawValue).capitalized } } }
true
c8e708ec2a2cddff871fde2424bc0c33d3004702
Swift
S2dentik/Cobain
/CobainFramework/Extensions/SequenceExtensions.swift
UTF-8
528
3.125
3
[]
no_license
extension Collection where Self: SubsequenceInitializable { var droppingFirst: Self { return type(of: self).init(subsequence: dropFirst()) } } public protocol SubsequenceInitializable { associatedtype SubSequence init(subsequence: SubSequence) } extension String: SubsequenceInitializable { public init(subsequence: SubSequence) { self.init(subsequence) } } extension Array: SubsequenceInitializable { public init(subsequence: SubSequence) { self.init(subsequence) } }
true
bee195ef635db81cbfd36750e2fc2575549b90ef
Swift
CarterMiller/TextFieldExtensions
/TextFieldExtensions/ViewController.swift
UTF-8
3,021
2.921875
3
[]
no_license
// // ViewController.swift // TextFieldPopupView // // Created by Russell Morgan on 16/01/2017. // Copyright © 2017 Carter Miller. All rights reserved. // import UIKit import Foundation class ViewController: UIViewController, UITextFieldDelegate, UITextFieldExtendedDelegate { @IBOutlet weak var textField1: UITextFieldExtendedView! @IBOutlet weak var textField2: UITextFieldExtendedView! @IBOutlet weak var textField3: UITextFieldExtendedView! @IBOutlet weak var textField4: UITextFieldExtendedView! @IBOutlet weak var textField5: UITextFieldExtendedView! @IBOutlet weak var textField6: UITextFieldExtendedView! var sampleData1 = ["one", "two", "three", "four", "five"] var sampleData2 = ["cat", "dog", "mouse", "horse", "hamster", "snake"] var sampleData3 = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] var dataSelected = ["Monday", "Wednesday", "Saturday"] override func viewDidLoad() { super.viewDidLoad() // set up the popup data. You can do this at any time textField2.setupPopup(dataSet: sampleData2, controlTag: textField2.tag, delegate: self) textField3.setupPopup(dataSet: sampleData3, controlTag: textField3.tag, delegate: self) textField6.setupPopup(dataSet: sampleData3, dataSetSelected: dataSelected, controlTag: 5, delegate: self) // but to stop editing when the user taps anywhere on the view, add this gesture recogniser let tapGestureBackground = UITapGestureRecognizer(target: self, action: #selector(self.backgroundTapped(_:))) self.view.addGestureRecognizer(tapGestureBackground) } func backgroundTapped(_ sender: UITapGestureRecognizer) { view.endEditingWithPopups(true) // end editing for any UITextField controls, and also for standard controls } // UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return false } // UITextFieldExtendedDelegate func multiPopupUpdated(valueReturn: [String], control: UITextFieldExtendedView, valueChanged: Bool) { var text : String = "" for dataEntry in valueReturn { text += dataEntry if dataEntry != valueReturn.last { text += ", " } } if control.tag == 5 { control.text = text } } func popupPickerViewChanged(valueReturn : String, control : UITextFieldExtendedView, valueChanged : Bool) { if valueChanged == false { return } if control.tag == 1 { // do something for control 1 } if control.tag == 2 { // do something for control 2 } if control.tag == 3 { // do something for control 3 } } }
true
d1d9c140e4307ccb67510947c7ee7dd374b3a69e
Swift
ZeusMode/swift_textfield
/TextFieldConceito/ViewController.swift
UTF-8
2,445
3.03125
3
[]
no_license
// // ViewController.swift // TextFieldConceito // // Created by Wesley Cintra Nascimento on 19/10/16. // Copyright © 2016 Wesley Cintra Nascimento. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { // MARK: - Estados da View override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Habilita o delegate do textField textField.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Actions @IBAction func transportaTexto(_ sender: UIButton) { // Dispensar o teclado if textField.resignFirstResponder() { // Transporta o texto digitado para label labelAlterado.text = textField.text } } // MARK: - Outlets @IBOutlet weak var textField: UITextField! @IBOutlet weak var labelAlterado: UILabel! @IBOutlet weak var btnTransporte: UIButton! // MARK: - TextField Delegates func textFieldShouldReturn(_ textField: UITextField) -> Bool { // Transporta o texto transportaTexto(btnTransporte) // Dispensa o teclado textField.resignFirstResponder() return true } func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason){ } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { // Campo deve ter no mínimo 5 caracteres if (textField.text?.characters.count)! < 5 { // Exibe erro let alerta = UIAlertController(title: "Erro de Consistência", message: "O campo deve conter pelo menos 5 caracteres", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: nil) alerta.addAction(action) present(alerta, animated: true, completion: nil) return false } return true } // MARK: - Tratamento de gestos override var canBecomeFirstResponder: Bool { return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // Dispensar o teclado self.becomeFirstResponder() } }
true
ea76e3ce7031f2b52fbca1f3d108017d566c46f5
Swift
prufect/SmackTheSlackCloneiOS12
/Smack/Controller/SignUpVC.swift
UTF-8
1,138
2.515625
3
[]
no_license
// // SignUpVC.swift // Smack // // Created by Prudhvi Gadiraju on 10/11/18. // Copyright © 2018 Kore. All rights reserved. // import UIKit class SignUpVC: UIViewController { @IBOutlet weak var userName: UITextField! @IBOutlet weak var email: UITextField! @IBOutlet weak var password: UITextField! override func viewDidLoad() { super.viewDidLoad() let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) view.addGestureRecognizer(tap) } @objc func dismissKeyboard(){ view.endEditing(true) } @IBAction func closeBtnPressed(_ sender: Any) { performSegue(withIdentifier: "segueToChannel", sender: nil) } @IBAction func SignUpBtnPressed(_ sender: Any) { guard let e = email.text , email.text != "" else {return} guard let pass = password.text, password.text != "" else {return} AuthService.instance.registerUser(email: e, password: pass) { (success) in if success { print("registered user!") } } } }
true
a8198050f0e271fa9b7e96eddd86540e593e994a
Swift
bryantm1123/trail-of-history-ios
/Trail of History/DetailViewController.swift
UTF-8
7,051
2.640625
3
[]
no_license
// // DetailViewController.swift // Trail of History // // Created by Matt Bryant on 9/3/16. // Copyright © 2016 CLT Mobile. All rights reserved. // import UIKit class DetailViewController: UIPageViewController { // MARK: Properties weak var dotsDelegate: DetailViewControllerDelegate? private(set) lazy var orderedViewControllers: [UIViewController] = { return [self.loadViewController("alpha"), self.loadViewController("beta"), self.loadViewController("gamma"), self.loadViewController("delta") ] }() override func viewDidLoad() { super.viewDidLoad() dataSource = self delegate = self // if let initialViewController = orderedViewControllers.first { // setViewControllers([initialViewController], direction: .Forward, animated: true, completion: nil) // } if let initialViewController = orderedViewControllers.first { scrollToViewController(initialViewController) } dotsDelegate?.detailViewController(self, didUpdatePageCount: orderedViewControllers.count) } func loadViewController(id: String) -> UIViewController { return UIStoryboard(name: "Detail", bundle: nil) . instantiateViewControllerWithIdentifier("\(id)") } // Scroll to the next view controller func scrollToNextViewController() { if let visibleViewController = viewControllers?.first, let nextViewController = pageViewController(self, viewControllerAfterViewController: visibleViewController) { scrollToViewController(nextViewController) } } // Scrolls to the view controller at the given index. Automatically calculates the direction. func scrollToViewController(index newIndex: Int) { if let firstViewController = viewControllers?.first, let currentIndex = orderedViewControllers.indexOf(firstViewController) { let direction: UIPageViewControllerNavigationDirection = newIndex >= currentIndex ? .Forward : .Reverse let nextViewController = orderedViewControllers[newIndex] scrollToViewController(nextViewController, direction: direction) } } // Scrolls to the given viewController page func scrollToViewController(viewController: UIViewController, direction: UIPageViewControllerNavigationDirection = .Forward) { setViewControllers([viewController], direction: direction, animated: true, completion: { (finished) -> Void in // Notify the tutorialDelegate about the new index self.notifyTutorialDelegateOfNewIndex() }) } // Notifies tutorialDelegate that current page was updated func notifyTutorialDelegateOfNewIndex() { if let firstViewController = viewControllers?.first, let index = orderedViewControllers.indexOf(firstViewController) { dotsDelegate?.detailViewController(self, didUpdatePageIndex: index) } } /* func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int { return orderedViewControllers.count } func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int { guard let firstViewController = viewControllers?.first, firstViewControllerIndex = orderedViewControllers.indexOf(firstViewController) else { return 0 } return firstViewControllerIndex } */ /* override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } // MARK: Datasource extension DetailViewController: UIPageViewControllerDataSource { func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else { return nil } let previousIndex = viewControllerIndex - 1 guard previousIndex >= 0 else { return orderedViewControllers.last // return nil to deactivate loop } guard orderedViewControllers.count > previousIndex else { return nil } return orderedViewControllers[previousIndex] } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else { return nil } let nextIndex = viewControllerIndex + 1 let orderedViewControllersCount = orderedViewControllers.count guard orderedViewControllersCount != nextIndex else { return orderedViewControllers.first // return nil to deactivate loop } guard orderedViewControllersCount > nextIndex else { return nil } return orderedViewControllers[nextIndex] } } extension DetailViewController: UIPageViewControllerDelegate { func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { notifyTutorialDelegateOfNewIndex() // if let firstViewController = viewControllers?.first { // let index = orderedViewControllers.indexOf(firstViewController) // } // // dotsDelegate?.detailViewController(self, didUpdatePageIndex: index) } } protocol DetailViewControllerDelegate: class { /** Called when the number of pages is updated - parameter detailViewController: the DetailViewController instance - parameter count: total number of pages */ func detailViewController(detailPageViewController: DetailViewController, didUpdatePageCount count: Int) /** Called when the current index is updated - parameter detailViewController: the DetailViewController instance - parameter index: the index of the currently visible page */ func detailViewController(detailViewController: DetailViewController, didUpdatePageIndex index: Int) }
true
1582a60a849adb2981cc4404525747ef3c787766
Swift
paresh1994/Base-Project
/BaseProject/Networking/APIRouter.swift
UTF-8
1,346
2.65625
3
[]
no_license
// // APIRouter.swift // BaseProject // // Created by Rohit Makwana on 04/06/18. // Copyright © 2018 Rohit Makwana. All rights reserved. // import Foundation import Alamofire //======================================================================= // MARK:- Routable //======================================================================= protocol Routable { var path : String { get } var method : HTTPMethod { get } var parameters : Parameters? { get } var headers : HTTPHeaders { get } } enum APIRouter: Routable { case getData(Parameters) } extension APIRouter { var path: String { switch self { case .getData: return baseUrl + "" } } } extension APIRouter { var method: HTTPMethod { switch self { case .getData: return .get //ot .post } } } extension APIRouter { var parameters: Parameters? { switch self { case .getData(let param): return param } } } extension APIRouter { var headers: HTTPHeaders { if let token = AppDeli.user?.token { return ["Content-Type":"application/json", "accesstoken": token] } else { return ["Content-Type":"application/json"] } } }
true
1cf3e31511e09fe34f936a1d311452cff1932ad7
Swift
mRs-/RxFileMonitor
/RxFileMonitor/Change.swift
UTF-8
2,883
2.796875
3
[ "MIT" ]
permissive
// // Change.swift // RxFileMonitor // // Created by Christian Tietze on 08/11/16. // Copyright © 2016 RxSwiftCommunity https://github.com/RxSwiftCommunity // import Foundation /// Option set wrapper around some `FSEventStreamEventFlags` /// which are useful to monitor folders. public struct Change: OptionSet { public var rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public init(eventFlags: FSEventStreamEventFlags) { self.rawValue = Int(eventFlags) } public static let isDirectory = Change(rawValue: kFSEventStreamEventFlagItemIsDir) public static let isFile = Change(rawValue: kFSEventStreamEventFlagItemIsFile) public static let isHardlink = Change(rawValue: kFSEventStreamEventFlagItemIsHardlink) public static let isLastHardlink = Change(rawValue: kFSEventStreamEventFlagItemIsLastHardlink) public static let isSymlink = Change(rawValue: kFSEventStreamEventFlagItemIsSymlink) public static let created = Change(rawValue: kFSEventStreamEventFlagItemCreated) public static let modified = Change(rawValue: kFSEventStreamEventFlagItemModified) public static let removed = Change(rawValue: kFSEventStreamEventFlagItemRemoved) public static let renamed = Change(rawValue: kFSEventStreamEventFlagItemRenamed) public static let changeOwner = Change(rawValue: kFSEventStreamEventFlagItemChangeOwner) public static let finderInfoModified = Change(rawValue: kFSEventStreamEventFlagItemFinderInfoMod) public static let inodeMetaModified = Change(rawValue: kFSEventStreamEventFlagItemInodeMetaMod) public static let xattrsModified = Change(rawValue: kFSEventStreamEventFlagItemXattrMod) } extension Change: Hashable { public var hashValue: Int { return 879 &* rawValue } } extension Change: CustomStringConvertible { public var description: String { var names: [String] = [] if self.contains(.isDirectory) { names.append("isDir") } if self.contains(.isFile) { names.append("isFile") } if self.contains(.isHardlink) { names.append("isHardlink") } if self.contains(.isLastHardlink) { names.append("isLastHardlink") } if self.contains(.isSymlink) { names.append("isSymlink") } if self.contains(.created) { names.append("created") } if self.contains(.modified) { names.append("modified") } if self.contains(.removed) { names.append("removed") } if self.contains(.renamed) { names.append("renamed") } if self.contains(.changeOwner) { names.append("changeOwner") } if self.contains(.finderInfoModified) { names.append("finderInfoModified") } if self.contains(.inodeMetaModified) { names.append("inodeMetaModified") } if self.contains(.xattrsModified) { names.append("xattrsModified") } return names.joined(separator: ", ") } }
true
311da7e41db41c34f16d89a7edafee816148a4ee
Swift
coe/Dynamics
/Tests/DynamicsTests/DynamicsTests.swift
UTF-8
4,531
2.71875
3
[ "MIT" ]
permissive
import XCTest import Dynamics final class DynamicsTests: XCTestCase { private let data = """ { "true_value": true, "false_value": false, "string_value": "red", "one_value": 1, "zero_value": 0, "minus_value": -1, "int_value": 123, "double_value": 3.14, "null_value": null, "array_list": [12, 23], "object_list": { "user_id": "A1234567", "user_name": "Yamada Taro" } } """.data(using: .utf8)! func testJson() throws { let json = try JSON(data: data) XCTAssertEqual(json.true_value?.boolValue, true) XCTAssertEqual(json.false_value?.boolValue, false) XCTAssertEqual(json.string_value?.stringValue, "red") XCTAssertEqual(json.one_value?.numberValue, 1) XCTAssertEqual(json.one_value?.boolValue, true) XCTAssertEqual(json.zero_value?.numberValue, 0) XCTAssertEqual(json.zero_value?.boolValue, false) XCTAssertEqual(json.minus_value?.numberValue, -1) XCTAssertEqual(json.int_value?.numberValue, 123) XCTAssertEqual(json.double_value?.numberValue, 3.14) XCTAssertEqual(json.array_list?[0]?.numberValue, 12) XCTAssertEqual(json.array_list?.arrayValue?[0].numberValue, 12) XCTAssertEqual(json.object_list?.user_id?.stringValue, "A1234567") XCTAssertEqual(json.object_list?.objectValue?["user_id"]?.stringValue, "A1234567") XCTAssertEqual(json.null_value?.nullValue, NSNull()) XCTAssertNil(json.undefined_value) } func testJsonThrow() throws { XCTAssertThrowsError(try JSON(data: Data())) } func testJSONDataGenerator() { let generator = JSONDataGenerator() let jsonData = generator(int_value: 120, string_value: "string", bool_value: true, array_value: [1,"2",true], dictionary_value: ["1":1,"2":"2"], null_value: nil) if let json = try? JSONSerialization.jsonObject(with: jsonData!, options: []) as? [String:Any] { print(json) XCTAssertEqual(json["int_value"] as? Int, 120) XCTAssertEqual(json["string_value"] as? String, "string") XCTAssertEqual(json["bool_value"] as? Bool, true) XCTAssertNil(json["null_value"]) XCTAssertNil(json["undefined_value"]) } else { XCTFail() } } func testJSONDataGeneratorWithDate() { let generator = JSONDataGenerator() let jsonData = generator(date: Date()) XCTAssertNil(jsonData) } func testDictionaryGenerator() { let generator = DictionaryGenerator() let dictionary = generator(int_value: 120, string_value: "string", bool_value: true, array_value: [1,"2",true], dictionary_value: ["1":1,"2":"2"], null_value: nil) XCTAssertEqual(dictionary["int_value"] as? Int, 120) XCTAssertEqual(dictionary["string_value"] as? String, "string") XCTAssertEqual(dictionary["bool_value"] as? Bool, true) XCTAssertNil(dictionary["null_value"]) XCTAssertNil(dictionary["undefined_value"]) } func testDictionaryGeneratorWithDate() { let date = Date() let generator = DictionaryGenerator() let dictionary = generator(date: date) XCTAssertEqual(dictionary["date"] as? Date, date) } func testURLQueryItemsGenerator() { let generator = URLQueryItemsGenerator() let queryItems = generator(string_value: "string", null_value: nil) XCTAssertTrue(queryItems.contains(URLQueryItem(name: "string_value", value: "string"))) XCTAssertTrue(queryItems.contains(URLQueryItem(name: "null_value", value: nil))) XCTAssertFalse(queryItems.contains(URLQueryItem(name: "undefined_value", value: nil))) } static var allTests = [ ("testJson", testJson), ("testJsonThrow", testJsonThrow), ("testJSONDataGenerator", testJSONDataGenerator), ("testJSONDataGeneratorWithDate", testJSONDataGeneratorWithDate), ("testURLQueryItemsGenerator", testURLQueryItemsGenerator), ] }
true
1ec32b88d130c4601d00b1a2d02369efe98e2772
Swift
ActumLab/ActumStudio_iOS
/ActumStudio/Common/ApiError.swift
UTF-8
681
2.890625
3
[]
no_license
// // ApiError.swift // Mikomax // // Created by Rafał Sowa on 10/05/2018. // Copyright © 2018 Actum Lab. All rights reserved. // import Foundation enum ApiError: AppError { case netowrkIsUnreachable case server case message(String) var title: String { switch self { case .netowrkIsUnreachable: return "Network is unreachable" case .server: return "Something went wrong." case .message(_): return "Error" } } var description: String { switch self { case let .message(msg): return msg default: return "" } } }
true
755e44c4ca369ac50345de2726494fc42d5f5b82
Swift
Lakshmi-reddy9/The-ArithMETic-App
/The ArithMETic App/ExerciseCoach.swift
UTF-8
1,067
3.390625
3
[]
no_license
// // ExerciseCoach.swift // The ArithMETic App // // Created by Sai Sri Lakshmi on 14/02/19. // Copyright © 2019 Sai Sri Lakshmi. All rights reserved. // import Foundation struct ExerciseCoach{ static let sports:[String:Double] = ["Bicycling":8.0,"Jumping rope":12.3,"Running - slow":9.8,"Running - fast":23.0,"Tennis":8.0,"Swimming":5.8] static func energyConsumed(during: String,weight: Double,time: Double) -> Double{ let met = sports[during]! let caloriesBurned:String = String(format: "%.1f", ((met * 3.5 * (weight/2.2))/200)*time) let energyConsumed:Double = Double(caloriesBurned)! return energyConsumed } static func timeToLose1Pound(during: String,weight: Double) -> Double{ let met:Double = sports[during]! let fitness:String = String(format: "%.1f",(3500/((met * 3.5 * (weight/2.2))/200))) let timeTook = Double(fitness)! return timeTook } } // //I took lot of time and energy to create this app i need full score for this!!!!!!
true
c61f31e034706833e1701827e535f8d507ff16ed
Swift
SuperDeker-GitHub/iosSDAPP
/SuperDeker/EmailViewController.swift
UTF-8
6,954
2.671875
3
[]
no_license
// // ViewController.swift // SuperDeker // // Created by Luis Bermudez on 10/14/20. // import UIKit struct EmailModel: Codable { let email: String let used: Bool } class EmailViewController: UIViewController, UITextFieldDelegate { //MARK: Properties @IBOutlet weak var emailSaveButton: UIBarButtonItem! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var problemEmail: UILabel! override func viewDidLoad() { super.viewDidLoad() //let img = UIImage(named: "TransSuperDekerLogo") //navigationController?.navigationBar.setBackgroundImage(img, for: .default) navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.isTranslucent = true // Do any additional setup after loading the view. let defaults = UserDefaults.standard let emailText = defaults.string(forKey: "email") emailTextField.text = emailText emailTextField?.delegate = self; if conformsToEmail(email: emailText ?? ""){ emailSaveButton.isEnabled=true }else{ emailSaveButton.isEnabled=false } } override func viewDidDisappear(_ animated: Bool) { let email = emailTextField.text let defaults = UserDefaults.standard defaults.set(email, forKey: "email") } //MARK: UITextFieldDelegate func textFieldDidBeginEditing(_ textField: UITextField) { // Disable the Save button while editing. let text = textField.text ?? "" if conformsToEmail(email: text){ emailSaveButton.isEnabled=true }else{ emailSaveButton.isEnabled=false } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let updatedString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) if conformsToEmail(email: updatedString ?? ""){ emailSaveButton.isEnabled=true }else{ emailSaveButton.isEnabled=false } return true; } func textFieldShouldReturn(_ textField: UITextField)-> Bool{ // Hide the keyboard textField.resignFirstResponder() let text = textField.text ?? "" if conformsToEmail(email: text){ emailDone(emailSaveButton) }else{ emailSaveButton.isEnabled=false } return true } func textFieldDidEndEditing(_ textField: UITextField) { textField.resignFirstResponder() } func conformsToEmail(email: String)-> Bool{ //una sola palabra de 4 o más caracteres, hasta 20 if !email.isEmail { problemEmail.text="email format should be like name@company.com or nick@place.net or similar" return false } problemEmail.text="" return true } //MARK Actions @IBAction func emailDone(_ sender: UIBarButtonItem) { let spin = SpinnerViewController() // add the spinner view controller showSpin(vspin:spin) // checking on https://dossierplus-srv.com/superdeker/api/CheckEmailUsed.php/Email let email = emailTextField.text ?? "" // Create URL let url = URL(string: "https://dossierplus-srv.com/superdeker/api/CheckEmailUsed.php/"+email) guard let requestUrl = url else { fatalError() } // Create URL Request var request = URLRequest(url: requestUrl) // Specify HTTP Method to use request.httpMethod = "GET" // Send HTTP Request let task = URLSession.shared.dataTask(with: request) { (data, response, error) in self.hideSpin(vspin: spin) if let error = error { print("Error took place \(error)") return } // Read HTTP Response Status code if let response = response as? HTTPURLResponse { print("Response HTTP Status code: \(response.statusCode)") } // Convert HTTP Response Data to a simple String if let data = data, let dataString = String(data: data, encoding: .utf8) { let emailNew=self.parseEmailModel(data: data) let used = emailNew?.used if (used ?? false){ self.PopAlert(mess: "This email is registered, verify if this is your email") } else{ let defaults = UserDefaults.standard defaults.set(email, forKey: "email") self.JumpToPWD() } print("email:"+emailNew!.email ) print("used:" + (emailNew!.used ? "true":"false")) } } task.resume() } func parseEmailModel(data: Data) -> EmailModel? { var returnValue: EmailModel? do { returnValue = try JSONDecoder().decode(EmailModel.self, from: data) } catch { print("Error took place\(error.localizedDescription).") } return returnValue } func showSpin(vspin: SpinnerViewController){ addChild(vspin) vspin.view.frame = view.frame view.addSubview(vspin.view) vspin.didMove(toParent: self) } func hideSpin(vspin: SpinnerViewController){ DispatchQueue.main.async { vspin.willMove(toParent: nil) vspin.view.removeFromSuperview() vspin.removeFromParent()// Check if Error took place } } func PopAlert(mess: String){ DispatchQueue.main.async { let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let nextViewController = storyBoard.instantiateViewController(withIdentifier: "AlertViewController") as! AlertViewController nextViewController.modalPresentationStyle = .popover nextViewController.modalTransitionStyle = .coverVertical self.present(nextViewController, animated: true, completion: nil) nextViewController.MessageLabel?.text=mess //self.navigationController?.pushViewController(nextViewController, animated: true) } } func JumpToPWD(){ DispatchQueue.main.async { let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PWDViewController") as! PWDViewController self.navigationController?.pushViewController(nextViewController, animated: true) } } }
true
7a5f35b8c2df785ddd180810872a679da39cc73d
Swift
PhraxayaM/SPD2-4
/Assigment5.playground/Contents.swift
UTF-8
1,825
4.5625
5
[]
no_license
# Implement a linked list # Done in Python class Node(): def __init__(self, data): self.data = data self.next = None class LinkedList(): def __init__(self, items=[]): # ["a"] -> ["b"] -> ["c"] -> None self.head = None self.tail = None for item in items: self.append(item) # append method def append(self, val): node = Node(val) # if empty add to the head, set the head and tail to the item if self.head is None: self.head = node self.tail = self.head # if not empty add to the end of the ll, then update the tail else: self.tail.next = node self.tail = self.tail.next # Given a singly-linked list, find the middle value in the list. # Example: If the given linked list is A → B → C → D → E, return C. # Assumptions: The length (n) is odd so the linked list has a definite middle. def findMiddleVal(L): # N = # of items in L # Space: O(N) # Time: O(N) items_array = [] # O(1) curr = L.head # O(1) # Traverse LL to convert LL to a regular array while curr != None: # O(N) items_array.append(curr.data) # O(1) curr = curr.next # O(1) # find middle index middle = len(items_array)//2 # O(1) # return middle value return items_array[middle] # O(1) # Implement this with space O(1) --> no arrays, tuples, hashtables, anything # brainstorm approaches: # Helper method find length --> O(N) time, O(1) space # Keep a counter and increment that at each iteration # counter will give us the length of the linked list # Calculate middle using helper method # Traverse with counter till you reach middle def testFindMiddleVal(): print("Testing linked list") L = LinkedList(["a", "b", "c"]) assert(findMiddleVal(L) == "b") print("PASSED") testFindMiddleVal()
true
a15eeaf8bfcb85269a729ad2675e5048f1cd84ce
Swift
jamescavallo/app
/Long Term/View Controllers/login_ViewController.swift
UTF-8
2,504
2.890625
3
[]
no_license
// // login_ViewController.swift // Long Term // // Created by James Cavallo on 7/10/21. // import UIKit import FirebaseAuth class login_ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var user_field: UITextField! @IBOutlet weak var pass_field: UITextField! @IBOutlet weak var errorLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() initializeHideKeyboard() self.pass_field.delegate = self self.user_field.delegate = self Utilities.styleTextField(user_field, text: "Email") Utilities.styleTextField(pass_field, text: "Password") Utilities.setupLeftImage(imageName: "username", button: user_field) Utilities.setupLeftImage(imageName: "password", button: pass_field) errorLabel.alpha = 0 } @IBAction func handleLogin(_ sender: Any) { let usernameText = user_field.text!.trimmingCharacters(in: .whitespacesAndNewlines) let passwordText = pass_field.text!.trimmingCharacters(in: .whitespacesAndNewlines) //Sign the user in from the given email and password combo Auth.auth().signIn(withEmail: usernameText, password: passwordText) { (result, error) in if error != nil{ //sign in failed self.errorLabel.alpha = 1 }else{ let homeViewController = self.storyboard?.instantiateViewController(identifier: "homeVC") self.view.window?.rootViewController = homeViewController self.view.window?.makeKeyAndVisible() } } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return false } func initializeHideKeyboard(){ //Declare a Tap Gesture Recognizer which will trigger our dismissMyKeyboard() function let tap: UITapGestureRecognizer = UITapGestureRecognizer( target: self, action: #selector(dismissMyKeyboard)) //Add this tap gesture recognizer to the parent view view.addGestureRecognizer(tap) } @objc func dismissMyKeyboard(){ //endEditing causes the view (or one of its embedded text fields) to resign the first responder status. //In short- Dismiss the active keyboard. view.endEditing(true) } }
true
13f77095e2b1a6d6e843ac68d3fddb2f2beaeafa
Swift
shenkuantipang/word-deposit-ios
/worddeposit/Reusable Components/BackItem.swift
UTF-8
635
2.578125
3
[]
no_license
// // SetupBackItem.swift // worddeposit // // Created by Maksim Kalik on 9/26/20. // Copyright © 2020 Maksim Kalik. All rights reserved. // import UIKit class BackItem { static func setupWith(imageName: String?) { let view = UIView(frame: CGRect(x: 0, y: 0, width: 42, height: 42)) let imageView = UIImageView(frame: CGRect(x: 0, y: 10, width: 24, height: 24)) if let imgBackArrow = UIImage(named: imageName ?? "icon_back") { let tintedImage = imgBackArrow.withRenderingMode(.alwaysTemplate) imageView.image = tintedImage imageView.tintColor = Colors.blue } } }
true
63323b350bb42ca8c546667971f20bba2314c396
Swift
iappetos/Expenseeble
/ExpenseWatch/IncomeModeObject.swift
UTF-8
560
2.78125
3
[]
no_license
// // IncomeModeObject.swift // ExpenseWatch // // Created by Ioannis Karagogos on 17/5/18. // Copyright © 2018 Ioannis. All rights reserved. // import UIKit class IncomeModeObject: NSObject, NSCoding { var mode : Bool init(mode: Bool){ self.mode = mode } required convenience init?(coder decoder: NSCoder) { let mode = decoder.decodeBool(forKey: "mode") self.init( mode: mode ) } func encode(with coder: NSCoder) { coder.encode(self.mode, forKey:"mode") } }
true
536741abe3150089a2085a87cef2ab4f3cb2751e
Swift
tilljernst/F14_ProjektArbeit
/F14_ProjektArbeit_Surveys/F14_ProjektArbeit_Surveys/SurveyHelper.swift
UTF-8
1,455
3.09375
3
[]
no_license
// // SurveyHelper.swift // F14_ProjektArbeit_Surveys // // Created by Till J. Ernst on 31.05.17. // Copyright © 2017 Till J. Ernst. All rights reserved. // import Foundation import ResearchKit struct SurveyHelper{ /** creates a single text choice researchKit question step with one or multiple text-questions - Parameter identifier: unique identifier of the researchKit question - Parameter title: the title of the question - Parameter text: (optional) text below the title - Parameter items: the single question items with the corresponding answer in a tuple array - Returns: a researchKit ORKQuestionStep */ static func createSingleTextChoiceQuestionStep(ORKQuestionIdentifier identifier:String, QuestionTitle title:String, QuestionText text:String = "", QuestionItems items:[(textChoice:String, answerValue:String)]) -> ORKQuestionStep { var textChoices = [ORKTextChoice]() for item in items { textChoices.append(ORKTextChoice(text: item.textChoice, value: item.answerValue as NSCoding & NSCopying & NSObjectProtocol)) } let answerFormat = ORKAnswerFormat.choiceAnswerFormat(with: .singleChoice, textChoices: textChoices) let questionStep = ORKQuestionStep(identifier: identifier, title: title, answer: answerFormat) if text != "" { questionStep.text = text } return questionStep } }
true
9be2aecc36a835153045a1ebcd1b8765f574bbb7
Swift
TurtleJermine/poke
/YourDiary/YourDiary/username.swift
UTF-8
694
2.8125
3
[]
no_license
// // username.swift // YourDiary // // Created by Apple on 2019/12/10. // Copyright © 2019 feng. All rights reserved. // import Foundation import UIKit class username: NSObject, NSCoding { func encode(with aCoder: NSCoder) { aCoder.encode(userName, forKey: "nameKey") } required init?(coder aDecoder: NSCoder) { userName = aDecoder.decodeObject(forKey: "nameKey") as? String } var userName: String? static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! init( userName: String?) { self.userName = userName } }
true
378d7a17759b742ac7994cabdc06f8df6af1d855
Swift
Lv-249iOS/TouristGuide
/iTourist/Classes/Weather/Forecast.swift
UTF-8
1,254
2.90625
3
[]
no_license
// // Forecast.swift // iTourist // // Created by Andriy_Moravskyi on 8/4/17. // Copyright © 2017 Kristina Del Rio Albrechet. All rights reserved. // import UIKit class Forecast { enum ForecastWeatherKeyPath: String { case condition = "condition" case code = "code" case mintemp = "mintemp_c" case date = "date" case day = "day" case maxtemp = "maxtemp_c" } var maxtemp: Int var mintemp: Int var date: String var currentTemp: Int? var feelsTemp: Int? var imagecode: String? var image: UIImage? init(forecast: [String: Any]) { maxtemp = forecast[ForecastWeatherKeyPath.maxtemp.rawValue] as? Int ?? 0 mintemp = forecast[ForecastWeatherKeyPath.mintemp.rawValue] as? Int ?? 0 date = forecast[ForecastWeatherKeyPath.date.rawValue] as? String ?? "Unknown" if let condition = forecast[ForecastWeatherKeyPath.condition.rawValue] as? [String: Any] { let icon = condition[ForecastWeatherKeyPath.code.rawValue] as? Int ?? 0 imagecode = String(icon) if let imgName = imagecode, let img = UIImage(named: imgName + ".png") { image = img } } } }
true
7ce7a73a41e207b336ca871a97c304e5f0b2a570
Swift
MyColourfulLife/MacDevelopPractice
/List/List/ViewBasedTableViewController.swift
UTF-8
2,923
3
3
[]
no_license
// // ViewBasedTableViewController.swift // List // // Created by Ekko on 2019/12/11. // Copyright © 2019 Ekko. All rights reserved. // import Cocoa class ViewBasedTableViewController: NSViewController { @IBOutlet weak var tableView: NSTableView! var datas = [NSDictionary]() override func viewDidLoad() { super.viewDidLoad() updateData() } func updateData() { self.datas = [ ["name":"john","address":"USA","gender":"male","married":1], ["name":"mary","address":"China","gender":"female","married":0], ["name":"park","address":"Japan","gender":"female","married":0], ["name":"Daba","address":"Russia","gender":"male","married":1], ] } } extension ViewBasedTableViewController:NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { return datas.count } } extension ViewBasedTableViewController:NSTableViewDelegate { func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { // data let data = datas[row] // cell let key = (tableColumn?.identifier)! // cellvalue let value = data[key] // 根据列标示 创建单元视图 let view = tableView.makeView(withIdentifier: key, owner: self) // 获取所有子视图 let subviews = view?.subviews if (subviews?.count)! <= 0 { return nil } switch key.rawValue { case "name","address": let textField = subviews?[0] as! NSTextField if value != nil { textField.stringValue = value as! String } case "gender": let combox = subviews?[0] as! NSComboBox if value != nil { combox.stringValue = value as! String } case "married": let checked = subviews?[0] as! NSButton if value != nil { checked.state = NSControl.StateValue(value as! Int) } default: break } return view } // 定制选中样式 func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? { guard let rowView = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "rowView"), owner: self) as? CustomTableRowView else { let row = CustomTableRowView() row.identifier = NSUserInterfaceItemIdentifier(rawValue: "rowView") return row } return rowView } } // 定制选中样式 class CustomTableRowView: NSTableRowView { override func drawSelection(in dirtyRect: NSRect) { if selectionHighlightStyle != .none { // 绘制选中样式 NSColor.cyan.setFill() dirtyRect.fill() } } }
true
87b057eb8dfeac8e202715178c97e0e83a73aae2
Swift
YundoRocket/Delicatessen
/DLCommons/DLCommons/Extensions/UIKit/UIStackView.swift
UTF-8
759
2.796875
3
[]
no_license
// // UIStackView.swift // DLCommons // // Created by Bertrand BLOC'H on 01/12/2020. // import UIKit public extension UIStackView { convenience init(views: [UIView] = [], distribution: UIStackView.Distribution = .fill, alignment: UIStackView.Alignment = .fill, axis: NSLayoutConstraint.Axis, spacing: CGFloat = 0) { self.init(arrangedSubviews: views) self.distribution = distribution self.alignment = alignment self.axis = axis self.spacing = spacing } func removeAllArrangedSubviews() { arrangedSubviews.forEach { $0.removeFromSuperview() } } func addArrangedSubviews(_ views: [UIView]) { views.forEach { self.addArrangedSubview($0) } } }
true
decb06f3dbc9f1474db9e266a7cccaa021b8315e
Swift
pablosanchez027/PracticaTabs
/tabs/Models/Lugar.swift
UTF-8
753
2.734375
3
[]
no_license
// // Lugar.swift // tabs // // Created by Alumno on 26/09/18. // Copyright © 2018 Alumno. All rights reserved. // import Foundation import UIKit class Lugar { var nombreLugar : String var descripcionLugar : String var imagenLugar : UIImage var imagenDetalleLugar : UIImage init() { nombreLugar = "" descripcionLugar = "" imagenLugar = UIImage() imagenDetalleLugar = UIImage() } init(nombreLugar : String, descripcionLugar : String, imagenLugar : UIImage, imagenDetalleLugar : UIImage) { self.nombreLugar = nombreLugar self.descripcionLugar = descripcionLugar self.imagenLugar = imagenLugar self.imagenDetalleLugar = imagenDetalleLugar } }
true
83c5b13d7d39e8bf4efedd83f17e3ff4c5e68abe
Swift
ZouhirASSAIB/LBC
/LBC/LBC/Classes/Modules/Advertisements/Protocols/AdvertisementsProtocol.swift
UTF-8
2,903
2.8125
3
[]
no_license
// // AdvertisementsProtocol.swift // LBC // // Created by Zouhair ASSAIB on 05/03/2021. // import UIKit // MARK: View Output (Presenter -> View) protocol PresenterToViewAdvertisementsProtocol: class { func onFetchAdvertisementsSuccess() func onFetchAdvertisementsFailure(error: Error) func presentActivity() func dismissActivity() func deselectRowAt(row: Int) } // MARK: View Input (View -> Presenter) protocol ViewToPresenterAdvertisementsProtocol: class { var view: PresenterToViewAdvertisementsProtocol? { get set } var interactor: PresenterToInteractorAdvertisementsProtocol? { get set } var router: PresenterToRouterAdvertisementsProtocol? { get set } var advertisements: Advertisements? { get set } var categories: Categories? { get set } var categoryID: Int? { get set } func viewDidLoad() func refresh() func numberOfRowsInSection() -> Int func getAdvertisementImage(indexPath: IndexPath) -> URL? func getAdvertisementTitle(indexPath: IndexPath) -> String? func getAdvertisementPrice(indexPath: IndexPath) -> String? func getAdvertisementCreationDate(indexPath: IndexPath)-> String? func getAdvertisementCategoryName(indexPath: IndexPath)-> String? func isAdvertisementUrgent(indexPath: IndexPath)-> Bool? func didSelectRowAt(index: Int) func deselectRowAt(index: Int) func presentCategories() } // MARK: Interactor Input (Presenter -> Interactor) protocol PresenterToInteractorAdvertisementsProtocol: class { var presenter: InteractorToPresenterAdvertisementsProtocol? { get set } var advertisementsAPIService: AdvertisementsAPIServiceProtocol?{ get set } var categoriesAPIService: CategoriesAPIServiceProtocol?{ get set } var advertisements: Advertisements? { get set } var categories: Categories? { get set } func loadAdvertisements(categoryID: Int?) func retrieveAdvertisement(at index: Int) func presentCategories() } // MARK: Interactor Output (Interactor -> Presenter) protocol InteractorToPresenterAdvertisementsProtocol: class { func fetchAdvertisementsSuccess(advertisements: Advertisements) func fetchAdvertisementsFailure(error: Error) func getAdvertisementSuccess(_ advertisement: AdvertisementModel) func getAdvertisementFailure() func fetchCategoriesSuccess(categories: Categories) func getCategoriesSuccess(_ categories: Categories) } // MARK: Router Input (Presenter -> Router) protocol PresenterToRouterAdvertisementsProtocol: class { static func createModule() -> UINavigationController func presentAdvertisementDetail(on view: PresenterToViewAdvertisementsProtocol, with advertisement: AdvertisementModel) func presentCategories(on view: PresenterToViewAdvertisementsProtocol, with categories: Categories) }
true
95eaf341c94e50c583c2b60b461f292a317cc62a
Swift
gioe/FreeFi
/FreeFi/Controllers/LoginViewController.swift
UTF-8
3,520
2.671875
3
[]
no_license
// // LoginViewController.swift // FreeFi // // Created by Matt Gioe on 11/1/17. // Copyright © 2017 Matt Gioe. All rights reserved. // import UIKit class LoginViewController: UIViewController { let appIcon: UIImageView = { let imageView = UIImageView() let wifiImage = UIImage(named: "wifi") imageView.image = wifiImage imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() let signupButton: UIButton = { let button = UIButton() button.backgroundColor = .black button.setTitle("Sign Up", for: .normal) let orange = UIColor(red: 234, green: 91, blue: 0, alpha: 1) button.setTitleColor(orange, for: .normal) button.addTarget(self, action: #selector(signup), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false button.clipsToBounds = true button.layer.cornerRadius = 25 return button }() let loginButton: UIButton = { let button = UIButton() button.backgroundColor = .black button.setTitle("Log In", for: .normal) let orange = UIColor(red: 234, green: 91, blue: 0, alpha: 1) button.setTitleColor(orange, for: .normal) button.addTarget(self, action: #selector(login), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false button.clipsToBounds = true button.layer.cornerRadius = 25 return button }() override func viewDidLoad() { super.viewDidLoad() let backgroundColor = UIColor(red: 202/255, green: 187/255, blue: 154/255, alpha: 1) view.backgroundColor = backgroundColor setupViews() setupConstraints() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupViews() { [appIcon, loginButton, signupButton].forEach{ view.addSubview($0) } } func setupConstraints() { appIcon.heightAnchor.constraint(equalToConstant: 200).isActive = true appIcon.widthAnchor.constraint(equalToConstant: 200).isActive = true appIcon.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true appIcon.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true loginButton.topAnchor.constraint(equalTo: appIcon.bottomAnchor, constant: 50).isActive = true loginButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30).isActive = true loginButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30).isActive = true loginButton.heightAnchor.constraint(equalToConstant: 50).isActive = true signupButton.topAnchor.constraint(equalTo: loginButton.bottomAnchor, constant: 30).isActive = true signupButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30).isActive = true signupButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30).isActive = true signupButton.heightAnchor.constraint(equalToConstant: 50).isActive = true } @objc private func login() { let mapView = MapViewController() navigationController?.pushViewController(mapView, animated: true) } @objc private func signup() { print("Signup") } }
true
f4b5767cd605059082aad3459a8f80d56066d1a1
Swift
BlackHatzz/CoolDeal
/CoolDeal/Views/CategoriesCollectionView.swift
UTF-8
2,258
2.6875
3
[]
no_license
// // CategoriesCollectionView.swift // CoolDeal // // Created by Nguyễn Đức Huy on 1/15/21. // Copyright © 2021 Nguyễn Đức Huy. All rights reserved. // import UIKit //UICollectionViewFlowLayout class CategoriesCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var data: [(imageName: String, title: String)] = [ ("food", "Food"), ("bag", "Bag"), ("book", "Book"), ("clothes", "Clothes"), ("shoe", "Shoe"), ("hotel&resort", "Relaxation"), ("technology", "Technology"), ("traveling", "Traveling") ] func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 8 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CategoryCell.cellId, for: indexPath) as! CategoryCell cell.categoryBlockView.imageView.image = UIImage(named: data[indexPath.row].imageName) cell.categoryBlockView.titleLabel.text = data[indexPath.row].title return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 80, height: 80) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 5 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 5 } override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) register(CategoryCell.self, forCellWithReuseIdentifier: CategoryCell.cellId) self.delegate = self self.dataSource = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
8b96d64bd5e53cc346a3759ee5b6df533e97bb91
Swift
NewPointe/NP-Kiosk-iOS
/NPKiosk/WebView/Plugins/RpcClient/Data/RpcData.swift
UTF-8
1,913
2.78125
3
[ "MIT" ]
permissive
// // RpcData.swift // NPKiosk // // Created by Tyler Schrock on 5/13/20. // Copyright © 2020 NewPointe Community Church. All rights reserved. // import Foundation /// An RPC request struct RpcRequest<T> { let jsonrpc: String = "2.0" let id: RpcIdentifier? let method: String let params: RpcParameters<T> } extension RpcRequest: Encodable where T: Encodable { } extension RpcRequest: Decodable where T: Decodable { } /// An RPC response with a result struct RpcResponseWithResult<T> { let jsonrpc: String = "2.0" let id: RpcIdentifier let result: T } extension RpcResponseWithResult: Encodable where T: Encodable { } extension RpcResponseWithResult: Decodable where T: Decodable { } /// An RPC response with an error struct RpcResponseWithError<T> where T: AnyRpcError { let jsonrpc: String = "2.0" let id: RpcIdentifier let error: T } extension RpcResponseWithError: Encodable where T: Encodable { } extension RpcResponseWithError: Decodable where T: Decodable { } /// Any RPC error protocol AnyRpcError: Error { var code: Int { get } var message: String { get } } /// An RPC error with no additional data struct RpcError: AnyRpcError, Codable { let code: Int let message: String } /// An RPC error with additional data struct RpcErrorWithData<T>: AnyRpcError { let code: Int let message: String let data: T } extension RpcErrorWithData: Encodable where T: Encodable { } extension RpcErrorWithData: Decodable where T: Decodable { } /// An encodable wrapper for encoding any Encodable struct AnyEncodable: Encodable { let value: Encodable func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try value.encode(to: &container) } } extension Encodable { func encode(to container: inout SingleValueEncodingContainer) throws { try container.encode(self) } }
true
71267806313f01428aa999b917c675e7dd83be9a
Swift
thachgiasoft/SwiftUI_Views
/SwiftUI_Views/OtherViews/Color/Color_ColorMultiply.swift
UTF-8
1,988
3.328125
3
[]
no_license
// // Color_2_00_ColorMultiply.swift // 100Views // // Created by Mark Moeykens on 6/18/19. // Copyright © 2019 Mark Moeykens. All rights reserved. // import SwiftUI struct Color_2_00_ColorMultiply : View { var body: some View { VStack(spacing: 40) { Text("Color") .font(.largeTitle) Text("Color Multiply") .font(.title) .foregroundColor(.gray) Text("You can combine colors to form new colors with the color multiply modifier.") .frame(maxWidth: .infinity) .padding() .background(Color.orange) .foregroundColor(Color.black) .font(.title) .layoutPriority(1) HStack { Color.pink .frame(width: 88, height: 88) Image(systemName: "plus") .font(.title) Color.blue .frame(width: 88, height: 88) Image(systemName: "equal") .font(.title) Color.pink.colorMultiply(Color.blue) .frame(width: 88, height: 88) } HStack { Color.yellow .frame(width: 88, height: 88) Image(systemName: "plus") .font(.title) Color.blue .frame(width: 88, height: 88) Image(systemName: "equal") .font(.title) Color.yellow.colorMultiply(Color.blue) .frame(width: 88, height: 88) } HStack { Color.yellow .frame(width: 88, height: 88) Image(systemName: "plus") .font(.title) Color.red .frame(width: 88, height: 88) Image(systemName: "equal") .font(.title) Color.yellow.colorMultiply(Color.red) .frame(width: 88, height: 88) } } } } #if DEBUG struct Color_2_00_ColorMultiply_Previews : PreviewProvider { static var previews: some View { Color_2_00_ColorMultiply() } } #endif
true
8ef3292d0236787765a01279bb69f55de6f5c67d
Swift
kondranton/tilcher
/TiLcher/Module/Authorization/Pages/UserType/UserTypeViewController.swift
UTF-8
902
2.59375
3
[]
no_license
import SnapKit final class UserTypeViewController: UIViewController { var onBack: () -> Void var onNext: (UserRole) -> Void init( onBack: @escaping () -> Void, onNext: @escaping (UserRole) -> Void ) { self.onBack = onBack self.onNext = onNext super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { let view = UIView() let subview = UserTypeView( onNextTap: { [weak self] selectedIndex in self?.onNext(selectedIndex == 0 ? .stylist : .consumer) }, onBackTap: onBack ) view.addSubview(subview) subview.snp.makeConstraints { make in make.edges.equalToSuperview() } self.view = view } }
true
0a0f94353380e40d04f8b7b568f85a48d75bd854
Swift
kanesornkamthawee/Ishihara
/Ishihara/ViewController.swift
UTF-8
1,729
2.828125
3
[]
no_license
// // ViewController.swift // Ishihara // // Created by iMac12 on 6/22/2559 BE. // Copyright © 2559 iMac12. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var ishiharaImageView: UIImageView! @IBOutlet weak var answerTextField: UITextField! //Explicit var strAnswer:String = "0" var intIndex:Int = 0 var arrayImage = ["ishihara_01.png","ishihara_02.png","ishihara_03.png","ishihara_04.png","ishihara_05.png", "ishihara_06.png","ishihara_07.png","ishihara_08.png","ishihara_09.png","ishihara_10.png"] var myAnswer = ["3","5","6","12","29","45","75","42","0","0"] var score:Int = 0 var myMaster = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } //Main Func override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //didReceive @IBAction func answerButton(sender: AnyObject) { strAnswer = String(answerTextField.text) print("strAnswer ==> \(strAnswer)") if (intIndex <= 9) { intIndex += 1 }else{ intIndex = 0 } print("intIndex ==> \(intIndex)") ishiharaImageView.image = UIImage(named: arrayImage[intIndex]) if (strAnswer == myAnswer[intIndex]) { score += 1 print("Score ==> \(score)") } } //answerButton }//Main Class
true
2ee3b9b007df42a34e69e2a8457a4a5252ad9034
Swift
rjbritt/Curiosities
/Curiosities/Curiosities.swift
UTF-8
1,581
3.265625
3
[]
no_license
// // Item.swift // Curiosity // // import UIKit class CuriositySpriteNode: SKSpriteNode { /// An effect that is stored as a closure for later use. var storedEffect:(() -> ())? /** Class method that generates a Curiosity "orb" with a particular color. These orbs are used as generic items that can have any stored effect and will have an automatic pulsing action. - parameter color: UIColor to make the orb - returns: An ItemSpriteNode that is configured as a circular orb with a forever pulsing action. */ class func orbItemWithColor(_ color:UIColor) -> CuriositySpriteNode { let image = UIImage(named: "spark") let tempItem = CuriositySpriteNode(texture: SKTexture(image: image!)) tempItem.physicsBody = SKPhysicsBody(texture: tempItem.texture!, alphaThreshold: 0.9, size: tempItem.size) tempItem.physicsBody?.isDynamic = false tempItem.physicsBody?.categoryBitMask = PhysicsCategory.item.rawValue tempItem.physicsBody?.collisionBitMask = PhysicsCategory.character.rawValue tempItem.physicsBody?.contactTestBitMask = PhysicsCategory.character.rawValue tempItem.color = color tempItem.colorBlendFactor = 0.8 let pulse = SKAction.repeatForever(SKAction.sequence([SKAction.scale(by: 2.0, duration: 1), SKAction.scale(to: 1.0, duration: 1)])) tempItem.run(pulse) return tempItem } }
true
c1422376e3a7bd011183b2dd587fb8d42d54622e
Swift
mhelvey/IS543
/Scripture Maps/GeoPlace.swift
UTF-8
3,077
3.078125
3
[]
no_license
// // GeoPlace.swift // Map Scriptures // // Created by Steve Liddle on 11/5/14. // Copyright (c) 2014 IS 543. All rights reserved. // import Foundation import SQLite class GeoPlace { enum GeoCategory: Int { // Categories represent geocoded places we've constructed from various // Church history sources (1) or the Open Bible project (2) case ChurchHistory = 1, OpenBible = 2 } enum GeoFlag: String { // Flags indicate different levels of certainty in the Open Bible database case None = "", Open1 = "~", Open2 = ">", Open3 = "?", Open4 = "<", Open5 = "+" } var id: Int! var placename: String! var latitude: Double! var longitude: Double! var flag: GeoFlag! var viewLatitude: Double? var viewLongitude: Double? var viewTilt: Double? var viewRoll: Double? var viewAltitude: Double? var viewHeading: Double? var category: GeoCategory! init(fromRow: Row) { id = fromRow.get(gGeoTagGeoPlaceId) placename = fromRow.get(gGeoPlacePlacename) latitude = fromRow.get(gGeoPlaceLatitude) longitude = fromRow.get(gGeoPlaceLongitude) category = GeoCategory(rawValue: fromRow.get(gGeoPlaceCategory)!) if let geoFlag = fromRow.get(gGeoPlaceFlag) { flag = GeoFlag(rawValue: geoFlag)! } else { flag = GeoFlag.None } if let vLatitude = fromRow.get(gGeoPlaceViewLatitude) { viewLatitude = vLatitude viewLongitude = fromRow.get(gGeoPlaceViewLongitude) viewTilt = fromRow.get(gGeoPlaceViewTilt) viewRoll = fromRow.get(gGeoPlaceViewRoll) viewAltitude = fromRow.get(gGeoPlaceViewAltitude) viewHeading = fromRow.get(gGeoPlaceViewHeading) } } // class func fromTagRow(geoRecord: Row) -> GeoPlace { // var geoplace = GeoPlace() // // geoplace.id = geoRecord.get(gGeoTagGeoPlaceId)! // geoplace.placename = geoRecord.get(gGeoPlacePlacename)! // geoplace.latitude = geoRecord.get(gGeoPlaceLatitude)! // geoplace.longitude = geoRecord.get(gGeoPlaceLongitude)! // geoplace.category = GeoCategory(rawValue: geoRecord.get(gGeoPlaceCategory)!) // // if let flag = geoRecord.get(gGeoPlaceFlag) { // geoplace.flag = GeoFlag(rawValue: flag) // } else { // geoplace.flag = GeoFlag.None // } // // if let viewLatitude = geoRecord.get(gGeoPlaceViewLatitude) { // geoplace.viewLatitude = viewLatitude // geoplace.viewLongitude = geoRecord.get(gGeoPlaceViewLongitude) // geoplace.viewTilt = geoRecord.get(gGeoPlaceViewTilt) // geoplace.viewRoll = geoRecord.get(gGeoPlaceViewRoll) // geoplace.viewAltitude = geoRecord.get(gGeoPlaceViewAltitude) // geoplace.viewHeading = geoRecord.get(gGeoPlaceViewHeading) // } // // return geoplace // } }
true
7304545dbdc1337ee928318873a1fbc75b923495
Swift
Laithmiehiar/OnlineTestSystem-AdminPortal-iOS
/MUM-CareetTest-AdminPortal/Model/SubCategory.swift
UTF-8
671
2.609375
3
[]
no_license
// // SubCategory.swift // MUM-CareetTest-AdminPortal // // Created by Laith Mihyar on 10/10/17. // Copyright © 2017 Laith Miehiar. All rights reserved. // import Foundation struct SubCategory { var id: Int var name: String var enabled: Bool var categoryId: Int var questionCount: Int var category: String init(json: [String: Any]) { id = json["id"] as? Int ?? -1 name = json["name"] as? String ?? "" enabled = json["enabled"] as? Bool ?? false categoryId = json["categoryId"] as? Int ?? -1 questionCount = json["questionCount"] as? Int ?? -1 category = json["category"] as? String ?? "" } }
true
7e88b48ecf484ada10f0eb3f03479f8dd034b52c
Swift
timlaieng/airmilesiOS
/MileageCalculator/AirportSelectTableViewController.swift
UTF-8
3,968
2.765625
3
[]
no_license
// // AirportSelectTableViewController.swift // MileageCalculator // // Created by Tim Lai on 25/09/2017. // Copyright © 2017 Tim Lai. All rights reserved. // import UIKit import Foundation let airports = AirportsModel() class AirportSelectTableViewController: UITableViewController { let sectionTitles = ["A", "B", "C"] override func viewDidLoad() { super.viewDidLoad() tableView.reloadData() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { return sectionTitles.index(of: title)! } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return airports.airportsArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "AirportCell", for: indexPath) let airport = airports.airportsArray[indexPath.row] cell.textLabel?.text = airport.IATA cell.detailTextLabel?.text = "\(airport.name), \(airport.city), \(airport.country)" return cell } override func sectionIndexTitles(for tableView: UITableView) -> [String]? { return sectionTitles } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let selectedIndexPath = tableView.indexPathForSelectedRow else {return} let selectedAirport = airports.airportsArray[selectedIndexPath.row] let mainViewController = segue.destination as? MainViewController mainViewController?.departureAirportTextField.text = selectedAirport.IATA // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } }
true
1d986443b8b6b021d439b03806259dba4f4a11c3
Swift
candostdagdeviren/SwiftBackend
/Sources/SwiftBackendLib/DatabaseInteraction.swift
UTF-8
1,256
3.03125
3
[]
no_license
import Foundation import CouchDB import SwiftyJSON public struct DatabaseInteraction { var db: Database public init(db: Database) { self.db = db } func addNewUser(_ user: User, handler: @escaping (String?, String?, JSON?, NSError?) -> ()) { let userDict: [String: Any] = [ "username": user.name, "userId": user.id ] let userJSON = JSON(userDict) db.create(userJSON) { (id, revision, doc, error) in if let error = error { print("oops something went wrong error: \(error)") handler(nil, nil, nil, error) return } else { handler(id, revision, doc, nil) } } } func getUser(with id: String, handler: @escaping (String?, JSON?, NSError?) -> ()) { db.retrieve(id as String, callback: { (document: JSON?, error: NSError?) in if let error = error { print("Oops something went wrong; could not read document.") print("Error: \(error.localizedDescription) Code: \(error.code)") handler(id, nil, error) } else { print(">> Successfully read the following JSON document with ID " + "\(id) from CouchDB:\n\t\(document)") handler(id, document, nil) } }) } }
true
d04ead8a7718b8fc3155199d3c924330200c781b
Swift
moKelani/MovieApp
/MovieApp/Movie/Model/Movie.swift
UTF-8
385
2.546875
3
[]
no_license
// // Movie.swift // ProtocolBasedNetworkingTutorialFinal // // Created by James Rochabrun on 11/27/17. // Copyright © 2017 James Rochabrun. All rights reserved. // import Foundation struct Movie: Decodable { let id: Int? let title: String? let poster_path: String? let overview: String? let releaseDate: String? let backdrop_path: String? let release_date: String? }
true
2b21be8efa53a1441ab30dadfd03ca99c56b9785
Swift
Andrewtcr/dicteeapp
/dicteeapp/RecordUIViewControl.swift
UTF-8
7,325
2.515625
3
[]
no_license
// // RecordUIViewControl.swift // demoone // // Created by Yu Sun on 7/3/18. // Copyright © 2018 Yu Sun. All rights reserved. // import UIKit import AVFoundation import FirebaseDatabase import FirebaseStorage class RecordUIViewControl: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate { @IBOutlet weak var numTextView: UILabel! @IBOutlet weak var answerTextView: UITextField! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var recordButton: UIButton! let storage = Storage.storage() var ref: DatabaseReference! var index: Int = 1 var soundRecorder : AVAudioRecorder! var recordingSession: AVAudioSession! var SoundPlayer : AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. recordingSession = AVAudioSession.sharedInstance() ref = Database.database().reference() let storageRef = storage.reference() do { try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord, mode: AVAudioSessionModeSpokenAudio, options: []) try recordingSession.setActive(true) recordingSession.requestRecordPermission() { [unowned self] allowed in DispatchQueue.main.async { if allowed { // print("OK Ready to record") } else { // failed to record! } } } } catch { // failed to record! } //setupRecorder() } @IBAction func onPlayClicked(_ sender: UIButton) { if sender.titleLabel?.text == "Play" { recordButton.isEnabled = false sender.setTitle("Stop", for: UIControlState.normal) preparePlayer() SoundPlayer.play() } else { SoundPlayer.stop() sender.setTitle("Play", for: UIControlState.normal) } } @IBAction func onRecordClicked(_ sender: UIButton) { if sender.titleLabel?.text == "Record"{ setupRecorder() //soundRecorder.record() sender.setTitle("Stop", for: UIControlState.normal) playButton.isEnabled = false } else { soundRecorder.stop() sender.setTitle("Record", for: UIControlState.normal) playButton.isEnabled = true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupRecorder() { let recordSettings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.m4a") do { soundRecorder = try AVAudioRecorder(url: audioFilename, settings: recordSettings) soundRecorder.delegate = self soundRecorder.record() } catch { finishRecording(success: false) } } func finishRecording(success: Bool) { soundRecorder.stop() soundRecorder = nil if success { recordButton.setTitle("Tap to Re-record", for: .normal) } else { recordButton.setTitle("Tap to Record", for: .normal) // recording failed :( } } func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return paths[0] } func preparePlayer() { var error : NSError? do { let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.m4a") SoundPlayer = try AVAudioPlayer(contentsOf: audioFilename) } catch { print("Failed to play") } if let err = error { NSLog("Failed to play") } else { SoundPlayer.delegate = self SoundPlayer.prepareToPlay() SoundPlayer.volume = 1.0 } } func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { playButton.isEnabled = true } func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { recordButton.isEnabled = true playButton.setTitle("Play", for:UIControlState.normal) } @IBAction func onSubmitClicked(_ sender: UIButton) { // Create a root reference let storageRef = storage.reference() // Create a reference to "mountains.jpg" //let mountainsRef = storageRef.child("mountains.jpg") // Create a reference to 'images/mountains.jpg' //let mountainImagesRef = storageRef.child("images/mountains.jpg") // While the file names are the same, the references point to different files //mountainsRef.name == mountainImagesRef.name; // true //mountainsRef.fullPath == mountainImagesRef.fullPath; // false // File located on disk // let localFile = URL(string: "path/to/image")! let localFile = getDocumentsDirectory().appendingPathComponent("recording.m4a") // Create a reference to the file you want to upload let riversRef = storageRef.child("tests-audio/recording" + UUID().uuidString + ".m4a") // Upload the file to the path "images/rivers.jpg" let uploadTask = riversRef.putFile(from: localFile, metadata: nil) uploadTask.observe(.success) { snapshot in // Upload completed successfully print("Successfully uploaded!") riversRef.downloadURL { (url, error) in print(url) guard let downloadURL = url else { // Uh-oh, an error occurred! print("Error in here") return } print(downloadURL.absoluteString) var title = self.title! self.ref.child("myfirstios/" + title + "/" + String(self.index) + "/title").setValue(NSDate().timeIntervalSince1970) self.ref.child("myfirstios/" + title + "/" + String(self.index) + "/answer").setValue(self.answerTextView.text) self.ref.child("myfirstios/" + title + "/" + String(self.index) + "/url").setValue(downloadURL.absoluteString) self.index += 1 self.numTextView.text = "Question " + String(self.index) // resetup all text self.answerTextView.text = "" } } } /* // 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
12b474a6173c6ee8315a0799f9d72c97d67a880f
Swift
ra1028/monkey-lang-swift
/Sources/Parser/Parser.swift
UTF-8
12,356
3.078125
3
[ "MIT" ]
permissive
import Token import Lexer import AST public struct Parser { public var lexer: Lexer public var currentToken: Token public var peekToken: Token public var errors: [ParseError] public init(input: String) { let lexer = Lexer(input: input) self.init(lexer: lexer) } public init(lexer: Lexer) { self.lexer = lexer self.currentToken = self.lexer.nextToken() self.peekToken = self.lexer.nextToken() self.errors = [] } public mutating func parse() -> Program { var statements = [Statement]() while currentToken.kind != .eof { if let statement = parseStatement() { statements.append(statement) } nextToken() } return Program(statements: statements) } } private extension Parser { mutating func nextToken() { currentToken = peekToken peekToken = lexer.nextToken() } mutating func parseStatement() -> Statement? { switch currentToken.kind { case .let: return parseLetStatement() case .return: return parseReturnStatement() default: return parseExpressionStatement() } } mutating func parseLetStatement() -> LetStatement? { let token = currentToken guard expectPeek(kind: .identifier) else { return nil } let name = parseIdentifierExpression() guard expectPeek(kind: .assign) else { return nil } nextToken() guard let value = parseExpression(precendence: .lowest) else { errors.append(.initialValueNotFound(name: name)) return nil } if currentToken.kind == .semicolon { nextToken() } return LetStatement(token: token, name: name, value: value) } mutating func parseReturnStatement() -> ReturnStatement? { let token = currentToken nextToken() guard let returnValue = parseExpression(precendence: .lowest) else { errors.append(.returnValueNotFound) return nil } if currentToken.kind == .semicolon { nextToken() } return ReturnStatement(token: token, returnValue: returnValue) } mutating func parseExpressionStatement() -> ExpressionStatement? { let token = currentToken let expression = parseExpression(precendence: .lowest) if peekToken.kind == .semicolon { nextToken() } return expression.map { expression in ExpressionStatement(token: token, expression: expression) } } mutating func parseBlockStatement() -> BlockStatement? { let token = currentToken var statements = [Statement]() nextToken() while currentToken.kind != .rBrace && currentToken.kind != .eof { if let statement = parseStatement() { statements.append(statement) } nextToken() } return BlockStatement(token: token, statements: statements) } mutating func parseExpression(precendence: Precedence) -> Expression? { var expression: Expression? switch currentToken.kind { case .identifier: expression = parseIdentifierExpression() case .int: expression = parseIntegerExpression() case .string: expression = parseStringExpression() case .true, .false: expression = parseBooleanExpression() case .bang, .minus: expression = parsePrefixExpression() case .lParen: expression = parseGroupedExpreession() case .if: expression = parseIfExpression() case .function: expression = parseFunctionExpression() case .lBracket: expression = parseArrayExpression() case .lBrace: expression = parseHashExpression() default: return nil } while let left = expression, peekToken.kind != .semicolon && precendence < peekToken.kind.precedence { switch peekToken.kind { case .plus, .minus, .slash, .asterisk, .eq, .notEq, .lt, .gt: nextToken() expression = parseInfixExpression(left: left) case .lParen: nextToken() expression = parseCallExpression(function: left) case .lBracket: nextToken() expression = parseIndexExpression(left: left) default: return expression } } return expression } mutating func parseGroupedExpreession() -> Expression? { nextToken() let expression = parseExpression(precendence: .lowest) guard expectPeek(kind: .rParen) else { return nil } return expression } mutating func parseIdentifierExpression() -> IdentifierExpression { return IdentifierExpression(token: currentToken) } mutating func parseIntegerExpression() -> IntegerExpression? { let token = currentToken guard let value = Int64(token.literal) else { errors.append(.illegalCharacterFoundInIntegerLiteral(token.literal)) return nil } return IntegerExpression(token: token, value: value) } mutating func parseStringExpression() -> StringExpression { return StringExpression(token: currentToken) } mutating func parseBooleanExpression() -> BooleanExpression? { let token = currentToken guard let value = Bool(token.literal) else { errors.append(.illegalCharacterFoundInBooleanLiteral(token.literal)) return nil } return BooleanExpression(token: token, value: value) } mutating func parsePrefixExpression() -> PrefixExpression? { let token = currentToken let `operator` = token.literal nextToken() guard let right = parseExpression(precendence: .prefix) else { errors.append(.prefixOperatorRightValueNotFound(operator: `operator`)) return nil } return PrefixExpression(token: token, operator: `operator`, right: right) } mutating func parseInfixExpression(left: Expression) -> InfixExpression? { let token = currentToken let `operator` = token.literal let precedence = currentToken.kind.precedence nextToken() guard let right = parseExpression(precendence: precedence) else { errors.append(.infixOperatorRightValueNotFound(operator: `operator`)) return nil } return InfixExpression(token: token, left: left, operator: `operator`, right: right) } mutating func parseIfExpression() -> IfExpression? { let token = currentToken guard expectPeek(kind: .lParen) else { return nil } nextToken() guard let condition = parseExpression(precendence: .lowest) else { return nil } guard expectPeek(kind: .rParen) else { return nil } guard expectPeek(kind: .lBrace) else { return nil } guard let consequence = parseBlockStatement() else { return nil } let alternative: BlockStatement? if peekToken.kind == .else { nextToken() alternative = expectPeek(kind: .lBrace) ? parseBlockStatement() : nil } else { alternative = nil } return IfExpression( token: token, condition: condition, consequence: consequence, alternative: alternative ) } mutating func parseFunctionExpression() -> FunctionExpression? { let token = currentToken guard expectPeek(kind: .lParen) else { return nil } let parameters = parseFunctionParameterExpressions() guard expectPeek(kind: .lBrace) else { return nil } guard let body = parseBlockStatement() else { return nil } return FunctionExpression( token: token, parameters: parameters, body: body ) } mutating func parseFunctionParameterExpressions() -> [IdentifierExpression] { guard peekToken.kind != .rParen else { nextToken() return [] } nextToken() var parameters = [parseIdentifierExpression()] while peekToken.kind == .comma { nextToken() nextToken() parameters.append(parseIdentifierExpression()) } guard expectPeek(kind: .rParen) else { return [] } return parameters } mutating func parseCallExpression(function: Expression) -> CallExpression { let token = currentToken let arguments = parseExpressionList(endTokenKind: .rParen) return CallExpression(token: token, function: function, arguments: arguments) } mutating func parseArrayExpression() -> ArrayExpression { let token = currentToken let elements = parseExpressionList(endTokenKind: .rBracket) return ArrayExpression(token: token, elements: elements) } mutating func parseExpressionList(endTokenKind: TokenKind) -> [Expression] { guard peekToken.kind != endTokenKind else { nextToken() return [] } nextToken() guard let firstArgument = parseExpression(precendence: .lowest) else { return [] } var arguments = [firstArgument] while peekToken.kind == .comma { nextToken() nextToken() if let expression = parseExpression(precendence: .lowest) { arguments.append(expression) } } guard expectPeek(kind: endTokenKind) else { return [] } return arguments } mutating func parseIndexExpression(left: Expression) -> IndexExpression? { let token = currentToken nextToken() guard let index = parseExpression(precendence: .lowest) else { return nil } if !expectPeek(kind: .rBracket) { return nil } return IndexExpression(token: token, left: left, index: index) } mutating func parseHashExpression() -> HashExpression? { let token = currentToken var pairs = [(key: Expression, value: Expression)]() while peekToken.kind != .rBrace { nextToken() guard let key = parseExpression(precendence: .lowest) else { return nil } guard expectPeek(kind: .colon) else { return nil } nextToken() guard let value = parseExpression(precendence: .lowest) else { return nil } pairs.append((key, value)) if peekToken.kind != .rBrace && !expectPeek(kind: .comma) { return nil } } if !expectPeek(kind: .rBrace) { return nil } return HashExpression(token: token, pairs: pairs) } mutating func expectPeek(kind: TokenKind) -> Bool { if peekToken.kind == kind { nextToken() return true } else { errors.append(.invalidTokenFound(expected: kind, got: peekToken.kind)) return false } } } private extension TokenKind { var precedence: Precedence { switch self { case .eq, .notEq: return .equals case .lt, .gt: return .lessGreater case .plus, .minus: return .sum case .slash, .asterisk: return .product case .lParen: return .call case .lBracket: return .index default: return .lowest } } }
true
7dc2af7ba5d70b79127c55cabedd94deedb4e7b7
Swift
dankinsoid/VDCodable
/Sources/VDCodable/Utils/Int++.swift
UTF-8
1,389
3.21875
3
[ "MIT" ]
permissive
// // Int++.swift // Coders // // Created by Данил Войдилов on 23/12/2018. // Copyright © 2018 daniil. All rights reserved. // import Foundation protocol SignedBitPatternInitializable: FixedWidthInteger, SignedInteger where Self.Magnitude: UnsignedBitPatternInitializable, Self.Magnitude.Signed == Self { init(bitPattern: Magnitude) } protocol UnsignedBitPatternInitializable: FixedWidthInteger, UnsignedInteger where Signed.Magnitude == Self { associatedtype Signed: SignedBitPatternInitializable init(bitPattern: Signed) } extension Int: SignedBitPatternInitializable {} extension Int8: SignedBitPatternInitializable {} extension Int16: SignedBitPatternInitializable {} extension Int32: SignedBitPatternInitializable {} extension Int64: SignedBitPatternInitializable {} extension UInt: UnsignedBitPatternInitializable { typealias Signed = Int } extension UInt8: UnsignedBitPatternInitializable { typealias Signed = Int8 } extension UInt16: UnsignedBitPatternInitializable { typealias Signed = Int16 } extension UInt32: UnsignedBitPatternInitializable { typealias Signed = Int32 } extension UInt64: UnsignedBitPatternInitializable { typealias Signed = Int64 } extension Decimal { public var fractionLength: Int { return max(-exponent, 0) } } extension Double { init(_ value: Decimal) { self = (value as NSDecimalNumber).doubleValue } }
true
4f33d6440a43b37249f8196ae284c93c26476fcf
Swift
Abdelrahman001/Marasi
/Marasi/Networking/TargetType.swift
UTF-8
729
3
3
[]
no_license
// // TargetType.swift // Marasi // // Created by Abdelrahman Hassan on 12/11/2021. // import Foundation enum HTTPMethod: String { case get = "GET" case post = "POST" case put = "PUT" case delete = "DELETE" } enum Task { /// A request with no additional data. case requestPlain } protocol TargetType { var baseURL: URLEnvironment { get } /// The path to be appended to `baseURL` to form the full `URL`. var path: URLs.Paths { get } /// The HTTP method used in the request. var method: HTTPMethod { get } /// The type of HTTP task to be performed. var task: Task { get } /// The headers to be used in the request. var headers: [String: String]? { get } }
true
ba8e4081f032051ca83305dd9ed05a5af296d8b2
Swift
trannhanbk/Mapdemo
/MapViewDemo/CircleView/CircleView.swift
UTF-8
1,039
2.9375
3
[]
no_license
// // CircleView.swift // MapViewDemo // // Created by Nhan Tran D on 6/26/19. // Copyright © 2019 MBA0145. All rights reserved. // import UIKit class CircleView : UIView { var outGoingLine : CAShapeLayer? var inComingLine : CAShapeLayer? var inComingCircle : CircleView? var outGoingCircle : CircleView? override init(frame: CGRect) { super.init(frame: frame) self.layer.cornerRadius = self.frame.size.width / 2 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func lineTo(circle: CircleView) -> CAShapeLayer { let path = UIBezierPath() path.move(to: self.center) path.addLine(to: circle.center) let line = CAShapeLayer() line.path = path.cgPath line.lineWidth = 3 line.strokeColor = UIColor.blue.cgColor circle.inComingLine = line outGoingLine = line outGoingCircle = circle circle.inComingCircle = self return line } }
true
43a2f897a43d630eddf29df90893256a51ad1a9c
Swift
mcheng8/KWK_2020
/D3.L7 - Classes&Objects - Projects/PackerExample/PackerExample/Packer.swift
UTF-8
496
3.546875
4
[]
no_license
class PackerC { // Step 1. Declaring a class let containerType = "can" // Step 2. Defining constant and varying properties var stuffInside : String init(itemType : String){ // Step 3. Assigning a Varying Property with an Initializer stuffInside = itemType } func description() { // Step 4. Declaring the function print("A \(stuffInside) will pop out of the \(containerType)") } }
true
33a07717ccbb934dffdc5974be61cf53fcd6d697
Swift
lxj916904395/CommandPattern2Swift
/命令模式2swift/Simple1/DynamicInvoker.swift
UTF-8
1,092
3.0625
3
[]
no_license
// // DynamicInvoker.swift // 命令模式2swift // // Created by lxj on 2018/6/30. // Copyright © 2018年 zhongding. All rights reserved. // import Foundation class DynamicInvoker: NSObject { private var receiver:TMMachie private var commands = Array<TMCommandProtocol>() init(receiver:TMMachie) { self.receiver = receiver; } func toLeft() { self.receiver.toLeft(s:"ss") self.addCommand(method: TMMachie.toLeft) } func toRight(){ self.receiver.toRight(s:"ss") self.addCommand(method: TMMachie.toRight) } func addCommand(method:@escaping (TMMachie)->(String)->(Void)) { self.commands.append(DynamicCommand(receiver: self.receiver, block: { (tm) in method(tm)("哈哈") })) } func undo() { if self.commands.count > 0 { self.commands.removeLast().execute() } } func undoAll(){ for command in self.commands { command.execute() } self.commands.removeAll() } }
true
6ab33ee15dace87059b6932ab58461f0436e793d
Swift
LysenkoOleg/ColorView
/ColorView/ColorView.swift
UTF-8
955
3.71875
4
[]
no_license
// // ColorView.swift // ColorView // // Created by Олег Лысенко on 31.10.2021. // import SwiftUI struct ColorView: View { private var red: Double private var green: Double private var blue: Double private var opacity: Double init(red: Double, green: Double, blue: Double, opacity: Double) { self.red = red self.green = green self.blue = blue self.opacity = opacity } var body: some View { Color(red: red/255, green: green/255, blue: blue/255, opacity: opacity) .frame(width: 350.0, height: 150.0) .cornerRadius(20) .overlay( RoundedRectangle(cornerRadius: 20) .stroke(lineWidth: 4) .foregroundColor(.white) ) } } struct ColorView_Previews: PreviewProvider { static var previews: some View { ColorView(red: 1.0, green: 1.0, blue: 1.0, opacity: 1.0) } }
true
8a1b55c95a52eff59a560e2b3f15c135f815fe4a
Swift
widget-/XMLCoder
/Sources/XMLCoder/Decoder/XMLUnkeyedDecodingContainer.swift
UTF-8
8,946
2.90625
3
[ "MIT" ]
permissive
// // XMLUnkeyedDecodingContainer.swift // XMLCoder // // Created by Shawn Moore on 11/21/17. // Copyright © 2017 Shawn Moore. All rights reserved. // import Foundation struct _XMLUnkeyedDecodingContainer: UnkeyedDecodingContainer { // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: _XMLDecoder /// A reference to the container we're reading from. private let container: UnkeyedBox /// The path of coding keys taken to get to this point in decoding. public private(set) var codingPath: [CodingKey] /// The index of the element we're about to decode. public private(set) var currentIndex: Int // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. init(referencing decoder: _XMLDecoder, wrapping container: UnkeyedBox) { self.decoder = decoder self.container = container codingPath = decoder.codingPath currentIndex = 0 } // MARK: - UnkeyedDecodingContainer Methods public var count: Int? { return container.count } public var isAtEnd: Bool { return currentIndex >= count! } public mutating func decodeNil() throws -> Bool { guard !isAtEnd else { throw DecodingError.valueNotFound(Any?.self, DecodingError.Context( codingPath: decoder.codingPath + [_XMLKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end." )) } if container[self.currentIndex].isNull { currentIndex += 1 return true } else { return false } } public mutating func decode(_ type: Bool.Type) throws -> Bool { return try decode(type) { decoder, box in try decoder.unbox(box) } } public mutating func decode(_ type: Int.Type) throws -> Int { return try decodeSignedInteger(type) } public mutating func decode(_ type: Int8.Type) throws -> Int8 { return try decodeSignedInteger(type) } public mutating func decode(_ type: Int16.Type) throws -> Int16 { return try decodeSignedInteger(type) } public mutating func decode(_ type: Int32.Type) throws -> Int32 { return try decodeSignedInteger(type) } public mutating func decode(_ type: Int64.Type) throws -> Int64 { return try decodeSignedInteger(type) } public mutating func decode(_ type: UInt.Type) throws -> UInt { return try decodeUnsignedInteger(type) } public mutating func decode(_ type: UInt8.Type) throws -> UInt8 { return try decodeUnsignedInteger(type) } public mutating func decode(_ type: UInt16.Type) throws -> UInt16 { return try decodeUnsignedInteger(type) } public mutating func decode(_ type: UInt32.Type) throws -> UInt32 { return try decodeUnsignedInteger(type) } public mutating func decode(_ type: UInt64.Type) throws -> UInt64 { return try decodeUnsignedInteger(type) } public mutating func decode(_ type: Float.Type) throws -> Float { return try decodeFloatingPoint(type) } public mutating func decode(_ type: Double.Type) throws -> Double { return try decodeFloatingPoint(type) } public mutating func decode(_ type: String.Type) throws -> String { return try decode(type) { decoder, box in try decoder.unbox(box) } } public mutating func decode<T: Decodable>(_ type: T.Type) throws -> T { return try decode(type) { decoder, box in try decoder.unbox(box) } } private mutating func decodeSignedInteger<T>(_ type: T.Type) throws -> T where T: BinaryInteger & SignedInteger & Decodable { return try decode(type) { decoder, box in try decoder.unbox(box) } } private mutating func decodeUnsignedInteger<T>(_ type: T.Type) throws -> T where T: BinaryInteger & UnsignedInteger & Decodable { return try decode(type) { decoder, box in try decoder.unbox(box) } } private mutating func decodeFloatingPoint<T>(_ type: T.Type) throws -> T where T: BinaryFloatingPoint & Decodable { return try decode(type) { decoder, box in try decoder.unbox(box) } } private mutating func decode<T: Decodable>( _ type: T.Type, decode: (_XMLDecoder, Box) throws -> T? ) throws -> T { guard !isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context( codingPath: decoder.codingPath + [_XMLKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end." )) } decoder.codingPath.append(_XMLKey(index: currentIndex)) defer { self.decoder.codingPath.removeLast() } let box = container[self.currentIndex] let value = try decode(decoder, box) defer { currentIndex += 1 } if value == nil, let type = type as? AnyOptional.Type { return type.init() as! T } guard let decoded: T = value else { throw DecodingError.valueNotFound(type, DecodingError.Context( codingPath: decoder.codingPath + [_XMLKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead." )) } return decoded } public mutating func nestedContainer<NestedKey>( keyedBy _: NestedKey.Type ) throws -> KeyedDecodingContainer<NestedKey> { decoder.codingPath.append(_XMLKey(index: currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !isAtEnd else { throw DecodingError.valueNotFound( KeyedDecodingContainer<NestedKey>.self, DecodingError.Context( codingPath: codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end." ) ) } let value = self.container[self.currentIndex] guard !value.isNull else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context( codingPath: codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead." )) } guard let keyed = value as? KeyedBox else { throw DecodingError._typeMismatch(at: codingPath, expectation: [String: Any].self, reality: value) } currentIndex += 1 let container = _XMLKeyedDecodingContainer<NestedKey>( referencing: decoder, wrapping: keyed ) return KeyedDecodingContainer(container) } public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { decoder.codingPath.append(_XMLKey(index: currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !isAtEnd else { throw DecodingError.valueNotFound( UnkeyedDecodingContainer.self, DecodingError.Context( codingPath: codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end." ) ) } let value = container[self.currentIndex] guard !value.isNull else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context( codingPath: codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead." )) } guard let unkeyed = value as? UnkeyedBox else { throw DecodingError._typeMismatch(at: codingPath, expectation: UnkeyedBox.self, reality: value) } currentIndex += 1 return _XMLUnkeyedDecodingContainer(referencing: decoder, wrapping: unkeyed) } public mutating func superDecoder() throws -> Decoder { decoder.codingPath.append(_XMLKey(index: currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !isAtEnd else { throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context( codingPath: codingPath, debugDescription: "Cannot get superDecoder() -- unkeyed container is at end." )) } let value = container[self.currentIndex] currentIndex += 1 return _XMLDecoder(referencing: value, at: decoder.codingPath, options: decoder.options) } }
true
207518ec02e1af7df431a1556977472313b98b1c
Swift
Genosis-Inc/Muse
/Muse/ViewController.swift
UTF-8
5,762
2.59375
3
[]
no_license
// // ViewController.swift // Muse // // Created by Dongkyu Shin on 2015. 9. 3.. // Copyright (c) 2015년 Genosis. All rights reserved. // import UIKit import MediaPlayer class ViewController: UIViewController { @IBOutlet weak var artWorkView: UIImageView! @IBOutlet var lblTitle: UILabel! @IBOutlet var lblArtistAlbum: UILabel! @IBOutlet var btnPlayStop: UIButton! @IBOutlet var btnShuffleMode: UIButton! let player = MPMusicPlayerController.applicationMusicPlayer() // TODO: Artwork의 기본 이미지를 정해야 합니다. let defaultAlbumArtwork: MPMediaItemArtwork! = nil let defaultAlbumArtist: String = "Unknown Aritst" let defaultAlbumTitle: String = "Unknown Album" let defaultSongTitle: String = "Unknown Song" required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! // Device의 모든 곡을 조회하여 Player의 Queue에 담습니다. let mediaItems = MPMediaQuery.songsQuery().items! player.setQueueWithItemCollection(MPMediaItemCollection(items: mediaItems)) // 현재 곡을 첫번째 곡으로 설정합니다. player.nowPlayingItem = mediaItems.first as MPMediaItem? // Shuffle Mode 를 설정합니다. player.shuffleMode = .Off // Notification을 등록 합니다. NSNotificationCenter.defaultCenter().addObserver(self, selector: "NowPlayingItemDidChanged:", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "PlaybakStateChanged:", name: MPMusicPlayerControllerPlaybackStateDidChangeNotification, object: nil) player.beginGeneratingPlaybackNotifications() } deinit { player.endGeneratingPlaybackNotifications() } /// Muse 재생 화면을 출력합니다. override func viewDidLoad() { super.viewDidLoad() displayShuffleMode() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// Shuffle mode를 변경 합니다. /// - parameter sender: shuffle mode button @IBAction func setShuffleMode(sender: AnyObject) { let shuffleMode = player.shuffleMode switch (shuffleMode) { case .Songs, .Albums, .Default: player.shuffleMode = .Off case .Off: player.shuffleMode = .Songs } displayShuffleMode() } /// Playback 현재 음악 재생 /// play 버튼은 play / pause 두 개의 동작을 toggle 합니다. @IBAction func play(sender: UIButton) { let playbackState: MPMusicPlaybackState = player.playbackState switch (playbackState) { case MPMusicPlaybackState.Playing: player.pause() case MPMusicPlaybackState.Stopped, MPMusicPlaybackState.Paused: player.play() default: break } } /// Playback 이전 음악 재생 @IBAction func PlayPrev(sender: AnyObject) { player.skipToPreviousItem() } /// Playback 다음 음악 재생 @IBAction func PlayNext(sender: AnyObject) { player.skipToNextItem() } /// MPMediaItem의 정보를 반환합니다. /// - parameter item: `MPMediaItem` /// - returns: artWork: 앨범의 이미지 /// artist: 아티스트 명 /// album: 앨범 명 /// title: 노래 명 func getItem(item: MPMediaItem) -> (artWork: MPMediaItemArtwork!, artist: String, album: String, title: String) { return (item.artwork ?? defaultAlbumArtwork, item.albumArtist ?? defaultAlbumArtist, item.albumTitle ?? defaultAlbumTitle, item.title ?? defaultSongTitle) } /// `MPMusicPlayerControllerNowPlayingItemDidChangeNotification`의 이벤트 핸들러 func NowPlayingItemDidChanged(notification: NSNotification) { guard let playingItem = player.nowPlayingItem else { return } let item = getItem(playingItem) artWorkView.image = item.artWork == nil ? nil : item.artWork!.imageWithSize(artWorkView.intrinsicContentSize()) lblTitle.text = item.title lblArtistAlbum.text = String("\(item.artist) - \(item.album)") } /// `MPMusicPlayerControllerPlaybackStateDidChangeNotification`의 이벤트 핸들러 func PlaybakStateChanged(notification: NSNotification) { let playbackState: MPMusicPlaybackState = player.playbackState switch (playbackState) { case MPMusicPlaybackState.Playing: btnPlayStop.setTitle("Pause", forState: .Normal) case MPMusicPlaybackState.Stopped, MPMusicPlaybackState.Paused: btnPlayStop.setTitle("Play", forState: .Normal) default: break } } /// Shuffle mode 설명을 화면에 출력 합니다. func displayShuffleMode() { // TODO: 어떤 shuffle mode인지 명시적으로 사용자에게 알려줬으면 합니다. let shuffleMode = player.shuffleMode switch (shuffleMode) { case .Off: btnShuffleMode.setTitle("Off", forState: .Normal) case .Default: btnShuffleMode.setTitle("Default", forState: .Normal) case .Albums: btnShuffleMode.setTitle("Albums", forState: .Normal) case .Songs: btnShuffleMode.setTitle("Songs", forState: .Normal) } } }
true
3fa6a9e071538e81894c941822712bb36b3594b2
Swift
cheborneck/tiKit
/tiKit/ColorSpinnerItemRenderer.swift
UTF-8
1,342
3.046875
3
[]
no_license
// // ColorSpinnerItemRenderer.swift // // Created by Thomas Hare on 8/21/15. // Copyright (c) 2015 raBit Software. All rights reserved. // // based on Simon Gladman's "NumericDial" example of "ColorSpinner" https://github.com/FlexMonkey/NumericDialDemo.git // // renders the current line on the spinner. There is a label and a color swatch import UIKit class ColorSpinnerItemRenderer: UIControl { let label = UILabel(frame: CGRectZero) let swatch = UIView(frame: CGRectZero) // initialize the control frame init(frame : CGRect, color : NamedColor) { // tell the controller the dimensions super.init(frame: CGRect(x: 0, y: 0, width: 200, height: 80)) // set the text and color swatch label.text = color.name swatch.backgroundColor = color.color swatch.layer.borderWidth = 1.5 // add the items to the control view addSubview(label) addSubview(swatch) } required init?(coder: NSCoder) { super.init(coder: coder) } // whenever the window object changes notify so the objects can be sized within override func didMoveToWindow() { label.frame = CGRect(x: 0, y: 0, width: 200, height: 80) swatch.frame = CGRect(x: 160, y: 80 / 2 - 7, width: 34, height: 14) } }
true
ae21b62e865e6845783815e83753c45e82acc941
Swift
Gontse/The-BusyShop-Assesment
/IkhokhaStore/Source/Repository/ProductsRepository.swift
UTF-8
3,697
2.703125
3
[]
no_license
// // Products.swift // IkhokhaStore // // Created by Gontse Ranoto on 2021/02/08. // import Foundation import Firebase import CodableFirebase import CoreData final class ProductsRepository: IProductsRepository { // MARK: - Properties let databaseReference = Database.database().reference() // Get a reference to the storage service using the default Firebase App let storage = Storage.storage() // Create a storage reference from our storage service private lazy var coreDataManager = CoreDataManager(modelName: AppCoreData.Model.products) var managedObjectContext: NSManagedObjectContext? // MARK: - FireBase func fetchProduct(WithIdentifier identifier: String, always:@escaping () -> Void, onCompletion: @escaping (ProductItem) -> Void, onError: @escaping (Error) -> Void) { databaseReference.child(identifier).observeSingleEvent(of: .value) { (snapShot) in always() guard let value = snapShot.value else { return } do { let productItem = try FirebaseDecoder().decode(ProductItem.self, from: value) onCompletion(productItem) } catch let (error) { onError(error) } } } func fetchImageUrl(_ imageName: String, completion: @escaping((URL) -> Void)) { let storageRef = storage.reference(forURL: "\(AppUrl.imageBase)/\(imageName)" ) storageRef.downloadURL { (url, error) in if let error = error { print(error) } else { if let url = url { completion(url)} } } } } // MARK: Core Data extension ProductsRepository { func fetcProducts(onCompletion: @escaping ([ProductItem]) -> Void, onError: @escaping (Error) -> Void) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } let managedContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: AppCoreData.Entity.product) do { let result = try managedContext.fetch(fetchRequest) as! [NSManagedObject] let productList = result.map { ProductItem(description: $0.value(forKey: AppCoreData.Field.itemDescription) as? String, image: "", price: $0.value(forKey: AppCoreData.Field.price) as? Double) } onCompletion(productList) } catch { print("Failed") } } func addProduct(_ productItem: ProductItem) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } let managedContext = appDelegate.persistentContainer.viewContext let productEntity = NSEntityDescription.entity(forEntityName: AppCoreData.Entity.product, in: managedContext)! let product = NSManagedObject(entity: productEntity, insertInto: managedContext) product.setValue(productItem.description, forKey: AppCoreData.Field.itemDescription) product.setValue( productItem.price ?? 0.0, forKey: AppCoreData.Field.price) do { try managedContext.save() } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } } }
true
5700584fa703ccee52f2e098d7dfa85449222619
Swift
insidegui/CloudKitCodable
/Tests/CloudKitCodableTests/TestUtils.swift
UTF-8
3,299
2.828125
3
[ "BSD-2-Clause" ]
permissive
// // TestUtils.swift // CloudKitCodableTests // // Created by Guilherme Rambo on 12/05/18. // Copyright © 2018 Guilherme Rambo. All rights reserved. // import XCTest import CloudKit @testable import CloudKitCodable extension CKRecord { /// Creates a temporary record to simulate what would happen when encoding a CKRecord /// from a value that was previosly encoded to a CKRecord and had its system fields set static var systemFieldsDataForTesting: Data { let zoneID = CKRecordZone.ID(zoneName: "ZoneABCD", ownerName: "OwnerABCD") let recordID = CKRecord.ID(recordName: "RecordABCD", zoneID: zoneID) let testRecord = CKRecord(recordType: "Person", recordID: recordID) let coder = NSKeyedArchiver(requiringSecureCoding: true) testRecord.encodeSystemFields(with: coder) coder.finishEncoding() return coder.encodedData } static var testRecord: CKRecord { get throws { guard let url = Bundle.module.url(forResource: "Rambo", withExtension: "ckrecord") else { fatalError("Required test asset Rambo.ckrecord not found") } let data = try Data(contentsOf: url) let record = try NSKeyedUnarchiver.unarchivedObject(ofClass: CKRecord.self, from: data) return try XCTUnwrap(record) } } } /// Validates that all fields in `record` match the expectations of encoding the test `Person` struct to a `CKRecord` /// /// - Parameter record: A record generated by encoding `Person.rambo` with `CloudKitRecordEncoder` func _validateRamboFields(in record: CKRecord) throws { XCTAssertEqual(record.recordType, "Person") XCTAssertEqual(record["name"] as? String, "Guilherme Rambo") XCTAssertEqual(record["age"] as? Int, 26) XCTAssertEqual(record["website"] as? String, "https://guilhermerambo.me") XCTAssertEqual(record["isDeveloper"] as? Bool, true) guard let asset = record["avatar"] as? CKAsset else { XCTFail("URL property with a file URL should encode to a CKAsset") return } let filePath = try XCTUnwrap(asset.fileURL?.path) XCTAssertEqual(filePath, "/Users/inside/Library/Containers/br.com.guilhermerambo.CloudKitRoundTrip/Data/Library/Caches/CloudKit/aa007d03cf247aebef55372fa57c05d0dc3d8682/Assets/7644AD10-A5A5-4191-B4FF-EF412CC08A52.01ec4e7f3a4fe140bcc758ae2c4a30c7bbb04de8db") XCTAssertNil(record[_CKSystemFieldsKeyName], "\(_CKSystemFieldsKeyName) should NOT be encoded to the record directly") } extension Person { /// Sample person for tests static let rambo = Person( cloudKitSystemFields: nil, name: "Guilherme Rambo", age: 26, website: URL(string:"https://guilhermerambo.me")!, avatar: URL(fileURLWithPath: "/Users/inside/Library/Containers/br.com.guilhermerambo.CloudKitRoundTrip/Data/Library/Caches/CloudKit/aa007d03cf247aebef55372fa57c05d0dc3d8682/Assets/7644AD10-A5A5-4191-B4FF-EF412CC08A52.01ec4e7f3a4fe140bcc758ae2c4a30c7bbb04de8db"), isDeveloper: true ) } extension PersonWithCustomIdentifier { static let rambo = PersonWithCustomIdentifier(cloudKitSystemFields: nil, cloudKitIdentifier: "MY-ID", name: "Guilherme Rambo") }
true
912300accfca2c5e79f17085d3d9233d8672dcc2
Swift
rednguyen/Printest
/Printest/ImageViewController.swift
UTF-8
961
2.671875
3
[]
no_license
// // ImageViewController.swift // Printest // // Created by Red Nguyen on 9/12/21. // import UIKit class ImageViewController: UIViewController { let imageView: UIImageView! init(item: UIImage) { self.imageView = UIImageView(image: item) super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.imageView.frame.size.width = self.view.frame.width self.imageView.frame.size.height = 200 imageView.center = self.view.center imageView.contentMode = UIView.ContentMode.scaleAspectFill view.addSubview(imageView) // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(false, animated: true) } }
true
50da589d7ac9bf2260de651a54072d8884dab072
Swift
adamnemecek/Expressions
/Sources/Operators/Binary/Protocols/ComparativeOperatorProtocol.swift
UTF-8
996
3.078125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // ComparativeOperatorProtocol.swift // Expression // // Created by Michael Pangburn on 12/18/17. // Copyright © 2017 Michael Pangburn. All rights reserved. // /// A binary operator that operates on comparable types. public protocol ComparativeOperatorProtocol: EquatableOperatorProtocol where Operand: Comparable { } // MARK: - Operators extension ComparativeOperatorProtocol { public static var lessThan: Self { return .init(identifier: "<", apply: <, precedence: .comparison, associativity: .none, isCommutative: false) } public static var lessThanOrEqual: Self { return .init(identifier: "<=", apply: <=, precedence: .comparison, associativity: .none, isCommutative: false) } public static var greaterThan: Self { return .init(identifier: ">", apply: >, precedence: .comparison, associativity: .none, isCommutative: false) } public static var greaterThanOrEqual: Self { return .init(identifier: ">=", apply: >=, precedence: .comparison, associativity: .none, isCommutative: false) } }
true
05c9fc06af8014207dbdb36dfbb9992d1c0db1c5
Swift
Swift-gavin/HelloWorldSwift
/Source/Animator/ScaleAnimator.swift
UTF-8
537
2.640625
3
[]
no_license
// // ScaleAnimator.swift // HelloWorldSwift // // Created by liu kai on 2019/1/25. // Copyright © 2019 liu kai. All rights reserved. // import UIKit open class ScaleAnimator: FadeAnimator { open var scale: CGFloat = 0.5 open override func hide(view: UIView) { super.hide(view: view) view.transform = CGAffineTransform.identity.scaledBy(x: scale, y: scale) } open override func show(view: UIView) { super.show(view: view) view.transform = CGAffineTransform.identity } }
true
5a99087ebc395e0a832898d533bcb46d8472958b
Swift
iwheelbuy/Projects
/Sources/Catcher/Classes+Safely.swift
UTF-8
1,004
2.96875
3
[]
no_license
import CatcherObjc private enum Result<T> { case error(Swift.Error) case exception(NSException, file: String, line: Int) case undefined case value(T) func final() throws -> T { switch self { case .error(let error): throw error case .exception(let exception, file: let file, line: let line): throw NSError(domain: file, code: line, userInfo: ["NSException": exception]) case .undefined: Swift.assertionFailure() throw NSError() case .value(let value): return value } } } @discardableResult public func safely<T>(_ block: () throws -> T, file: String = #file, line: Int = #line) throws -> T { var result = Result<T>.undefined Safely.try({ do { let value = try block() result = .value(value) } catch { result = .error(error) } }, catch: { exception in result = .exception(exception, file: file, line: line) }) return try result.final() }
true
04d2564de2fbe64397a5f68887b5c9b2a3fffbfe
Swift
tarappo/ios_test_sample_code
/Samples/Xcode11.0/xcode11.0/ViewController.swift
UTF-8
517
2.515625
3
[ "MIT" ]
permissive
// // ViewController.swift // xcode11.0 // // Created by Toshiyuki Hirata on 2020/03/14. // Copyright © 2020 tarappo. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var label: UILabel! var count: Int = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func buttonTap(_ sender: UIButton) { count = count + 1 label.text = "tap: \(count)" } }
true
28916124f2fcc431636a87ddeb719197f3113f4b
Swift
ltakuno/arquivos
/Swift/youtube/longestSubstring.swift
UTF-8
1,770
4.09375
4
[]
no_license
/* Problem: Given a string, find the length of the longest substring without repeating characters. Examples: Given: "abcabcbb", the answer is "abc", which the length is 3 Given: "bbbb", the answer is "b", with the length of 1 Given: "pwwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. */ func findLongestSubstring(_ word: String) -> Int { if word.count == 0 { return 0 } var charTable = [Character: Int]() var maxLength: Int = 0 var lastDuplicateIndex: Int = -1 let charArray = Array(word) for i in 0..<charArray.count{ let currentChar = charArray[i] if let charIndex = charTable[currentChar], lastDuplicateIndex < charIndex { lastDuplicateIndex = charIndex } let currentLength = i-lastDuplicateIndex maxLength = max(maxLength, currentLength) charTable[currentChar] = i } return maxLength } print("Result: ", findLongestSubstring("abcabcbb")) print("Result: ", findLongestSubstring("bbbb")) print("Result: ", findLongestSubstring("pwedk")) /* >>>>>> TRACKING <<<<<< Example: "abcabcbb" --------------------------------- NOTE!!!: currentLength is always compare to previous maxLength current char : a -> b -> c -> a -> b -> c -> b -> b current index : 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 lastDuplicateIndex : -1 -> -1 -> -1 -> 0 -> 1 -> 2 -> 4 -> 6 currentLength : 1 -> 2 -> 3 -> 3 -> 3 -> 3 -> 2 -> 1 maxLenght : 0 -> 1 -> 2 -> 3 -> 3 -> 3 -> 3 -> 3 --------------------------------- charTable: [a:0] -> [a:0, b:1] -> [a:0, b:1, c:2] -> [a:3, b:1, c:2] -> [a:3, b:4, c:2] -> [a:3, b:4, c:5] -> [a:3, b:6, c:5] -> [a:3, b:7, c:5] -> */
true
bafc02893ba18e92edd726f3ac5fe078443a33ee
Swift
RomanEsin/Klich
/Klich/Views/Kliches/Search.swift
UTF-8
1,029
2.6875
3
[]
no_license
// // Search.swift // Klich // // Created by Роман Есин on 23.05.2021. // import SwiftUI struct Search: View { @Binding var selectedTab: Int var body: some View { NavigationView { List { Section { NavigationLink("Поиск", destination: KlichLike(selectedTab: $selectedTab)) } NavigationLink("Сообщества", destination: KlichLike(selectedTab: $selectedTab)) NavigationLink("Помощь", destination: KlichLike(selectedTab: $selectedTab)) NavigationLink("Проекты", destination: KlichLike(selectedTab: $selectedTab)) NavigationLink("Поиск соседа", destination: KlichLike(selectedTab: $selectedTab)) } .listStyle(InsetGroupedListStyle()) .navigationTitle("Поиск") } } } struct Search_Previews: PreviewProvider { static var previews: some View { Search(selectedTab: .constant(1)) } }
true
6d51c8e9b1e91838eb28e512407d4981a32ce6f4
Swift
scubers/puyopuyo
/Example/Puyopuyo/Demos/Properties/ZPropertiesVC.swift
UTF-8
7,966
2.578125
3
[ "MIT" ]
permissive
// // ZPropertiesVC.swift // Puyopuyo_Example // // Created by Jrwong on 2019/12/10. // Copyright © 2019 CocoaPods. All rights reserved. // import Puyopuyo import UIKit class ZPropertiesVC: BaseViewController { override func viewDidLoad() { super.viewDidLoad() HBox().attach(view) { getMenu().attach($0).size(.fill, .fill) getZBox().attach($0).size(.fill, .fill) } .padding(view.py_safeArea()) .size(.fill, .fill) } let text = State("demo") let width = State<SizeDescription>(.fill) let height = State<SizeDescription>(.fill) let alignmentVert = State<Alignment>(.vertCenter) let alignmentHorz = State<Alignment>(.horzCenter) let marginTop = State<CGFloat>(0) let marginLeft = State<CGFloat>(0) let marginBottom = State<CGFloat>(0) let marginRight = State<CGFloat>(0) let paddingTop = State<CGFloat>(0) let paddingLeft = State<CGFloat>(0) let paddingBottom = State<CGFloat>(0) let paddingRight = State<CGFloat>(0) func getMenu() -> UIView { func getSelectionView<T: Equatable, I: Inputing>(title: String, input: I, values: [Selector<T>], selected: T? = nil) -> UIView where I.InputType == T { return HBox().attach { UILabel().attach($0) .text(title) PlainSelectionView<T>(values, selected: selected).attach($0) .size(.fill, 50) .onEvent(input) } .space(8) .padding(horz: 4) .borders([.thick(Util.pixel(1)), .color(Theme.dividerColor)]) .justifyContent(.center) .width(.fill) .view } return ScrollingBox<VBox> { $0.attach { Label(""" Change to landscape """).attach($0) .textAlignment(.left) .numberOfLines(0) .fontSize(20, weight: .bold) HBox().attach($0) { UILabel().attach($0) .text("input:") UITextField().attach($0) .size(.fill, .fill) .onText(text) } .justifyContent(.center) .size(.fill, 30) getSelectionView(title: "Width", input: width, values: [Selector<SizeDescription>(desc: ".fill", value: .fill), Selector<SizeDescription>(desc: ".fix(100)", value: .fix(100)), Selector<SizeDescription>(desc: ".wrap", value: .wrap)], selected: width.value).attach($0) getSelectionView(title: "Height", input: height, values: [Selector<SizeDescription>(desc: ".fill", value: .fill), Selector<SizeDescription>(desc: ".fix(100)", value: .fix(100)), Selector<SizeDescription>(desc: ".wrap", value: .wrap)], selected: height.value).attach($0) getSelectionView(title: "H alignment", input: alignmentHorz, values: (Alignment.horzAlignments + [.leading, .trailing]).map { Selector(desc: "\($0)", value: $0) }, selected: alignmentHorz.value).attach($0) getSelectionView(title: "V alignment", input: alignmentVert, values: Alignment.vertAlignments.map { Selector(desc: "\($0)", value: $0) }, selected: alignmentVert.value).attach($0) let insets: [CGFloat] = [0, 10, 20, 30, 40] getSelectionView(title: "MarginTop", input: marginTop, values: insets.map { Selector<CGFloat>(desc: "\($0)", value: $0) }, selected: marginTop.value).attach($0) getSelectionView(title: "MarginLeft", input: marginLeft, values: insets.map { Selector<CGFloat>(desc: "\($0)", value: $0) }, selected: marginLeft.value).attach($0) getSelectionView(title: "MarginBottom", input: marginBottom, values: insets.map { Selector<CGFloat>(desc: "\($0)", value: $0) }, selected: marginBottom.value).attach($0) getSelectionView(title: "MarginRight", input: marginRight, values: insets.map { Selector<CGFloat>(desc: "\($0)", value: $0) }, selected: marginRight.value).attach($0) getSelectionView(title: "PaddingTop", input: paddingTop, values: insets.map { Selector<CGFloat>(desc: "\($0)", value: $0) }, selected: paddingTop.value).attach($0) getSelectionView(title: "PaddingLeft", input: paddingLeft, values: insets.map { Selector<CGFloat>(desc: "\($0)", value: $0) }, selected: paddingLeft.value).attach($0) getSelectionView(title: "PaddingBottom", input: paddingBottom, values: insets.map { Selector<CGFloat>(desc: "\($0)", value: $0) }, selected: paddingBottom.value).attach($0) getSelectionView(title: "PaddingRight", input: paddingRight, values: insets.map { Selector<CGFloat>(desc: "\($0)", value: $0) }, selected: paddingRight.value).attach($0) } .padding(all: 4) } .attach() .view } func getZBox() -> UIView { let alignment = Outputs.combine(alignmentVert, alignmentHorz).map { Alignment([$0.0, $0.1]) } return ZBox().attach { ZBox().attach($0) { Label.demo("").attach($0) .text(text) .alignment(alignment) .size(width, height) .margin(top: marginTop, left: marginLeft, bottom: marginBottom, right: marginRight) } .padding(top: paddingTop, left: paddingLeft, bottom: paddingBottom, right: paddingRight) .borders([.color(UIColor.lightGray), .thick(Util.pixel(1))]) .animator(Animators.default) .size(.fill, .fill) Util.randomViewColor(view: $0) } .padding(all: 16) .animator(Animators.default) .view } }
true
2474927c6d3ab70643a78d5d89719c3cd1a39491
Swift
abhi9044/ash
/Ash/StoryScreen/DateUtil.swift
UTF-8
2,209
3.421875
3
[ "MIT" ]
permissive
// // DateUtil.swift // Ash // // Created by Oliver ONeill on 4/2/18. // import UIKit /** * Courtesy of Linus Oleander * See: https://gist.github.com/minorbug/468790060810e0d29545#gistcomment-2272953 */ extension Date { private struct Item { /// The plural form of the human readable time since self let plural: String /// The singular form of the human readable time since self let single: String /// The number of days/weeks/months etc. since date let value: Int? } /// Returns the components from self to now private var components: DateComponents { return Calendar.current.dateComponents( [.minute, .hour, .day, .weekOfYear, .month, .year, .second], from: self, to: Date() ) } /// Lazy load human readable components since self private var items: [Item] { return [ Item(plural: "years ago", single: "1 year ago", value: components.year), Item(plural: "months ago", single: "1 month ago", value: components.month), Item(plural: "weeks ago", single: "1 week ago", value: components.weekday), Item(plural: "days ago", single: "1 day ago", value: components.day), Item(plural: "minutes ago", single: "1 minute ago", value: components.minute), Item(plural: "seconds ago", single: "Just now", value: components.second) ] } /** * Get how long ago this date was in human readable form, ie. the time since * now. * * - Returns: human readable form of time between this date and now */ func timeAgo() -> String { // Run through all of them items that make up this date. These are // all lazy loaded to ensure the latest date is used for item in items { switch (item.value) { case let .some(step) where step == 0: continue case let .some(step) where step == 1: return item.single case let .some(step): return String(step) + " " + item.plural default: continue } } return "Just now" } }
true
fcaf92ba7af60304547204e8d8c39f7e3dd97820
Swift
donka-s27/GeoConfess
/Sources/Objects.swift
UTF-8
4,277
3.296875
3
[]
no_license
// // Objects.swift // GeoConfess // // Created by Andreas Muller on 4/6/16. // Reviewed by Dan Dobrev on 5/9/16. // Copyright © 2016 DanMobile. All rights reserved. // import Foundation import Alamofire import SwiftyJSON // MARK: - REST Object /// Type for all unique, REST-ish resources ID. typealias ResourceID = UInt64 /// A top-level protocol for REST-ish objects/resources. protocol RESTObject: CustomStringConvertible { /// Uniquely identifies this resource. var id: ResourceID { get } } /// Default implementations. extension RESTObject { var description: String { return "\(self.dynamicType)(id: \(self.id))" } } // MARK: - JSON Coding /// JSON encoding. extension JSON { init(_ id: ResourceID) { self.init(NSNumber(unsignedLongLong: id)) } var resourceID: ResourceID? { return self.uInt64 } } /// Support for **JSON** compatible decoding. protocol JSONDecoding { /// Parses a JSON-encoded representation of this object. init?(fromJSON: JSON) } /// Support for **JSON** compatible encoding. protocol JSONCoding { /// Returns a JSON-encoded representation of this object. func toJSON() -> JSON } // MARK: - DisplayDescription Protocol protocol DisplayDescription { var displayDescription: String { get } } // MARK: - UserInfo Struct /// Partial information about a given **penitent** or **priest**. struct UserInfo: RESTObject, Equatable, JSONCoding { let id: ResourceID let name: String let surname: String /// Priest has location if he is active right *now*. let location: CLLocationCoordinate2D? init(id: ResourceID, name: String, surname: String, location: CLLocationCoordinate2D? = nil) { self.id = id self.name = name self.surname = surname self.location = location } init(fromJSON json: [String: JSON]) { precondition(json.count <= 5) let id = json["id"]!.resourceID! let name = json["name"]!.string! let surname = json["surname"]!.string! let location: CLLocationCoordinate2D? if let lat = json["latitude"]?.double, let lon = json["longitude"]?.double { location = CLLocationCoordinate2D( latitude: CLLocationDegrees(lat), longitude: CLLocationDegrees(lon)) } else { location = nil } self.init(id: id, name: name, surname: surname, location: location) } func toJSON() -> JSON { var json: [String: JSON] = [ "id": JSON(id), "name": JSON(name), "surname": JSON(surname) ] if let location = self.location { json["latitude"] = JSON(location.latitude) json["longitude"] = JSON(location.longitude) } return JSON(json) } init(fromUser user: User) { let id = user.id let name = user.name let surname = user.surname let location = user.location?.coordinate self.init(id: id, name: name, surname: surname, location: location) } /// Parses complete/partial user info from the specified dictionary. /// For example: /// /// { /// "id": 10, /// "priest_id": 24, /// ... /// "penitent": { /// "id": 25, /// "name": "Test user", /// "surname": "Surname", /// "latitude": "12.234", /// "longitude": "23.345" /// } /// } /// /// If extended information is missing, we assume it most /// be about the current user (and fulfill it accordingly). init?(embeddedInJSON json: [String: JSON], forRole role: User.Role) { let userKey: String switch role { case .Penitent, .Admin: userKey = "penitent" case .Priest: userKey = "priest" } if let singleId = json["\(userKey)_id"]?.resourceID { precondition(json[userKey] == nil) self.init(copyFromCurrentUserWithID: singleId) } else if let userJSON = json[userKey]?.dictionary { if userJSON.count == 1 { self.init(copyFromCurrentUserWithID: userJSON["id"]!.resourceID!) } else { self.init(fromJSON: userJSON) } } else { return nil } } private init(copyFromCurrentUserWithID id: ResourceID) { let user = User.current! precondition(user.id == id, "Expecting current user") self.init(id: id, name: user.name, surname: user.surname, location: nil) } } func ==(x: UserInfo, y: UserInfo) -> Bool { return x.id == y.id && x.name == y.name && x.surname == y.surname }
true
6b8c9f4879f91df822d501746536c784843064e8
Swift
danieljvdm/QuikCric
/QuikCric WatchKit Extension/InterfaceController.swift
UTF-8
1,934
2.53125
3
[]
no_license
// // InterfaceController.swift // QuikCric WatchKit Extension // // Created by Daniel on 12/28/15. // Copyright © 2015 danieljvdm. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { var matches = [Match]() @IBOutlet var tableView: WKInterfaceTable! @IBOutlet var noMatchesLabel: WKInterfaceLabel! func setupTable() { tableView.setNumberOfRows(matches.count, withRowType: "MatchRow") for var i = 0; i < matches.count; ++i { if let row = tableView.rowControllerAtIndex(i) as? MatchRow { let match = matches[i] row.matchName.setText(match.prettyNameWithFlag) row.currentScore.setText(match.innings.first?.score) row.lead.setText(match.innings.first?.relativeScore) } } } func loadData() { APIService.query(QueryType.LiveMatches){ (matches: [Match]?) in if let matches = matches { self.matches = matches self.setupTable() } else { self.noMatchesLabel.setHidden(false) } } } override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) loadData() // Configure interface objects here. } override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) { self.pushControllerWithName("showDetails", context: matches[rowIndex]) } @IBAction func refresh() { loadData() } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } }
true
748616e64d4fc4fc5b02afebd40c3e9701569317
Swift
mattpolzin/JSONAPI-OpenAPI
/JSONAPI.playground/Pages/OpenAPI Full Simple Example.xcplaygroundpage/Contents.swift
UTF-8
2,228
3.171875
3
[ "MIT" ]
permissive
//: [Previous](@previous) import Foundation import JSONAPI import OpenAPIKit import JSONAPIOpenAPI import Sampleable let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted // // First describe the resource object // struct WidgetDescription: JSONAPI.ResourceObjectDescription { static var jsonType: String { return "widgets" } struct Attributes: JSONAPI.Attributes { let productName: Attribute<String> } struct Relationships: JSONAPI.Relationships { let subcomponents: ToManyRelationship<Widget, NoMetadata, NoLinks> } } typealias Widget = JSONAPI.ResourceObject<WidgetDescription, NoMetadata, NoLinks, String> // // Then make things sampleable // This is needed because the only way to use reflection on // your attributes and relationships structs is to create // instances of them. // extension WidgetDescription.Attributes: Sampleable { static var sample: WidgetDescription.Attributes { return .init(productName: .init(value: "Fillihizzer Nob Hub")) } } extension WidgetDescription.Relationships: Sampleable { static var sample: WidgetDescription.Relationships { return .init(subcomponents: .init(ids: [.init(rawValue: "1")])) } } // // We can create a JSON Schema for the Widget at this point // let widgetJSONSchema = Widget.openAPISchema(using: encoder) // // Describe a JSON:API response body with 1 widget and // any number of related widgets included. // typealias SingleWidgetDocumentWithIncludes = Document<SingleResourceBody<Widget>, NoMetadata, NoLinks, Include1<Widget>, NoAPIDescription, BasicJSONAPIError<String>> // // Finally we can create a JSON Schema for the response body of a successful request // let jsonAPIResponseSchema = SingleWidgetDocumentWithIncludes.SuccessDocument.openAPISchema(using: encoder) print(String(data: try! encoder.encode(jsonAPIResponseSchema), encoding: .utf8)!) // // Or a failed request // let jsonAPIResponseErrorSchema = SingleWidgetDocumentWithIncludes.ErrorDocument.openAPISchema(using: encoder) // // Or a schema describing the response as `oneOf` the success or error respones // let jsonAPIResponseFullSchema = SingleWidgetDocumentWithIncludes.openAPISchema(using: encoder)
true
c349e650a2f6b5b9b3266fbfd1d97a651f41b879
Swift
dubslara/MeLiMobileChallenge
/MeLiMobileChallenge/Models/Product.swift
UTF-8
1,589
3.171875
3
[]
no_license
// // Product.swift // MeLiMobileChallenge // // Created by Lara Dubs on 23/04/2021. // import Foundation import Alamofire import PromiseKit struct Product: Codable { let id: String let condition: String let title: String let price: Double let thumbnail: URL let availableCount: Int let soldCount: Int var priceFormatted: String { "$ \(String(format: "%g", price))" } enum CodingKeys: String, CodingKey { case id case condition case title case price case thumbnail case availableCount = "available_quantity" case soldCount = "sold_quantity" } } extension Product { private struct Response: Codable { let query: String let results: [Product] } static func url(search: String) -> String { return "https://api.mercadolibre.com/sites/MLA/search?q=\(search.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? "")" } static func get(text: String) -> Promise<[Self]> { .init { seal in let request = AF.request(url(search: text)) request.responseDecodable(of: Response.self) { response in if let error = response.error { seal.reject(error) } guard let result = response.value else { return seal.reject(AppError(title: "Parsing Error", message: "Couldn't parse response from search product request")) } seal.fulfill(result.results) } } } }
true
b2159c2ad91614e7e01ed458ba245d16cf0a0db8
Swift
Y3454R/Swift-Practice
/part7.swift
UTF-8
1,692
4.25
4
[]
no_license
// Enumerations //https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html print("=====Enumerations======") enum compass { case north case south case east case west } var direction = compass.west direction = .east // changing the value to east switch direction { case .north: print("North") case .south: print("South") case .east: print("East") case .west: print("West") } enum Barcode { case upc(Int, Int, Int, Int) case qrCode(String) } //Associated values var productBarcode = Barcode.upc(8, 85909, 51226, 3) //productBarcode = .qrCode("ABCDEFGHIJKLMNOP") switch productBarcode { case .upc(let numberSystem, let manufacturer, let product, let check): print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).") case .qrCode(let productCode): // var dileo hoy, but mutated dekhay print("QR code: \(productCode).") } // Optional is an... slide 54, bujhi nai enum OptionalInt { case None case Some(Int) } var maybeInt: OptionalInt = .None maybeInt = .Some(42) print(maybeInt) // khali value ta kemne print kore??? // raw values enum example1: Int { case Samin = 1 case Yeasar = 2 case Abir = 3 } let example1Value = example1.Abir.rawValue print("Raw value of Abir: \(example1Value)") enum Planet: Int { case mercury = 10, venus, earth, mars, jupiter, saturn, uranus, neptune } print("Earth: \(Planet.earth.rawValue)") // not in slide: // Not working: /* enum Beverage: CaseIterable { case coffee, tea, juice } let numberOfChoices = Beverage.allCases.count print("\(numberOfChoices) beverages available") for beverage in Beverage.allCases { print(beverage) } */
true
509dcfd686834b3143a533ad2d05d4ab7fe8bc5f
Swift
cindelina/SustainableMe
/SustainableMe/DescriptionView.swift
UTF-8
736
2.671875
3
[]
no_license
// // DescriptionView.swift // SustainableMe // // Created by Tony Dang on 21/8/21. // import UIKit class DescriptionView: UIViewController { // get the descriptions for the tasks // @IBOutlet var description1: UILabel? // @IBOutlet var description2: UILabel? // @IBOutlet var description3: UILabel? @IBOutlet weak var description1: UITextView! @IBOutlet weak var description2: UITextView! @IBOutlet weak var description3: UITextView! override func viewDidLoad() { description1?.text = descriptions[randomNum] description2?.text = descriptions[(randomNum+1) % descriptions.count] description3?.text = descriptions[(randomNum+2) % descriptions.count] } }
true
1de011293c78e7417434e14583d272ff86933336
Swift
LeoAndo/swiftui-combine-corelocation
/swiftui-combine-location/View/ContentView.swift
UTF-8
1,125
2.859375
3
[]
no_license
// // ContentView.swift // swiftui-combine-location // // Created by yorifuji on 2021/05/16. // import SwiftUI struct ContentView: View { @ObservedObject var viewModel: ViewModel var body: some View { VStack(spacing: 16) { HStack(spacing: 16) { Button("request") { viewModel.requestAuthorization() } Button("start") { viewModel.startTracking() } Button("stop") { viewModel.stopTracking() } } Text(viewModel.authorizationStatus.description) Text(String(format: "longitude: %f", viewModel.longitude)) Text(String(format: "latitude: %f", viewModel.latitude)) }.onAppear { viewModel.activate() }.onDisappear { viewModel.deactivate() } } } struct ContentView_Previews: PreviewProvider { static let viewModel = ViewModel(model: LocationDataSource()) static var previews: some View { ContentView(viewModel: viewModel) } }
true
1de09c9a00dbf9e9d5673834c034cb4ed7b05b1f
Swift
leandroramosss/SwiftUIMVVM
/MVMWeatherApp/View/WeatherView.swift
UTF-8
1,056
3.171875
3
[]
no_license
// // WeatherView.swift // MVMWeatherApp // // Created by Leandro Ramos on 10/11/20. // import Foundation import SwiftUI struct WeatherView: View { @ObservedObject var weatherViewModel = WeatherViewModel() var body: some View { VStack (spacing: 10) { Text("\(self.weatherViewModel.temperature)") .font(.largeTitle) .foregroundColor(Color.white) Text("\(self.weatherViewModel.humidity)") .foregroundColor(Color.white) .opacity(0.7) Picker(selection: self.$weatherViewModel.temperatureUnit, label: Text("Select a Unit")) { ForEach(TemperatureUnit.allCases,id: \.self) { unit in Text(unit.title) } }.pickerStyle(SegmentedPickerStyle()) } .padding() .frame(width: 300, height: 150) .background(Color.blue) .clipShape(RoundedRectangle(cornerRadius: 8.0, style: .continuous)) } }
true
0110860087062d650de1c5555e16f473baf6584f
Swift
luciventura/Project10-Challenge
/Project10-Challenge2/ViewController.swift
UTF-8
1,677
2.765625
3
[]
no_license
// // ViewController.swift // Project10-Challenge2 // // Created by Luciene Ventura on 25/04/21. // import UIKit class ViewController: UICollectionViewController { var pictures = [String]() var flagInitial = [InitialFlag]() override func viewDidLoad() { super.viewDidLoad() let fm = FileManager.default let path = Bundle.main.resourcePath! let flags = try! fm.contentsOfDirectory(atPath: path) for flag in flags { if flag.hasSuffix("png") { pictures.append(flag) } } title = "Flags" navigationController?.navigationBar.prefersLargeTitles = true } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pictures.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Flag", for: indexPath) as? FlagCell else { fatalError("Unable") } cell.imageView.image = UIImage(named: pictures[indexPath.item]) cell.imageView.layer.borderWidth = 1 return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let vc = storyboard?.instantiateViewController(identifier: "Detail") as? DetailViewController { vc.selectedFlag = pictures[indexPath.item] navigationController?.pushViewController(vc, animated: true) } } }
true
b6423e82769858fa3fe2e78bc3bad08a7d792d44
Swift
engueroryan15/GitHub-UsersList-Enguero
/GitHubList/GitHubList/Model/UserList.swift
UTF-8
3,032
2.8125
3
[]
no_license
// // UserList.swift // GitHubList // // Created by Ryan Enguero on 4/21/21. // import Foundation struct UserList: Codable { var login : String? var id : Int? var node_id : String? var avatar_url : String? var gravatar_id : String? var url : String? var html_url : String? var followers_url : String? var following_url : String? var gists_url : String? var starred_url : String? var subscriptions_url : String? var organizations_url : String? var repos_url : String? var events_url : String? var received_events_url : String? var type : String? var site_admin : Bool? enum CodingKeys: String, CodingKey { case login = "login" case id case node_id = "node_id" case avatar_url = "avatar_url" case gravatar_id = "gravatar_id" case url = "url" case html_url = "html_url" case followers_url = "followers_url" case following_url = "following_url" case gists_url = "gists_url" case starred_url = "starred_url" case subscriptions_url = "subscriptions_url" case organizations_url = "organizations_url" case repos_url = "repos_url" case events_url = "events_url" case received_events_url = "received_events_url" case type = "type" case site_admin } init(from decoder: Decoder) throws{ let container = try decoder.container(keyedBy: CodingKeys.self) login = try container.decodeIfPresent(String.self, forKey: .login) id = try container.decodeIfPresent(Int.self, forKey: .id) node_id = try container.decodeIfPresent(String.self, forKey: .node_id) avatar_url = try container.decodeIfPresent(String.self, forKey: .avatar_url) gravatar_id = try container.decodeIfPresent(String.self, forKey: .gravatar_id) url = try container.decodeIfPresent(String.self, forKey: .url) html_url = try container.decodeIfPresent(String.self, forKey: .html_url) followers_url = try container.decodeIfPresent(String.self, forKey: .followers_url) following_url = try container.decodeIfPresent(String.self, forKey: .following_url) gists_url = try container.decodeIfPresent(String.self, forKey: .gists_url) starred_url = try container.decodeIfPresent(String.self, forKey: .starred_url) subscriptions_url = try container.decodeIfPresent(String.self, forKey: .subscriptions_url) organizations_url = try container.decodeIfPresent(String.self, forKey: .organizations_url) repos_url = try container.decodeIfPresent(String.self, forKey: .repos_url) events_url = try container.decodeIfPresent(String.self, forKey: .events_url) received_events_url = try container.decodeIfPresent(String.self, forKey: .received_events_url) type = try container.decodeIfPresent(String.self, forKey: .type) site_admin = try container.decodeIfPresent(Bool.self, forKey: .site_admin) } }
true
1c08c8ebb7b77629724b025842497a392791bb50
Swift
alexisakers/metrobuddy
/MetroKit/Core Data/Helpers/PersistentStore.swift
UTF-8
1,916
3.0625
3
[ "MIT" ]
permissive
import CoreData /// A list of the different types of persistent stores, that can be converted to a `NSPersistentStoreDescription`. public enum PersistentStore { /// The data will be stored and read in memory, and will be discarded when the process exits. case inMemory /// The data will be stored and read from disk, at the specified location. case onDisk(SymbolicLocation) // MARK: - Helpers /// Creates a persistent store descriptor to use when initalizing the `NSPersistentContainer`. /// - parameter fileManager: The file manager to use to resolve any symbolic location. /// - parameter name: The name of the persistent descriptor. /// - throws: Any error thrown when resolving symbolic location. See `SymbolicLocation` for possible failures. /// - returns: A ready-to-load `NSPersistentStoreDescription`. func makePersistentStoreDescriptor(in fileManager: FileManager, name: String) throws -> NSPersistentStoreDescription { var storeDescription: NSPersistentStoreDescription switch self { case .inMemory: storeDescription = NSPersistentStoreDescription() storeDescription.type = NSInMemoryStoreType case .onDisk(let location): let url = try! fileManager .resolve(location) .appendingPathComponent(name) .appendingPathExtension("sqlite") storeDescription = NSPersistentStoreDescription(url: url) storeDescription.type = NSSQLiteStoreType storeDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) } storeDescription.shouldAddStoreAsynchronously = false storeDescription.shouldInferMappingModelAutomatically = true storeDescription.shouldMigrateStoreAutomatically = true return storeDescription } }
true
943f0dd643fecac3b33aceed9ca83994450e816a
Swift
6263k/ArcsinusSampleApp
/ArcsinusSampleApp/Extensions/Single+Extensions.swift
UTF-8
1,162
2.71875
3
[ "MIT" ]
permissive
// // Single+Extensions.swift // ArcsinusSampleApp // // Created by Danil Blinov on 20.03.2021. // import RxSwift import RxCocoa extension PrimitiveSequence where Trait == SingleTrait, Element == Result<Data, APIError> { func map<T: Decodable>(to type: T.Type, decodingStrategy: JSONDecoder.DateDecodingStrategy = .secondsSince1970, haveHierarchy: Bool = false) -> Single<Result<T, APIError>> { return flatMap { element -> Single<Result<T, APIError>> in switch element { case .success(let json): do { guard let obj = try json.decode(as: T.self, decodingStrategy) else { return .just(.failure(.invalidData)) } return .just(.success(obj)) } catch let error { print(error) return .just(.failure(.jsonConversationFailed)) } case .failure(let error): return .just(.failure(error)) } } } } private extension Data { func decode<T: Decodable>(as type: T.Type, _ decodingStrategy: JSONDecoder.DateDecodingStrategy) throws -> T? { do { let decoder = JSONDecoder() decoder.dateDecodingStrategy = decodingStrategy return try decoder.decode(type, from: self) } catch { throw error } } }
true
0ce6ab67574220e9a19af80347b4fbc786016067
Swift
trapsignal/SwiftDataStructures
/SwiftDataStructures/SwiftDataStructures/OrderedDictionary.swift
UTF-8
1,782
3.484375
3
[]
no_license
// // OrderedDictionary.swift // SwiftDataStructures // // @author trapsignal <trapsignal@yahoo.com> // import RedBlackTree // MARK: - OrderedDictionary public struct OrderedDictionary<Key: Comparable, Value>: Mapping { // MARK: Types private typealias Pair = OrderedKeyValuePair<Key, Value> // MARK: Properties var count: Int { return tree.count } private var tree = RedBlackTree<Pair>() // MARK: Initialization public init() { } // MARK: Public API func keys() -> AnySequence<Key> { return AnySequence(tree.values().lazy.map { $0.key }) } mutating func set(_ value: Value, for key: Key) { tree.add(Pair(key: key, value: value)) } func value(for key: Key) -> Value? { return pair(for: key)?.value } @discardableResult mutating func removeValue(for key: Key) -> Value? { guard let pair = pair(for: key) else { return nil } tree.remove(pair) return pair.value } // MARK: Implementation private func pair(for key: Key) -> Pair? { return tree.find { if key == $0.key { return .orderedSame } else if key < $0.key { return .orderedAscending } else { return .orderedDescending } } } } // MARK: - OrderedKeyValuePair private struct OrderedKeyValuePair<Key: Comparable, Value>: Comparable { let key: Key let value: Value static func ==(left: OrderedKeyValuePair, right: OrderedKeyValuePair) -> Bool { return left.key == right.key } static func <(left: OrderedKeyValuePair, right: OrderedKeyValuePair) -> Bool { return left.key < right.key } }
true
e8bc10c20c1590e8da31f25f97135fe1a7ce0754
Swift
5573352/MosMetroMapKit
/Sources/MosMetroMapKit/Metro/Utils.swift
UTF-8
5,601
2.734375
3
[]
no_license
// // Utils.swift // PackageTester // // Created by Кузин Павел on 17.08.2021. // import UIKit class Utils { //MARK: - Get Root VC static func root() -> UIViewController? { if let root = UIApplication.shared.keyWindow?.rootViewController { return root } return nil } //MARK: - HTML to String static func convert(html toString: String) -> NSMutableAttributedString { let htmlText = toString.htmlToAttributedString let mutableStr = NSMutableAttributedString(attributedString: htmlText!) mutableStr.setFontFace(font: UIFont.BODY_S, color: .textPrimary) return mutableStr } //MARK: - Time From Now static func getTimeFromNow(_ seconds: Double) -> String { let moscow = Region(calendar: Calendars.gregorian, zone: Zones.europeMoscow, locale: Locales.russian) let date = DateInRegion(Date(), region: moscow) let time = date.dateByAdding(Int(seconds), .second) return time.toFormat("H:mm") } //MARK: - Period of Time static func getPeriodFromNow(_ seconds: Double) -> String { let moscow = Region(calendar: Calendars.gregorian, zone: Zones.europeMoscow, locale: Locales.russian) let date = DateInRegion(Date(), region: moscow) let end = date.dateByAdding(Int(seconds), .second) //let period = TimePeriod(start: date, end: date.dateByAdding(Int(seconds/60), .minute)) return "\(date.toFormat("H:mm")) – \(end.toFormat("H:mm"))" } //MARK: - Total Time static func getTotalTime(_ seconds: Double, units: NSCalendar.Unit = [.hour,.minute]) -> String { let moscow = Region(calendar: Calendars.gregorian, zone: Zones.europeMoscow, locale: Localize.currentLanguage() == "ru" ? Locales.russian : Locales.english) let date = DateInRegion(Date(), region: moscow) let period = TimePeriod(start: date, end: date.dateByAdding(Int(seconds/60), .minute)) let duration = period.duration return duration.toString { $0.maximumUnitCount = 4 //$0.allowedUnits = [.hour, .minute] $0.allowedUnits = units $0.collapsesLargestUnit = false $0.unitsStyle = .abbreviated } } //MARK: - Total Time (seconds) static func getAudioTotalTime(_ seconds: Double) -> String { let moscow = Region(calendar: Calendars.gregorian, zone: Zones.europeMoscow, locale: Localize.currentLanguage() == "ru" ? Locales.russian : Locales.english) let date = DateInRegion(Date(), region: moscow) let period = TimePeriod(start: date, end: date.dateByAdding(Int(seconds), .second)) let duration = period.duration return duration.toString { $0.maximumUnitCount = 0 $0.allowedUnits = [.hour, .minute, .second] $0.collapsesLargestUnit = false $0.zeroFormattingBehavior = .pad $0.unitsStyle = .positional } } //MARK: - Get status bar Height static func getStatusBarHeight() -> CGFloat { var statusBarHeight: CGFloat = 0 if #available(iOS 13.0, *) { let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first statusBarHeight = window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0 } else { statusBarHeight = UIApplication.shared.statusBarFrame.height } return statusBarHeight } //MARK: - Arrival Time static func getArrivalTime(_ seconds: Double) -> String { let moscow = Region(calendar: Calendars.gregorian, zone: Zones.europeMoscow, locale: Localize.currentLanguage() == "ru" ? Locales.russian : Locales.english) let date = DateInRegion(Date(), region: moscow) return date.dateByAdding(Int(seconds), .second).toString(.time(.short)) } //MARK: - Get Top Padding static func getTopPadding() -> CGFloat { let window = UIApplication.shared.keyWindow guard let topPadding = window?.safeAreaInsets.top else { return 0 } return topPadding } static func downsample(image data: Data, to pointSize: CGSize, scale: CGFloat = UIScreen.main.scale, callback: @escaping (UIImage?) -> ()) { // Create an CGImageSource that represent an image DispatchQueue.global(qos: .userInteractive).async { let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary guard let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else { callback(nil) return } // Calculate the desired dimension let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale // Perform downsampling let downsampleOptions = [ kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceShouldCacheImmediately: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels ] as CFDictionary guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else { callback(nil) return } callback(UIImage(cgImage: downsampledImage)) } // Return the downsampled image as UIImage } }
true
8136e74c6e1575527f00a2977d7795c0ef840bc5
Swift
pxzhu/Swift-Study
/Seventeenth.playground/Contents.swift
UTF-8
3,422
3.90625
4
[]
no_license
import UIKit struct Student17211 { var name: String var number: Int } class School17211 { var number: Int = 0 var students: [Student17211] = [Student17211]() func addStudent(name: String) { let student: Student17211 = Student17211(name: name, number: self.number) self.students.append(student) self.number += 1 } func addStudents(names: String...) { for name in names { self.addStudent(name: name) } } subscript(index: Int) -> Student17211? { if index < self.number { return self.students[index] } return nil } } let highSchool17211: School17211 = School17211() highSchool17211.addStudents(names: "MiJeong", "JuHyun", "JiYoung", "SeongUk", "MoonDuk") let aStudent17211: Student17211? = highSchool17211[1] print("\(aStudent17211?.number) \(aStudent17211?.name)") /* Optional(1) Optional("JuHyun") */ struct Student17311 { var name: String var number: Int } class School17311 { var number: Int = 0 var students: [Student17311] = [Student17311]() func addStudent(name: String) { let student: Student17311 = Student17311(name: name, number: self.number) self.students.append(student) self.number += 1 } func addStudents(names: String...) { for name in names { self.addStudent(name: name) } } subscript(index: Int) -> Student17311? { get { if index < self.number { return self.students[index] } return nil } set { guard var newStudent: Student17311 = newValue else { return } var number: Int = index if index > self.number { number = self.number self.number += 1 } newStudent.number = number self.students[number] = newStudent } } subscript(name: String) -> Int? { get { return self.students.filter { $0.name == name }.first?.number } set { guard var number: Int = newValue else { return } if number > self.number { number = self.number self.number += 1 } let newStudent: Student17311 = Student17311(name: name, number: number) self.students[number] = newStudent } } subscript(name: String, number: Int) -> Student17311? { return self.students.filter { $0.name == name && $0.number == number }.first } } let highSchool17311: School17311 = School17311() highSchool17311.addStudents(names: "MiJeong", "JuHyun", "JiYoung", "SeongUk", "MoonDuk") let aStudent17311: Student17311? = highSchool17311[1] print("\(aStudent17311?.number) \(aStudent17311?.name)") /* Optional(1) Optional("JuHyun") */ print(highSchool17311["MiJeong"]) /* Optional(0) */ print(highSchool17311["DongJin"]) /* nil */ highSchool17311[0] = Student17311(name: "HongEui", number: 0) highSchool17311["MangGu"] = 1 print(highSchool17311["JuHyun"]) /* nil */ print(highSchool17311["MangGu"]) /* Optional(1) */ print(highSchool17311["SeongUk", 3]) /* Optional(__lldb_expr_254.Student17311(name: "SeongUk", number: 3)) */ print(highSchool17311["HeeJin", 3]) /* nil */ // Type Script enum School17411: Int { case elemtary = 1, middle, high, unibersity static subscript(level: Int) -> School17411? { return Self(rawValue: level) } } let school17411: School17411? = School17411[2] print(school17411) /* Optional(__lldb_expr_292.School17411.middle) */
true
2edbb9f49425443e9180f57700f1353664aa39e2
Swift
pointfreeco/episode-code-samples
/0198-tca-concurrency-pt4/swift-composable-architecture/Examples/VoiceMemos/VoiceMemos/VoiceMemo.swift
UTF-8
3,777
3.09375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import ComposableArchitecture import Foundation import SwiftUI struct VoiceMemo: Equatable, Identifiable { var date: Date var duration: TimeInterval var mode = Mode.notPlaying var title = "" var url: URL var id: URL { self.url } enum Mode: Equatable { case notPlaying case playing(progress: Double) var isPlaying: Bool { if case .playing = self { return true } return false } var progress: Double? { if case let .playing(progress) = self { return progress } return nil } } } enum VoiceMemoAction: Equatable { case audioPlayerClient(Result<AudioPlayerClient.Action, AudioPlayerClient.Failure>) case playButtonTapped case delete case timerUpdated(TimeInterval) case titleTextFieldChanged(String) } struct VoiceMemoEnvironment { var audioPlayerClient: AudioPlayerClient var mainRunLoop: AnySchedulerOf<RunLoop> } let voiceMemoReducer = Reducer< VoiceMemo, VoiceMemoAction, VoiceMemoEnvironment > { memo, action, environment in enum TimerId {} switch action { case .audioPlayerClient(.success(.didFinishPlaying)), .audioPlayerClient(.failure): memo.mode = .notPlaying return .cancel(id: TimerId.self) case .delete: return .merge( environment.audioPlayerClient.stop().fireAndForget(), .cancel(id: TimerId.self) ) case .playButtonTapped: switch memo.mode { case .notPlaying: memo.mode = .playing(progress: 0) let start = environment.mainRunLoop.now return .merge( Effect.timer(id: TimerId.self, every: 0.5, on: environment.mainRunLoop) .map { .timerUpdated($0.date.timeIntervalSince1970 - start.date.timeIntervalSince1970) }, environment.audioPlayerClient .play(memo.url) .catchToEffect(VoiceMemoAction.audioPlayerClient) ) case .playing: memo.mode = .notPlaying return .concatenate( .cancel(id: TimerId.self), environment.audioPlayerClient.stop().fireAndForget() ) } case let .timerUpdated(time): switch memo.mode { case .notPlaying: break case let .playing(progress: progress): memo.mode = .playing(progress: time / memo.duration) } return .none case let .titleTextFieldChanged(text): memo.title = text return .none } } struct VoiceMemoView: View { let store: Store<VoiceMemo, VoiceMemoAction> var body: some View { WithViewStore(store) { viewStore in let currentTime = viewStore.mode.progress.map { $0 * viewStore.duration } ?? viewStore.duration HStack { TextField( "Untitled, \(viewStore.date.formatted(date: .numeric, time: .shortened))", text: viewStore.binding( get: \.title, send: VoiceMemoAction.titleTextFieldChanged) ) Spacer() dateComponentsFormatter.string(from: currentTime).map { Text($0) .font(.footnote.monospacedDigit()) .foregroundColor(Color(.systemGray)) } Button(action: { viewStore.send(.playButtonTapped) }) { Image(systemName: viewStore.mode.isPlaying ? "stop.circle" : "play.circle") .font(.system(size: 22)) } } .buttonStyle(.borderless) .frame(maxHeight: .infinity, alignment: .center) .padding(.horizontal) .listRowBackground(viewStore.mode.isPlaying ? Color(.systemGray6) : .clear) .listRowInsets(EdgeInsets()) .background( Color(.systemGray5) .frame(maxWidth: viewStore.mode.isPlaying ? .infinity : 0) .animation( viewStore.mode.isPlaying ? .linear(duration: viewStore.duration) : nil, value: viewStore.mode.isPlaying ), alignment: .leading ) } } }
true
69f9afb0a77a0296b3ae9b9952f859f480165ef1
Swift
rafaelekol/unstoppable-wallet-ios
/BankWallet/BankWallet/Modules/Balance/BalanceViewItemFactory.swift
UTF-8
2,228
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
import Foundation class BalanceViewItemFactory: IBalanceViewItemFactory { func viewItem(item: BalanceItem, currency: Currency) -> BalanceViewItem { let balanceTotal = item.balanceTotal ?? 0 let balanceLocked = item.balanceLocked ?? 0 var exchangeValue: CurrencyValue? var currencyValueTotal: CurrencyValue? var currencyValueLocked: CurrencyValue? if let marketInfo = item.marketInfo { exchangeValue = CurrencyValue(currency: currency, value: marketInfo.rate) currencyValueTotal = CurrencyValue(currency: currency, value: balanceTotal * marketInfo.rate) currencyValueLocked = CurrencyValue(currency: currency, value: balanceLocked * marketInfo.rate) } return BalanceViewItem( wallet: item.wallet, coin: item.wallet.coin, coinValue: CoinValue(coin: item.wallet.coin, value: balanceTotal), exchangeValue: exchangeValue, diff: item.marketInfo?.diff, currencyValue: currencyValueTotal, state: item.state ?? .notReady, marketInfoExpired: item.marketInfo?.expired ?? false, chartInfoState: item.chartInfoState, coinValueLocked: CoinValue(coin: item.wallet.coin, value: balanceLocked), currencyValueLocked: currencyValueLocked ) } func headerViewItem(items: [BalanceItem], currency: Currency) -> BalanceHeaderViewItem { var total: Decimal = 0 var upToDate = true items.forEach { item in if let balanceTotal = item.balanceTotal, let marketInfo = item.marketInfo { total += balanceTotal * marketInfo.rate if marketInfo.expired { upToDate = false } } if case .synced = item.state { // do nothing } else { upToDate = false } } let currencyValue = CurrencyValue(currency: currency, value: total) return BalanceHeaderViewItem( currencyValue: currencyValue, upToDate: upToDate ) } }
true
c13f655162cf1afb12263f842b59c70d984661a6
Swift
Monsteel/DGSW-Petition_iOS
/DGSW-Petition_iOS/Source/Service/APIs/AuthAPI.swift
UTF-8
1,616
2.828125
3
[]
no_license
// // AuthAPI.swift // DGSW-Petition_iOS // // Created by 이영은 on 2021/04/19. // import Foundation import Moya enum AuthAPI { case checkRegisteredUser(_ userId: String) case login(_ request: LoginRequest) case register(_ request: RegisterRequest) } extension AuthAPI: TargetType { var baseURL: URL { return URL(string: Constants.SERVER_IP+"auth")! } var path: String { switch self { case .checkRegisteredUser(_): return "/register/check" case .login: return "/login" case .register: return "/register" } } var method: Moya.Method { switch self { case .checkRegisteredUser: return .get case .login: return .post case .register: return .post } } var sampleData: Data { return Data() } var task: Task { switch self { case .checkRegisteredUser(let userId): return .requestParameters(parameters:["userId": userId], encoding: URLEncoding.queryString) case .login(let request): return .requestData(try! JSONEncoder().encode(request)) case .register(let request): return .requestData(try! JSONEncoder().encode(request)) } } var validationType: Moya.ValidationType { return .successAndRedirectCodes } var headers: [String : String]? { return ["Content-Type": "application/json"] } }
true
0445899d34ab93d11f7deab83b2d1263296363b2
Swift
niilohlin/Rask
/Sources/Parsers+OneOf.swift
UTF-8
1,249
3.546875
4
[]
no_license
import Foundation extension Parsers { public struct OneOf: Parser { public let set: Set<Character> public init(string: String) { self.set = Set(string) } public func parse(_ input: String, _ index: inout String.Index) throws -> Character { guard input.endIndex > index else { throw AnyUnexpectedToken(expected: "not eof", actual: "") } let firstElement = input[index] guard set.contains(firstElement) else { throw NotOneOfError(expected: set, actual: firstElement) } index = input.index(after: index) return firstElement } } } extension Parsers { public static func one(of string: String) -> Parsers.OneOf { Parsers.OneOf(string: string) } public static func digit() -> Parsers.OneOf { Parsers.one(of: "0123456789") } } extension Parsers.OneOf { public func or(other: Parsers.OneOf) -> Parsers.OneOf { let otherString = other.set.map { String($0) }.joined(separator: "") let upstreamString = `set`.map { String($0) }.joined(separator: "") return Parsers.OneOf(string: upstreamString + otherString) } }
true
a9c7f342334bbb4f13e3df8609e5b786576a5551
Swift
meech-ward/AudioProcessor
/Sources/AudioIO/AudioRecorder.swift
UTF-8
2,454
2.65625
3
[]
no_license
// // AudioRecorder.swift // AudioProcessorPackageDescription // // Created by Sam Meech-Ward on 2017-11-21. // import Foundation public typealias AudioRecorderDataClosure = ((_ audioSample: AudioSample, _ audioRecordable: AudioRecordable) -> (Void)) public struct AudioRecorder { public var recordable: AudioRecordable { return _recordable } public var isRecording: Bool { return _recordable.isRecording } private let _recordable: AudioRecordable private let dataClosure: AudioRecorderDataClosure private let dataTimer: TimerType? private let powerTracker: AudioPowerTracker? private let frequencyTracker: AudioFrequencyTracker? private let amplitudeTracker: AudioAmplitudeTracker? public init(recordable: AudioRecordable, powerTracker: AudioPowerTracker? = nil, frequencyTracker: AudioFrequencyTracker? = nil, amplitudeTracker: AudioAmplitudeTracker? = nil, dataTimer: TimerType? = nil, dataClosure: AudioRecorderDataClosure? = nil) { self._recordable = recordable self.dataClosure = dataClosure ?? {_,_ in } self.dataTimer = dataTimer self.powerTracker = powerTracker self.frequencyTracker = frequencyTracker self.amplitudeTracker = amplitudeTracker } public func start(closure: (@escaping (_ successfully: Bool) -> ()) = {_ in }) { sendNewDataSample() self.dataTimer?.start(self.sendNewDataSample) _recordable.start() { successful in closure(successful) } } /// Create an audio sample and send it to the data closure private func sendNewDataSample() { let sample = newDataSample() self.dataClosure(sample, _recordable) } private func newDataSample() -> AudioSample { // Ampiltude let amplitude = self.amplitudeTracker?.amplitude let leftAmplitude = self.amplitudeTracker?.leftAmplitude let rightAmplitude = self.amplitudeTracker?.rightAmplitude // Fequency let frequency = self.frequencyTracker?.frequency // Power let power = powerTracker?.averageDecibelPower(forChannel: 0) // Recording let time = _recordable.currentTime return AudioSample(time: time, amplitude: amplitude, rightAmplitude: rightAmplitude, leftAmplitude: leftAmplitude, frequency: frequency, power: power) } public func stop(closure: (@escaping (_ successfully: Bool) -> ()) = {_ in }) { _recordable.stop() { successful in closure(successful) } self.dataTimer?.stop() } }
true
5d19111c8ecd681fe5f7bb63859efbe69f8d3766
Swift
kolyasev/SwiftJSONRPC
/Sources/SwiftJSONRPC/RequestExecutor/HTTP/HTTPRequestExecutor.swift
UTF-8
8,831
2.609375
3
[ "MIT" ]
permissive
// ---------------------------------------------------------------------------- // // HTTPRequestExecutor.swift // // @author Denis Kolyasev <kolyasev@gmail.com> // // ---------------------------------------------------------------------------- import Foundation public class HTTPRequestExecutor: RequestExecutor { // MARK: - Properties public let config: HTTPRequestExecutorConfig public var requestAdapter: HTTPRequestAdapter = DefaultHTTPRequestAdapter() public var responseAdapter: HTTPResponseAdapter = DefaultHTTPResponseAdapter() public var requestRetrier: HTTPRequestRetrier? // MARK: - Private Properties private let httpClient: HTTPClient private let tasks = Atomic<[RPCTask]>([]) private let httpTasks = Atomic<[HTTPTask]>([]) // MARK: - Initialization public convenience init(url: URL) { let config = HTTPRequestExecutorConfig(baseURL: url) self.init(config: config) } public convenience init(config: HTTPRequestExecutorConfig) { let httpClient = URLSessionHTTPClient() self.init(config: config, httpClient: httpClient) } init(config: HTTPRequestExecutorConfig, httpClient: HTTPClient) { self.config = config self.httpClient = httpClient } // MARK: - Functions public func execute(request: Request, completionHandler: @escaping (RequestExecutorResult) -> Void) { let task = RPCTask(request: request, handler: completionHandler) dispatch(task: task) } public func activeHTTPRequest(forRequest request: Request) -> HTTPRequest? { return self.httpTasks.withValue { httpTasks in return httpTasks.first(where: { $0.requests.contains(where: { $0 === request }) })?.httpRequest } } // MARK: - Private Functions private func dispatch(task: RPCTask) { switch self.config.throttle { case .disabled: perform(tasks: [task]) case .interval(let interval): dispatch(task: task, withThrottleInterval: interval) } } private func dispatch(task: RPCTask, withThrottleInterval interval: DispatchTimeInterval) { enqueue(task: task) DispatchQueue.global().asyncAfter(deadline: .now() + interval) { [weak self] in self?.performQueuedTasks() } } private func performQueuedTasks() { while let tasks = dequeueTasks(), !tasks.isEmpty { perform(tasks: tasks) } } private func perform(tasks: [RPCTask]) { let httpRequest = buildHTTPRequest(forRequests: tasks.map { $0.request }) perform(httpRequest: httpRequest, forTasks: tasks) } private func perform(httpRequest: HTTPRequest, forTasks tasks: [RPCTask]) { do { let httpRequest = try self.requestAdapter.adapt(request: httpRequest) let httpTask = HTTPTask(httpRequest: httpRequest, requests: tasks.map { $0.request }) enqueue(httpTask: httpTask) weak var weakSelf = self self.httpClient.perform(request: httpRequest) { result in guard let instance = weakSelf else { return } switch result { case .success(let response): do { let response = try instance.responseAdapter.adapt(response: response, forRequest: httpRequest) instance.dispatch(httpResponse: response, forRequest: httpRequest, tasks: tasks) } catch let error as HTTPResponseError { let cause = HTTPRequestExecutorError(error: error, request: httpRequest, response: response) instance.dispatch(error: cause, forRequest: httpRequest, tasks: tasks) } catch { fatalError("HTTPResponseAdapter can only throw instance of HTTPResponseError.") } case .error(let error): let cause = HTTPRequestExecutorError(error: error, request: httpRequest, response: nil) instance.dispatch(error: cause, forRequest: httpRequest, tasks: tasks) } instance.dequeue(httpTask: httpTask) } } catch let error as HTTPRequestError { let cause = HTTPRequestExecutorError(error: error, request: httpRequest, response: nil) dispatch(error: cause, forRequest: httpRequest, tasks: tasks) } catch { fatalError("HTTPRequestAdapter can only throw instance of HTTPResponseError.") } } private func buildHTTPRequest(forRequests requests: [Request]) -> HTTPRequest { let payload: Any let isBatch = requests.count != 1 if !isBatch { // Do not use batch call format if we have only one request payload = requests[0].buildBody() } else { payload = requests.map { $0.buildBody() } } let body: Data do { body = try JSONSerialization.data(withJSONObject: payload, options: []) } catch { fatalError("Build data from request failed.") } return HTTPRequest(method: .post, url: self.config.baseURL, headers: [:], body: body) } private func dispatch(httpResponse: HTTPResponse, forRequest request: HTTPRequest, tasks: [RPCTask]) { do { let responses: [Response] let payload = try JSONSerialization.jsonObject(with: httpResponse.body, options: []) switch payload { case let item as [String: Any]: responses = [try Response(response: item)] case let items as [[String: Any]]: responses = try items.map { try Response(response: $0) } default: throw HTTPResponseSerializationError( cause: HTTPResponseSerializationError.UnexpectedPayloadTypeError(payload: payload) ) } dispatch(responses: responses, forTasks: tasks) } catch let error as HTTPResponseSerializationError { let cause = HTTPRequestExecutorError(error: error, request: request, response: httpResponse) dispatch(error: cause, forRequest: request, tasks: tasks) } catch let error { let error = HTTPResponseSerializationError(cause: error) let cause = HTTPRequestExecutorError(error: error, request: request, response: httpResponse) dispatch(error: cause, forRequest: request, tasks: tasks) } } private func dispatch(error: HTTPRequestExecutorError, forRequest request: HTTPRequest, tasks: [RPCTask]) { if let retrier = self.requestRetrier, retrier.should(executor: self, retryRequest: request, afterError: error) { perform(httpRequest: request, forTasks: tasks) } else { for task in tasks { task.handler(.error(error)) } } } private func dispatch(responses: [Response], forTasks tasks: [RPCTask]) { for task in tasks { if let response = responses.first(where: { $0.id == task.request.id }) { task.handler(.response(response)) } else { fatalError("Void requests is not supported yet!") } } } private func enqueue(task: RPCTask) { _ = self.tasks.modify { tasks in var tasks = tasks tasks.append(task) return tasks } } private func dequeueTasks() -> [RPCTask]? { let allTasks = self.tasks.modify { tasks in return Array(tasks.dropFirst(self.config.maxBatchCount)) } guard !allTasks.isEmpty else { return nil } return Array(allTasks.prefix(self.config.maxBatchCount)) } private func enqueue(httpTask: HTTPTask) { _ = self.httpTasks.modify { httpTasks in var httpTasks = httpTasks httpTasks.append(httpTask) return httpTasks } } private func dequeue(httpTask: HTTPTask) { _ = self.httpTasks.modify { httpTasks in var httpTasks = httpTasks if let idx = httpTasks.firstIndex(where: { $0.httpRequest == httpTask.httpRequest }) { httpTasks.remove(at: idx) } return httpTasks } } // MARK: - Inner Types private struct RPCTask { let request: Request let handler: (RequestExecutorResult) -> Void } private struct HTTPTask { let httpRequest: HTTPRequest let requests: [Request] } } extension HTTPResponseSerializationError { // MARK: - Inner Types struct UnexpectedPayloadTypeError: Error { let payload: Any } }
true
e34bca28d5edbc808c1b14214c09c2b7efee2c02
Swift
ziadGhali/MovieTask
/MovieTask/Utilities/Extension.swift
UTF-8
784
2.96875
3
[]
no_license
// // UIView+Extension.swift // MovieTask // // Created by ziad ghali on 1/12/19. // Copyright © 2019 ziad ghali. All rights reserved. // import Foundation import UIKit extension UIImageView { public func imageFromUrl(_ urlString: String) { if let url = URL(string: urlString) { let request = URLRequest(url: url) URLSession.shared.dataTask(with: request){ data, response, error in if let data = data{ DispatchQueue.main.async { self.image = UIImage(data: data) } } }.resume() } } } extension UIView{ func roundView(){ self.layer.cornerRadius = self.bounds.height / 2 self.layer.masksToBounds = true } }
true
60f6739de918177028f25eb48f0faa5deb4874c2
Swift
ballard/CryptoAppUI
/Sources/CryptoAppUI/View/CoinsListView.swift
UTF-8
1,016
2.921875
3
[]
no_license
// // CoinsListView.swift // CryptoApp // // Created by Иван Лазарев on 13.03.2020. // Copyright © 2020 Иван Лазарев. All rights reserved. // import SwiftUI struct CoinRow: View { let item: CoinItem var body: some View { NavPushButton(destination: CoinView(item: item)) { VStack(alignment: .leading) { Text(self.item.name) .font(.title) Text(self.item.symbol) .font(.callout) .foregroundColor(.gray) } } } } struct CoinsListView: View { @EnvironmentObject var viewModel: CoinsListViewModel var body: some View { List(viewModel.items) { item in VStack(alignment: .leading) { CoinRow(item: item) } } .onAppear() { self.viewModel.fetch() } } } struct CoinsListView_Previews: PreviewProvider { static var previews: some View { CoinsListView() } }
true
c7aae0f0ca4d1cecbce5b7e49b133902738671c4
Swift
okiookio/Monotone
/Monotone/Components/Views/Common/GradientView.swift
UTF-8
2,102
2.765625
3
[ "MIT" ]
permissive
// // GradientView.swift // Monotone // // Created by Xueliang Chen on 2021/1/1. // import UIKit class GradientView: BaseView { public var lightColors: [CGColor]?{ didSet{ self.updateGradient() } } public var darkColors: [CGColor]?{ didSet{ self.updateGradient() } } public var locations: [NSNumber]?{ didSet{ self.updateGradient() } } public var startPoint: CGPoint?{ didSet{ self.updateGradient() } } public var endPoint: CGPoint?{ didSet{ self.updateGradient() } } private var gradientLayer: CAGradientLayer? /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ private func updateGradient(){ let colorsByUserInterface = self.traitCollection.userInterfaceStyle == .dark ? darkColors : lightColors guard let colors = colorsByUserInterface, let startPoint = self.startPoint, let endPoint = self.endPoint else{ return } // Remove. self.gradientLayer?.removeFromSuperlayer() // Create. self.gradientLayer = CAGradientLayer() self.gradientLayer!.frame = self.bounds self.gradientLayer!.colors = colors self.gradientLayer!.startPoint = startPoint self.gradientLayer!.endPoint = endPoint self.gradientLayer!.locations = locations self.layer.addSublayer(self.gradientLayer!) } override func layoutSubviews() { super.layoutSubviews() self.updateGradient() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) self.updateGradient() } }
true
7bbd3105c60c0c3163341a7015fa5b4765d40bef
Swift
MargauxRUSSEIL/Vin21
/vin21/Views/WineView.swift
UTF-8
1,585
3
3
[]
no_license
// // WineView.swift // vin21 // // Created by Margaux RUSSEIL on 10/02/2021. // import Foundation import SwiftUI struct WineView: View { let model: Model let wine: Wine var body: some View { VStack(alignment: .leading) { HStack { if wine.color == "rouge" { Image("wine-bottle-rouge") .resizable() .aspectRatio(contentMode: .fill) .frame(width: 20, height: 50, alignment: .center) } else if wine.color == "blanc" { Image("wine-bottle-blanc") .resizable() .aspectRatio(contentMode: .fill) .frame(width: 20, height: 50, alignment: .center) } else if wine.color == "rose" { Image("wine-bottle-rose") .resizable() .aspectRatio(contentMode: .fill) .frame(width: 20, height: 50, alignment: .center) } Text("x") .bold() Text(String(wine.number)) .bold() Text(wine.title) } HStack { if wine.producer != "" { Text(wine.producer) } if wine.millesime != "" { Text(" - ") Text(wine.millesime) } } } } }
true
4d1e2f21eae3471e6677e07415f1efba6ccf5464
Swift
bulletproof391/Albums
/Albums/ViewModel/AlbumDetailedViewModel.swift
UTF-8
1,585
2.859375
3
[]
no_license
// // AlbumDetailedViewModel.swift // Albums // // Created by Дмитрий Вашлаев on 21.06.18. // Copyright © 2018 Дмитрий Вашлаев. All rights reserved. // import Foundation import ReactiveSwift class AlbumDetailedViewModel { // MARK: - Private Properties private var artistName: String? private var collectionName: String? private var songs: [Song]? private var mutablePropertySongs: MutableProperty<[Song]>? // MARK: - Public Properties private(set) var albumImage: MutableProperty<UIImage>? // MARK: - Initializer init(with album: Album?, image: MutableProperty<UIImage>?) { self.artistName = album?.info?.artistName self.collectionName = album?.info?.collectionName self.mutablePropertySongs = album?.songs mutablePropertySongs?.producer.startWithResult{ [weak self] (receivedSongs) in guard let weakSelf = self else { return } if let array = receivedSongs.value { weakSelf.songs = array } } self.albumImage = image } // MARK: - Public Methods func getArtistName() -> String? { return artistName } func getAlbumName() -> String? { return collectionName } func numberOfSections() -> Int { return 1 } func numberOfRowsInSection(_ section: Int) -> Int { guard let count = songs?.count else { return 0 } return count } func songForRow(_ indexPath: IndexPath) -> String? { return songs?[indexPath.row].trackName } }
true
d40e150a98a4f108e44dbe43504cc2ec873d7c7a
Swift
hhy5277/iVisual
/iVisual/Classes/StaticImageOverlay.swift
UTF-8
809
2.515625
3
[]
no_license
// // StaticImageOverlay.swift // SmartVideoEditor // // Created by jinfeng on 2021/11/9. // import Foundation import CoreMedia import CoreImage import UIKit /// 静态图片贴纸 public class StaticImageOverlay: OverlayProvider { public var frame: CGRect = .zero public var timeRange: CMTimeRange = .zero public var extent: CGRect = .zero public var visualElementId: VisualElementIdentifer = .invalid public var userTransform: CGAffineTransform = .identity public var image: CIImage! public func applyEffect(at time: CMTime) -> CIImage? { image } public init(image: CIImage) { self.image = image frame = CGRect(origin: .zero, size: image.extent.size) extent = image.extent } private init() {} }
true
359e7601fb05fe540e8d87208465e791b047388f
Swift
adamnemecek/Expressions
/Expression.playground/Sources/Extensions/UIImage.swift
UTF-8
571
3.015625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import UIKit import PlaygroundSupport extension UIImage { public func saveToDocumentsDirectory(as name: String) { guard let data = UIImagePNGRepresentation(self) else { print("Could not obtain image data."); return } // To save properly, there must be a "Shared Playground Data" folder in Documents with the appropriate permissions set. let filename = playgroundSharedDataDirectory.appendingPathComponent(name) try! data.write(to: filename) // This will spit out the appropriate error in the Playground console if it occurs. } }
true
7ccbd63ca2f5f9baf10773ddeb86e1593a5a6630
Swift
chaoshin/DemoPerformSegue
/DemoPerformSegue/Page1ViewController.swift
UTF-8
1,446
2.734375
3
[]
no_license
// // Page1ViewController.swift // DemoPerformSegue // // Created by Chao Shin on 2018/4/27. // Copyright © 2018 Chao Shin. All rights reserved. // import UIKit class Page1ViewController: UIViewController { @IBAction func buttonPress(_ sender: Any) { performSegue(withIdentifier: "ToPage2Segue", sender: sender) //指定segue到下一個畫面,並將物件的Tag傳遞給prepare() } /* @IBAction func button1Press(_ sender: UIButton) { performSegue(withIdentifier: "ToPage2Segue", sender: "Button1") } @IBAction func button2Press(_ sender: UIButton) { performSegue(withIdentifier: "ToPage2Segue", sender: "Button2") } */ override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let controller = segue.destination as? Page2ViewController // 指定要去的controller if let button = sender as? UIButton { // 轉型為UIButton if button.tag == 0 { // 判斷Tag controller?.text = "Button1" // 修改property }else { controller?.text = "Button2" // 修改property } } } }
true
e3a8cc8e3113cbbd83ffd1413373f181f39996b9
Swift
thanhhvt7196/Coordinator-RxSwift-structure
/RxSwiftCoordinator/MVVMCoordinatorStructure/Utils/Extensions/URL+Extension.swift
UTF-8
820
2.921875
3
[ "MIT" ]
permissive
// // URL.swift // MVVMCoordinatorStructure // // Created by thanh tien on 9/15/20. // Copyright © 2019 kennyS. All rights reserved. // import Foundation extension URL { func value(for queryKey: String) -> String? { guard let items = URLComponents(string: absoluteString)?.queryItems else { return nil } for item in items where item.name == queryKey { return item.value } return nil } func appendingQueryParameters(_ parameters: [String: String]) -> URL { var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true)! var queryItems = urlComponents.queryItems ?? [] queryItems += parameters.map { URLQueryItem(name: $0, value: $1) } urlComponents.queryItems = queryItems return urlComponents.url! } }
true
20e1e67dfda73cb58b7d630ce2f0fbd157192a41
Swift
Trabiza/Prego
/Prego/View Controller/ProfileVC.swift
UTF-8
2,684
2.546875
3
[]
no_license
// // ProfileVC.swift // Prego // // Created by owner on 9/28/19. // Copyright © 2019 Y2M. All rights reserved. // import UIKit class ProfileVC: UIViewController { @IBOutlet weak var infoImage: UIImageView! @IBOutlet weak var infoLabel: UILabel! @IBOutlet weak var infoView: UIView! @IBOutlet weak var addressImage: UIImageView! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var addressView: UIView! @IBOutlet weak var addressContainerView: UIView! @IBOutlet weak var infoContainerView: UIView! let infoType: String = "info" let addressType: String = "address" override func viewDidLoad() { super.viewDidLoad() } @IBAction func backAction(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func infoAction(_ sender: Any) { toogleAction(type: infoType) } @IBAction func addressAction(_ sender: Any) { toogleAction(type: addressType) } func toogleAction(type: String){ switch type { case infoType: infoChoosed() break case addressType: addressChoosed() break default: break } } func infoChoosed(){ self.infoLabel.textColor = AppColorsManager.orangeColor self.infoView.backgroundColor = AppColorsManager.orangeColor self.infoImage.image = self.infoImage.image?.withRenderingMode(.alwaysTemplate) self.infoImage.tintColor = AppColorsManager.orangeColor self.addressLabel.textColor = UIColor.darkGray self.addressView.backgroundColor = UIColor.lightGray self.addressImage.image = self.addressImage.image?.withRenderingMode(.alwaysTemplate) self.addressImage.tintColor = UIColor.darkGray self.infoContainerView.isHidden = false self.addressContainerView.isHidden = true } func addressChoosed(){ addressLabel.textColor = AppColorsManager.orangeColor addressView.backgroundColor = AppColorsManager.orangeColor addressImage.image = addressImage.image?.withRenderingMode(.alwaysTemplate) addressImage.tintColor = AppColorsManager.orangeColor infoLabel.textColor = UIColor.darkGray infoView.backgroundColor = UIColor.lightGray infoImage.image = infoImage.image?.withRenderingMode(.alwaysTemplate) infoImage.tintColor = UIColor.darkGray self.infoContainerView.isHidden = true self.addressContainerView.isHidden = false } }
true
cfd0847830a7201e5384c9fde959165ab5756cef
Swift
CabageMan/tableViewAppWithProtocol
/RamotionTableViewApp/CustomTableViewCell.swift
UTF-8
784
2.796875
3
[]
no_license
// // CustomTableViewCell.swift // RamotionTableViewApp // // Created by ViktorsMacbook on 31.01.19. // Copyright © 2019 Viktor Bednyi Inc. All rights reserved. // import UIKit class CustomTableViewCell: UITableViewCell, Fillable { func fill(data: String) { textLabel?.text = data } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if selected { self.tintColor = UIColor.red self.contentView.backgroundColor = #colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1) accessoryType = .checkmark } else { self.contentView.backgroundColor = nil accessoryType = .none } } }
true
405df0024af720bcd5416e85e28731278a9e3485
Swift
timmybea/APIBackedApp
/APIBackedApp/APIBackedApp/Controller/ViewController.swift
UTF-8
1,950
2.796875
3
[]
no_license
// // ViewController.swift // APIBackedApp // // Created by Tim Beals on 2018-09-23. // Copyright © 2018 Roobi Creative. All rights reserved. // import UIKit //MARK: Properties and inherited methods class ViewController: UIViewController { var dataSource = [Person]() { didSet { DispatchQueue.main.async { self.tableView.reloadData() } } } lazy var tableView: UITableView = { let tv = UITableView() tv.delegate = self tv.dataSource = self tv.register(PersonCell.self, forCellReuseIdentifier: PersonCell.reuseIdentifier) return tv }() override func viewDidLoad() { super.viewDidLoad() APIService.fetchData(with: .json) { (data, error) in guard error == nil else { print(error!.localizedDescription); return } if let unwrappedData = data { self.dataSource = Person.getPeople(from: unwrappedData) } } } override func viewWillLayoutSubviews() { tableView.removeFromSuperview() self.tableView.frame = view.frame view.addSubview(tableView) } } //MARK: UITableView delegate and datasource extension ViewController : UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: PersonCell.reuseIdentifier, for: indexPath) as! PersonCell cell.setup(for: self.dataSource[indexPath.row]) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } }
true
1e3f026e62212608bef3b3b5f1fa69edbeb19b7d
Swift
jlawanson/flashcards
/Flashcards/ViewController.swift
UTF-8
3,058
2.640625
3
[]
no_license
// // ViewController.swift // Flashcards // // Created by Jordan Lawanson on 2/14/20. // Copyright © 2020 Jordan Lawanson. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var frontLabel: UILabel! @IBOutlet weak var backLabel: UILabel! @IBOutlet weak var card: UIView! @IBOutlet weak var btnOptionOne: UIButton! @IBOutlet weak var btnOptionTwo: UIButton! @IBOutlet weak var btnOptionThree: UIButton! override func viewDidLoad() { super.viewDidLoad() frontLabel.layer.cornerRadius = 20.0 frontLabel.clipsToBounds = true backLabel.layer.cornerRadius = 20.0 backLabel.clipsToBounds = true backLabel.layer.borderWidth = 3.0 backLabel.layer.borderColor = #colorLiteral(red: 1, green: 0.7360894084, blue: 0.7559660077, alpha: 1) card.layer.cornerRadius = 20.0 card.layer.shadowRadius = 15.0 card.layer.shadowOpacity = 0.2 btnOptionOne.layer.cornerRadius = 10.0 btnOptionOne.layer.borderWidth = 3.0 btnOptionOne.layer.borderColor = #colorLiteral(red: 1, green: 0.7360894084, blue: 0.7559660077, alpha: 1) btnOptionTwo.layer.cornerRadius = 10.0 btnOptionTwo.layer.borderWidth = 3.0 btnOptionTwo.layer.borderColor = #colorLiteral(red: 1, green: 0.7360894084, blue: 0.7559660077, alpha: 1) btnOptionThree.layer.cornerRadius = 10.0 btnOptionThree.layer.borderWidth = 3.0 btnOptionThree.layer.borderColor = #colorLiteral(red: 1, green: 0.7360894084, blue: 0.7559660077, alpha: 1) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let navigationController = segue.destination as! UINavigationController let creationController = navigationController.topViewController as! CreationViewController creationController.flashcardsController = self if segue.identifier == "EditSegue" { creationController.initialQuestion = frontLabel.text creationController.initialAnswer = backLabel.text } } @IBAction func didTapOnFlashcard(_ sender: Any) { if frontLabel.isHidden { frontLabel.isHidden = false btnOptionOne.isHidden = false btnOptionThree.isHidden = false } } func updateFlashcard(question: String, answerOne: String, answerTwo: String, answerThree: String) { frontLabel.text = question backLabel.text = answerTwo btnOptionOne.setTitle(answerOne, for: .normal) btnOptionTwo.setTitle(answerTwo, for: .normal) btnOptionThree.setTitle(answerThree, for: .normal) } @IBAction func didTapOptionOne(_ sender: Any) { btnOptionOne.isHidden = true } @IBAction func didTapOptionTwo(_ sender: Any) { frontLabel.isHidden = true } @IBAction func didTapOptionThree(_ sender: Any) { btnOptionThree.isHidden = true } }
true