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
b5df0084f2c0af3382740dec6eea7ef6e5875296
Swift
lizhi0123/LoopScrollView
/LoopScrollView/ViewController.swift
UTF-8
2,584
2.890625
3
[]
no_license
// // ViewController.swift // LoopScrollView // // Created by mac on 11/29/15. // Copyright © 2015 mc. All rights reserved. // import UIKit class ViewController: UIViewController,UIScrollViewDelegate { @IBOutlet weak var label1: UILabel! @IBOutlet weak var label2: UILabel! @IBOutlet weak var label3: UILabel! @IBOutlet weak var scrollview: UIScrollView! var curpage : Int = 1 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let width:CGFloat = view.frame.size.width let height:CGFloat = view.frame.size.height - 20 scrollview.frame = CGRect(x: 0, y: 20, width: width, height: height) label1.frame = CGRect(x: width, y: 0, width: width, height: height) label2.frame = CGRect(x: 2 * width, y: 0, width: width, height: height) label3.frame = CGRect(x: 0, y: 0, width: width, height: height) scrollview.contentSize = CGSize(width: width * 3, height: height) scrollview.contentOffset = CGPoint(x: width, y: 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { //当前 page let width:CGFloat = view.frame.size.width let height:CGFloat = view.frame.size.height - 20 curpage = Int(scrollview.contentOffset.x / view.frame.size.width) print(curpage) switch curpage { case 0 : //3 ,1 exchange var tmpLabel = label3 label3 = label1 label1 = tmpLabel //1 , 2 exchange tmpLabel = label2 label2 = label3 label3 = tmpLabel break case 1: break case 2: // 1 ,2 exchange var tmpLabel = label2 label2 = label1 label1 = tmpLabel //3,1 exchange tmpLabel = label3 label3 = label2 label2 = tmpLabel break default: break } label1.frame = CGRect(x: width, y: 0, width: width, height: height) label2.frame = CGRect(x: 2 * width, y: 0, width: width, height: height) label3.frame = CGRect(x: 0, y: 0, width: width, height: height) scrollview.contentOffset = CGPoint(x: width, y: 0) } }
true
ffd423953443e3bb3b13a8371ccbf1bf929eca13
Swift
AlexanderKvamme/Algorithms
/AlgorithmsTests/HashTableTests.swift
UTF-8
1,888
3.203125
3
[]
no_license
// // HashTableTests.swift // Algorithms // // Created by Alexander Kvamme on 06/03/2017. // Copyright © 2017 Alexander Kvamme. All rights reserved. // import XCTest @testable import Algorithms // globale variabler private let capacity: Int = 5 class HashTableTests: XCTestCase { var hashTable = HashTable<String,String>(capacity: capacity) // override func setUp() {f // super.setUp() // } // // override func tearDown() { // super.tearDown() // } func test_hashTableInit_ShouldMakeTable(){ XCTAssertEqual(hashTable.count, 0) } func test_hashTable_isFillable(){ hashTable["Erik"] = "ripped" XCTAssertEqual(hashTable["Erik"], "ripped") } func test_hashTable_isNillable(){ hashTable["Erik"] = "something" hashTable["Erik"] = nil XCTAssertNil(hashTable["Erik"]) } func test_takesMultipleValues(){ hashTable["Tony"] = "Montana" XCTAssertEqual(hashTable["Tony"], "Montana") hashTable["Richard"] = "Travelman" hashTable["Erik"] = "Something" hashTable["KZ"] = "Skrallemester" hashTable["The Kid"] = "Luremesteren" hashTable["Tony"] = "Banana" XCTAssertEqual(hashTable["Tony"], "Banana") hashTable["Kim"] = "Traveller" // ser ut som om Kim - traveller blir lagt til men at det funksjonen streiker print("testprint: ", hashTable["Kim"]) // printer: nil XCTAssertEqual(hashTable["Kim"], "Traveller") // kim returnerer Montana // XCTAssertEqual(hashTable["Richard"], "Travelman") // XCTAssertEqual(hashTable["Tony"], "Montana") // XCTAssertEqual(hashTable["KZ"], "Skrallemester") // XCTAssertEqual(hashTable["The Kid"], "Luremesteren") } }
true
b7724147e4d12f0cf5c54a3cdbddd83149e92050
Swift
Pigpocket/VirtualTourist
/Virtual Tourist/Client/FlickrConvenience.swift
UTF-8
3,886
2.8125
3
[]
no_license
// // FlickrConvenience.swift // Virtual Tourist // // Created by Tomas Sidenfaden on 1/18/18. // Copyright © 2018 Tomas Sidenfaden. All rights reserved. // import UIKit import Foundation import CoreData extension FlickrClient { func getImagesFromFlickr(pin: Pin, context: NSManagedObjectContext, page: Any, completionHandlerForGetImages: @escaping (_ success: Bool, _ errorString: String?) -> Void) { let methodParameters = [ Constants.FlickrParameterKeys.Method: Constants.FlickrParameterValues.FlickrPhotosSearch, Constants.FlickrParameterKeys.APIKey: Constants.FlickrParameterValues.APIKey, Constants.FlickrParameterKeys.Format: Constants.FlickrParameterValues.ResponseFormat, Constants.FlickrParameterKeys.Extras: Constants.FlickrParameterValues.MediumURL, Constants.FlickrParameterKeys.NoJSONCallback: Constants.FlickrParameterValues.DisableJSONCallback, Constants.FlickrParameterKeys.Lat: pin.latitude as Any, Constants.FlickrParameterKeys.Lon: pin.longitude as Any, Constants.FlickrParameterKeys.PerPage: Constants.FlickrParameterValues.PerPage, Constants.FlickrParameterKeys.Page: page ] taskForGetImages(methodParameters: methodParameters, latitude: pin.latitude, longitude: pin.longitude) { (results, error) in if let error = error { completionHandlerForGetImages(false, "There was an error getting the images: \(error)") } else { // Create a dictionary from the data: /* GUARD: Are the "photos" and "photo" keys in our result? */ if let photosDictionary = results![Constants.FlickrResponseKeys.Photos] as? [String:AnyObject], let photoArray = photosDictionary[Constants.FlickrResponseKeys.Photo] as? [[String:AnyObject]] { for photo in photoArray { let image = Images(context: CoreDataStack.sharedInstance().context) // GUARD: Does our photo have a key for 'url_m'? guard let imageUrlString = photo[Constants.FlickrResponseKeys.MediumURL] as? String else { completionHandlerForGetImages(false, "Unable to find key '\(Constants.FlickrResponseKeys.MediumURL)' in \(photo)") return } // Get metadata let imageURL = URL(string: imageUrlString)! let title = photo["title"] as? String ?? "" // Assign the metadata to images NSManagedObject image.imageURL = String(describing: imageURL) image.pin = pin image.title = title CoreDataStack.sharedInstance().context.insert(image) } CoreDataStack.sharedInstance().saveContext() } completionHandlerForGetImages(true, nil) } } } func withBigImage(_ urlString: String?, completionHandler handler: @escaping (_ image:UIImage) -> Void){ DispatchQueue.global(qos: .userInitiated).async { () -> Void in if let url = URL(string: urlString!) { if let imgData = try? Data(contentsOf: url) { if let img = UIImage(data: imgData) { performUIUpdatesOnMain { handler(img) } } } } } } }
true
9c43068bbb312c8a6d38c742f5c7ddc471bd8074
Swift
gusmega/adyen-ios
/Adyen/UI/UI Style/ButtonStyle.swift
UTF-8
798
3.046875
3
[ "MIT" ]
permissive
// // Copyright (c) 2020 Adyen N.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation /// Indicates any "Button" UI style. public struct ButtonStyle: ViewStyle { /// Indicates title text style of the button. public var title: TextStyle /// Indicates the corner radius of the button. public var cornerRadius: CGFloat /// :nodoc: public var backgroundColor: UIColor = .defaultBlue /// Initializes the button style /// /// - Parameter title: The button title text style. /// - Parameter cornerRadius: The button corner radius. public init(title: TextStyle, cornerRadius: CGFloat) { self.title = title self.cornerRadius = cornerRadius } }
true
e6fa53e92821ec9ccd577ad86b79e7e11b1bf326
Swift
Quizer1349/OpenSeaWidgets
/source_code/OpenSeaWidgets/Networking/Protocols/URLSessionProtocol.swift
UTF-8
784
2.828125
3
[ "MIT" ]
permissive
// // URLSessionProtocol.swift // RickMorty // // Created by Oleksii Skliarenko on 06.07.2021. // import Foundation public protocol URLSessionProtocol { typealias DataTaskResult = (Data?, URLResponse?, Error?) -> Void func dataTask(with request: URLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol } public protocol URLSessionDataTaskProtocol { func resume() func cancel() } extension URLSession: URLSessionProtocol { public func dataTask(with request: URLRequest, completionHandler: @escaping URLSessionProtocol.DataTaskResult) -> URLSessionDataTaskProtocol { return dataTask(with: request, completionHandler: completionHandler) as URLSessionDataTask } } extension URLSessionDataTask: URLSessionDataTaskProtocol {}
true
0ca8a0e441267e477b59916c8ad0d7483c6e2fd8
Swift
mmoiseienko/ranalyze
/Ranalyse/Extensions/UserDefaults+keys.swift
UTF-8
530
2.578125
3
[]
no_license
// // UserDefaults+keys.swift // Ranalyse // // Created by Mykhailo Moiseienko on 5/21/19. // Copyright © 2019 Mykhailo Moiseienko. All rights reserved. // import Foundation //let maxHeartRate extension UserDefaults { public enum Key: String { case maxHeartRate } public static func get<T>(key: Key) -> T? { return UserDefaults.standard.value(forKey: key.rawValue) as? T } public static func set<T>(value: T?, forKey key: Key) { UserDefaults.standard.set(value, forKey: key.rawValue) } }
true
fccbe7275c29328cbe9d85673478a711e77d9316
Swift
no1tx/MPDRemote
/src/extensions/UIGestureRecognizer+Extensions.swift
UTF-8
3,470
2.625
3
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// UIGestureRecognizer+Extensions.swift // Copyright (c) 2017 Nyx0uf // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import ObjectiveC private final class Wrapper<T> { let value: T init(_ x: T) { self.value = x } } final class Associator { static private func wrap<T>(_ x: T) -> Wrapper<T> { return Wrapper(x) } static func setAssociatedObject<T>(_ object: Any, value: T?, associativeKey: UnsafeRawPointer, policy: objc_AssociationPolicy) { if let v = value { objc_setAssociatedObject(object, associativeKey, v, policy) } else { objc_setAssociatedObject(object, associativeKey, wrap(value), policy) } } static func getAssociatedObject<T>(_ object: Any, associativeKey: UnsafeRawPointer) -> T? { if let v = objc_getAssociatedObject(object, associativeKey) as? T { return v } else if let v = objc_getAssociatedObject(object, associativeKey) as? Wrapper<T> { return v.value } else { return nil } } } private class MultiDelegate : NSObject, UIGestureRecognizerDelegate { @objc func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } extension UIGestureRecognizer { struct PropertyKeys { static var blockKey = "key-block" static var multiDelegateKey = "key-delegate" } private var block:((_ recognizer:UIGestureRecognizer) -> Void) { get { return Associator.getAssociatedObject(self, associativeKey: &PropertyKeys.blockKey)! } set { Associator.setAssociatedObject(self, value: newValue, associativeKey: &PropertyKeys.blockKey, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } private var multiDelegate:MultiDelegate { get { return Associator.getAssociatedObject(self, associativeKey: &PropertyKeys.multiDelegateKey)! } set { Associator.setAssociatedObject(self, value: newValue, associativeKey: &PropertyKeys.multiDelegateKey, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } convenience init(block:@escaping (_ recognizer:UIGestureRecognizer) -> Void) { self.init() self.block = block self.multiDelegate = MultiDelegate() self.delegate = self.multiDelegate self.addTarget(self, action: #selector(UIGestureRecognizer.didInteractWithGestureRecognizer(_:))) } @objc func didInteractWithGestureRecognizer(_ sender:UIGestureRecognizer) { block(sender) } }
true
f197b17185a055312ac8c3cb394383aa00058fad
Swift
koramit/MatchMeIfYouCan
/MatchMeIfYouCan/ViewController.swift
UTF-8
4,487
2.9375
3
[]
no_license
// // ViewController.swift // MatchMeIfYouCan // // Created by Koramit Pichanaharee on 21/10/18. // Copyright © 2018 Lullabears. All rights reserved. // import UIKit class ViewController: UIViewController { // v 0.2 // lazy var cannot have observer lazy var game = MatchMeIfYouCan(numberOfPairsOfCards: (cardButtons.count + 1) / 2) // v 0.2 // Class 'ViewController' has no initializers // var flipCount: Int // swift is extremry strong type // var flipCount: Int = 0 // but switf can inferred var flipCount = 0 { // property observer pattern didSet { flipCountLabel.text = "Flips: \(flipCount)" } } @IBOutlet weak var flipCountLabel: UILabel! // @IBAction xcode auto add this directive // func => function // Names of argument (internal+external names) // @IBAction func touchCard(_ sender: UIButton) { // flipCount += 1 // flipCard(withEmoji: "🐻", on: sender) // } // // @IBAction func touchSecondCard(_ sender: UIButton) { // flipCount += 1 // flipCard(withEmoji: "🙉", on: sender) // } // array always return optional data [set] or [not set] // nil = not set case of optional @IBOutlet var cardButtons: [UIButton]! var emojiChoicesTemplate = ["🐻", "🐨", "🐷", "👩🏻", "🙉", "🐦", "🐶", "🐼", "🐛", "🐚", "🍟", "🍕", "🍱", "🥘", "🍉", "🍎","🌸", "😜", "👵🏻", "👴🏻", "🍄", "🍡", "🌈", "🍻"] lazy var emojiChoices = emojiChoicesTemplate // v0.2 // var emoji = Dictionary<Int, String>() var emoji = [Int:String]() // v0.2 @IBAction func touchCard(_ sender: UIButton) { flipCount += 1 // add ! at the end of 'cardButtons.firstIndex(of: sender)' // to assume that cardButtons is initiated // but will crash in case of nil // so we can use if for exception handle. if let cardNumber = cardButtons.firstIndex(of: sender) { // flipCard(withEmoji: emojiChoices[cardNumber], on: sender) // let game handle instead of fliCard() game.chooseCard(at: cardNumber) updateViewFromModel() } else { print("card not in the array") } } func updateViewFromModel() { for index in cardButtons.indices { let button = cardButtons[index] let card = game.cards[index] if card.isFaceUp { button.setTitle(emoji(for: card), for: UIControl.State.normal) button.backgroundColor = #colorLiteral(red: 0.6679978967, green: 0.4751212597, blue: 0.2586010993, alpha: 1) } else { button.setTitle(card.isMatched ? "":"🎃", for: UIControl.State.normal) button.backgroundColor = card.isMatched ? #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0) : #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) } } } func emoji(for card: Card) -> String { if emoji[card.identifier] == nil, emojiChoices.count > 0 { let randomIndex = Int(arc4random_uniform(UInt32(emojiChoices.count))) emoji[card.identifier] = emojiChoices.remove(at: randomIndex) } return emoji[card.identifier] ?? "?" } // names order => external internal // name = _ => no external name for Objective c interoperable // if declare only one name => external and internal use the same name func flipCard(withEmoji emoji: String, on button: UIButton) { // print("flipCard(withEmoji: \(emoji))") if button.currentTitle == emoji { button.setTitle("🎃", for: UIControl.State.normal) button.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) } else { button.setTitle(emoji, for: UIControl.State.normal) button.backgroundColor = #colorLiteral(red: 0.6679978967, green: 0.4751212597, blue: 0.2586010993, alpha: 1) } } @IBAction func newGame(_ sender: UIButton) { flipCount = 0 emojiChoices = emojiChoicesTemplate game = MatchMeIfYouCan(numberOfPairsOfCards: (cardButtons.count + 1) / 2) for button in cardButtons { button.setTitle("🎃", for: UIControl.State.normal) button.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) } } }
true
6a707d37d904b3ca9bc0680aaa9df11a553b8b1e
Swift
thmsbfft/another-day
/AnotherDay/Preferences.swift
UTF-8
2,586
3.09375
3
[]
no_license
// // Preferences.swift // today // // Created by thmsbfft on 8/9/18. // Copyright © 2018 thmsbfft. All rights reserved. // import Foundation struct Preferences { var font: String { get { let defaultFont = "System" if let setFont = UserDefaults.standard.string(forKey: "font") { return setFont } UserDefaults.standard.set(defaultFont, forKey: "font") return defaultFont } set { UserDefaults.standard.set(newValue, forKey: "font") } } var size: String { get { let defaultSize = "Small" if let setSize = UserDefaults.standard.string(forKey: "size") { return setSize } UserDefaults.standard.set(defaultSize, forKey: "size") return defaultSize } set { UserDefaults.standard.set(newValue, forKey: "size") } } var someday: Bool { get { return UserDefaults.standard.bool(forKey: "someday") } set { UserDefaults.standard.set(newValue, forKey: "someday") } } var folder: URL { get { let path = UserDefaults.standard.url(forKey: "folder") let fileManager = FileManager.default // check if preference is set if path != nil { var isDir: ObjCBool = false if (fileManager.fileExists(atPath: path!.path, isDirectory: &isDir)) { // the folder exists // return the path return path! } // the folder doesn't exist (moved or trashed) // we'll fallback on the default folder... } // create a default folder let defaultPath = fileManager.homeDirectoryForCurrentUser.appendingPathComponent("Documents").appendingPathComponent("Another Day") do { try fileManager.createDirectory(atPath: defaultPath.path, withIntermediateDirectories: false) } catch { print(error) } // set the default path UserDefaults.standard.set(defaultPath, forKey: "folder") // return the default path return defaultPath } set { UserDefaults.standard.set(newValue, forKey: "folder") } } }
true
db813479c8755a03e4d37ee6dd35276cbbe4cf4c
Swift
Loriens/VK-Cup-2020-Document-List
/VK Document List/Presentation Layer/User Stories/Safari/SafariViewModel.swift
UTF-8
682
2.609375
3
[]
no_license
// // SafariViewModel.swift // VK Document List // // Created by Vladislav on 24.02.2020. // Copyright © 2020 Vladislav Markov. All rights reserved. // protocol SafariViewModelInput { func configure(with data: Any?) } class SafariViewModel { // MARK: - Props var documentItem: DocumentItem? // MARK: - Initialization init() { } // MARK: - Public functions } // MARK: - Module functions extension SafariViewModel { } // MARK: - SafariViewModelInput extension SafariViewModel: SafariViewModelInput { func configure(with data: Any?) { if let documentItem = data as? DocumentItem { self.documentItem = documentItem } } }
true
283123af15e2e7cc92f93805ac4e96f9ff5924a7
Swift
radude89/footballgather-ios
/FootballGather/MVVM/FootballGather/Networking/Services/LoginService.swift
UTF-8
1,891
2.546875
3
[]
no_license
// // LoginService.swift // FootballGather // // Created by Dan, Radu-Ionut (RO - Bucharest) on 15/04/2019. // Copyright © 2019 Radu Dan. All rights reserved. // import Foundation // MARK: - Service final class LoginService: NetworkService { var session: NetworkSession var urlRequest: URLRequestFactory private var appKeychain: ApplicationKeychain init(session: NetworkSession = URLSession.shared, urlRequest: URLRequestFactory = StandardURLRequestFactory(endpoint: StandardEndpoint("/api/users/login")), appKeychain: ApplicationKeychain = FootbalGatherKeychain.shared) { self.session = session self.urlRequest = urlRequest self.appKeychain = appKeychain } func login(user: UserRequestModel, completion: @escaping (Result<Bool, Error>) -> Void) { var request = urlRequest.makeURLRequest() request.httpMethod = "POST" let basicAuth = BasicAuth(username: user.username, password: Crypto.hash(message: user.password)!) request.setValue("Basic \(basicAuth.encoded)", forHTTPHeaderField: "Authorization") session.loadData(from: request) { [weak self] (data, response, error) in if let error = error { completion(.failure(error)) return } guard let data = data, data.isEmpty == false else { completion(.failure(ServiceError.expectedDataInResponse)) return } guard let loginResponse = try? JSONDecoder().decode(LoginResponseModel.self, from: data) else { completion(.failure(ServiceError.unexpectedResponse)) return } self?.appKeychain.token = loginResponse.token completion(.success(true)) } } }
true
19c38fe2d5f89ee0c5e7a433834252d166cdebe4
Swift
tomoyukim/swiftui-rss-reader-sample
/RssReader/Model/Entry.swift
UTF-8
564
2.5625
3
[]
no_license
// // Entry.swift // RssReader // // Created by Tomoyuki Murakami on 2021/01/09. // Copyright © 2021 tomoyukim. All rights reserved. // import Foundation struct Entry: Decodable, Hashable, Identifiable { let id: String let title: String let summary: String let content: String let updated: String let published: String let links: [Link] enum CodingKeys: String, CodingKey { case id case title case summary case content case updated case published case links = "link" } }
true
6949e8e7f3a331fd938e2b0c7b0cc65855fae9f2
Swift
jschindleratt/NearbyObjects
/CaptivateSpace/PreferencesViewController.swift
UTF-8
1,309
2.78125
3
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
// // PreferencesViewController.swift // CaptivateSpace // // Created by Joshua Schindler on 4/28/18. // Copyright © 2018 Joshua Schindler. All rights reserved. // import UIKit class PreferencesViewController: UIViewController { @IBOutlet weak var lblLunarLengths: UILabel! @IBOutlet weak var lblYears: UILabel! @IBOutlet weak var sldLunarLengths: UISlider! @IBOutlet weak var sldYears: UISlider! override func viewDidLoad() { super.viewDidLoad() let lunarDistances: Float = UserDefaults.standard.float(forKey: "lunarDistances") lblLunarLengths.text = lunarDistances.description sldLunarLengths.setValue(Float(lunarDistances), animated: true) let numberOfYears: Float = UserDefaults.standard.float(forKey: "numberOfYears") lblYears.text = numberOfYears.description sldYears.setValue(Float(numberOfYears), animated: true) } @IBAction func sliderValueChanged(_ sender: UISlider) { var key:String = "lunarDistances" var label:UILabel = lblLunarLengths if (sender == sldYears) { key = "numberOfYears" label = lblYears } let currentValue = Float(sender.value) label.text = "\(currentValue)" UserDefaults.standard.set(currentValue, forKey: key) } }
true
5a06f8e53f426e20db3df25583c69659ea8b6df9
Swift
EmilKaczmarski/Gitwise
/Gitwise/Gitwise/Network/BitbucketService.swift
UTF-8
1,261
2.71875
3
[]
no_license
// // BitbucketService.swift // Gitwise // // Created by emil.kaczmarski on 06/06/2021. // import Foundation import Moya enum BitbucketService { case repositories(BitbucketModel.Request.Repositories) } extension BitbucketService: TargetType { var baseURL: URL { URL(string: "https://api.bitbucket.org/2.0")! } var path: String { switch self { case .repositories: return "/repositories" } } var method: Moya.Method { switch self { case .repositories: return .get } } var sampleData: Data { Data() } var task: Task { switch self { case .repositories: return .requestParameters(parameters: parameters, encoding: URLEncoding.default) } } var parameters: [String: Any] { switch self { case let .repositories(payload): return [ "fields": payload.fields, "page": payload.page, "pagelen": payload.pageLen, ] } } var headers: [String : String]? { nil } }
true
fff7d778f75d1be6b1f621075d461e021ce4789a
Swift
dmaulikr/HealthyLife
/HealthyLife/Manager/FoodManager.swift
UTF-8
2,691
3.03125
3
[ "Apache-2.0" ]
permissive
// // FoodManager.swift // HealthyLife // // Created by Duy Nguyen on 3/8/16. // Copyright © 2016 NHD group. All rights reserved. // import Foundation import UIKit import Firebase class FoodManager { static func uploadFood(description: String?, image: UIImage?, withCompletion completion:() -> (), failure: (NSError) -> ()) { //: Upload JSON to realtime database let newFood = Food.createNewFood(description) //: Upload Image guard var foodImage = image else { completion() return } foodImage = foodImage.resizeImage(CGSize(width: 500.0, height: 500.0)) let imageData: NSData = UIImagePNGRepresentation(foodImage)! // Upload the file to the path ""images/\(key)" newFood.imageRef.putData(imageData, metadata: nil) { metadata, error in if (error != nil) { // Uh-oh, an error occurred! failure(error!) } else { // Metadata contains file metadata such as size, content-type, and download URL. let downloadURL = metadata!.downloadURL print(downloadURL) print("does it work") completion() } } } static func getFoods(limit: UInt, withCompletion completion:(foods: [Food]) -> (), failure: (NSError) -> ()) { Food.ChildRef.queryLimitedToLast(limit).observeEventType(.Value, withBlock: { snapshot in // The snapshot is a current look at our jokes data. print(snapshot.value) var foods = [Food]() if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] { for snap in snapshots { // Make our jokes array for the tableView. if let postDictionary = snap.value as? Dictionary<String, AnyObject> { let key = snap.key let food = Food(key: key, dictionary: postDictionary) // Items are returned chronologically, but it's more fun with the newest jokes first. foods.insert(food, atIndex: 0) } } } completion(foods: foods) }, withCancelBlock: { error in failure(error) } ) } }
true
a5d5fa9aebd9a40bfba8c2919afd06b10b1a5741
Swift
KimEklund13/iOS-13-Development
/EightBall/EightBall/ViewController.swift
UTF-8
883
2.890625
3
[]
no_license
// // ViewController.swift // EightBall // // Created by Kim Eklund on 8/8/19. // Copyright © 2019 Kim Eklund. All rights reserved. // import UIKit class ViewController: UIViewController { let ballArray : [String] = ["ball1", "ball2", "ball3", "ball4", "ball5"] var randomBallNumber : Int = 0 @IBOutlet weak var imageView: UILabel! @IBOutlet weak var imageBall: UIImageView! override func viewDidLoad() { super.viewDidLoad() newBallImage() } @IBAction func askButtonPressed(_ sender: Any) { newBallImage() } func newBallImage() { randomBallNumber = Int(arc4random_uniform(5)) imageBall.image = UIImage(named: ballArray[randomBallNumber]) print(randomBallNumber) } override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { newBallImage() } }
true
18b56b1f543c5f69fbe78e299e1da9087daac61f
Swift
yuchan/Pile
/Pile/Classes/Pile.swift
UTF-8
997
2.921875
3
[ "MIT" ]
permissive
// // Pile.swift // Pile // // Created by Yusuke Ohashi on 2017/08/29. // import Foundation public enum TransitionType: String { case push = "push" case pop = "pop" case present = "present" case dismiss = "dismiss" case popover = "popover" case appear = "appear" } open class Pile { static var shared = Pile() static var stacks = [[String: Any]]() static let limited = 5 public static func add(vc: UIViewController, action: TransitionType = .appear) { if stacks.count == limited { stacks.removeFirst() } stacks.append(["name": NSStringFromClass(vc.classForCoder).components(separatedBy: ".").last!, "action": action.rawValue, "created_at": Date()]) // we need to persist immediately and clear memory. } public static func last() -> [String: Any] { return stacks.last! } public static func dump() { print(stacks) } }
true
0b438735b080d1596b4adb21e894785025338eb8
Swift
rodri2d2/WeatherlyPic
/WeatherlyPic/Models/WeatherModels/OpenWeatherData.swift
UTF-8
1,697
3.28125
3
[ "MIT" ]
permissive
// // OpenWeatherData.swift // WeatherlyPic // // Created by Rodrigo Candido on 19/12/20. // import Foundation import UIKit /** Weather Condition class to use as an OpenWeatherMap JSON translator This class represents not only an entire Weather condition, but also a Coordinate object that can be use to send as a location. This class does not match exactly with OpenWetherMap Json respose. - Author: Rodrigo Candido - Version: v1.0 - Attention: For more information about json response check out the official documentation https://openweathermap.org/current */ struct OpenWeatherData: Codable{ var name: String var main: Temperature var weather: [Weather] var coord: Coordinate var wind: Wind /** Computed property that returns **last** avaible icon By doing this way if the weather changes during the day The user will see the equivalent icon for the last/actual weather condition */ var weatherImage: String { let id = self.weather.last?.id ?? self.weather[0].id switch id{ case 200...232: return WeatherIconCase.storm.rawValue case 300...321: return WeatherIconCase.drizzle.rawValue case 500...531: return WeatherIconCase.rain.rawValue case 600...622: return WeatherIconCase.snow.rawValue case 701...781: return WeatherIconCase.mist.rawValue case 801...804: return WeatherIconCase.cloud.rawValue default: return WeatherIconCase.clear.rawValue } } }
true
45d653f51ab9bba323dc77c3f53f13cc544dad14
Swift
RevenueCat/purchases-ios
/Sources/Misc/Concurrency/OperationDispatcher.swift
UTF-8
2,202
2.5625
3
[ "MIT" ]
permissive
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // OperationDispatcher.swift // // Created by Andrés Boedo on 8/5/20. // import Foundation class OperationDispatcher { private let mainQueue: DispatchQueue = .main private let workerQueue: DispatchQueue = .init(label: "OperationDispatcherWorkerQueue") private let maxJitterInSeconds: Double = 5 static let `default`: OperationDispatcher = .init() /// Invokes `block` on the main thread asynchronously /// or synchronously if called from the main thread. func dispatchOnMainThread(_ block: @escaping @Sendable () -> Void) { if Thread.isMainThread { block() } else { self.mainQueue.async(execute: block) } } /// Dispatch block on main thread asynchronously. func dispatchAsyncOnMainThread(_ block: @escaping @Sendable () -> Void) { self.mainQueue.async(execute: block) } func dispatchOnMainActor(_ block: @MainActor @escaping @Sendable () -> Void) { Self.dispatchOnMainActor(block) } func dispatchOnWorkerThread(withRandomDelay: Bool = false, block: @escaping @Sendable () -> Void) { if withRandomDelay { let delay = Double.random(in: 0..<self.maxJitterInSeconds) self.workerQueue.asyncAfter(deadline: .now() + delay, execute: block) } else { self.workerQueue.async(execute: block) } } } extension OperationDispatcher { static func dispatchOnMainActor(_ block: @MainActor @escaping @Sendable () -> Void) { if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) { Task<Void, Never> { @MainActor in block() } } else { DispatchQueue.main.async { @Sendable in block() } } } } // `DispatchQueue` is not `Sendable` as of Swift 5.8, but this class performs no mutations. extension OperationDispatcher: @unchecked Sendable {}
true
e8ff1fb915faa9e1b835f1102eadd2bce19db54f
Swift
zhangle520/ZSCarouselView
/ZSCarouselView/Classes/SphereView/ZSSphereCarouselView.swift
UTF-8
3,910
2.734375
3
[ "MIT" ]
permissive
// // ZSSphereCarouselView.swift // Pods-ZSViewUtil_Example // // Created by 张森 on 2020/3/13. // import UIKit @objcMembers open class ZSSphereCarouselView: UIView { /// 是否开启自动滚动,默认为 true public var isAutoRotate: Bool = true /// 自动滚动的速度,默认是 6 度 / 秒,惯性的大小和速度影响手指拖拽时滚动的速度 public var autoRotateSpeed: CGFloat = 6 /// 是否开启滚动惯性,默认为 true public var isInertiaRotate: Bool = true /// 惯性的初始大小,默认为 20,惯性的大小和速度影响手指拖拽时滚动的速度 public var inertiaRotatePower: CGFloat = 20 /// 是否开启翻转手势,defult:true public var isRotationGesture: Bool = true /// 是否开启拖动手势,defult:true public var isPanGesture: Bool = true var property = Property() struct Property { /// 惯性滚动的方向,x=1为左, x=-1为右,y=1为下,y=-1为上 var intervalRotatePoint: CGPoint = CGPoint(x: 1, y: 1) /// 滚动动画每秒多少帧 var fps: CGFloat = 60 /// 自动滚动的定时器 var displayLink: ZSSphereDisplayLink? /// 惯性滚动的定时器 var inertiaDisplayLink: ZSSphereDisplayLink? /// item的集合 var items: [UIView] = [] /// 每一个item的位置 var itemPoints: [PFPoint] = [] /// 拖动以前的位置 var previousLocationInView: CGPoint = .zero /// 拖动之后的位置 var originalLocationInView: CGPoint = .zero /// 拖拽最后的x var lastXAxisDirection: PFAxisDirection = PFAxisDirectionNone /// 拖拽最后的y var lastYAxisDirection: PFAxisDirection = PFAxisDirectionNone /// 惯性的力度,逐渐减弱,直到为0 var inertiaRotatePower: CGFloat = 0 /// 最后旋转的角度 var lastSphereRotationAngle: CGFloat = 1 } public override init(frame: CGRect) { super.init(frame: frame) setUpGestureRecognizer() } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func layoutSubviews() { super.layoutSubviews() } deinit { stopDisplay() stopInertiaDisplay() } /// 初始化设置球体内部的item /// - Parameter items: item集合 open func zs_setSphere(_ items: [UIView]) { guard items.count > 0 else { return } property.items = Array(items) } open func zs_beginAnimation() { guard frame != .zero else { return } guard property.items.count > 0 else { return } let inc = Double.pi * (3 - sqrt(5)) let offset = 2 / Double(property.items.count) for (index, item) in property.items.enumerated() { let y = Double(index) * offset - 1 + (offset * 0.5) let r = sqrt(1 - pow(y, 2)) let phi = Double(index) * inc let point = PFPoint(x: CGFloat(cos(phi)*r), y: CGFloat(y), z: CGFloat(sin(phi)*r)) property.itemPoints.append(point) item.center = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5) addSubview(item) layoutIfNeeded() let time = TimeInterval(CGFloat(arc4random() % UInt32(property.fps)) / property.fps) UIView.animate(withDuration: time) { self.layout(item, with: point) } } if isAutoRotate { startDisplay() } else { runDisplayLink() } } }
true
96b8e3be4abafe3595dc0357c3752d682b0667b6
Swift
JubrilO/SmartAlumni
/SmartAlumni/PollVisibility/View/PollVisibilityViewController.swift
UTF-8
8,364
2.53125
3
[]
no_license
// // PollVisibilityViewController.swift // SmartAlumni // // Created by Jubril on 11/23/17. // Copyright (c) 2017 Kornet. All rights reserved. // import UIKit protocol PollVisibilityViewControllerInput: PollVisibilityPresenterOutput { } protocol PollVisibilityViewControllerOutput { var schools: [School] {get set} var departments: [Department] {get set} var faculties: [Faculty] {get set} var pickerData: [String] {get set} var targetSchool: School? {get set} var targetDeparments: [Department] {get set} var targetFaculties: [Faculty] {get set} var targetSets: [String] {get set} func fetchSchools() func fetchFaculties(schoolIndex: Int) func fetchDepartments() func fetchSets() func getPollVisiblityData() func saveVisibilityOptions() } final class PollVisibilityViewController: UIViewController{ var output: PollVisibilityViewControllerOutput! var router: PollVisibilityRouterProtocol! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var copyLabel: UILabel! var pollMode = true let pickerView = UIPickerView() var pickerData = [String]() var selectedIndex = 0 var doneBarButton = UIBarButtonItem() var textFieldType = ["Target School", "Faculty", "Department", "Set"] init(configurator: PollVisibilityConfigurator = PollVisibilityConfigurator.sharedInstance) { super.init(nibName: nil, bundle: nil) configure() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } // MARK: - Configurator private func configure(configurator: PollVisibilityConfigurator = PollVisibilityConfigurator.sharedInstance) { configurator.configure(viewController: self) } // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() setupNavBar() pickerView.delegate = self tableView.tableFooterView = UIView() if pollMode { copyLabel.text = "Choose who can participate in this poll" } else { copyLabel.text = "Choose who can participate in this project" } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setupTextfields() output.getPollVisiblityData() } // MARK: - Load data func fetchSchools() { output.fetchSchools() } func setupTextfields() { if output.targetSchool?.category == SchoolCategory.Secondary.rawValue || output.targetSchool?.category == SchoolCategory.Primary.rawValue { if textFieldType.count > 2 { textFieldType.remove(at: 1) textFieldType.remove(at: 2) let deparmentIndexPath = IndexPath(row: 2, section: 0) let facultyIndexPath = IndexPath(row: 1, section: 0) tableView.deleteRows(at: [facultyIndexPath, deparmentIndexPath], with: .automatic) } } else { textFieldType = ["Target School", "Faculty", "Department", "Set"] tableView.reloadData() } } func setupNavBar() { title = "Visibility" doneBarButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(saveVisibilitySettings)) doneBarButton.tintColor = UIColor.black navigationItem.setRightBarButton(doneBarButton, animated: false) navigationItem.rightBarButtonItem?.isEnabled = false } @objc func saveVisibilitySettings() { print("saving visibility settings") if let targetSchool = output.targetSchool { router.navigateToNewPollScene(school: targetSchool, faculties: output.targetFaculties, departments: output.targetDeparments, sets: output.targetSets) } else { displayErrorModal(error: "Please select a school who can view this") } } } // MARK: - PollVisibilityPresenterOutput extension PollVisibilityViewController: PollVisibilityViewControllerInput { // MARK: - Display logic func displayTargetSchool(school: String) { let schoolCell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! VisibilityCell schoolCell.titleTextField.text = school doneBarButton.isEnabled = true } func displayTargetDepartments(departments: String) { if let index = textFieldType.index(of: "Department") { let departmentCell = tableView.cellForRow(at: IndexPath(row: Int(index), section: 0)) as! VisibilityCell departmentCell.titleTextField.text = departments } } func displayTargetFaculties(faculties: String) { if let index = textFieldType.index(of: "Faculty"){ let facultyCell = tableView.cellForRow(at: IndexPath(row: Int(index), section: 0)) as! VisibilityCell facultyCell.titleTextField.text = faculties } } func displayTargetSets(sets: String) { if textFieldType.count > 1 { if output.targetSchool?.category == SchoolCategory.Secondary.rawValue || output.targetSchool?.category == SchoolCategory.Primary.rawValue { let setCell = tableView.cellForRow(at: IndexPath(row: Int(1), section: 0)) as! VisibilityCell setCell.titleTextField.text = sets } else { let setCell = tableView.cellForRow(at: IndexPath(row: Int(3), section: 0)) as! VisibilityCell setCell.titleTextField.text = sets } } } } extension PollVisibilityViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return textFieldType.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: Constants.CellIdentifiers.VisibilityCell) as! VisibilityCell cell.titleTextField.delegate = self cell.titleTextField.inputView = pickerView cell.titleTextField.placeholder = textFieldType[indexPath.row] cell.titleTextField.tag = indexPath.row return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 48 } } extension PollVisibilityViewController: UIPickerViewDelegate { func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return output.pickerData[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let currentFirstResponder = UIResponder.first as! UITextField currentFirstResponder.text = output.pickerData[row] } } extension PollVisibilityViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return false } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { switch textField.tag { case 0: router.navigateToVisibilityOptionScene(dataType: .School) case 1: guard output.targetSchool != nil else {displayErrorModal(error: "Select a target school first"); return false} router.navigateToVisibilityOptionScene(dataType: .Faculty) case 2: guard output.targetSchool != nil else {displayErrorModal(error: "Select a target school first"); return false} router.navigateToVisibilityOptionScene(dataType: .Department) case 3: guard output.targetSchool != nil else {displayErrorModal(error: "Select a target school first"); return false} router.navigateToVisibilityOptionScene(dataType: .Set) default: break } return false } func textFieldDidBeginEditing(_ textField: UITextField) { } func textFieldDidEndEditing(_ textField: UITextField) { pickerData = [String]() } }
true
92bed9f64c94003a169b9c711b7601a1115bc616
Swift
ProyectoIntegrador2018/EEMI_IOS
/EEMI/EEMI/MedicalRecord.swift
UTF-8
1,506
3.0625
3
[]
no_license
// // MedicalRecord.swift // EEMI // // Created by Pablo Cantu on 3/20/19. // Copyright © 2019 Io Labs. All rights reserved. // import Foundation import SwiftyJSON class MedicalRecord { let mother: String let father: String var summaries = [Summary]() var immunizations = [Immunization]() init(json: JSON) { mother = json["mother"].stringValue father = json["father"].stringValue let jsonImmunizations = json["immunizations"].arrayValue for jsonImmunization in jsonImmunizations { let name = jsonImmunization["immunization"].stringValue let status = jsonImmunization["status"].intValue immunizations.append(Immunization(name: name, status: status)) } let jsonSummaries = json["summary"].arrayValue for jsonSummary in jsonSummaries { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" let date = dateFormatter.date(from: jsonSummary["date"].stringValue) let reason = jsonSummary["reason"].stringValue let description = jsonSummary["summary"].stringValue summaries.append(Summary(date: date, reason: reason, description: description)) } } struct Immunization { var name: String var status: Int } struct Summary { var date: Date? var reason: String var description: String } }
true
d8b86dc0c4e505b0bf43b51a5ae2c48f5f984cfb
Swift
BakerMatthew/SwiftProjects
/VariousProjects/PhotoLibrary/PhotoLibrary/imageVC.swift
UTF-8
819
2.640625
3
[]
no_license
// // imageVC.swift // PhotoLibrary // // Created by Matt Baker on 2/29/16. // Copyright © 2016 usu. All rights reserved. // import UIKit import RealmSwift class imageVC: UIViewController { var imageData: ImageData! @IBOutlet weak var imageTitle: UILabel! @IBOutlet weak var imageLocation: UILabel! @IBOutlet weak var userImage: UIImageView! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("Location: \(imageData.location) , Title: \(imageData.title)"); //Set image userImage.image = UIImage(data: imageData.photo! as Data) //Set location imageLocation.text = imageData.location //Set Title imageTitle.text = imageData.title } }
true
6273918e541030e436cf6b6007923bd059158837
Swift
brisingrc/CryptoConverter1
/CryptoConverter/Controller/DetailViewController.swift
UTF-8
1,455
2.78125
3
[]
no_license
// // DetailViewController.swift // CryptoConverter // // Created by Мак on 11/3/19. // Copyright © 2019 Aidar Zhussupov. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var nameLabelTwo: UILabel! @IBOutlet weak var percentLabel: UILabel! @IBOutlet weak var lastUpdated: UILabel! @IBOutlet weak var supplyLabel: UILabel! @IBOutlet weak var marketLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var symbolLabel: UILabel! var quote: Quote? override func viewDidLoad() { super.viewDidLoad() updateUI() } } extension DetailViewController { func updateUI() { if let quote = quote { //nameLabel.text = "\(quote.name)" nameLabelTwo.text = "name: \(quote.name)" title = quote.name imageView.image = quote.image symbolLabel.text = "Symbol: \(quote.symbol)" priceLabel.text = "Price: \(quote.price_usd) $" marketLabel.text = "Market cap usd: \(quote.market_cap_usd)" supplyLabel.text = "Available supply: \(quote.max_supply)" percentLabel.text = "percent change 7d: \(quote.percent_change_7d)" lastUpdated.text = "last updated \(quote.last_updated)" } } }
true
4c0f78c96097227f825cc8b9ab03077580d750a3
Swift
zephox/SecureProgramming
/IrunT/test/controllers/registerViewController.swift
UTF-8
4,329
2.53125
3
[]
no_license
// // registerViewController.swift // test // // Created by Alex Iakab on 29/11/2018. // Copyright © 2018 Alex Iakab. All rights reserved. // import UIKit import FirebaseAuth class registerViewController: UIViewController { @IBOutlet weak var button: UIButton! @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var passwordCheckField: UITextField! @IBOutlet weak var imageView: UIImageView! @IBOutlet var registerView: UIView! let currentUser = Auth.auth().currentUser // var email = "" // var password = "" // var passwordCheck = "" override func viewDidLoad() { super.viewDidLoad() button.setCorner(8) imageView.image = imageView.image!.withRenderingMode(.alwaysTemplate) imageView.tintColor = UIColor.goodGreen button.layer.borderWidth = 1 button.layer.borderColor = UIColor.goodGreen.cgColor emailField.setBorderBottom(false) passwordField.setBorderBottom(false) passwordCheckField.setBorderBottom(false) registerView.backgroundColor = UIColor(patternImage: UIImage(named: "BackgroundD")!) } override func viewDidAppear(_ animated: Bool) { } @IBAction func editingStartP(_ sender: UITextField) { sender.setBorderBottom(true) } @IBAction func editingEndP(_ sender: UITextField) { sender.setBorderBottom(false) } @IBAction func registerPressed(_ sender: UIButton) { let emailInput = emailField.text let passwordInput = passwordField.text let passwordCheckInput = passwordCheckField.text if currentUser == nil { if ((emailInput?.isEmpty)!) || ((passwordInput?.isEmpty)!) || ((passwordCheckInput?.isEmpty)!){ alert(title: "Zonk", message: "Please fill in all the fields", option: "Try Again") } else { if (passwordInput?.count)! < 6 { alert(title: "Zonk", message: "Password needs to be at least 6 characters", option: "Try Again") } else{ registerUser(email: emailInput!, password: passwordInput!, checkPassword: passwordCheckInput!) self.performSegue(withIdentifier: "registerPressed", sender: self) } } } else { alert(title: "Logged In", message: "Something went wrong, you should not be here, please restart the app", option: "OK") } } func registerUser(email: String, password: String, checkPassword: String) { if password == checkPassword { Auth.auth().createUser(withEmail: email, password: password) { (authResult, error) in print(error) print(authResult) guard let user = authResult?.user else {return} } } else { alert(title: "Zonk", message: "Passwords do not match!", option: "Try Again") } } func alert(title: String, message: String, option: String) { let alert = UIAlertController(title: title, message: message , preferredStyle: .alert) let action = UIAlertAction(title: option, style: .default, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) } } extension UIView{ func setBorderBottom(_ color : Bool ){ let lineView = UIView() lineView.translatesAutoresizingMaskIntoConstraints = false // This is important! self.addSubview(lineView) let metrics = ["width" : NSNumber(value: 2)] let views = ["lineView" : lineView] self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[lineView]|", options:NSLayoutConstraint.FormatOptions(rawValue: 0), metrics:metrics, views:views)) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[lineView(width)]|", options:NSLayoutConstraint.FormatOptions(rawValue: 0), metrics:metrics, views:views)) if color == true { lineView.backgroundColor = UIColor.orange } else{ lineView.backgroundColor = UIColor.white } } }
true
b5a2e7eb2850818b08da72518d72bcf6b1324a83
Swift
linaamdouni/HamHamaIOS
/HamHamaIOS/New Group/checkBox3.swift
UTF-8
1,053
3.015625
3
[]
no_license
// // checkBox3.swift // HamHamaIOS // // Created by Mac on 4/22/19. // Copyright © 2019 Mac. All rights reserved. // import UIKit class checkBox3: UIButton { //images let checkedImage = UIImage(named: "checked") as! UIImage let uncheckedImage = UIImage(named: "nochecked") as! UIImage //bool property var ischecked: Bool = false{ didSet{ if ischecked == true{ self.setImage(checkedImage, for: .normal) }else{ self.setImage(uncheckedImage, for: .normal) } } } override func awakeFromNib() { self.addTarget(self, action:#selector(buttonClicked(sender:)), for: .touchUpInside) self.ischecked = false } @objc func buttonClicked(sender: UIButton){ if sender == self{ if ischecked == true{ ischecked = false sender.tag = 5 }else{ ischecked = true sender.tag = 6 } } } }
true
da2149d5cc833885b8ca5570b04cc253d8acba9d
Swift
bendoppler/coffee-storyboard
/coffee-storyboard/CustomTabBar/TabBarViewController.swift
UTF-8
3,608
2.765625
3
[]
no_license
// // TabBarViewController.swift // coffee-storyboard // // Created by Do Thai Bao on 11/28/19. // Copyright © 2019 Do Thai Bao. All rights reserved. // import UIKit class TabBarViewController: UITabBarController { var customTabBar: TabBarMenu! var tabBarHeight: CGFloat = 75.0 var screenHeight: CGFloat = 0.0 let stateController = StateController() override func viewDidLoad() { super.viewDidLoad() screenHeight = self.view.bounds.height tabBarHeight = screenHeight*0.08370535714 self.loadTabBar() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let shadowPath = UIBezierPath(rect: customTabBar.bounds) customTabBar.layer.masksToBounds = false customTabBar.layer.shadowColor = UIColor.black.cgColor customTabBar.layer.shadowOffset = CGSize(width: 0, height: -0.5) customTabBar.layer.shadowOpacity = 0.4 customTabBar.layer.shadowPath = shadowPath.cgPath } private func loadTabBar() { let tabItems: [TabItem] = [.home, .order, .pien, .user] self.setupCustomTabMenu(for: tabItems) { (controllers) in self.viewControllers = controllers } for vc in self.viewControllers! { if vc.contents is HomeViewController { let homeVC = vc.contents as! HomeViewController homeVC.stateController = stateController } if vc.contents is UserViewController { let userVC = vc.contents as! UserViewController userVC.stateController = stateController } if vc.contents is OrderViewController { let orderVC = vc.contents as! OrderViewController orderVC.stateController = stateController } } self.selectedIndex = 0 } private func setupCustomTabMenu(for items: [TabItem], completion: @escaping ([UIViewController]) -> Void) { let frame = tabBar.frame var controllers = [UIViewController]() //hide the tab bar tabBar.isHidden = true self.customTabBar = TabBarMenu(menuItems: items, frame: frame, height: screenHeight) self.customTabBar.translatesAutoresizingMaskIntoConstraints = false self.customTabBar.clipsToBounds = true self.customTabBar.itemTapped = self.changeTab //add it to the view self.view.addSubview(customTabBar) // Add positioning constraints to place the nav menu right where the tab bar should be NSLayoutConstraint.activate([ self.customTabBar.leadingAnchor.constraint(equalTo: tabBar.leadingAnchor), self.customTabBar.trailingAnchor.constraint(equalTo: tabBar.trailingAnchor), self.customTabBar.widthAnchor.constraint(equalToConstant: tabBar.frame.width), self.customTabBar.heightAnchor.constraint(equalToConstant: tabBarHeight), self.customTabBar.bottomAnchor.constraint(equalTo: tabBar.bottomAnchor) ]) for i in 0 ..< items.count { controllers.append(items[i].viewController) } self.view.layoutIfNeeded() completion(controllers) } func changeTab(of index: Int) { self.selectedIndex = index } } extension UIViewController { var contents: UIViewController { if let navcon = self as? UINavigationController { return navcon.visibleViewController ?? navcon } else { return self } } }
true
ae91ae98a511ce845f3d5d9e921b35c257d25a02
Swift
darkFunction/GoldenRetriever
/Sources/GoldenRetriever/Endpoint.swift
UTF-8
818
2.875
3
[ "MIT" ]
permissive
// // Endpoint.swift // GoldenRetriever // // Created by Sam Taylor on 18/12/2018. // import Foundation public protocol Endpoint { var baseAddress: URL { get } var info: EndpointInfo { get } } public extension Endpoint { var url: URL? { if var urlComponents = URLComponents(url: baseAddress, resolvingAgainstBaseURL: true) { if let pathComponents = URLComponents(string: urlComponents.path + info.path) { urlComponents.path = pathComponents.path urlComponents.query = pathComponents.query } urlComponents.queryItems = info.parameters?.map { (key, value) -> URLQueryItem in return URLQueryItem(name: key, value: value ?? "") } return urlComponents.url } return nil } }
true
a84fed886094d1eb62a2ce8dad06100675962864
Swift
hoangtaiki/Spider
/Sources/Spider/StubURLProtocol.swift
UTF-8
2,353
2.609375
3
[ "MIT" ]
permissive
// // StubURLProtocol.swift // Spider // // Created by Harry Tran on 7/16/19. // Copyright © 2019 Harry Tran. All rights reserved. // import Foundation final class StubURLProtocol: URLProtocol { override class func canInit(with request: URLRequest) -> Bool { return request.url != nil } override class func canonicalRequest(for request: URLRequest) -> URLRequest { return request } override func startLoading() { // Get stub response from stub array // If not found return not found stub for request guard let stubResponse = Spider.default.response(for: request) else { let error = NSError(domain: NSExceptionName.internalInconsistencyException.rawValue, code: 0, userInfo: [NSLocalizedDescriptionKey: "Handling request without a matching stub."]) client?.urlProtocol(self, didFailWithError: error) return } switch stubResponse { case let .success(statusCode, data): sendResponseData(data, statusCode: statusCode) case let .failed(statusCode, data, error): if let responseData = data { sendResponseData(responseData, statusCode: statusCode) return } else if let responseError = error { sensendResponseError(responseError) } let error = NSError(domain: NSExceptionName.internalInconsistencyException.rawValue, code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed response dont contain any data or error"]) client?.urlProtocol(self, didFailWithError: error) } } override func stopLoading() { } private func sendResponseData(_ data: Data, statusCode: Int) { let response = HTTPURLResponse(url: request.url!, statusCode: statusCode, httpVersion: nil, headerFields: request.allHTTPHeaderFields)! client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) client?.urlProtocol(self, didLoad: data) client?.urlProtocolDidFinishLoading(self) } private func sensendResponseError(_ error: Error) { client?.urlProtocol(self, didFailWithError: error) } }
true
3130f022f44a9c6a5148a1b6736e631061216339
Swift
massi-ang/amazon-freertos-ble-ios-sdk
/AmazonFreeRTOS/Services/NetworkConfig/NetworkMessage.swift
UTF-8
546
2.703125
3
[ "Apache-2.0", "MIT" ]
permissive
/// Generic network config message. public struct NetworkMessage: Decborable { init?(dictionary: NSDictionary) { guard let typeRawValue = dictionary.object(forKey: CborKey.type.rawValue) as? Int, let type = NetworkMessageType(rawValue: typeRawValue) else { return nil } self.type = type } /// Network message type. public var type: NetworkMessageType static func toSelf<T: Decborable>(dictionary: NSDictionary) -> T? { return NetworkMessage(dictionary: dictionary) as? T } }
true
0245ada10e81c87c9a74ebfc9ea6abb68e532b08
Swift
kconner/AllYourFault
/Code/AllYourFault/APIResult.swift
UTF-8
478
3.328125
3
[]
no_license
// // APIResult.swift // AllYourFault // // Created by Kevin Conner on 8/4/15. // Copyright (c) 2015 Kevin Conner. All rights reserved. // // Haskell's Either a b, or LlamaKit's Result. Contains one kind of value or the other. enum APIResult<A, B> { case Success(A) case Failure(B) static func success(_ value: A) -> APIResult<A, B> { return .Success(value) } static func failure(_ value: B) -> APIResult<A, B> { return .Failure(value) } }
true
e30eaee944d02c5672c8bf1b5acb12c402d1c942
Swift
PeledTomer/SmallWorld
/SmallWorld/ViewControllers/CountriesAllTVC.swift
UTF-8
1,660
2.65625
3
[]
no_license
// // CountriesAllTVC.swift // SmallWorld // // Created by Tomer Peled on 8/17/18. // Copyright © 2018 Tomer Peled. All rights reserved. // import UIKit class CountriesAllTVC: UITableViewController { let cellId = "allCountriesIdentifier" let segueId = "showBorders" var countries: [Country]? { didSet{ self.tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() fetchCountries() } func fetchCountries() { DataManager.sharedInstance.fetchAllCountries{ [weak self] (countries: [Country]) in self?.countries = countries } } // MARK: - UITableView methods override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return countries?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) cell.textLabel?.text = countries?[indexPath.item].name ?? "" cell.detailTextLabel?.text = countries?[indexPath.item].nativeName ?? "" return cell } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == segueId { if let destinationVC = segue.destination as? CountriesBordersTVC { if let indexPath = self.tableView.indexPathForSelectedRow { destinationVC.selectedCountry = countries?[indexPath.row] } } } } }
true
f9782810318cc592bd1c1235b35c5426c305e950
Swift
Mylittleswift/algorithm-questions
/Leetcode/250.swift
UTF-8
1,069
3.640625
4
[]
no_license
/*** 250 Count Univalue Subtrees Medium Problem: Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of the subtree have the same value. For example: Given binary tree, 5 / \ 1 5 / \ \ 5 5 5 return 4. ***/ class Solution250 { func countUnivalSubtrees(_ root:TreeNode?) -> Int { var b:Bool = true return isUnival(root, &b) } func isUnival(_ root:TreeNode?,_ b:inout Bool) -> Int { if root == nil { return 0 } var l:Bool = true var r:Bool = true var res:Int = isUnival(root?.left, &l) + isUnival(root?.right, &r) b = l && r if root?.left != nil { b = b && (root!.val == root!.left!.val) } else { b = b && true } if root?.right != nil { b = b && (root!.val == root!.right!.val) } else { b = b && true } var num:Int = b ? 1 : 0 return res + num } }
true
13d5abade15e1bf707ec4960b145775f8abe60c0
Swift
davidmhidary/LunchTime
/LunchTime/DetailViewController.swift
UTF-8
1,820
2.578125
3
[]
no_license
// // DetailViewController.swift // LunchTime // // Created by David Hidary on 8/4/17. // Copyright © 2017 Upperline Code. All rights reserved. // import UIKit import MapKit class DetailViewController: UIViewController { var restaurantName: String! var restaurantLocation: CLLocation! var pricesLabel: String! let newPin = MKPointAnnotation() @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var nameOfRestaurant: UILabel! override func viewDidLoad() { super.viewDidLoad() // let leaningTower = CLLocation (latitude: 43.723225, longitude: 10.394724) descriptionLabel.text = pricesLabel nameOfRestaurant.text = restaurantName centerOnLocation(location: restaurantLocation, mapView: mapView) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func centerOnLocation(location: CLLocation, mapView: MKMapView) { let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 1050, 1050) newPin.coordinate = restaurantLocation.coordinate mapView.addAnnotation(newPin) mapView.setRegion(coordinateRegion, animated: true) mapView.mapType = .standard } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
8f38713a5686f43273517c16cd216678bd422323
Swift
vctrsmelo/Studis
/Studis/StudisTests/PersistenceManagerTests.swift
UTF-8
1,512
2.96875
3
[]
no_license
// // PersistenceManagerTests.swift // StudisTests // // Created by Victor Melo on 03/03/18. // Copyright © 2018 Victor S Melo. All rights reserved. // import XCTest import Disk @testable import Studis class PersistenceManagerTests: XCTestCase { private class PersistenceManagerTest: PersistenceManager { private(set) var areasTest: Set<Area> = [] override func fetchData() { do { self.areasTest = try Disk.retrieve("areaTest.json", from: .temporary, as: Set<Area>.self) } catch { fatalError("Couldn't fetch data: \(error.localizedDescription)") } } override func storeData() { do { try Disk.save(areasTest, to: .temporary, as: FileNames.area.rawValue) } catch { fatalError("Couldn't store data: \(error.localizedDescription)") } } } let persistenceManager = PersistenceManagerTest.shared override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testStoring() { persistenceManager.addArea(name: "College", topics: ["Database class"]) persistenceManager.storeData() persistenceManager.fetchData() XCTAssertEqual(persistenceManager.areas.count, 1) XCTAssertTrue(persistenceManager.areas.contains(where: {$0.name == "College"})) } }
true
b089212f3492b5518d1a16d8c53797b640748dc5
Swift
misolubarda/Travel
/Travel/Model/Application/LocalStorage/LocalStorage.swift
UTF-8
1,654
2.875
3
[]
no_license
// // LocalStorage.swift // Travel // // Created by Miso Lubarda on 21/08/16. // Copyright © 2016 test. All rights reserved. // import Foundation struct LocalStorage { static func fetchTrips<T: Trip>() throws -> [T] { let defaults = NSUserDefaults.standardUserDefaults() let defaultsKey = try self.defaultsKeyForTripType(T) guard let tripArray = defaults.objectForKey(defaultsKey) as? [[String: AnyObject]] else { return [] } let trips: [T] = try tripArray.map { try T(JSONDict: $0) } return trips } static func saveTrips<T: Trip>(trips: [T]) throws { let tripArray: [[String: AnyObject]] = trips.map { $0.exportToJSONDict() } let defaults = NSUserDefaults.standardUserDefaults() let defaultsKey = try self.defaultsKeyForTripType(T) defaults.setObject(tripArray, forKey: defaultsKey) } static func defaultsKeyForTripType<T: Trip>(type: T.Type) throws -> String { var defaultsKey: String? if T.self == FlightTrip.self { defaultsKey = "flightsKey" } else if T.self == BusTrip.self { defaultsKey = "busesKey" } else if T.self == TrainTrip.self { defaultsKey = "trainsKey" } guard let recognizedDefaultsKey = defaultsKey else { throw LocalStorageError.DefaultsKeyUnknown } return recognizedDefaultsKey } } extension LocalStorage { enum LocalStorageError: ErrorType { case DefaultsKeyUnknown } }
true
3cb565f67ad3f0e82ddb9b5c04d23a647c968450
Swift
rpassis/XStreamSwift
/XStream/Stream.swift
UTF-8
5,287
3.1875
3
[ "MIT" ]
permissive
// // Stream.swift // XStream // // Created by Daniel Tartaglia on 9/3/16. // Copyright © 2016 Daniel Tartaglia. MIT License. // import Foundation public protocol StreamConvertable { associatedtype Value func asStream() -> Stream<Value> } public class Stream<T>: StreamConvertable { public typealias Value = T public typealias ListenerType = AnyListener<Value> /** Adds a "debug" listener to the stream. There can only be one debug listener. A debug listener is like any other listener. The only difference is that a debug listener is "stealthy": its presence/absence does not trigger the start/stop of the stream (or the producer inside the stream). This is useful so you can inspect what is going on without changing the behavior of the program. If you have an idle stream and you add a normal listener to it, the stream will start executing. But if you set a debug listener on an idle stream, it won't start executing (not until the first normal listener is added). Don't use this to build app logic. In most cases the debug operator works just fine. Only use this if you know what you're doing. */ public var debugListener: ListenerType? = nil /// Creates a Stream that does nothing. It never emits any event. public convenience init() { self.init(producer: AnyProducer<Value>(start: { _ in }, stop: { })) } /// Creates a Stream that immediately emits the "complete" notification when started, and that's it. public static func empty<Value>() -> Stream<Value> { let producer = AnyProducer<Value>(start: { $0.complete() }, stop: { }) return Stream<Value>(producer: producer) } /// Creates a Stream that immediately emits an "error" notification with the value you passed as the `error` argument when the stream starts, and that's it. public convenience init(error: Error) { self.init(producer: AnyProducer<Value>(start: { $0.error(error) }, stop: { })) } /// Creates a Stream that immediately emits the arguments that you give to of, then completes. public convenience init(of args: Value...) { self.init(producer: FromArrayProducer(array: args)) } /// Converts an array to a stream. The returned stream will emit synchronously all the items in the array, and then complete. public convenience init(from array: [Value]) { self.init(producer: FromArrayProducer(array: array)) } /// Creates a new Stream given a Producer. public init<P: Producer>(producer: P) where P.ProducerValue == Value { self.producer = AnyProducer<Value>(producer) } public typealias RemoveToken = String /// Adds a Listener to the Stream. public func add<L: Listener>(listener: L) -> RemoveToken where Value == L.ListenerValue { return add(listener: AnyListener(listener)) } public func add(listener: ListenerType) -> RemoveToken { guard ended == false else { return "" } let removeToken = UUID().uuidString listeners[removeToken] = listener if listeners.count == 1 { if let stopID = stopID { cancel_delay(stopID) } else { producer.start(for: AnyListener(next: self.next, complete: self.complete, error: self.error)) } } return removeToken } /// Removes a Listener from the Stream, assuming the Listener was added to it. public func removeListener(_ token: RemoveToken) { remove(token) } /** *imitate* changes this current Stream to emit the same events that the `other` given Stream does. This method returns nothing. This method exists to allow one thing: **circular dependency of streams**. For instance, let's imagine that for some reason you need to create a circular dependency where stream `first$` depends on stream `second$` which in turn depends on `first$` */ public func imitate(target: Stream) { precondition(target is MemoryStream == false) if let imitateToken = imitateToken, let _target = self.target { _target.remove(imitateToken) } imitateToken = target.add(listener: AnyListener(next: self.next, complete: self.complete, error: self.error)) } public func asStream() -> Stream<Value> { return self } func next(_ value: Value) { debugListener?.next(value) notify { $0.next(value) } } func complete() { debugListener?.complete() notify { $0.complete() } tearDown() } func error(_ error: Error) { debugListener?.error(error) notify { $0.error(error) } tearDown() } private let producer: AnyProducer<Value> private var listeners: [String: ListenerType] = [:] private var ended = false private var stopID: dispatch_cancelable_closure? = nil private var target: Stream? private var imitateToken: RemoveToken? private func notify(_ fn: (ListenerType) -> Void) { for listener in listeners.values { fn(listener) } } private func tearDown() { guard listeners.isEmpty == false else { return } producer.stop() listeners = [:] ended = true } private func remove(_ token: RemoveToken) { listeners.removeValue(forKey: token) if listeners.count == 0 { stopID = delay(0.1) { self.producer.stop() } } } } /// Creates a stream that periodically emits incremental numbers, every `period` seconds. public func periodicStream(_ period: TimeInterval) -> Stream<Int> { return Stream(producer: PeriodicProducer(period: period)) } let noListener = AnyListener<Void>(next: { _ in }, complete: { }, error: { _ in })
true
e894611a799b890e27b5e99a173943bb2c9fca2d
Swift
LukieNL/Todo-itSimple
/Todo-itSimple/Controller/CategoryViewController.swift
UTF-8
5,003
2.703125
3
[]
no_license
// // CategoryViewController.swift // Todo-itSimple // // Created by Lucas van Leerdam on 20/05/2020. // Copyright © 2020 Lucas van Leerdam. All rights reserved. // import UIKit import RealmSwift import ChameleonFramework class CategoryViewController: SwipeTableViewController { let realm = try! Realm() var categoryArray: Results<Category>? override func viewDidLoad() { super.viewDidLoad() loadCategories() tableView.rowHeight = 60.0 } override func viewWillAppear(_ animated: Bool) { setColor() } //MARK: - TableView Datasource Methods override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return categoryArray?.count ?? 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: indexPath) let message = categoryArray?[indexPath.row] cell.textLabel?.text = message?.name ?? "No Categories Added Yet" cell.backgroundColor = UIColor(hexString: message?.color ?? "ffffff") cell.textLabel?.textColor = ContrastColorOf(cell.backgroundColor!, returnFlat: true) return cell } //MARK: - Delete Data with Swipe override func updateModel(at indexPath: IndexPath) { if let deleteCategory = self.categoryArray?[indexPath.row] { do { try self.realm.write { self.realm.delete(deleteCategory) } } catch { print("Error deleting category, \(error)") } } } //MARK: - Add New Items @IBAction func addButtonPressed(_ sender: UIBarButtonItem) { var textField = UITextField() let alert = UIAlertController(title: "Add New Category", message: "", preferredStyle: .alert) let action = UIAlertAction(title: "Add", style: .default) { (action) in if textField.text != "" { let newCategory = Category() newCategory.name = textField.text! newCategory.color = RandomFlatColor().hexValue() self.saveCategories(category: newCategory) } else { print("Nothing added!") } } alert.addTextField { (alertTextField) in alertTextField.autocapitalizationType = .sentences alertTextField.placeholder = "Create new category" textField = alertTextField } alert.addAction(action) present(alert, animated: true, completion: nil) } //MARK: - TableView Delegate Methods override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "goToItems", sender: self) tableView.deselectRow(at: indexPath, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let destinationVC = segue.destination as! TodoListViewController if let indexPath = tableView.indexPathForSelectedRow { destinationVC.selectedCategory = categoryArray?[indexPath.row] } let backItem = UIBarButtonItem() backItem.title = "Categories" navigationItem.backBarButtonItem = backItem } //MARK: - Data Manipulation Methods func saveCategories(category: Category) { do { try realm.write { realm.add(category) } } catch { print("Error saving categories, \(error)") } self.tableView.reloadData() } func loadCategories() { categoryArray = realm.objects(Category.self) tableView.reloadData() } //MARK: - Color Methods func setColor() { guard let navBar = navigationController?.navigationBar else {fatalError("Navigation controller does not exist.")} let navBarAppearance = UINavigationBarAppearance() navBarAppearance.configureWithOpaqueBackground() let color = UIColor(hexString: "1D9BF6") let contrastColour = ContrastColorOf(color!, returnFlat: true) navBarAppearance.titleTextAttributes = [.foregroundColor: contrastColour] navBarAppearance.largeTitleTextAttributes = [.foregroundColor: contrastColour] navBarAppearance.backgroundColor = color navBar.tintColor = contrastColour navBar.standardAppearance = navBarAppearance navBar.scrollEdgeAppearance = navBarAppearance } }
true
6506432fd0d11a124de7b687062c7acccf4ae70a
Swift
billmartensson/SwiftCoreData
/SwiftCoreData/ViewController.swift
UTF-8
3,603
2.8125
3
[]
no_license
// // ViewController.swift // SwiftCoreData // // Created by Bill Martensson on 2020-10-29. // import UIKit import CoreData class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var shopTextfield: UITextField! @IBOutlet weak var shopTableview: UITableView! let appDelegate = UIApplication.shared.delegate as! AppDelegate var context : NSManagedObjectContext! var shoppingItems = [ShopItem]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. context = appDelegate.persistentContainer.viewContext shopTableview.dataSource = self shopTableview.delegate = self /* var thingToBuy = ShopItem(context: context) thingToBuy.title = "Äpple" thingToBuy.amount = 50 thingToBuy.isBought = true do { try context.save() } catch { } */ /* let getShop : NSFetchRequest<ShopItem> = ShopItem.fetchRequest() let sorting = NSSortDescriptor(key: "title", ascending: false) getShop.sortDescriptors = [sorting] getShop.predicate = NSPredicate(format: "isBought == false") do { let shopStuff = try context.fetch(getShop) for shopthing in shopStuff { print(shopthing.title) } } catch { } */ loadShopping() } func loadShopping() { let getShop : NSFetchRequest<ShopItem> = ShopItem.fetchRequest() let sorting = NSSortDescriptor(key: "isBought", ascending: true) getShop.sortDescriptors = [sorting] do { shoppingItems = try context.fetch(getShop) shopTableview.reloadData() } catch { } } @IBAction func addShop(_ sender: Any) { var thingToBuy = ShopItem(context: context) thingToBuy.title = shopTextfield.text thingToBuy.amount = 1 thingToBuy.isBought = false do { try context.save() loadShopping() } catch { } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return shoppingItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let currentShopItem = shoppingItems[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "shopcell") if(currentShopItem.isBought == true) { cell?.backgroundColor = UIColor.green } else { cell?.backgroundColor = UIColor.white } cell?.textLabel?.text = "\(currentShopItem.title!) \(currentShopItem.amount) st" return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let currentShopItem = shoppingItems[indexPath.row] if(currentShopItem.isBought == true) { currentShopItem.isBought = false } else { currentShopItem.isBought = true } do { try context.save() loadShopping() } catch { } } }
true
9fc211a2cb4bbcab37f5cf41169913610c819d75
Swift
pinchih/SamsClubChallengeMobile-iOS
/Sam'sClubChallengeMobile-iOS/ProductViewController.swift
UTF-8
7,754
2.515625
3
[ "MIT" ]
permissive
// // ProductViewController.swift // Sam'sClubChallengeMobile-iOS // // Created by Pin-Chih on 8/7/17. // Copyright © 2017 Pin-Chih Lin. All rights reserved. // import UIKit class ProductViewController : UIViewController{ // NetworkActivityDisplayable typealias returnedData = [Product] var loadingView: UIActivityIndicatorView = { let view = UIActivityIndicatorView() view.color = .lightGray return view }() var errorView: UILabel = { let view = UILabel() view.numberOfLines = 2 view.textAlignment = .center view.textColor = .lightGray return view }() var networkStatus: NetworkResult<[Product]> = NetworkResult<[Product]>.uninitialized{ didSet { updateNetworkStatus() } } var isFetchingProducts = false // Other views lazy var collectionView : UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.delegate = self cv.dataSource = self cv.register(ProductCollectionViewCell.self, forCellWithReuseIdentifier: ProductCollectionViewCell.cellID()) cv.translatesAutoresizingMaskIntoConstraints = false cv.backgroundColor = .white cv.alwaysBounceVertical = true return cv }() // Attributes var currentPageNumber : Int = 1 var pageSize : Int = 0 var products = [Product](){ didSet{ NotificationCenter.default.post(name:.numbersOfProductsDidChanged, object: nil, userInfo: ["productCount":products.count]) } } } //MARK:- VC life cycle extension ProductViewController{ override func viewDidLoad() { setupViews() fetchProducts() } convenience init(withPageSize pageSize:Int){ self.init(nibName: nil, bundle: nil) self.pageSize = pageSize } } //MARK:- Helper functions extension ProductViewController{ fileprivate func setupViews(){ view.backgroundColor = .white // Setup collectionView - fill superview view.addSubview(collectionView) collectionView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true collectionView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true collectionView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true // Setup NetworkActivityDisplayableViews setupNetworkActivityDisplayableViews() setupNavigationBar() } fileprivate func setupNavigationBar(){ navigationItem.title = "Sam's Club" } fileprivate func fetchProducts(){ switch networkStatus { case .uninitialized: networkStatus = NetworkResult<[Product]>.loading default: break } isFetchingProducts = true currentPageNumber += 1 NetworkManger.shared.fetchProductsForPage(number: currentPageNumber, size: pageSize) { (result) in self.configureNetworkResult(result) self.isFetchingProducts = false } } fileprivate func configureNetworkResult(_ result:NetworkResult<[Product]>){ switch result{ case .success(data: let data): self.products.append(contentsOf: data) self.collectionView.reloadData() self.networkStatus = NetworkResult<[Product]>.success(data:data) case .error(message:let message): self.networkStatus = NetworkResult<[Product]>.error(message: message) default: break } } fileprivate func configureImageFetchingNetworkResult(_ result:NetworkResult<UIImage>,for cell:ProductCollectionViewCell){ switch result{ case .success(data: let data): cell.productImage.image = data cell.productImage.loadingView.stopAnimating() cell.productImage.backgroundColor = .white case .error(message:_): cell.productImage.loadingView.stopAnimating() default: break } } fileprivate func configure(_ cell: ProductCollectionViewCell, for indexPath:IndexPath){ let product = products[indexPath.row] cell.productNameLabel.text = product.name cell.productPriceLabel.text = product.price cell.ratingView.rating = Double(product.reviewRating ?? 0.0) cell.ratingView.text = product.reviewCount.flatMap({ return "(\($0))"}) NetworkManger.shared.fetchImageFor(url:product.imageURL) { (result) in self.configureImageFetchingNetworkResult(result, for: cell) } } } //MARK:- UICollectionViewDataSource, UICollectionViewDelegate extension ProductViewController : UICollectionViewDelegate, UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ProductCollectionViewCell.cellID(), for: indexPath) as! ProductCollectionViewCell // Prepare cell to display configure(cell, for:indexPath) // If this cell is the last cell and we're not currently fetching any data, load more data from the server if indexPath.row == products.count - 1 && isFetchingProducts == false { print("[DEBUG] Current page number : \(currentPageNumber)") fetchProducts() } return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return products.count } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let vc = ProductDetailViewController() vc.delegate = self vc.productCounts = products.count vc.productIndex = indexPath.row navigationController?.pushViewController(vc, animated: true) } } //MARK:- UICollectionViewDelegateFlowLayout extension ProductViewController:UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: self.view.frame.width/2 , height: (self.view.frame.width/2)*1.2 ) } } //MARK:- NetworkActivityDisplayable extension ProductViewController :NetworkActivityDisplayable{ } //MARK:- ProductDetailViewControllerDelegate extension ProductViewController :ProductDetailViewControllerDelegate{ func productAt(Index: Int) -> Product? { if Index < products.count { return products[Index] }else{ // Load more data fetchProducts() return nil } } func shouldFetchProducts() { fetchProducts() } }
true
a1c45ffde7e57a114867c35184d7828a17c55cac
Swift
ajunlonglive/OpenSesame
/Shared/AutoFill/Credentials.swift
UTF-8
3,518
2.8125
3
[ "MIT" ]
permissive
// // Credentials.swift // Credentials // // Created by Ethan Lipnik on 8/19/21. // import CoreData import AuthenticationServices import DomainParser import KeychainAccess extension CredentialProviderViewController { /* Prepare your UI to list available credentials for the user to choose from. The items in 'serviceIdentifiers' describe the service the user is logging in to, so your extension can prioritize the most relevant credentials in the list. */ override func prepareInterfaceToProvideCredential(for credentialIdentity: ASPasswordCredentialIdentity) { self.autoFillService.selectedCredential = credentialIdentity } override func prepareCredentialList(for serviceIdentifiers: [ASCredentialServiceIdentifier]) { print("Preparing credentials") do { try autoFillService.loadAccountsForServiceIdentifiers(serviceIdentifiers) } catch { print(error) } } func decryptedAccount(_ account: Account) throws -> (username: String, password: String) { #if targetEnvironment(simulator) let accessibility: Accessibility = .always #else let accessibility: Accessibility = .whenUnlockedThisDeviceOnly #endif #if !os(macOS) let authenticationPolicy: AuthenticationPolicy = .biometryCurrentSet #else let authenticationPolicy: AuthenticationPolicy = [.biometryCurrentSet, .or, .watch] #endif if let masterPassword = try OpenSesameKeychain() .accessibility(accessibility, authenticationPolicy: authenticationPolicy) .authenticationPrompt("Authenticate to login to view your accounts") .get("masterPassword") { CryptoSecurityService.loadEncryptionKey(masterPassword) let decryptPassword = try CryptoSecurityService.decrypt(account.password!) print("Returned decrypted account") return (account.username!, decryptPassword!) } else { print("No master password") throw CocoaError(.coderValueNotFound) } } override func provideCredentialWithoutUserInteraction(for credentialIdentity: ASPasswordCredentialIdentity) { autoFillService.selectedCredential = credentialIdentity guard let account = credentialIdentity.asAccount(autoFillService.allAccounts) else { extensionContext.cancelRequest(withError: ASExtensionError(.failed)); return } func decrypt() throws { let decryptedAccount = try decryptedAccount(account) let passwordCredential = ASPasswordCredential(user: decryptedAccount.username, password: decryptedAccount.password) extensionContext.completeRequest(withSelectedCredential: passwordCredential, completionHandler: nil) } #if os(macOS) extensionContext.cancelRequest(withError: ASExtensionError(.userInteractionRequired)) #else do { try decrypt() } catch { extensionContext.cancelRequest(withError: ASExtensionError(.userInteractionRequired)) DispatchQueue.main.asyncAfter(deadline: .now() + 1) { try? decrypt() } } #endif } } extension ASPasswordCredentialIdentity { func asAccount(_ accounts: [Account]) -> Account? { return accounts.first(where: { $0.username == self.user && $0.domain == self.serviceIdentifier.identifier }) } }
true
caf17f5978b76f82a40b780882bcf3e249fc2dac
Swift
tobitech/code-labs
/ios/Cloudy2/CloudyTests/Test Cases/WeekViewViewModelTests.swift
UTF-8
1,296
2.828125
3
[]
no_license
// // WeekViewViewModelTests.swift // CloudyTests // // Created by Bart Jacobs on 05/12/2017. // Copyright © 2017 Cocoacasts. All rights reserved. // import XCTest @testable import Cloudy class WeekViewViewModelTests: XCTestCase { // MARK: - Properties var viewModel: WeekViewViewModel! // MARK: - Set Up & Tear Down override func setUp() { super.setUp() // Load Stub let data = loadStubFromBundle(withName: "darksky", extension: "json") let weatherData: WeatherData = try! JSONDecoder.decode(data: data) // Initialize View Model viewModel = WeekViewViewModel(weatherData: weatherData.dailyData) } override func tearDown() { super.tearDown() } // MARK: - Tests for Number of Sections func testNumberOfSections() { XCTAssertEqual(viewModel.numberOfSections, 1) } // MARK: - Tests for Number of Days func testNumberOfDays() { XCTAssertEqual(viewModel.numberOfDays, 8) } // MARK: - Tests for View Model for Index func testViewModelForIndex() { let weatherDayViewViewModel = viewModel.viewModel(for: 5) XCTAssertEqual(weatherDayViewViewModel.day, "Saturday") XCTAssertEqual(weatherDayViewViewModel.date, "July 15") } }
true
78bc53195ded5fc3761a32a81dd2ec94c9d3e980
Swift
drewg233/Kota
/Kota/Classes/ScreenShotViewController.swift
UTF-8
5,668
2.59375
3
[ "MIT" ]
permissive
// // CameraViewController.swift // Pods // // Created by Khanh Pham on 5/11/17. // // import UIKit class ScreenShotViewController: UIViewController { @IBOutlet var imageView: UIImageView! @IBOutlet weak var greenButton: UIButton! @IBOutlet weak var blueButton: UIButton! @IBOutlet weak var redButton: UIButton! var lastPoint:CGPoint! var isSwiping:Bool! var red:CGFloat! var green:CGFloat! var blue:CGFloat! let kota = KotaController.shared override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. chooseGreen() if KotaData.shared.screenshotImage != nil { imageView.image = KotaData.shared.screenshotImage imageView.layer.shadowColor = UIColor.black.cgColor imageView.layer.shadowOffset = CGSize(width: 0, height: 0) imageView.layer.shadowOpacity = 0.5 imageView.layer.shadowRadius = 5 imageView.layer.cornerRadius = 4 imageView.clipsToBounds = false } } override func viewWillAppear(_ animated: Bool) { if !kota.isHidden { kota.hideView() } } @IBAction func undoDrawing(_ sender: AnyObject) { self.imageView.image = nil } func image(_ image: UIImage, withPotentialError error: NSErrorPointer, contextInfo: UnsafeRawPointer) { UIAlertView(title: nil, message: "Image successfully saved to Photos library", delegate: nil, cancelButtonTitle: "Dismiss").show() } //MARK: Touch events override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){ isSwiping = false if let touch = touches.first{ lastPoint = touch.location(in: imageView) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?){ isSwiping = true; if let touch = touches.first{ let currentPoint = touch.location(in: imageView) UIGraphicsBeginImageContext(self.imageView.frame.size) self.imageView.image?.draw(in: CGRect(x: 0, y: 0, width: self.imageView.frame.size.width, height: self.imageView.frame.size.height)) UIGraphicsGetCurrentContext()?.move(to: CGPoint(x: lastPoint.x, y: lastPoint.y)) UIGraphicsGetCurrentContext()?.addLine(to: CGPoint(x: currentPoint.x, y: currentPoint.y)) UIGraphicsGetCurrentContext()?.setLineCap(CGLineCap.round) UIGraphicsGetCurrentContext()?.setLineWidth(9.0) UIGraphicsGetCurrentContext()?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0) UIGraphicsGetCurrentContext()?.strokePath() self.imageView.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() lastPoint = currentPoint } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?){ if(!isSwiping) { // This is a single touch, draw a point UIGraphicsBeginImageContext(self.imageView.frame.size) self.imageView.image?.draw(in: CGRect(x: 0, y: 0, width: self.imageView.frame.size.width, height: self.imageView.frame.size.height)) UIGraphicsGetCurrentContext()?.setLineCap(CGLineCap.round) UIGraphicsGetCurrentContext()?.setLineWidth(9.0) UIGraphicsGetCurrentContext()?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0) UIGraphicsGetCurrentContext()?.move(to: CGPoint(x: lastPoint.x, y: lastPoint.y)) UIGraphicsGetCurrentContext()?.addLine(to: CGPoint(x: lastPoint.x, y: lastPoint.y)) UIGraphicsGetCurrentContext()?.strokePath() self.imageView.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } } @IBAction func greenButtonTapped(_ sender: Any) { chooseGreen() } @IBAction func blueButtonTapped(_ sender: Any) { chooseBlue() } @IBAction func redButtonTapped(_ sender: Any) { chooseRed() } func chooseGreen() { removeBorders() red = (113.0/255.0) green = (219.0/255.0) blue = (100.0/255.0) greenButton.layer.borderWidth = 2 greenButton.layer.borderColor = UIColor.black.cgColor } func chooseBlue() { removeBorders() red = (100.0/255.0) green = (179.0/255.0) blue = (219.0/255.0) blueButton.layer.borderWidth = 2 blueButton.layer.borderColor = UIColor.black.cgColor } func chooseRed() { removeBorders() red = (219.0/255.0) green = (100.0/255.0) blue = (100.0/255.0) redButton.layer.borderWidth = 2 redButton.layer.borderColor = UIColor.black.cgColor } func removeBorders() { greenButton.layer.borderWidth = 0 blueButton.layer.borderWidth = 0 redButton.layer.borderWidth = 0 } @IBAction func dismissVScreen(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func sendScreenShotButtonPressed(_ sender: Any) { performSegue(withIdentifier: "sendScreenShotSegue", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { KotaData.shared.screenshotImage = self.imageView.image } }
true
9440fa0b3fb0516b2ab5e9a13291496cf9564317
Swift
aubarton/HackerRank
/Interview Preparation Kit/05 - String Manipulation/Strings Making Anagrams/main.swift
UTF-8
1,465
3.78125
4
[ "MIT" ]
permissive
// // main.swift // Strings Making Anagrams // // Created by Alexey Barton on 07.03.2020. // Copyright © 2020 Alexey Barton. All rights reserved. // import Foundation func makeAnagram(a: String, b: String) -> Int { var cacheA = [String:Int]() var cacheB = [String:Int]() var cacheC = [String:Int]() for char in a { let charString = String(char) let value = (cacheA[charString] ?? 0) + 1 cacheA[charString] = value } for char in b { let charString = String(char) let value = (cacheB[charString] ?? 0) + 1 cacheB[charString] = value } for key in cacheA.keys { let valueA = cacheA[key] let valueB = cacheB[key] if valueA != nil && valueB != nil { cacheC[key] = min(valueA!, valueB!) } } var anagramLength = 0 for value in cacheC.values { anagramLength += value } return a.count - anagramLength + b.count - anagramLength } print("Case: 1") print("Expected Output: 4") let a1 = "cde" let b1 = "abc" let result1 = makeAnagram(a: a1, b: b1) print(result1, "\n") print("Case: 2") print("Expected Output: 30") let a2 = "fcrxzwscanmligyxyvym" let b2 = "jxwtrhvujlmrpdoqbisbwhmgpmeoke" let result2 = makeAnagram(a: a2, b: b2) print(result2, "\n") print("Case: 3") print("Expected Output: 2") let a3 = "showman" let b3 = "woman" let result3 = makeAnagram(a: a3, b: b3) print(result3, "\n")
true
854d0699abc126c7a19edc26fff6061e75f0b255
Swift
OBaller/AppStoreClone
/AppStoreCloneNas/AppStoreCloneNas/NetworkService/Service.swift
UTF-8
5,159
2.625
3
[]
no_license
// // Service.swift // AppStoreCloneNas // // Created by Decagon on 13/08/2021. // import Foundation class Service { static let shared = Service() // singleton func fetchApps(searchTerm: String, completion: @escaping ([Result], Error?) -> ()) { let urlString = "https://itunes.apple.com/search?term=\(searchTerm)&entity=software" guard let url = URL(string: urlString) else {return} // fetch data from internet URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { print("failed to fetch apps", error) completion([], nil) } guard let data = data else {return} do { let jsonDecoder = try JSONDecoder().decode(SearchResult.self, from: data) completion(jsonDecoder.results, nil) } catch let jsonErr { print("failed to decode json data", jsonErr) completion([], nil) } }.resume() } func fetchTopGrossing(completion: @escaping (AppGroupModel?, Error?) -> ()) { let urlString = "https://rss.itunes.apple.com/api/v1/us/ios-apps/top-grossing/all/50/explicit.json" fetchAppGroup(urlString: urlString, completion: completion) } func fetchGames(completion: @escaping (AppGroupModel?, Error?) -> ()) { fetchAppGroup(urlString: "https://rss.itunes.apple.com/api/v1/us/ios-apps/new-games-we-love/all/25/explicit.json", completion: completion) } func fetchTopFree(completion: @escaping (AppGroupModel?, Error?) -> ()) { fetchAppGroup(urlString: "https://rss.itunes.apple.com/api/v1/us/ios-apps/top-free/all/25/explicit.json", completion: completion) } // helper for multiple fetch func fetchAppGroup(urlString: String, completion: @escaping (AppGroupModel?, Error?) -> Void) { guard let url = URL(string: urlString) else {return} URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { completion(nil, error) } guard let data = data else {return} do { let gameDecoder = try JSONDecoder().decode(AppGroupModel.self, from: data) completion(gameDecoder, nil) } catch let jsErr { completion(nil, jsErr) } }.resume() } func FetchHeaderData(urlString: String, completion: @escaping ([HeaderModel]?, Error?) -> Void) { let urlString = "https://api.letsbuildthatapp.com/appstore/social" guard let url = URL(string: urlString) else {return} // fetch data from internet URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { print("failed to fetch apps", error) completion(nil, error) } guard let data = data else {return} do { let jsonDecoder = try JSONDecoder().decode([HeaderModel].self, from: data) completion(jsonDecoder, nil) } catch let jsonErr { print("failed to decode json data", jsonErr) completion(nil, jsonErr) } }.resume() } func fetchDetails(detailId: String, completion: @escaping ([Result], Error?) -> ()) { let urlString = "https://itunes.apple.com/lookup?id=\(detailId)" guard let url = URL(string: urlString) else {return} // fetch data from internet URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { print("failed to fetch apps", error) completion([], nil) } guard let data = data else {return} do { let details = try JSONDecoder().decode(SearchResult.self, from: data) completion(details.results, nil) } catch let jsonErr { print("failed to decode json data", jsonErr) completion([], nil) } }.resume() } func fetchGenericJSONData<T: Decodable>(urlString: String, completion: @escaping (T?, Error?) -> ()) { guard let url = URL(string: urlString) else { return } URLSession.shared.dataTask(with: url) { (data, resp, err) in if let err = err { completion(nil, err) return } do { let objects = try JSONDecoder().decode(T.self, from: data!) // success completion(objects, nil) } catch { completion(nil, error) } }.resume() } }
true
1fba8c2178f6c50d1e737bb53e2c9bb88f3c6a72
Swift
listen-li/DYZB
/DYZB/DYZB/Classes/Tools/Extension/NSDateExtension.swift
UTF-8
390
2.734375
3
[ "MIT" ]
permissive
// // NSDateExtension.swift // DYZB // // Created by admin on 17/7/24. // Copyright © 2017年 smartFlash. All rights reserved. // import Foundation extension NSDate{ class func getCurrentTime() -> String { //获取当前时间 let nowDate = NSDate() let interval = nowDate.timeIntervalSince1970 return "\(interval)" } }
true
c099e570d707d591d503b4ef27b6a9e6f661b9a5
Swift
csr/Flags
/Example/Example/ListFlags/ListFlagsModel.swift
UTF-8
1,035
2.796875
3
[ "MIT" ]
permissive
// // ListFlagsModel.swift // Example // // Created by Cruz on 04/11/2018. // Copyright © 2018 Cruz. All rights reserved. // import UIKit import Flags import IGListKit import RxCocoa import RxSwift import RxIGListKit protocol FlagType { var emoji: String { get } var countryCode: String { get } var countryName: String? { get } } extension Flag: FlagType {} class FlagDiffable: SectionModelDiffable { var flag: FlagType var countryCode: String { return flag.countryCode } var text: String? { return Flag(countryCode: countryCode)?.emojiWithName } init?(flag: FlagType?) { guard let flag = flag else { return nil } self.flag = flag } func diffIdentifier() -> NSObjectProtocol { return countryCode as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { if let flag = object as? FlagDiffable { return countryCode == flag.countryCode } return self === object } }
true
f73505c8ae421749ad5d7be27d97b52013fc4877
Swift
kennic/PixelKit
/Sources/PixelKit/PIX/PIXs/Effects/Single/Blur/BlurPIX.swift
UTF-8
6,164
2.59375
3
[ "MIT" ]
permissive
// // BlurPIX.swift // PixelKit // // Created by Anton Heestand on 2018-08-02. // Open Source - MIT License // import RenderKit import Resolution import CoreGraphics import MetalKit #if !os(tvOS) && !targetEnvironment(simulator) // MPS does not support the iOS simulator. import MetalPerformanceShaders #endif final public class BlurPIX: PIXSingleEffect, CustomRenderDelegate, PIXViewable { public typealias Model = BlurPixelModel private var model: Model { get { singleEffectModel as! Model } set { singleEffectModel = newValue } } override public var shaderName: String { return "effectSingleBlurPIX" } // MARK: - Public Properties /// Gaussian blur is the most performant, tho it's not supported in the simulator. public enum BlurStyle: String, Enumable { case gaussian case box case angle case zoom case random public static let `default`: BlurStyle = { #if !os(tvOS) && !targetEnvironment(simulator) return .gaussian #else return .box #endif }() public var index: Int { switch self { case .gaussian: return 0 case .box: return 1 case .angle: return 2 case .zoom: return 3 case .random: return 4 } } public var typeName: String { rawValue } public var name: String { switch self { case .gaussian: return "Guassian" case .box: return "Box" case .angle: return "Angle" case .zoom: return "Zoom" case .random: return "Random" } } } @LiveEnum("style") public var style: BlurStyle = .default /// radius is relative. default at 0.5 /// /// 1.0 at 4K is max, tho at lower resolutions you can go beyond 1.0 @LiveFloat("radius", increment: 0.125) public var radius: CGFloat = 0.5 @LiveEnum("quality") public var quality: SampleQualityMode = .mid @LiveFloat("angle", range: -0.5...0.5) public var angle: CGFloat = 0.0 @LivePoint("position") public var position: CGPoint = .zero // MARK: - Property Helpers public override var liveList: [LiveWrap] { [_style, _radius, _quality, _angle, _position] } var relRadius: CGFloat { let radius = self.radius let relRes: Resolution = ._4K let res: Resolution = finalResolution let relHeight = res.height / relRes.height let relRadius = radius * relHeight let maxRadius: CGFloat = 32 * 10 let mappedRadius = relRadius * maxRadius return mappedRadius } public override var uniforms: [CGFloat] { return [CGFloat(style.index), relRadius, CGFloat(quality.rawValue), angle, position.x, position.y] } override public var shaderNeedsResolution: Bool { return true } // MARK: - Life Cycle - public init(model: Model) { super.init(model: model) setup() } public required init() { let model = Model() super.init(model: model) setup() } // MARK: Setup private func setup() { customRenderDelegate = self } // MARK: - Live Model public override func modelUpdateLive() { super.modelUpdateLive() style = model.style radius = model.radius quality = model.quality angle = model.angle position = model.position super.modelUpdateLiveDone() } public override func liveUpdateModel() { super.liveUpdateModel() model.style = style model.radius = radius model.quality = quality model.angle = angle model.position = position super.liveUpdateModelDone() } // MARK: Gaussian override public func render() { #if !os(tvOS) && !targetEnvironment(simulator) customRenderActive = style == .gaussian #endif super.render() } public func customRender(_ texture: MTLTexture, with commandBuffer: MTLCommandBuffer) -> MTLTexture? { #if !os(tvOS) && !targetEnvironment(simulator) return gaussianBlur(texture, with: commandBuffer) #else return nil #endif } #if !os(tvOS) && !targetEnvironment(simulator) func gaussianBlur(_ texture: MTLTexture, with commandBuffer: MTLCommandBuffer) -> MTLTexture? { if #available(macOS 10.13, *) { guard let blurTexture = try? Texture.emptyTexture(size: CGSize(width: texture.width, height: texture.height), bits: PixelKit.main.render.bits, on: PixelKit.main.render.metalDevice, write: true) else { PixelKit.main.logger.log(node: self, .error, .generator, "Guassian Blur: Make texture faild.") return nil } let gaussianBlurKernel = MPSImageGaussianBlur(device: PixelKit.main.render.metalDevice, sigma: Float(relRadius)) gaussianBlurKernel.edgeMode = extend.mps! gaussianBlurKernel.encode(commandBuffer: commandBuffer, sourceTexture: texture, destinationTexture: blurTexture) return blurTexture } else { return nil } } #endif } public extension NODEOut { func pixBlur(_ radius: CGFloat) -> BlurPIX { let blurPix = BlurPIX() blurPix.name = ":blur:" blurPix.input = self as? PIX & NODEOut blurPix.radius = radius return blurPix } func pixZoomBlur(_ radius: CGFloat) -> BlurPIX { let blurPix = BlurPIX() blurPix.name = ":zoom-blur:" blurPix.style = .zoom blurPix.quality = .epic blurPix.input = self as? PIX & NODEOut blurPix.radius = radius return blurPix } func pixBloom(radius: CGFloat, amount: CGFloat) -> CrossPIX { let pix = self as? PIX & NODEOut let bloomPix = (pix!.pixBlur(radius) + pix!) / 2 return pixCross(pix!, bloomPix, at: amount) } }
true
c9a8a2fce0fe443e6f9b2be14dbaf2ca1d89a99f
Swift
cyrsis/SwiftSandBox
/Swift-Playgrounds/DeferAssignment.playground/Contents.swift
UTF-8
402
3.734375
4
[ "MIT" ]
permissive
//: Playground - noun: a place where people can play import Cocoa var wordOfWisdom :String //Defere the assignment to later wordOfWisdom = "Do or do not, There is no try" var one, two, three : Int //Interesting is the even constand can do let constantString :String constantString = "I want to be change" //constantString = "I want to be change again" //The constantString only can change once
true
2d960687919811e78fa1c1b688f9ff66f1e9a4f1
Swift
ArjunSa786/NewLoader
/NewLoader/Module/Signup/View+VC/SignupViewController.swift
UTF-8
2,378
2.515625
3
[]
no_license
import UIKit class SignupViewController: UIViewController { @IBOutlet weak var emailTextfield: UITextField! @IBOutlet weak var mobilenumberTextfield: UITextField! @IBOutlet weak var nameTextfield: UITextField! var ViewModel = LoginViewModel() override func viewDidLoad() { super.viewDidLoad() emailTextfield.text = "john.smith@mbrhe.ae" mobilenumberTextfield.text = "971556987002" // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { self.navigationController?.navigationBar.isHidden = true self.navigationController?.setNavigationBarHidden(true, animated: animated) } @IBAction func signupact_clicked(_ button: UIButton) { if nameTextfield.text ?? "" == "" { self.failureMessage(message: "Please enter name\n") } else if nameTextfield.text?.count ?? 0 < 3 { self.failureMessage(message: "name must be minimum 3 characters\n") } else if emailTextfield.text ?? "" == "" { self.failureMessage(message: "Please enter Email ID") } else if emailTextfield.text?.isEmail == false { self.failureMessage(message: "Please enter valid Email ID") } else if mobilenumberTextfield.text ?? "" == "" { self.failureMessage(message: "Please enter mobile number") } else if mobilenumberTextfield.text?.count ?? 0 < 10 { self.failureMessage(message: "Please enter valid mobile number\n") } else { self.ViewModel.delegate = self self.ViewModel.RegisterAPICall(name: nameTextfield.text ?? "", mobileno: mobilenumberTextfield.text ?? "", emailaddress: emailTextfield.text ?? "", unifiednumber: "123" , onSuccess: { status, msg in if status == true { self.successMessage(message: msg) let vc = self.storyboard?.instantiateViewController(withIdentifier: "newsVC") as! NewsViewController self.navigationController?.pushViewController(vc, animated: true) } else { self.failureMessage(message: msg) } }, onFailure: { msg in self.failureMessage(message: msg) }) } } } extension SignupViewController : LoginVCDelegate { }
true
4ec5410ca7300c0dd1725bb0cf62bc3267eb8efb
Swift
liu-haiwen/CatFrida
/CatFrida/Util/XThrottler.swift
UTF-8
1,315
2.75
3
[ "MIT" ]
permissive
// // XThrottler.swift // CatFrida // // Created by neilwu on 2021/1/13. // Copyright © 2021 nw. All rights reserved. // import Foundation public final class XThrottler { private let queue: DispatchQueue = DispatchQueue.global(qos: .background) private var job: DispatchWorkItem = DispatchWorkItem(block: {}) private var previousRun: Date = Date.distantPast private var maxInterval: TimeInterval private var fireLast: Bool public init(maxInterval: TimeInterval, fireLast: Bool = false) { self.maxInterval = maxInterval self.fireLast = fireLast } public func throttle(block: @escaping () -> ()) { job.cancel() job = DispatchWorkItem(){ [weak self] in self?.previousRun = Date() DispatchQueue.main.async { block() } } // 保证 maxInterval 内只运行一次 let past: TimeInterval = Date().timeIntervalSince(previousRun) if (past > maxInterval) { queue.async(execute: job) } else if (fireLast) { let delay: TimeInterval = maxInterval - past queue.asyncAfter(deadline: .now() + Double(delay), execute: job) } } func disable() { job.cancel() } }
true
1d045487ca06b93ae597391e332b84b8396a05c6
Swift
anton-vasilchenko/VKSwift
/VK/VK/Model/NewsModel.swift
UTF-8
2,107
2.875
3
[]
no_license
// // NewsModel.swift // VK // // Created by Антон Васильченко on 06.07.2020. // Copyright © 2020 Антон Васильченко. All rights reserved. // import UIKit class News: Decodable { var type: NewsItemType var author: Int = 0 var date: Double = 0 var text: String? = "" var commentsCount: Int = 0 var likesCount: Int = 0 var repostsCount: Int = 0 var viewsCount: Int = 0 var profile: Profile? enum CodingKeys: String, CodingKey { case type case author = "source_id" case date case text // case attachments case comments case likes case reposts case views case count } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let typeString = try container.decode(String.self, forKey: .type) self.type = NewsItemType(rawValue: typeString) ?? .post self.author = try container.decode(Int.self, forKey: .author) self.date = try container.decode(Double.self, forKey: .date) self.text = try container.decodeIfPresent(String.self, forKey: .text) ?? "" if let nestedContainer = try? container.nestedContainer(keyedBy: CodingKeys.self, forKey: .likes) { self.likesCount = try nestedContainer.decode(Int.self,forKey: .count) } if let nestedContainer = try? container.nestedContainer(keyedBy: CodingKeys.self, forKey: .comments) { self.commentsCount = try nestedContainer.decode(Int.self,forKey: .count) } if let nestedContainer = try? container.nestedContainer(keyedBy: CodingKeys.self, forKey: .reposts) { self.repostsCount = try nestedContainer.decode(Int.self,forKey: .count) } if let nestedContainer = try? container.nestedContainer(keyedBy: CodingKeys.self, forKey: .views) { self.viewsCount = try nestedContainer.decode(Int.self,forKey: .count) } } } //enum NewsItemType: String { // case post // case photo = "wall_photo" //}
true
5b3106554b7ec6b689f5fc2a88a63660badd353a
Swift
olgavorona/TestGitHub
/TestGitHub/Sources/UI/Swift/SwiftPresenter.swift
UTF-8
1,161
2.8125
3
[ "MIT" ]
permissive
// // SwiftPresenter.swift // TestGitHub // // Created by Olga Vorona on 23.12.2020. // import Foundation final class SwiftPresenter { private lazy var trendingService: TrendingServiceProtocol = { return TrendingService() }() private var viewModels: [RepoModel] = [] weak var view: SwiftViewInput? private func model(from entity: TrendingEntity) -> RepoModel { return RepoModel(title: entity.repo, description: entity.desc, stars: entity.stars, createDate:"", repoURL: entity.url) } } extension SwiftPresenter: SwiftViewOutput { func getItems(index: Int) { trendingService.getTrending(type: index, completion: { [weak self] result in guard let self = self else { return } switch result { case .success(let items): let models = items.map { self.model(from: $0)} self.view?.update(with: models) case .failure: self.view?.showError() break; } }) } }
true
815da6fbdee17a2b87f6c55ae6faed92ab7910df
Swift
misolubarda/cleanArchitectureSwiftUIDemo
/MovieDB/UILayer/UILayer/Components/Color+Assets.swift
UTF-8
1,307
2.515625
3
[]
no_license
// // Color+Assets.swift // UILayer // // Created by Miso Lubarda on 25.10.20. // import SwiftUI extension Color { // MARK: Background static let listItemBackground0 = Color.currentBundleColor("listItemBackground0") static let listItemBackground1 = Color.currentBundleColor("listItemBackground1") static let listItemBackground2 = Color.currentBundleColor("listItemBackground2") static let listItemBackground3 = Color.currentBundleColor("listItemBackground3") static let listItemBackground4 = Color.currentBundleColor("listItemBackground4") static let listItemBackgrounds: [Color] = [listItemBackground0, listItemBackground1, listItemBackground2, listItemBackground3, listItemBackground4] // MARK: Navigation static let navigationBar = Color.currentBundleColor("navigationBar") // MARK: Text static let textPrimary = Color.currentBundleColor("textPrimary") } private extension Color { static func currentBundleColor(_ name: String) -> Color { Color(name, bundle: currentBundle) } } private class Dummy {} private let currentBundle = Bundle(for: Dummy.self)
true
7f8411abf832508c146f3dcbf291703f1511d1af
Swift
JakeBent/ISSFriends
/ISSFriends/FriendInfoExpandedView.swift
UTF-8
1,395
2.640625
3
[]
no_license
// // FriendInfoExpandedView.swift // ISSFriends // // Created by Jacob Benton on 4/7/16. // Copyright © 2016 jakebent. All rights reserved. // import UIKit // This is the view that is shown when a FriendInfoTableViewCell is expanded. It just shows the next three times the ISS will pass over this friend. class FriendInfoExpandedView: UIView { var views = [PassTimeCell]() let passTimes: [String] init(passTimes: [String]) { self.passTimes = passTimes super.init(frame: CGRect.zero) clipsToBounds = true } func layoutViews() { if !views.isEmpty { for view in views { view.removeFromSuperview() } views = [] } var previousView: UIView? for passTime in passTimes { let toggleCell = PassTimeCell(passTime: passTime) addSubview(toggleCell) toggleCell.snp_makeConstraints { (make) -> Void in make.left.equalTo(snp_left) make.right.equalTo(snp_right) make.height.equalTo(40) make.top.equalTo(previousView == nil ? snp_top : previousView!.snp_bottom) } previousView = toggleCell views.append(toggleCell) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
4ac93554dad69414c5046d23477000bb8128c82b
Swift
naukri-engineering/SwiftNetworking
/SwiftNetworking/SwiftNetworking/Sources/ServiceGroup/HTTPMethod.swift
UTF-8
379
2.640625
3
[ "MIT" ]
permissive
// // HTTPMethod.swift // NaukriIndia // // Created by Himanshu Gupta on 01/08/18. // Copyright © 2018 Info Edge India Ltd. All rights reserved. // import Foundation public enum HTTPMethod: String{ case get = "GET" case post = "POST" case put = "PUT" case delete = "DELETE" case patch = "PATCH" case none = "" init() { self = .none } }
true
100df5364ba32e4bf5a1f23f559232b7d004bb8b
Swift
apple/swift
/test/IDE/print_clang_swift_name.swift
UTF-8
4,822
2.515625
3
[ "Apache-2.0", "Swift-exception" ]
permissive
// RUN: %empty-directory(%t) // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -print-module -source-filename %s -module-to-print=SwiftNameTests -function-definitions=false -print-regular-comments -F %S/Inputs/mock-sdk > %t.txt // RUN: diff -u <(tail -n +9 %s) %t.txt // REQUIRES: objc_interop // EXPECTED OUTPUT STARTS BELOW THIS LINE. @_exported import Foundation class Test : NSObject { // "Factory methods" that we'd rather have as initializers. @available(*, unavailable, message: "superseded by import of -[NSObject init]") convenience init() @available(*, unavailable, renamed: "init()", message: "Not available in Swift") class func a() -> Self convenience init(dummyParam: ()) @available(*, unavailable, renamed: "init(dummyParam:)", message: "Not available in Swift") class func b() -> Self convenience init(cc x: Any) @available(*, unavailable, renamed: "init(cc:)", message: "Not available in Swift") class func c(_ x: Any) -> Self convenience init(_ x: Any) @available(*, unavailable, renamed: "init(_:)", message: "Not available in Swift") class func d(_ x: Any) -> Self convenience init(aa a: Any, _ b: Any, cc c: Any) @available(*, unavailable, renamed: "init(aa:_:cc:)", message: "Not available in Swift") class func e(_ a: Any, e b: Any, e c: Any) -> Self /*not inherited*/ init(fixedType: ()) @available(*, unavailable, renamed: "init(fixedType:)", message: "Not available in Swift") class func f() -> Test // Would-be initializers. class func zz() -> Self @available(swift, obsoleted: 3, renamed: "zz()") class func testZ() -> Self class func yy(aa x: Any) -> Self @available(*, unavailable, renamed: "yy(aa:)", message: "Not available in Swift") class func testY(_ x: Any) -> Self class func xx(_ x: Any, bb xx: Any) -> Self @available(*, unavailable, renamed: "xx(_:bb:)", message: "Not available in Swift") class func testX(_ x: Any, xx: Any) -> Self init() } class TestError : NSObject { // Factory methods with NSError. convenience init(error: ()) throws @available(*, unavailable, renamed: "init(error:)", message: "Not available in Swift") class func err1() throws -> Self convenience init(aa x: Any?, error: ()) throws @available(*, unavailable, renamed: "init(aa:error:)", message: "Not available in Swift") class func err2(_ x: Any?) throws -> Self convenience init(aa x: Any?, error: (), block: @escaping () -> Void) throws @available(*, unavailable, renamed: "init(aa:error:block:)", message: "Not available in Swift") class func err3(_ x: Any?, callback block: @escaping () -> Void) throws -> Self convenience init(error: (), block: @escaping () -> Void) throws @available(*, unavailable, renamed: "init(error:block:)", message: "Not available in Swift") class func err4(callback block: @escaping () -> Void) throws -> Self convenience init(aa x: Any?) throws @available(*, unavailable, renamed: "init(aa:)", message: "Not available in Swift") class func err5(_ x: Any?) throws -> Self convenience init(aa x: Any?, block: @escaping () -> Void) throws @available(*, unavailable, renamed: "init(aa:block:)", message: "Not available in Swift") class func err6(_ x: Any?, callback block: @escaping () -> Void) throws -> Self convenience init(block: @escaping () -> Void) throws @available(*, unavailable, renamed: "init(block:)", message: "Not available in Swift") class func err7(callback block: @escaping () -> Void) throws -> Self // Would-be initializers. class func ww(_ x: Any?) throws -> Self @available(swift, obsoleted: 3, renamed: "ww(_:)") class func testW(_ x: Any?) throws -> Self class func w2(_ x: Any?, error: ()) throws -> Self @available(swift, obsoleted: 3, renamed: "w2(_:error:)") class func testW2(_ x: Any?) throws -> Self class func vv() throws -> Self @available(swift, obsoleted: 3, renamed: "vv()") class func testV() throws -> Self class func v2(error: ()) throws -> Self @available(swift, obsoleted: 3, renamed: "v2(error:)") class func testV2() throws -> Self init() } class TestSub : Test { @available(*, unavailable, message: "superseded by import of -[NSObject init]") convenience init() convenience init(dummyParam: ()) convenience init(cc x: Any) convenience init(_ x: Any) convenience init(aa a: Any, _ b: Any, cc c: Any) init() } class TestErrorSub : TestError { convenience init(error: ()) throws convenience init(aa x: Any?, error: ()) throws convenience init(aa x: Any?, error: (), block: @escaping () -> Void) throws convenience init(error: (), block: @escaping () -> Void) throws convenience init(aa x: Any?) throws convenience init(aa x: Any?, block: @escaping () -> Void) throws convenience init(block: @escaping () -> Void) throws init() }
true
607efb91a63b3bc1343aba10f94b301eefcde2b8
Swift
z-ohnami/graphs
/Graph/RandomDivider.swift
UTF-8
452
2.75
3
[]
no_license
// // RandomDivider.swift // Graph // // Created by Makoto Ohnami on 2019/11/02. // Copyright © 2019 Makoto Ohnami. All rights reserved. // import UIKit class RandomDivider { let total:CGFloat = 100.0 func call() -> [CGFloat] { var numbers:[CGFloat] = [0.0, 0.0, 0.0, 0.0, 0.0] for _ in 0..<100 { let index = Int.random(in: 0..<5) numbers[index] = numbers[index] + 1.0 } return numbers } }
true
9106a03af0ff21fbdc6af7d6c5eb92f1082eff91
Swift
bradonSheng777/UnsplashCloneApp
/UnsplashCloneApp/Modules/DetailsScreen/Model/ImageDetailsInformation.swift
UTF-8
432
2.609375
3
[]
no_license
// // ImageDetailsInformation.swift // UnsplashCloneApp // // Created by Yoonha Kim on 5/10/21. // import Foundation struct ImageDetailsInformation { var make: String = "Sony" var model: String = "Model" var shutterSpeed: String = "1/100s" var aperture: String = "3.5" var focalLength: Double = 3.5 var iso: Int = 400 var dimension: String = "3000 * 4500" var published: String = "March 21, 2020" }
true
0d623ce9d9f88f6639d544fd1f9819689f306a9f
Swift
peterfoxflick/onehundred
/onehundredTests/TaskDataManagerTests.swift
UTF-8
3,556
2.765625
3
[]
no_license
// // taskTests.swift // onehundredTests // // Created by Peter Flickinger on 9/16/19. // Copyright © 2019 Peter Flickinger. All rights reserved. // import XCTest @testable import onehundred class TaskDataManagerTests: XCTestCase { var sut: TaskDataManager! var coreDataStack: CoreDataTestStack! var goal : Goal! var day : Day! // MARK: - Lifecycle override func setUp() { super.setUp() coreDataStack = CoreDataTestStack() sut = TaskDataManager(context: coreDataStack.backgroundContext) goal = GoalDataManager(context: coreDataStack.backgroundContext).addGoal(text: "Code", durration: 100, checkpointLength: 10) day = DayDataManager(context: coreDataStack.backgroundContext).addDay(goalID: goal.id!) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. GoalDataManager(context: coreDataStack.backgroundContext).deleteGoal(id: self.goal.id!) } // MARK: - Tests // MARK: Init func test_init_contexts() { XCTAssertEqual(sut.managedObjectContext, coreDataStack.backgroundContext, "Error in context") } func test_add_task(){ let title = "My new task" let createdAt = Date() let task = sut.addTask(title: title, createdAt: createdAt, dayID: day.id!) XCTAssertEqual(task.title, title , "TaskDM - Failed to create task with title") XCTAssertEqual(task.createdAt, createdAt , "TaskDM - Failed to create task with creeaeted date") XCTAssertEqual(task.completedAt, createdAt , "TaskDM - Failed to create task with complete date") XCTAssertEqual(task.day, day , "TaskDM - Failed to add task to day") } func test_get_tasks(){ add_dummy_tasks() let tasks = sut.getTasksFromDay(dayID: day.id!) XCTAssert(tasks.count > 0, "TaskDM - Failed to fetch added tasks") //Test to ensure it isn't getting anouther days tasks } func test_update_task(){ let task = sut.addTask(title: "Read a book", createdAt: Date(), dayID: day.id!) let title = "Go for a walk" let now = Date() let updatedTask = sut.updateTask(id: task.id!, title: title, createdAt: now, completedAt: now) XCTAssertEqual(updatedTask!.title, title , "TaskDM - Failed to update task with title") XCTAssertEqual(updatedTask!.createdAt, now , "TaskDM - Failed to update task with creeaeted date") XCTAssertEqual(updatedTask!.completedAt, now , "TaskDM - Failed to update task with complete date") } func test_delete_task(){ add_dummy_tasks() let tasks = sut.getTasksFromDay(dayID: day.id!) let startCount = tasks.count for task in tasks{ sut.deleteTask(id: task.id!) } let endCount = sut.getTasksFromDay(dayID: day.id!).count XCTAssert(startCount > 0 , "TaskDM - Failed to add tasks") XCTAssert(endCount == 0 , "TaskDM - Failed to delete tasks, \(endCount) remaining") } func add_dummy_tasks(){ _ = sut.addTask(title: "Mow the lawn", createdAt: Date(), dayID: day.id!) _ = sut.addTask(title: "Get new shoes", createdAt: Date(), dayID: day.id!) _ = sut.addTask(title: "Go for a walk", createdAt: Date(), dayID: day.id!) } }
true
6ba2199b190ddaf2a312e12174557071b8041fa4
Swift
bastie/SwiftAdventure
/dmn/DMN/Sources/DMN13/ElementCollection.swift
UTF-8
1,480
2.921875
3
[]
no_license
// // File.swift // // // Created by Sͬeͥbͭaͭsͤtͬian on 04.07.21. // import Foundation /** The ElementCollection class is used to define named groups of DRGElement instances. ElementCollections may be used for any purpose relevant to an implementation, for example: * To identify the requirements subgraph of a set one or more decisions (i.e., all the elements in the closure of the requirements of the set). * To identify the elements to be depicted on a DRD. ElementCollection is a kind of NamedElement, from which an instance of ElementCollection inherits the name and optional id, description and label attributes, which are Strings. The id of an ElementCollection element SHALL be unique within the containing instance of Definitions. An ElementCollection element has any number of associated drgElements, which are the instances of DRGElement that this ElementCollection defines together as a group. Notice that an ElementCollection element must reference the instances of DRGElement that it collects, not contain them: instances of DRGElement can only be contained in Definitions elements. ElementCollection inherits all the attributes and model associations from NamedElement. */ class ElementCollection : NamedElement { /** This attribute lists the instances of DRGElement that this ElementCollection groups. */ var drgElement : [DRGElement]?; override init(newName: String) throws { try super.init(newName:newName); } }
true
db628e6985fb0b51eead382af6031b5474d34a40
Swift
TejaswiNallavolu/Fa21iOS-02
/HelloApp/HelloApp/ViewController.swift
UTF-8
643
2.859375
3
[]
no_license
// // ViewController.swift // HelloApp // // Created by Ajay Bandi on 8/26/21. // import UIKit class ViewController: UIViewController { @IBOutlet weak var InputText: UITextField! @IBOutlet weak var DisplayLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func Submit(_ sender: UIButton) { //Read the data from the text feild //Assign it to display label //DisplayLabel.text = InputText.text var ipText = InputText.text! DisplayLabel.text = "Hello, \(ipText)!" } }
true
909d7bb4af5d309f522638b2fc6b7daefc4e17fb
Swift
ArsalanWahid/swift-practise
/Swift5/chapter2.playground/Contents.swift
UTF-8
1,153
3.9375
4
[]
no_license
//: Playground - noun: a place where people can play import UIKit //: # Coding essentials and Playgorund basics //: Random practise //Some expression from the book page 42 ((8000 / (5 * 10)) - 32) >> (29 % 5) // check and all good // 11111111 (128)dec //: Q8 Chapter 2 Solution let dividend = 1993 let divisor = 16 let quotient = dividend / divisor let remainderWithoutModulus = dividend - (quotient * divisor) //: Q9 chapter 2 Solution // !!! Check what the formula is else its easy let degrees: Double = 360 let radians = degrees * (3.14 / 180) //: Q10 Chapter 2 solution - Eucleadian distance var x1 = 10.0 var x2 = 43.0 var y1 = 12.0 var y2 = 20.0 let distance = sqrt(pow(x2-y2, 2) - pow(x1-y1, 2)) func statues(statues: [Int]) //sort the array then find the max number and min number //add values from that range //sort again var toSort = statues toSort.sort() let max = statues.max() let min = statues.min() //4,5,6,8,7 //2,5,6,7,8 //2...8 //2,3,4,5,5,6,6,7,7,8,8 //remove first occurance of n for n in min...max{ toSort.append(n) } //remove repeated values for n in min...max{ toSort.remove(toSort.firstIndex(of:n)) }
true
e8281c55003103b28cb12ec9681a0619dd41d91b
Swift
O-O-wl/swift-syntax
/Swift 기본문법/if_switch.playground/Contents.swift
UTF-8
785
4.25
4
[]
no_license
import UIKit if(true){ print("bool 타입만 됩니다") } var myInt : Int = 39 switch(myInt){ case 0: print("\(myInt) 는 0 입니다") case 1..<100: print("범위 연산자를 통해서 분기할수도 있습니다. 0~99") case 100...200: print("...으로 하면 양 좌 우 수를 둘다 포함합니다" ) default: print("break 가 없네여? 또 한 default는 필수 입니다 .") } var name : String = "이동영" switch(name){ case "이동영","스티븐잡스": print("두개를 모두 포함하고싶다면 , case 에 , 로 이어주세요") case "break": print("break는 자동으로 걸립니다") case "break를 꼭 안걸리게 하고싶다!": fallthrough //를 사용하세요! default: print("아참 default는 필수예요") }
true
6bd23c06c2765d65ac6896c102c26c93b6a55088
Swift
FuYanfang/SwiftDemo
/Test/test.playground/Pages/06_class&Struct.xcplaygroundpage/Contents.swift
UTF-8
1,157
4.53125
5
[]
no_license
//: [Previous](05_enumerations) //: #类和结构体 import Foundation //: ###语法定义 struct Resolution { var width = 0 var height = 0 } class VideoModel { var resolution = Resolution() var interlaced = false var frameRate = 0 var name : String? } //: 结构体初始化 let someResolution = Resolution() let someVideoModel = VideoModel() let vga = Resolution(width: 640, height: 480) let hd = Resolution(width: 1920, height: 1080) var cinema = hd cinema.width = 2048 print("cinema is now \(cinema.width) pixels wide") print("hd is still \(hd.width) pixels wide") //: 类是引用类型 引用同一个Viewmodel let tenVideo = VideoModel() tenVideo.resolution = hd tenVideo.interlaced = true tenVideo.frameRate = 25 tenVideo.name = "1080i" let nineVideo = tenVideo nineVideo.frameRate = 30 print("The frameRate property of tenVideo is now \(tenVideo.frameRate)") //: 特征预算符 if (tenVideo === nineVideo) { print("tenVideo & nineVideo is the same VideoModel instance") } //: choose struct & class 结构体实例总是通过值来传递,而类实例总是通过引用来传递 //: [Next](07_properties)
true
b1e7f1cf3c39d65fe5a33bce2cd4311a30f0bb53
Swift
aditisaini91/CurrencyExchange
/CurrencyExchangeTests/CurrencyExchangeTests.swift
UTF-8
2,069
2.765625
3
[]
no_license
// // CurrencyExchanges.swift // CurrencyExchangeTests // import XCTest @testable import CurrencyExchange class CurrencyExchanges: XCTestCase { var urlSession: URLSession! override func setUp() { super.setUp() urlSession = URLSession(configuration: .default) } override func tearDown() { urlSession = nil } // Asynchronous test: success fast, failure slow func testValidCallToRevolutApi() { let url = URL(string: "https://europe-west1-revolut-230009.cloudfunctions.net/revolut-ios?pairs=USDGBP&pairs=GBPUSD") let expectations = expectation(description: "Status code: 200") let dataTask = urlSession.dataTask(with: url!) { data, response, error in if let error = error { XCTFail("Error: \(error.localizedDescription)") return } else if let statusCode = (response as? HTTPURLResponse)?.statusCode { if statusCode == 200 { expectations.fulfill() } else { XCTFail("Status code: \(statusCode)") } } } dataTask.resume() wait(for: [expectations], timeout: 5) } // Asynchronous test: success fast, failure fast func testValidCallToRevolutApiCompletes() { let url = URL(string: "https://europe-west1-revolut-230009.cloudfunctions.net/revolut-ios?pairs=USDGBP&pairs=GBPUSD") let expectations = expectation(description: "Completion handler invoked") var statusCode: Int? var responseError: Error? // when let dataTask = urlSession.dataTask(with: url!) { data, response, error in statusCode = (response as? HTTPURLResponse)?.statusCode responseError = error expectations.fulfill() } dataTask.resume() wait(for: [expectations], timeout: 5) // then XCTAssertNil(responseError) XCTAssertEqual(statusCode, 200) } }
true
96533ca2be17c1016b28f196e5db1d5615faec2b
Swift
inswag/Boostcamp
/BoostcampHomework/Model/MovieUserComments.swift
UTF-8
664
2.6875
3
[]
no_license
// // MovieUserComments.swift // BoostcampHomework // // Created by 박인수 on 17/12/2018. // Copyright © 2018 inswag. All rights reserved. // import Foundation struct MovieUserComments: Decodable { var movieID: String var comments: [Comments] enum CodingKeys: String, CodingKey { case comments case movieID = "movie_id" } } struct Comments: Decodable { var rating: Double var timestamp: Double var writer: String var movieID: String var contents: String enum CodingKeys: String, CodingKey { case rating, timestamp, writer, contents case movieID = "movie_id" } }
true
2e26e6307ea21c0f938caa770ffe5feb4db0a91e
Swift
mihaelamj/stargazer
/Stargazer/Stargazer/UI/CircleInitialLabel.swift
UTF-8
1,881
2.984375
3
[]
no_license
// // CircleInitialLabel.swift // Stargazer // // Created by Mihaela MJ on 15/07/2019. // Copyright © 2019 Mihaela MJ. All rights reserved. // import UIKit @IBDesignable @objcMembers class CircleInitialLabel: UILabel { enum CircleType: Int, CaseIterable { case small case big } // MARK: - // MARK: Init - override open func awakeFromNib() { super.awakeFromNib() setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } override public init(frame: CGRect) { super.init(frame: frame) setupView() } convenience init() { self.init(frame: .zero) } // MARK: - // MARK: Public Properties - public var type: CircleType = .small { didSet { updateType() } } // MARK: - // MARK: IB Properties - @IBInspectable var typeIndex: Int { get { return self.type.rawValue } set(newValue) { self.type = CircleType(rawValue: type.rawValue) ?? .small } } } // MARK: - // MARK: FW Overrides - extension CircleInitialLabel { override func layoutSubviews() { super.layoutSubviews() let cornerRadius: CGFloat = frame.size.height / 2.0 layer.cornerRadius = cornerRadius clipsToBounds = true layer.masksToBounds = true } } // MARK: - // MARK: Setup - private extension CircleInitialLabel { func updateType() { switch type { case .small: backgroundColor = .lightGray textColor = .white font = font.withSize(17) textAlignment = .center case .big: backgroundColor = .lightGray textColor = .black font = font.withSize(60) textAlignment = .center } } func setupView() { textAlignment = .center updateType() let widthC = widthAnchor.constraint(equalTo: heightAnchor, multiplier: 1.0); widthC.identifier = "widthC"; widthC.isActive = true } }
true
ff73b3af43466fb9ba42ca1fda6a3fa08cd13b5c
Swift
datnm8x/LHImagePicker
/Classes/LHImagePicker.swift
UTF-8
2,925
2.578125
3
[ "MIT" ]
permissive
// // LHImagePicker.swift // LHImagePicker // // Created by Dat Ng on 11/2020. // Copyright (c) 2020 Dat Ng. All rights reserved. // import UIKit public extension LHImagePicker { enum CropConfigs { public static var lineWidth: CGFloat = 10 public static var lineColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5) public static var diameterColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.95) public static var cropSize = CGSize(width: 300, height: 300) public static var backgroundColor = UIColor.black.withAlphaComponent(0.5) public enum ButtonsTitle { public static var cancel: String = "Cancel" public static var use: String = "Use" } } } @objc public protocol LHImagePickerDelegate: NSObjectProtocol { @objc optional func imagePicker(imagePicker: LHImagePicker, pickedImage: UIImage?) @objc optional func imagePickerDidCancel(imagePicker: LHImagePicker) } @objc public class LHImagePicker: NSObject { public var delegate: LHImagePickerDelegate? public var resizableCropArea = false private lazy var pickerDelegateHandler = LHImagePickerDelegateHandler() private var _imagePickerController: UIImagePickerController! public var imagePickerController: UIImagePickerController { _imagePickerController } override public init() { super.init() pickerDelegateHandler.imagePicker = self self._imagePickerController = UIImagePickerController() _imagePickerController.delegate = pickerDelegateHandler _imagePickerController.sourceType = .photoLibrary } } extension LHImagePicker: LHImageCropControllerDelegate { func imageCropController(imageCropController _: LHImageCropViewController, didFinishWithCroppedImage croppedImage: UIImage?) { delegate?.imagePicker?(imagePicker: self, pickedImage: croppedImage) } } internal class LHImagePickerDelegateHandler: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate { weak var imagePicker: LHImagePicker? internal func imagePickerControllerDidCancel(_ pickerController: UIImagePickerController) { pickerController.dismiss(animated: true, completion: nil) guard let imagePicker = self.imagePicker else { return } imagePicker.delegate?.imagePickerDidCancel?(imagePicker: imagePicker) } internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { guard let imagePicker = self.imagePicker, let originalImage = (info[UIImagePickerController.InfoKey.originalImage] as? UIImage) else { picker.dismiss(animated: true, completion: nil) return } let cropController = LHImageCropViewController() cropController.sourceImage = originalImage cropController.resizableCropArea = imagePicker.resizableCropArea cropController.delegate = imagePicker picker.pushViewController(cropController, animated: true) } }
true
ee62e953129333be889e67e79734b01eed7346fc
Swift
Bheem-singh-26/TheatreApp
/UpcomingMovies/Scenes/Movies/MovieDetail/MovieDetailInteractor.swift
UTF-8
1,965
2.734375
3
[ "MIT" ]
permissive
// // MovieDetailInteractor.swift // UpcomingMovies // // Created by Bheem Singh on 8/1/20. // Copyright © 2020 Bheem Singh. All rights reserved. // import Foundation import UpcomingMoviesDomain class MovieDetailInteractor: MovieDetailInteractorProtocol { private let movieUseCase: MovieUseCaseProtocol private let movieVisitUseCase: MovieVisitUseCaseProtocol private let genreUseCase: GenreUseCaseProtocol private let accountUseCase: AccountUseCaseProtocol private let authHandler: AuthenticationHandlerProtocol init(useCaseProvider: UseCaseProviderProtocol, authHandler: AuthenticationHandlerProtocol) { self.movieUseCase = useCaseProvider.movieUseCase() self.movieVisitUseCase = useCaseProvider.movieVisitUseCase() self.genreUseCase = useCaseProvider.genreUseCase() self.accountUseCase = useCaseProvider.accountUseCase() self.authHandler = authHandler } func isUserSignedIn() -> Bool { return authHandler.isUserSignedIn() } func findGenre(with id: Int, completion: @escaping (Result<Genre?, Error>) -> Void) { genreUseCase.find(with: id, completion: completion) } func getMovieDetail(for movieId: Int, completion: @escaping (Result<Movie, Error>) -> Void) { movieUseCase.getMovieDetail(for: movieId, completion: completion) } func markMovieAsFavorite(movieId: Int, favorite: Bool, completion: @escaping (Result<Bool, Error>) -> Void) { accountUseCase.markMovieAsFavorite(movieId: movieId, favorite: favorite, completion: completion) } func isMovieInFavorites(for movieId: Int, completion: @escaping (Result<Bool, Error>) -> Void) { movieUseCase.isMovieInFavorites(for: movieId, completion: completion) } func saveMovieVisit(with id: Int, title: String, posterPath: String?) { movieVisitUseCase.save(with: id, title: title, posterPath: posterPath) } }
true
e09778bf24b2178bf6b87c49aa714814bce9bbb2
Swift
ArtemMazeika/rs.ios.stage-task4
/Swift_Task4/ios.stage-task/Exercises/Exercise-2/FillWithColor.swift
UTF-8
1,492
3.4375
3
[]
no_license
import Foundation final class FillWithColor { func fillWithColor(_ image: [[Int]], _ row: Int, _ column: Int, _ newColor: Int) -> [[Int]] { let m = image.count if m == 0 { return [] } let n = image[0].count var tempImage = image let oldColor = tempImage[row][column] var queue: [[Int]] = [] print([row,column]) queue.append([row,column]) while !queue.isEmpty { let item = queue.removeFirst() let i = item[0] let j = item[1] tempImage[i][j] = newColor appendToQueu(tempImage, &queue, oldColor, newColor, i, j+1, m, n) appendToQueu(tempImage, &queue, oldColor, newColor, i, j-1, m, n) appendToQueu(tempImage, &queue, oldColor, newColor, i+1, j, m, n) appendToQueu(tempImage, &queue, oldColor, newColor, i-1, j, m, n) } return tempImage } func appendToQueu(_ image: [[Int]], _ queue:inout[[Int]], _ oldColor: Int, _ newColor: Int, _ i: Int, _ j: Int ,_ m: Int, _ n: Int) { if i < 0 || j < 0 || i >= m || j >= n || image[i][j] != oldColor || image[i][j] == newColor { return } queue.append([i,j]) } }
true
5ca39eb9aa190c9c90800724e849e18c6f02b887
Swift
iOSSaurabh/TableViewMenu
/TableViewMenu/MenuListVC/View/MenuHeaderCell.swift
UTF-8
939
2.84375
3
[]
no_license
import UIKit protocol MenuHeaderTableViewCellDelegate { func didSelectMenuHeaderTableViewCell(section: Int, header: MenuHeaderCell) } class MenuHeaderCell: UITableViewCell { @IBOutlet weak var lblmenuName: UILabel! @IBOutlet weak var btnHeader: UIButton! var delegate : MenuHeaderTableViewCellDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code } public func setData(name: String?){ if let menu = name { self.lblmenuName.text = menu.capitalized } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func selectedHeader(sender: AnyObject) { delegate?.didSelectMenuHeaderTableViewCell(section: sender.tag, header: self) } }
true
03e68c6e7ff107ce05c73137b0b44bde76d34f9a
Swift
san2ride/Innsbruck
/Oktoberfest/Oktoberfest/eCardViewController.swift
UTF-8
2,083
2.734375
3
[ "MIT" ]
permissive
// // eCardViewController.swift // Oktoberfest // // Created by don't touch me on 8/16/16. // Copyright © 2016 trvl, LLC. All rights reserved. import UIKit import AVFoundation class eCardViewController: UIViewController { @IBOutlet weak var selfieImage: UIImageView! @IBOutlet var backGroundImage: UIImageView! @IBOutlet weak var iconAnimationImage: UIImageView! var thePhoto: UIImage? var selectedBackGroundImage: UIImage? var backGroundPlayer: AVAudioPlayer? var timer: NSTimer? var imagesArray = [UIImage]() override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let theImage = self.thePhoto { self.selfieImage.image = theImage } if let theImage = self.selectedBackGroundImage { self.backGroundImage.image = theImage } self.backGroundPlayer = self.getAudioPlayer("Polka-Franzi", fileExt: "m4a") self.backGroundPlayer?.play() for i in 1...3 { if let image = UIImage(named: "\(i)of") { imagesArray.append(image) print("of_\(i)") } } iconAnimationImage.animationImages = imagesArray iconAnimationImage.animationDuration = 1.1 iconAnimationImage.animationRepeatCount = 0 iconAnimationImage.startAnimating() } func getAudioPlayer(filename: String, fileExt: String) -> AVAudioPlayer? { var audioPlayer: AVAudioPlayer? if let filePath = NSBundle.mainBundle().URLForResource(filename, withExtension: fileExt) { do { audioPlayer = try AVAudioPlayer(contentsOfURL: filePath) audioPlayer?.volume = 1.0 audioPlayer?.prepareToPlay() } catch { print("an error occured") } } else { print("I cant find the file") } return audioPlayer } }
true
efa705c690e669b1f2d67468feb4bc6868f804a9
Swift
Sephiroth87/C-swifty4
/C64/Joystick.swift
UTF-8
577
3.09375
3
[ "MIT" ]
permissive
// // Joystick.swift // C-swifty4 // // Created by Fabio Ritrovato on 02/03/2015. // Copyright (c) 2015 orange in a day. All rights reserved. // public enum JoystickXAxisStatus { case none case left case right } public enum JoystickYAxisStatus { case none case up case down } public enum JoystickButtonStatus { case released case pressed } final internal class Joystick { internal var xAxis: JoystickXAxisStatus = .none internal var yAxis: JoystickYAxisStatus = .none internal var button: JoystickButtonStatus = .released }
true
8adae667496707075ba1c7abf6f3ab35c760c58d
Swift
chatwyn/WBAnimationTest
/WBAnimationTest/InteractionController.swift
UTF-8
1,881
2.859375
3
[]
no_license
// // InteractionController.swift // WBAnimationTest // // Created by caowenbo on 16/2/14. // Copyright © 2016年 曹文博. All rights reserved. // import UIKit class InteractionController: UIPercentDrivenInteractiveTransition { var transitionContext: UIViewControllerContextTransitioning? = nil var gesture: UIScreenEdgePanGestureRecognizer init(gesture: UIScreenEdgePanGestureRecognizer) { self.gesture = gesture super.init() self.gesture.addTarget(self, action: "gestureAction:") } override func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext super.startInteractiveTransition(transitionContext) } private func percentForGesture(gesture: UIScreenEdgePanGestureRecognizer) -> CGFloat { let transitionContainerView = transitionContext?.containerView() let locationInSourceView = gesture.locationInView(transitionContainerView) let width = transitionContainerView!.bounds.width return (width - locationInSourceView.x) / width } /// 当手势有滑动时触发这个函数 func gestureAction(gestureRecognizer: UIScreenEdgePanGestureRecognizer) { switch gestureRecognizer.state { case .Began: break case .Changed: self.updateInteractiveTransition(self.percentForGesture(gesture)) //更新进度 case .Ended: // 手势滑动超过5分之一的时候完成转场 if self.percentForGesture(gestureRecognizer) >= 0.2 { self.finishInteractiveTransition() }else { self.cancelInteractiveTransition() } default: self.cancelInteractiveTransition() } } }
true
03c15b4d0c26a09910ef9938de7932738bebe59a
Swift
jeremygameso/RecipeTracker
/RecipeTracker/RecipeRow.swift
UTF-8
1,196
3.046875
3
[]
no_license
// // RecipeRow.swift // RecipeTracker // // Created by Lin Zhou on 5/4/20. // Copyright © 2020 Lazy Fish Inc. All rights reserved. // import SwiftUI struct RecipeRow: View { var recipe: Recipe var body: some View { HStack { recipe.image .resizable() .frame(width: 50, height: 50) .clipShape(Circle()) .overlay( Circle().stroke(Color.white, lineWidth: 4)) .shadow(radius: 10) Text(recipe.name) .font(.subheadline) .foregroundColor(Color.gray) .blendMode(/*@START_MENU_TOKEN@*/.luminosity/*@END_MENU_TOKEN@*/) Spacer() if recipe.isFavorite { Image(systemName: "star.fill") .imageScale(.medium) .foregroundColor(.yellow) } } } } struct RecipeRow_Previews: PreviewProvider { static var previews: some View { Group { RecipeRow(recipe: RecipeData[0]) RecipeRow(recipe: RecipeData[1]) } .previewLayout(.fixed(width: 300, height: 70)) } }
true
6f2c92cb16e01f6d3c439f736fc295eedf082dd9
Swift
thachgiasoft/CleanAir
/CleanAirModules/Shared/HTTPClient/Infra/URLSessionHTTPClient.swift
UTF-8
1,230
2.96875
3
[]
no_license
// // URLSessionHTTPClient.swift // CleanAir // // Created by Marko Engelman on 20/11/2020. // import Foundation public class URLSessionHTTPClient { struct UnexpectedValuesRepresentation: Error { } class WrappedTask: HTTPClientTask { weak var task: URLSessionTask? init(_ task: URLSessionTask) { self.task = task } func cancel() { task?.cancel() } } let session: URLSession public init(session: URLSession) { self.session = session } func clientResult(for data: Data?, response: URLResponse?, error: Error?) -> HTTPClient.Result { let result = Result { if let error = error { throw error } else if let data = data, let response = response as? HTTPURLResponse { return (data, response) } else { throw UnexpectedValuesRepresentation() } } return result } } // MARK: - HTTPClient extension URLSessionHTTPClient: HTTPClient { public func execute(request: URLRequest, completion: @escaping (HTTPClient.Result) -> Void) -> HTTPClientTask { let result = clientResult let task = session.dataTask(with: request) { completion(result($0, $1, $2)) } task.resume() return WrappedTask(task) } }
true
efee50b5b8ef40a467e346efb96bac1278e4c9d9
Swift
CodaFi/swift-compiler-crashes
/unique-crash-locations/swift_parser_parseidentifier_swift_identifier_swift_sourceloc_swift_diagnostic_const_87.swift
UTF-8
62
2.609375
3
[ "MIT" ]
permissive
../crashes-duplicates/12609-swift-parser-parseidentifier.swift
true
18f9fcd1cc763a7d9d05aa30e2c193c64a15b9ff
Swift
awesometen/Concept-iOS
/Concept/Resources/CustomView/CollectionCustomLayout.swift
UTF-8
1,690
2.609375
3
[]
no_license
// // CollectionCustomLayout.swift // Concept // // Created by Vijay Jayapal on 02/12/20. // import UIKit class CollectionCustomLayout: UICollectionViewFlowLayout { fileprivate var bannerWidth: CGFloat { return UIScreen.main.bounds.width } //MARK: Private properties init(_ itemSize: CGSize = .zero) { super.init() self.itemSize = itemSize } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() self.minimumInteritemSpacing = 0 self.minimumLineSpacing = 0 self.scrollDirection = .horizontal self.sectionInset = .zero self.collectionView?.decelerationRate = UIScrollView.DecelerationRate.fast } override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { guard let collectionView = self.collectionView else { let latestOffset = super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity) return latestOffset } let pageWidth = bannerWidth + self.minimumInteritemSpacing let approximatePage = collectionView.contentOffset.x/pageWidth let currentPage = velocity.x == 0 ? round(approximatePage) : (velocity.x < 0.0 ? floor(approximatePage) : ceil(approximatePage)) let flickVelocity = velocity.x * 0.3 let flickedPages = (abs(round(flickVelocity)) <= 1) ? 0 : round(flickVelocity) let newHorizontalOffset = ((currentPage + flickedPages) * pageWidth) - collectionView.contentInset.left return CGPoint(x: newHorizontalOffset, y: proposedContentOffset.y) } }
true
807ddc259ee437edd536b5de4429745829edc148
Swift
pdipaolo/Prototype
/Prototype/Prenotazioni/PrenotazioneViewController.swift
UTF-8
6,885
2.59375
3
[]
no_license
// // PrenotazioneViewController.swift // Prototype // // Created by Pierluigi Di paolo on 06/01/21. // import UIKit class PrenotazioneViewController: UIViewController { let arraySection = ["BOOK YOUR TABLE","Dove vuoi sederti?","Select Person","Quante persone?", "Orario"] @IBOutlet weak var prenotazioniCollection: UICollectionView! override func viewDidLoad() { super.viewDidLoad() setupTable() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { setup() } func setupTable(){ prenotazioniCollection.delegate=self prenotazioniCollection.dataSource=self let buttonNib = UINib(nibName: "PrenotazioneCollectionViewCell", bundle: nil) prenotazioniCollection.register(buttonNib, forCellWithReuseIdentifier: "PrenotazioneCell") let calendarNib = UINib(nibName: "CalendarCollectionViewCell", bundle: nil) prenotazioniCollection.register(calendarNib, forCellWithReuseIdentifier: "CalendarCell") let layout = UICollectionViewFlowLayout() layout.sectionInset = centerItemsInCollectionView(cellWidth: 80, numberOfItems: 3, spaceBetweenCell: 30, collectionView: prenotazioniCollection) self.prenotazioniCollection.register(HeaderCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HeaderCollectionReusableView") prenotazioniCollection.collectionViewLayout = layout prenotazioniCollection.translatesAutoresizingMaskIntoConstraints=true prenotazioniCollection.allowsMultipleSelection = true } } extension PrenotazioneViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{ func centerItemsInCollectionView(cellWidth: Double, numberOfItems: Double, spaceBetweenCell: Double, collectionView: UICollectionView) -> UIEdgeInsets { let totalWidth = cellWidth * numberOfItems let totalSpacingWidth = spaceBetweenCell * (numberOfItems - 1) let leftInset = (collectionView.frame.width - CGFloat(totalWidth + totalSpacingWidth)) / 2 let rightInset = leftInset return UIEdgeInsets(top: 0, left: leftInset, bottom: 0, right: rightInset) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { var numberCell = 0 switch section { case 0: numberCell = 1 case 1: numberCell = 2 case 2: numberCell = 3 case 3: numberCell = 3 case 4: numberCell = 9 default: break } return numberCell } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var cell = UICollectionViewCell() switch indexPath.section { case 0: cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CalendarCell", for: indexPath) as! CalendarCollectionViewCell case 1: cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PrenotazioneCell", for: indexPath) as! PrenotazioneCollectionViewCell case 2: cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PrenotazioneCell", for: indexPath) as! PrenotazioneCollectionViewCell case 3: cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PrenotazioneCell", for: indexPath) as! PrenotazioneCollectionViewCell case 4: cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PrenotazioneCell", for: indexPath) as! PrenotazioneCollectionViewCell default: break } return cell } func numberOfSections(in collectionView: UICollectionView) -> Int { 5 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var size = CGSize(width: 80, height: 80 ) switch indexPath.section { case 0: size = CGSize(width: 300, height: 300 ) case 1: size = CGSize(width: 80, height: 80 ) case 2: size = CGSize(width: 80, height: 80 ) case 3: size = CGSize(width: 80, height: 80 ) case 4: size = CGSize(width: 80, height: 80 ) default: break } return size } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: collectionView.frame.width, height: 40) } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { print("UICollectionViewDelegateFlowLayout") switch kind { case UICollectionView.elementKindSectionHeader: let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderCollectionReusableView", for: indexPath) as! HeaderCollectionReusableView headerView.titleLabel.text = arraySection[indexPath.section] return headerView case UICollectionView.elementKindSectionFooter: let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderCollectionReusableView", for: indexPath) as! HeaderCollectionReusableView footerView.titleLabel.text = "Footer" return footerView default: assert(false, "Unexpected element kind") } } func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { collectionView.indexPathsForSelectedItems?.filter({ $0.section == indexPath.section }).forEach({ collectionView.deselectItem(at: $0, animated: false) }) return true } } class HeaderCollectionReusableView: UICollectionReusableView { let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40)) override init(frame: CGRect) { super.init(frame: frame) // Customize here addSubview(titleLabel) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() titleLabel.textAlignment = .center titleLabel.font = UIFont.boldSystemFont(ofSize: 18.0) } }
true
f6f2a25b54c07303fead495dacd5c34b3cd07907
Swift
ihusnainalii/my-swift-journey
/_SwiftUI-Tmall/Tmall/TMHome/HomeViews/loopView/LoopCardView.swift
UTF-8
744
2.5625
3
[ "MIT" ]
permissive
// // LoopCardView.swift // Tmall // // Created by panzhijun on 2019/8/23. // Copyright © 2019 panzhijun. All rights reserved. // import SwiftUI struct LoopCardView: View { var loop: HomeLoopItem var body: some View { ZStack { Color(.clear).frame(height: 260, alignment: .center) loop.featureImage? .resizable() .frame(height: 150) .cornerRadius(10) .padding(.init(top: 100, leading: 10, bottom: 0, trailing: 10)) } } } #if DEBUG struct LoopCardView_Previews: PreviewProvider { static var previews: some View { LoopCardView(loop: loopData[0]) } } #endif
true
668f0303bd655afe28385f30c42c82f4af35371d
Swift
yusuga/TransformableObject
/Example/Tests/Util.swift
UTF-8
1,040
2.84375
3
[ "MIT" ]
permissive
// // Util.swift // TransformableObject // // Created by Yu Sugawara on 7/11/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import ObjectMapper extension ObjectType { func equalValues<T: ObjectType>(to other: T) -> Bool { return bool == other.bool && int == other.int && float == other.float && double == other.double && string == other.string && date.timeIntervalSince1970 == other.date.timeIntervalSince1970 && data == other.data } } struct JSONCreator { private init() {} static func json() -> [String: Any] { return ["bool": true, "int": IntMax(), "float": Float.greatestFiniteMagnitude, "double": Double.greatestFiniteMagnitude, "string": UUID().uuidString, "date": DateTransform().transformToJSON(Date())!, "data": DataTransform().transformToJSON(UUID().uuidString.data(using: .utf8)!)!] } }
true
464844911ac77c8146a1174fc0696754f2aee694
Swift
djavan-bertrand/CrashMapSnapshotter
/TestApp/ViewController.swift
UTF-8
3,297
2.984375
3
[]
no_license
// // ViewController.swift // TestApp // import UIKit import MapKit import CoreLocation class ViewController: UIViewController { /// Quality of the image to provide enum Quality: CustomStringConvertible { /// High quality case high /// Low quality case low var description: String { switch self { case .high: return "high" case .low: return "low" } } fileprivate var zoomValue: CGFloat { switch self { case .high: return 5.0 case .low: return 1.0 } } } @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var qualityLabel: UILabel! private var currentQuality = Quality.low private var mapRect: MKMapRect! override func viewDidLoad() { super.viewDidLoad() scrollView.contentInsetAdjustmentBehavior = .never let corners = [ CLLocationCoordinate2D(latitude: 48.86902670562927, longitude: 2.313831340704411), CLLocationCoordinate2D(latitude: 48.8683048314518, longitude: 2.3132453683057292), CLLocationCoordinate2D(latitude: 48.869139447805274, longitude: 2.310869070810895), CLLocationCoordinate2D(latitude: 48.869861309942024, longitude: 2.31145504320952) ] var mapRect = MKMapRect.null corners.forEach { mapRect = mapRect.union(MKMapRect(origin: MKMapPoint($0), size: MKMapSize(width: 0, height: 0))) } self.mapRect = mapRect } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) displaySatelliteImage(quality: .low) } private func displaySatelliteImage(quality: Quality) { currentQuality = quality let options = MKMapSnapshotter.Options() options.mapRect = mapRect options.mapType = .satellite options.size = CGSize(width: 892 * quality.zoomValue, height: 713 * quality.zoomValue) let snapshotter = MKMapSnapshotter(options: options) qualityLabel.text = "fetching \(quality)" snapshotter.start { [weak self] snapshot, error in switch (snapshot, error) { case let (snapshot?, _): self?.imageView.image = snapshot.image self?.qualityLabel.text = "Quality = \(quality)" case let (_, error?): self?.qualityLabel.text = "Error: \(error.localizedDescription)" case (.none, .none): // this should not happen self?.qualityLabel.text = "Error" } } } @IBAction func reload(_ sender: Any) { displaySatelliteImage(quality: .low) } } extension ViewController: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { // If the threshold is passed, fetch a better quality. // The best quality will be kept even if we unzoom. if currentQuality != .high && scrollView.zoomScale > 1.9 { displaySatelliteImage(quality: .high) } } }
true
c8381f5de1e20fd4f6bbd5e7bdc5018287f2273a
Swift
GregHilston/Code-Foo
/Challenges/challenge_49_detect_capital/dillon-mce/detectCapital.swift
UTF-8
489
3.296875
3
[]
no_license
import Foundation func detectCapitals(_ string: String) -> Bool { return string == string.lowercased() || string == string.uppercased() || string == string.capitalized } let startTime = CFAbsoluteTimeGetCurrent() assert(detectCapitals("USA")) // true assert(detectCapitals("leetcode")) // true assert(detectCapitals("Google")) // true assert(!detectCapitals("FlaG")) // false print("It took \(CFAbsoluteTimeGetCurrent() - startTime) seconds to check the four samples")
true
97c8b46595bca8fe7afb14e9d18f11297dea4974
Swift
tonylattke/swift_helpers
/Metal - Controlling Camera/MetalCube/Camera.swift
UTF-8
1,805
2.890625
3
[]
no_license
// // Camera.swift // MetalCube // // Created by Tony Lattke on 24.11.16. // Copyright © 2016 Hochschule Bremen. All rights reserved. // import Foundation import simd class Camera { // View Model Matrix var viewModelMatrix: float4x4! // Projection Matrix var projectionMatrix: float4x4! // Frustum let angle: Float let aspectRatio: Float let nearPlan: Float let farPlan: Float // Initalization init(position: float3, lookAt: float3, up: float3, aspectRatio: Float, angleDregrees: Float, nearPlan: Float, farPlan: Float) { // Set Frustum self.angle = float4x4.degrees(toRad: angleDregrees) self.aspectRatio = aspectRatio self.nearPlan = nearPlan self.farPlan = farPlan // Set Matrix viewModelMatrix = float4x4.makeLookAt(position.x, position.y, position.z, lookAt.x, lookAt.y, lookAt.z, up.x, up.y, up.z) projectionMatrix = float4x4.makePerspectiveViewAngle(self.angle, aspectRatio: self.aspectRatio, nearZ: self.nearPlan, farZ: self.farPlan) } // Get view matrix func getViewMatrix() -> float4x4 { return viewModelMatrix! } // Get projection matrix func getProjectionCamera() -> float4x4 { return projectionMatrix } // Update projection matrix func projectionMatrixUpdate(aspectRatio: Float){ let newProjectionMatrix = float4x4.makePerspectiveViewAngle(self.angle, aspectRatio: aspectRatio, nearZ: self.nearPlan, farZ: self.farPlan) self.projectionMatrix = newProjectionMatrix } }
true
541c61f5125c358a226a71f9d3b87b787dc52f61
Swift
ValeriyMaliuk/LeetCode
/Arrays.playground/Contents.swift
UTF-8
4,226
3.75
4
[]
no_license
// MARK: - previously done // Two sum - Easy func twoSum(_ nums: [Int], _ target: Int) -> [Int] { var map: [Int: [Int]] = [:] for i in nums.enumerated() { if var arr = map[i.element] { arr.append(i.offset) map[i.element] = arr } else { map[i.element] = [i.offset] } } for (idx, i) in nums.enumerated() { let seeked = target - i if let seekedIdx = map[seeked], !seekedIdx.isEmpty { for exSeekedIdx in seekedIdx { if exSeekedIdx != idx { return [idx, exSeekedIdx] } } } } return [] } // Median of two sorted arrays - hard func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double { let isEven = (nums1.count + nums2.count) % 2 == 0 let half = isEven ? (nums1.count + nums2.count) / 2 - 1 : (nums1.count + nums2.count) / 2 var i1 = 0 var i2 = 0 func next() -> Int { guard i1 < nums1.count else { let result = nums2[i2] i2 += 1 return result } guard i2 < nums2.count else { let result = nums1[i1] i1 += 1 return result } if nums1[i1] < nums2[i2] { let result = nums1[i1] i1 += 1 return result } else { let result = nums2[i2] i2 += 1 return result } } var median = 0.0 while i1 + i2 <= half { median = Double(next()) } if isEven { median = (median + Double(next())) / 2 } return median } // MARK: - 11.11 // Container with most water - medium func maxArea(_ height: [Int]) -> Int { var leftIdx = 0 var rightIdx = height.count - 1 var maxArea = 0 while leftIdx != rightIdx { maxArea = max( maxArea, (rightIdx - leftIdx) * min(height[leftIdx], height[rightIdx]) ) if height[leftIdx] >= height[rightIdx] { rightIdx -= 1 } else { leftIdx += 1 } } return maxArea } func testMaxArea() { let array = [1,8,6,2,5,4,8,3,7] // ER = 49 print(maxArea(array)) } // MARK: - 18.11 // 3Sum - medium func threeSum(_ nums: [Int]) -> [[Int]] { // create hashmap of numbers with number of their occurancies var set: [Int: Int] = [:] for i in 0..<nums.count { let curOccur = set[nums[i]] ?? 0 if curOccur < 3 { set[nums[i]] = curOccur + 1 } } // create shrinked version of list where there are only 3 occurancies of every number var numsReduced: [Int] = [] for i in set { for _ in 0..<i.value { numsReduced.append(i.key) } } var results = Set<[Int]>() for i in 0..<numsReduced.count { // remove 1 occurancy of current number if let index = set[numsReduced[i]] { set[numsReduced[i]] = index - 1 } // iterate over subarray for j in (i + 1)..<numsReduced.count { let target = -(numsReduced[j] + numsReduced[i]) if let numberOfTargetEntries = set[target], numberOfTargetEntries >= 1 { // don't count current second number if target == numsReduced[j] && numberOfTargetEntries == 1 { continue } results.insert([numsReduced[i], numsReduced[j], target].sorted()) } } } return Array(results) } func testThreeSum() { let nums = [-1, 0, 1, 2, -1, -4] // ER = [[-1, 0, 1], [-1, -1, 2]] print(threeSum(nums)) } //testThreeSum() // MARK: - 30.11 // Remove duplicates - Easy func removeDuplicates(_ nums: inout [Int]) -> Int { var i = 0, j = 1 while i < nums.count - 1 { if nums[i] != nums[i + 1] { nums[j] = nums[i + 1] j += 1 } i += 1 } return nums.isEmpty ? 0 : j } func testRemoveDuplicates() { var nums: [Int] = [0,0,1,1,1,2,2,3,3,4] // ER = 5, [0,1,2,3,4...] print(removeDuplicates(&nums)) print(nums) } //testRemoveDuplicates()
true
6f578c454cd7b91690e2f75725984705629723db
Swift
Bonnie3206/iOSFinal_0622_v2
/iOSFinal/View/RegisterView.swift
UTF-8
3,337
2.890625
3
[]
no_license
// // RegisterView.swift // iOSFinal // // Created by CK on 2021/5/5. //問題:帳號自首強迫大寫?/密碼不能隱藏 import SwiftUI import FirebaseAuth import FirebaseStorage import FirebaseStorageSwift//要有swift的,才有result enum RegsiterStatus { case ok case error } struct RegisterView: View { @State var playerRegisterMail: String @State var playerRegisterPassword: String @State var goStartView = false @State private var showAlert = false @State private var showErrorAlert = false @State private var alertContent = "" @State private var regsiterStatus = RegsiterStatus.error @State var searchRoomName: String var body: some View { HStack{ Image("cook2") .resizable() .scaledToFit() .frame(width: 200, height: 200) VStack{ Form{ Section(header: Text("使用者帳號(mail)")) { TextField("請輸入帳號",text:$playerRegisterMail) //.textFieldStyle(RoundedBorderTextFieldStyle()) .frame(width: 200) } Section(header: Text("密碼")) { TextField("請輸入密碼",text:$playerRegisterPassword) //.textFieldStyle(RoundedBorderTextFieldStyle()) .frame(width: 200) } } Button(action: { Auth.auth().createUser(withEmail: "\(playerRegisterMail)", password: "\(playerRegisterPassword)") { result, error in guard let user = result?.user, error == nil else { print(error?.localizedDescription) showAlert = true regsiterStatus = RegsiterStatus.error alertContent = "註冊失敗:\(error?.localizedDescription)" return } print(user.email, user.uid) showAlert = true regsiterStatus = .ok alertContent = "註冊成功!" } //goStartView = true }, label: { Text("註冊") .padding(7) .padding(.horizontal, 25) .background(Color(.systemGray6)) .cornerRadius(8) .padding(.horizontal, 10) }).alert(isPresented: $showAlert) { () -> Alert in Alert(title: Text("\(alertContent)"), message: Text(""), dismissButton: .default(Text("確定"), action: { if regsiterStatus == .ok { goStartView = true } else { } })) } } } .fullScreenCover(isPresented: $goStartView, content: { FirstView(playerSignInMail: "", playerSignInPassword: "", searchRoomName: "") }) } } struct RegisterView_Previews: PreviewProvider { static var previews: some View { RegisterView(playerRegisterMail: "", playerRegisterPassword: "", searchRoomName: "") .previewLayout(.fixed(width: 844, height: 390)) .previewDevice("iPhone 11") } }
true
b3cbf4b79d98aad8cfaba5a0593edb4024c19413
Swift
ProjectInTheClass/AlarmMap
/AlarmMap/AlarmData.swift
UTF-8
13,144
2.703125
3
[]
no_license
// // AlarmData.swift // AlarmMap // // Created by 김요환 on 2020/05/22. // Copyright © 2020 AalrmMapCompany. All rights reserved. // import Foundation import CoreLocation // by CSEDTD infix operator == func ==(lhs: RouteAlarm, rhs: RouteAlarm) -> Bool { return lhs.startTimer == rhs.startTimer } let secondsPerDay: Double = 86400 // by CSEDTD - 월화수목금토일 --> 일월화수목금토 let dates = ["일", "월", "화", "수", "목", "금", "토"] enum AheadOfTime { case none, five, fifteen, thirty func toString() ->String { switch self { case .none: return "정시" case .five: return "5분 전" case .fifteen: return "15분 전" case .thirty: return "30분 전" } } func toIndex() -> Int { switch self { case .none: return 0 case .five: return 1 case .fifteen: return 2 case .thirty: return 3 } } // by CSEDTD func toDouble() -> Double { switch self { case .none: return 0.0 * 60 case .five: return 5.0 * 60 case .fifteen: return 15.0 * 60 case .thirty: return 30.0 * 60 } } } class RouteAlarm{ var time:Date // label에 띄우는 용도 + 요일 계산 용도 // by CSEDTD var startTimer = Timer() let runLoop = RunLoop.current // var deadline: Date // 추가 기능 (지각 했을 때 notification 띄우는 용도) //var alarmIndex: Int // routeAlarmListTest의 index <-- 없앰 var repeatDates:[Bool] = [false,false,false,false,false,false,false] var repeats: Bool = false var isOn = true var infoIsOn: Bool var aheadOf: AheadOfTime var route: [WayPoint] var routeIndex: Int = -1 var alarmTimeDateFormatter = DateFormatter() // 0623 var routeTitle: String var routeSubtitle: String? var routeTotalDisplacement: Double var routeTotalTime: Int var pathFindingTV:UITableView? = nil init() { self.time = Date() self.route = [WayPoint(placeholder: 0), WayPoint(placeholder: 1)] self.aheadOf = .none self.isOn = false self.infoIsOn = false self.routeTitle = "" self.routeSubtitle = nil self.routeTotalDisplacement = -1.0 self.routeTotalTime = -1 } // by CSEDTD init(time:Date, repeatDates: [Bool], aheadOf: AheadOfTime, route: [WayPoint], repeats: Bool, infoIsOn: Bool, routeTitle: String, routeSubtitle: String?, routeTotalDisplacement: Double, routeTotalTime: Int) { // by CSEDTD self.repeatDates = repeatDates self.repeats = repeats self.aheadOf = aheadOf // TODO //self.route = dummyRouteInfo3.route //[kloongHouse, kloongGS25] self.route = route self.infoIsOn = infoIsOn self.time = time if Date() >= self.time - self.aheadOf.toDouble() { self.time += secondsPerDay print("here") } self.routeTitle = routeTitle self.routeSubtitle = routeSubtitle self.routeTotalDisplacement = routeTotalDisplacement self.routeTotalTime = routeTotalTime // TODO - time setting (오전12시 요일 문제 해결되면 firedate 사용 가능) self.startTimer = Timer(fireAt: self.time /*- 경로 시간 TODO*/ - self.aheadOf.toDouble(), interval: /*5.0*/secondsPerDay, target: self, selector: #selector(alarmStarts), userInfo: nil, repeats: self.repeats) runLoop.add(self.startTimer, forMode: .default) self.startTimer.tolerance = 5.0 self.alarmTimeDateFormatter.locale = Locale(identifier: "ko") self.alarmTimeDateFormatter.dateStyle = .none self.alarmTimeDateFormatter.timeStyle = .short } @objc func alarmStarts() { // by CSEDTD // TODO if (self.repeats) && (!self.infoIsOn) { print("self.infoIsOn == false") self.finished() } else if (self.repeats) && (!self.isOn) { print("self.isOn == false") self.detach() } else if (self.repeats) && (workingAlarmExists) { print("ERROR: 알람 시간대 중복! 알람 무시됨 (AlarmData.swift") scheduleNotifications(state: .blocked, sender: self) } else { print("타이머 정상 상태") if !((CLLocationManager.authorizationStatus() == .authorizedAlways) || (CLLocationManager.authorizationStatus() == .authorizedWhenInUse)) { locationAuthorized = false return } else { locationAuthorized = true } let weekday: Int = Calendar(identifier: .iso8601).dateComponents([.weekday], from: self.time).weekday! if self.repeatDates[weekday - 1] { // by CSEDTD - background // TODO globalManager.startUpdatingLocation() if headingAvailable { globalManager.startUpdatingHeading() } /* globalManager.desiredAccuracy = kCLLocationAccuracyBest globalManager.distanceFilter = 5.0 globalManager.showsBackgroundLocationIndicator = true // TODO - You so bad code... */ self.routeIndex = 0 // TODO scheduleNotifications(state: .start, sender: self) if workingAlarmExists { workingAlarm.finished() } workingAlarm = self workingAlarmExists = true // TODO currentDestination = self.getCurrentDestination() finalDestination = self.getFinalDestination() /* let locNotManager = LocalNotificationManager() locNotManager.requestPermission() locNotManager.addNotification(title: "길찾기 시작!") locNotManager.scheduleNotifications() */ // TODO notificationAlarm.start() notificationAlarmCount = 2 } } /* TODO - for test let locNotManager2 = LocalNotificationManager() locNotManager2.requestPermission() locNotManager2.addNotification(title: "5초 반복 타이머") locNotManager2.scheduleNotifications() */ // print("Timer fired: " + String(workingAlarm.isOn) + " " + String(self.isOn)) print(self.getTimeToString()) self.time += secondsPerDay } // by CSEDTD func detach() { self.isOn = false if self == workingAlarm { finished() } } // by CSEDTD func finished() { currentDestination = Location() finalDestination = Location() workingAlarm = RouteAlarm() workingAlarmExists = false routeIndex = -1 currentDistance = -1.0 // TODO notificationAlarm.finish() notificationAlarmCount = 2 // TODO - Big problem (background) globalManager.stopUpdatingLocation() if headingAvailable { globalManager.stopUpdatingHeading() } /* globalManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers globalManager.distanceFilter = CLLocationDistanceMax globalManager.showsBackgroundLocationIndicator = false // TODO - You so bad code... */ } func event(){ //do Something about route finding } func getRepeatDatesToString() -> String{ var repeatDatesString:String = "" for (index,doesRepeat) in repeatDates.enumerated(){ if(doesRepeat){ repeatDatesString += "\(dates[index]) " } } return repeatDatesString } func getTimeToString() -> String{ return self.alarmTimeDateFormatter.string(from: self.time) } // by CSEDTD func getStartingPoint() -> Location { return self.route.first?.location ?? Location() } func getCurrentDestination() -> Location { /*for point in route { print(point.location.name) } print(route[routeIndex].location.name)*/ return self.route[routeIndex].location } func getFinalDestination() -> Location { return self.route.last?.location ?? Location() } func getStartingPointString() -> String { if let waypoint = self.route.first { let name = waypoint.location.name if waypoint.type == .bus { return name + " 정류장" } else if waypoint.type == .metro { return name + " 역 (" + (waypoint.node as! MetroStation).line + ")" } else { return name } } else { return "nil" } } func getCurrentDestinationString() -> String { let waypoint = self.route[routeIndex] let name = waypoint.location.name if waypoint.type == .bus { return name + " 정류장" } else if waypoint.type == .metro { return name + " 역 (" + (waypoint.node as! MetroStation).line + ")" } else { return name } } func getFinalDestinationString() -> String { if let waypoint = self.route.last { let name = waypoint.location.name if waypoint.type == .bus { return name + " 정류장" } else if waypoint.type == .metro { return name + " 역 (" + (waypoint.node as! MetroStation).line + ")" } else { return name } } else { return "nil" } } struct CodableRouteAlarmStruct: Codable{ var time:Date // label에 띄우는 용도 + 요일 계산 용도 var repeatDates:[Bool] var repeats: Bool var isOn: Bool var infoIsOn: Bool var aheadOf: String var route: [WayPoint.CodableWayPointStruct] var routeTitle: String var routeSubtitle: String? var routeTotalDisplacement: Double var routeTotalTime: Int func toRouteAlarmClassInstance() -> RouteAlarm{ let instance = RouteAlarm(time: self.time, repeatDates: self.repeatDates, aheadOf: .none, route: [], repeats: self.repeats, infoIsOn: self.infoIsOn, routeTitle: self.routeTitle, routeSubtitle: self.routeSubtitle, routeTotalDisplacement: self.routeTotalDisplacement, routeTotalTime: self.routeTotalTime) instance.isOn = self.isOn switch self.aheadOf { case "정시": instance.aheadOf = .none case "5분 전": instance.aheadOf = .five case "15분 전": instance.aheadOf = .fifteen case "30분 전": instance.aheadOf = .thirty default: instance.aheadOf = .none } instance.route = self.route.map({(codableWayPointStruct) -> WayPoint in return codableWayPointStruct.toWayPointClassInstance() }) return instance } } func toCodableStruct() -> CodableRouteAlarmStruct{ var codableStruct = CodableRouteAlarmStruct(time: self.time, repeatDates: self.repeatDates, repeats: self.repeats, isOn: self.isOn, infoIsOn: self.infoIsOn, aheadOf: self.aheadOf.toString(), route: [], routeTitle: self.routeTitle, routeSubtitle: self.routeSubtitle, routeTotalDisplacement: self.routeTotalDisplacement, routeTotalTime: self.routeTotalTime) codableStruct.route = self.route.map({(waypoint) -> WayPoint.CodableWayPointStruct in return waypoint.toCodableStruct() }) return codableStruct } } // by CSEDTD var currentDestination: Location = Location() var finalDestination: Location = Location() var workingAlarm: RouteAlarm = RouteAlarm() var workingAlarmExists: Bool = false // TODO var notificationAlarm: NotificationAlarm = NotificationAlarm() var notificationAlarmCount: Int = 2 class NotificationAlarm { var timer = Timer() var runLoop = RunLoop.current func start() { timer = Timer(fireAt: Date(timeIntervalSinceNow: 30.0), interval: 30.0, target: self, selector: #selector(makeNotificationIfUrgent), userInfo: nil, repeats: true) runLoop.add(timer, forMode: .default) timer.tolerance = 3.0 } func finish() { self.timer.invalidate() } @objc func makeNotificationIfUrgent() { scheduleNotifications(state: .notifying, sender: workingAlarm) } }
true
d1d8256cc8f9259c36ce566f71bd912125d83cd6
Swift
julpanucci/National-Parks
/NationalParks/DetailViewController.swift
UTF-8
1,274
2.90625
3
[]
no_license
// // DetailViewController.swift // NationalParks // // Created by Julian Panucci on 10/12/16. // Copyright © 2016 Julian Panucci. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! let parkModel = ParkModel.sharedInstance var imageName = "" var caption = "" var parkName = "" @IBOutlet weak var captionLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() //If it is the first thing loaded when we have not yet touched on a cell(normally the case with iPad, then make the image the first image of the park albums) if imageName == "" { let photo = parkModel.photoInAlbumAtIndex(0, photoIndex: 0) imageName = photo.imageName caption = photo.caption parkName = parkModel.parkTitleAtIndex(0) } imageView.image = UIImage(named: imageName) captionLabel.text = caption self.navigationController?.navigationBar.topItem?.title = parkName } func configureDetailView(_ imageName:String, caption:String, title:String) { self.imageName = imageName self.caption = caption self.parkName = title } }
true
ca7b7686b073ccc564490f8fa88c03454c5abcdf
Swift
hsylife/SwiftyPickerPopover
/TextFieldCel.swift
UTF-8
637
2.59375
3
[ "MIT" ]
permissive
// // TextFieldCell.swift // SwiftyPickerPopoverDemo // // Created by Y.T. Hoshino on 2018/06/20. // Copyright © 2018年 Yuta Hoshino. All rights reserved. // import UIKit import SwiftyPickerPopover class TextFieldCell: UITableViewCell { @IBOutlet private weak var textField: UITextField! weak var delegate: UITableViewController! func updateView(text: String) { textLabel?.text = "TextFieldCell" textField?.text = text } @IBAction func onEditingDidBegin(_ sender: UITextField) { DatePickerPopover(title: "From Cell") .appear(originView: sender, baseViewController: delegate) } }
true
a499f03012dfc9ab2cb39ac3f5df596be262e2f8
Swift
ahmedmadian/MarleySpoon
/MarleySpoon/MarleySpoon/Modules/Recipes/RecipesContract.swift
UTF-8
937
2.859375
3
[]
no_license
// // RecipesContract.swift // MarleySpoon // // Created by Ahmed Madian on 9/23/20. // Copyright © 2020 Ahmed Madian. All rights reserved. // import Foundation protocol RecipesView: ViewInterface { func configHeader(with viewModel: ReceipesHeaderViewModel) func reloadData() } protocol RecipesPresentation: PresenterInterface { var numberOfSections: Int { get } func numberOrItems(in section: Int) -> Int func config(cell: RecipeItemView, at indexPath: IndexPath) func didSelectItem(at indexPath: IndexPath) } protocol RecipesInteraction: InteractorInterface { func getRecipes(_ completion: @escaping (Result<[Recipe], Error>) -> Void) } protocol RecipesWireframeInterface: WireframeInterface { func navigate(to option: RecipesWireframeNavigationOption) } enum RecipesWireframeNavigationOption { case detail(Recipe) } protocol RecipeItemView { func configView(with viewModel: RecipeViewModel) }
true
acfe0375e14c298aa3bf2690d4a6136106fc7c1b
Swift
sbporter/HomeMonitor
/HomeMonitor/TemperatureCell.swift
UTF-8
2,807
2.734375
3
[ "MIT" ]
permissive
// // TemperatureLiveButton.swift // HomeMonitor // // Created by Seth Porter on 12/5/16. // Copyright © 2016 sbporter. All rights reserved. // import UIKit class TemperatureCell: UICollectionViewCell { var gaugeView = GaugeView() var lastUpdatedLabel = UILabel() var valueLabel = UILabel() var value: Float = 60.0 { didSet { valueLabel.text = String(format: "%.1f°", value) gaugeView.percentage = value } } var lastUpdateString: String = "Loading..." { didSet { lastUpdatedLabel.text = lastUpdateString } } // Custom highlight tinting override override var isHighlighted: Bool { didSet { if (isHighlighted) { self.backgroundColor = Colors.lightGray } else { self.backgroundColor = Colors.darkGray } } } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = Colors.darkGray setupViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } extension TemperatureCell: ConstraintProtocol { func configureSubviews() { gaugeView.translatesAutoresizingMaskIntoConstraints = false gaugeView.isUserInteractionEnabled = false gaugeView.backgroundColor = UIColor.clear addSubview(gaugeView) valueLabel.font = Fonts.mediumLight valueLabel.adjustsFontSizeToFitWidth = true valueLabel.translatesAutoresizingMaskIntoConstraints = false valueLabel.textColor = Colors.trueWhite valueLabel.textAlignment = .center valueLabel.baselineAdjustment = .alignCenters valueLabel.backgroundColor = UIColor.clear addSubview(valueLabel) lastUpdatedLabel.font = Fonts.small lastUpdatedLabel.translatesAutoresizingMaskIntoConstraints = false lastUpdatedLabel.textColor = Colors.trueWhite lastUpdatedLabel.textAlignment = .center lastUpdatedLabel.backgroundColor = UIColor.clear addSubview(lastUpdatedLabel) } func configureConstraints() { gaugeView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsetsMake(10, 10, 10, 10)) valueLabel.autoCenterInSuperview() valueLabel.autoMatch(.width, to: .width, of: self, withMultiplier: 0.35) valueLabel.autoMatch(.height, to: .height, of: self, withMultiplier: 0.35) lastUpdatedLabel.autoPinEdge(toSuperviewEdge: .left, withInset: 5) lastUpdatedLabel.autoPinEdge(toSuperviewEdge: .right, withInset: 5) lastUpdatedLabel.autoPinEdge(toSuperviewEdge: .bottom, withInset: 5) } }
true
b84b482a72f212e3356b8961ba3ba9b5d199d9c8
Swift
andrewarrow/cactus-ios
/Cactus/Screens/Charts/WordBubblesChartView.swift
UTF-8
1,389
2.984375
3
[]
no_license
// // WordBubblesChartView.swift // Cactus // // Created by Neil Poulin on 8/24/20. // Copyright © 2020 Cactus. All rights reserved. // import SwiftUI struct WordBubblesChartController: UIViewControllerRepresentable { typealias UIViewControllerType = WordBubbleWebViewController var words: [InsightWord]? func makeUIViewController(context: Context) -> WordBubbleWebViewController { let uiViewController = WordBubbleWebViewController() uiViewController.words = self.words uiViewController.loadInsights() uiViewController.unlockInsights() return uiViewController } func updateUIViewController(_ uiViewController: WordBubbleWebViewController, context: Context) { uiViewController.words = self.words uiViewController.loadInsights() uiViewController.unlockInsights() } } struct WordBubblesChartView: View { var words: [InsightWord]? var body: some View { WordBubblesChartController(words: self.words) .frame(width: 300, height: 300) } } struct WordBubblesChartView_Previews: PreviewProvider { static var previews: some View { WordBubblesChartView(words: [ InsightWord(frequency: 1, word: "XCode"), InsightWord(frequency: 1, word: "Swift"), InsightWord(frequency: 1, word: "SwiftUI") ]) } }
true
b8e321483e0af4b20b7f5ba68761c2f29e4fb01f
Swift
v-denis/App_HowMaskDo
/App_HowMaskDo/App_HowMaskDo/Extensions/ViewWithLabelAndButton.swift
UTF-8
3,354
2.546875
3
[]
no_license
// // viewWithLabelAndButton.swift // Lesson11_homework // // Created by MacBook Air on 07.04.2020. // Copyright © 2020 Denis Valshchikov. All rights reserved. // import UIKit class ViewWithLabelAndButton: UIView { let button: UIButton = { let button = UIButton(type: .system) button.backgroundColor = .red button.layer.cornerRadius = 13 button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .body) button.layer.borderWidth = 0.5 button.layer.borderColor = UIColor.lightGray.cgColor button.setTitleColor(.white, for: .normal) return button }() let label = UILabel() let timeLabel = UILabel() let imageView = UIImageView(frame: .zero) init(labelText: String, labelFont: UIFont, buttonText: String, image: UIImage?, timeText: String) { super.init(frame: .zero) button.setTitle(buttonText, for: .normal) layer.cornerRadius = 15 layer.borderWidth = 1.0 layer.borderColor = UIColor.lightGray.cgColor backgroundColor = #colorLiteral(red: 0.9344067259, green: 0.9344067259, blue: 0.9344067259, alpha: 1) label.textAlignment = .center label.adjustsFontSizeToFitWidth = true label.text = labelText label.font = labelFont label.textColor = UIColor(named: "textColors") timeLabel.textColor = UIColor(named: "textColors") timeLabel.textAlignment = .center timeLabel.adjustsFontSizeToFitWidth = true timeLabel.font = UIFont.preferredFont(forTextStyle: .caption1) timeLabel.text = timeText imageView.image = image imageView.contentMode = .scaleAspectFit imageView.clipsToBounds = true Helper.tamicOff(views: [button, label, imageView, timeLabel]) Helper.addSubviews(superView: self, subviews: [button, label, imageView, timeLabel]) NSLayoutConstraint.activate([ label.topAnchor.constraint(equalTo: topAnchor, constant: 12), label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 7), label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -7), label.heightAnchor.constraint(equalToConstant: 20) ]) NSLayoutConstraint.activate([ timeLabel.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 2), timeLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 7), timeLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -7), timeLabel.heightAnchor.constraint(equalToConstant: 20) ]) NSLayoutConstraint.activate([ imageView.topAnchor.constraint(equalTo: timeLabel.bottomAnchor, constant: 10), imageView.trailingAnchor.constraint(equalTo: trailingAnchor), imageView.leadingAnchor.constraint(equalTo: leadingAnchor), imageView.bottomAnchor.constraint(equalTo: button.topAnchor, constant: -15) ]) imageView.setContentHuggingPriority(UILayoutPriority(rawValue: 150), for: .vertical) imageView.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 150), for: .vertical) NSLayoutConstraint.activate([ button.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20), button.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20), button.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -15), button.heightAnchor.constraint(equalToConstant: 40), button.widthAnchor.constraint(equalTo: widthAnchor, constant: -40) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
4c43fc435ac6f85d877b5e272e25cbacd37f6b69
Swift
intive/TOZ_iOS
/TOZ_iOS/GalleryTableViewCell.swift
UTF-8
1,478
2.78125
3
[ "Apache-2.0" ]
permissive
// // GalleryTableViewCell.swift // TOZ_iOS // // Created by Kobsonauta on 27.03.2017. // Copyright © 2017 intive. All rights reserved. // import UIKit class GalleryTableViewCell: UITableViewCell { @IBOutlet weak var animalImage: UIImageView! @IBOutlet weak var animalName: UILabel! @IBOutlet weak var animalType: UILabel! private var animalID: String? override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = Color.Cell.Background.secondary animalName.adjustsFontSizeToFitWidth = true } func configure(for animal: AnimalItem) { animalID = animal.animalID self.animalName.text = animal.name self.animalType.text = animal.type.localizedType let imageUrl: URL? = animal.imageUrl animalImage.contentMode = .scaleAspectFill animalImage.clipsToBounds = true switch animal.type { case .CAT: self.animalImage.image = #imageLiteral(resourceName: "placeholder_cat") case .DOG: self.animalImage.image = #imageLiteral(resourceName: "placeholder_dog") } if let imageUrl = imageUrl { PhotoManager.shared.getPhoto(from: imageUrl, completion: {(image) -> Void in if self.animalID == animal.animalID { if let image = image { self.animalImage.image = image } } }) } } }
true
31a506e80663213c909f9f1207c441df1987cbdc
Swift
renatofernandes28/Mosaic
/Mosaic/UWOpenDataAPIManager.swift
UTF-8
1,068
2.59375
3
[]
no_license
// // UWOpenDataAPIManager.swift // Mosaic // // Created by Renato Fernandes on 2015-07-14. // Copyright (c) 2015 CS446. All rights reserved. // import Foundation typealias ServiceResponse = (JSON, NSError?) -> Void class UWOpenDataAPIManager : NSObject { static let sharedInstance = UWOpenDataAPIManager() let baseURL = "https://api.uwaterloo.ca/v2/events.json?key=30d57450aff6393d2fd6a4efabaef581" func getEvents(onCompletion: (JSON) -> Void) { let route = baseURL makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) { let request = NSMutableURLRequest(URL: NSURL(string: path)!) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in let json:JSON = JSON(data: data) onCompletion(json, error) }) task.resume() } }
true
1828898e53e63838117faa2f66b3d6127a0ba7b8
Swift
safwen005/RickAndMorty
/rick&morty/Model/CharactersTableViewCell/CharactersCellDelegate.swift
UTF-8
115
2.578125
3
[]
no_license
import Foundation protocol CharactersCellDelegate { func setCharacterInfoData(_ characterData: CharacterData) }
true
a4bf76e1967de77d82dbe7f22621b161301f8f5c
Swift
GabrielAC17/Onde-tem-Comida
/Onde tem Comida/Model/Viewport.swift
UTF-8
192
2.609375
3
[]
no_license
// // Viewport.swift // Onde tem Comida // // Created by Gabriel De Andrade Cordeiro on 19/07/21. // import Foundation // MARK: - Viewport struct Viewport: Codable { let northeast, southwest: Location? }
true
c5d9b9bbc1e573622096864d5ed11608f9f5108a
Swift
ycs0405/MGDS_Swift
/MGDS_Swift/MGDS_Swift/Class/Home/Liveky/LivekyCycleHeader.swift
UTF-8
3,271
2.515625
3
[ "MIT" ]
permissive
// // LivekyCycleHeader.swift // MGDS_Swift // // Created by i-Techsys.com on 17/1/23. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit class LivekyCycleHeader: UIView { var type: LivekyTopicType = .top // MARK: - lazy属性 fileprivate lazy var carouselView: XRCarouselView = { [weak self] in let carouselView = XRCarouselView() carouselView.time = 2.0 carouselView.pagePosition = PositionBottomCenter carouselView.delegate = self return carouselView }() // 模型数组 fileprivate lazy var cycleHeaderModels = [CycleHeaderModel]() /// 图片回调 var imageClickBlock: ((_ cycleHeaderModel: CycleHeaderModel) -> ())? // MARK: - 系统方法 override init(frame: CGRect) { super.init(frame: frame) setUpUI() } override func layoutSubviews() { super.layoutSubviews() carouselView.frame = self.bounds } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 初始化UI 和请求数据 extension LivekyCycleHeader { fileprivate func setUpUI() { addSubview(carouselView) loadData() } /// 内部请求,不外部封装(要想看外部封装请看Miao文件下的 MGHotADCell) open func loadData() { let urlStr = "http://api.m.panda.tv/ajax_rmd_ads_get?__version=2.0.3.1352&__plat=ios&__channel=appstore" NetWorkTools.requestData(type: .get, urlString: urlStr, succeed: {[unowned self] (result, err) in guard let resultDict = result as? [String: Any] else { return } guard let resultArr = resultDict["data"] as? [[String: Any]] else { return } self.cycleHeaderModels.removeAll() for dict in resultArr { let model = CycleHeaderModel(dict: dict) self.cycleHeaderModels.append(model) } var imageUrls = [String]() var titleArr = [String]() for cycleHeaderModel in self.cycleHeaderModels { self.type == .top ? imageUrls.append(cycleHeaderModel.picture) : imageUrls.append(cycleHeaderModel.newimg) self.type == .top ? titleArr.append(cycleHeaderModel.name) : titleArr.append(cycleHeaderModel.notice) // if self.type == .top { // self.imageUrls.append(cycleHeaderModel.picture) // titleArr.append(cycleHeaderModel.name) // }else { // self.imageUrls.append(cycleHeaderModel.newimg) // titleArr.append(cycleHeaderModel.notice) // } } self.carouselView.imageArray = imageUrls self.carouselView.describeArray = titleArr }) { (err) in print(err) } } } // MARK: - XRCarouselViewDelegate extension LivekyCycleHeader: XRCarouselViewDelegate { internal func carouselView(_ carouselView: XRCarouselView!, didClickImage index: Int) { if imageClickBlock != nil { imageClickBlock!((self.cycleHeaderModels[index])) } } }
true
c4b6fa95aabdd52b4e475c30f3d6e8bf6c076d5f
Swift
DT021/Tradelytics
/Tradelytics/Model/TradeType.swift
UTF-8
538
2.875
3
[]
no_license
// // TradeType.swift // Tradelytics // // Created by Bhris on 11/19/19. // Copyright © 2019 chrisrvillanueva. All rights reserved. // import Foundation enum TradeType: String { case none = "Select Trade Type" case buyExec = "Buy Execution" case sellExec = "Sell Execution" case buyLimit = "Buy Limit" case sellLimit = "Sell Limit" case buyStop = "Buy Stop" case sellStop = "Sell Stop" } extension TradeType: CaseIterable { } extension TradeType: Identifiable { var id: String { rawValue } }
true