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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ab8923503bc3e09cdd551083f049c49e8b2ae52a
|
Swift
|
ChillyBwoy/gymtrack-app
|
/gymtrack-app/Managers/DataManagerMemory.swift
|
UTF-8
| 1,158
| 2.609375
| 3
|
[] |
no_license
|
//
// DataManagerMemory.swift
// gymtrack-app
//
// Created by Eugene Cheltsov on 03.05.2020.
// Copyright © 2020 Eugene Cheltsov. All rights reserved.
//
import CoreData
import Foundation
final class DataManagerMemory: DataProvider {
private(set) var containerName: String
private(set) var persistentContainer: NSPersistentContainer
private(set) var context: NSManagedObjectContext
init() {
containerName = "gymtrack_app"
let description = NSPersistentStoreDescription()
description.type = NSInMemoryStoreType
description.shouldAddStoreAsynchronously = false
let container = NSPersistentContainer(
name: containerName,
managedObjectModel: NSManagedObjectModel.mergedModel(from: [Bundle.main])!
)
container.persistentStoreDescriptions = [description]
container.loadPersistentStores { storeDescription, error in
precondition(storeDescription.type == NSInMemoryStoreType)
if let error = error as NSError? {
fatalError("In memory coordinator creation failed \(error), \(error.userInfo)")
}
}
persistentContainer = container
context = persistentContainer.viewContext
}
}
| true
|
f55e061a1241ae475b89224b2e64d1367d8c20dc
|
Swift
|
daeqws4/Jiny-Algorithms-hackerrank
|
/Simple Array Sum.swift
|
UTF-8
| 1,875
| 3.890625
| 4
|
[] |
no_license
|
Practice > Algorithms > Warmup > Simple Array Sum
Q.
Given an array of integers, find the sum of its elements.
For example, if the array , , so return .
Function Description
Complete the simpleArraySum function in the editor below. It must return the sum of the array elements as an integer.
simpleArraySum has the following parameter(s):
ar: an array of integers
Input Format
The first line contains an integer, , denoting the size of the array.
The second line contains space-separated integers representing the array's elements.
Constraints
Output Format
Print the sum of the array's elements as a single integer.
Sample Input
6
1 2 3 4 10 11
Sample Output
31
Explanation
We print the sum of the array's elements: 1 + 2 + 3 + 4 + 10 + 11 = 31.
A.
import Foundation
/*
* Complete the simpleArraySum function below.
*/
func simpleArraySum(ar: [Int]) -> Int {
/*
* Write your code here.
* 반복문으로 받은 인자를 모두 더해서 int형으로 return 시킨다.
*/
var sum = 0
for i in ar{
sum += i
}
return sum
}
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!
guard let arCount = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }
guard let arTemp = readLine() else { fatalError("Bad input") }
let ar: [Int] = arTemp.split(separator: " ").map {
if let arItem = Int($0.trimmingCharacters(in: .whitespacesAndNewlines)) {
return arItem
} else { fatalError("Bad input") }
}
guard ar.count == arCount else { fatalError("Bad input") }
let result = simpleArraySum(ar: ar)
fileHandle.write(String(result).data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)
| true
|
1dbabb25937f34d0acd3290278b1e78474dfc160
|
Swift
|
bdeasy/MCSCommerceWeb
|
/Example/FancyShopV7/FancyShopV7/Entities/PaymentMethod.swift
|
UTF-8
| 1,589
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// PaymentMethod.swift
// MerchantApp
//
// Created by Patel, Utkal on 1/24/18.
// Copyright © 2018 MasterCard. All rights reserved.
//
import Foundation
import MCSCommerceWeb
/// PaymentMethod object, handles the paymentMethod info after paymentMethod set by user.
class PaymentMethod: NSObject, NSCoding {
var paymentMethodObject : MCCPaymentMethod?
/// Singleton instance
static let sharedInstance : PaymentMethod = {
if let instance = DataPersisterManager.sharedInstance.getPaymentMethod() {
return instance
}
return PaymentMethod()
}()
// MARK: Initializers
/// Private intitializer
private override init() {
super.init()
}
// MARK: Methods
/// Saves the PaymentMethod
func savePaymentMethod(){
DataPersisterManager.sharedInstance.savePaymentMethod()
}
/// Removes the PaymentMethod
func removePaymentMethod(){
DataPersisterManager.sharedInstance.removePaymentMethod()
self.paymentMethodObject = nil
}
//MARK: NSCoding
/// NSCoding Initializer
///
/// - Parameters:
/// - coder: NSCoder instance
internal required init?(coder aDecoder: NSCoder) {
self.paymentMethodObject = aDecoder.decodeObject(forKey: "paymentMethodObject") as? MCCPaymentMethod
super.init()
}
/// NSCoding Method
///
/// - Parameter aCoder: NSCoder instance
func encode(with aCoder: NSCoder) {
aCoder.encode(self.paymentMethodObject, forKey:"paymentMethodObject")
}
}
| true
|
c30520a6fb3116ba963005f6334bf73c60d759f2
|
Swift
|
atrasc-hida/SpeechRecognizerSample
|
/SFSpeechRecognizer/ViewController.swift
|
UTF-8
| 1,696
| 2.859375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// SFSpeechRecognizer
//
// Created by 飛田 由加 on 2020/03/03.
// Copyright © 2020 atrasc. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let dest = segue.destination as? SecondViewController else { return }
switch segue.identifier {
case "japanese": dest.lang = .japanese
case "english": dest.lang = .english
case "simplified": dest.lang = .simplified
case "traditional": dest.lang = .traditional
case "korean": dest.lang = .korean
case "german": dest.lang = .german
case "italian": dest.lang = .italian
case "hindi": dest.lang = .hindi
default:
break
}
}
}
enum Language: String{
case japanese = "日本語"
case english = "英語"
case simplified = "簡体字中国語"
case traditional = "繁体字中国語"
case korean = "韓国語"
case german = "ドイツ語"
case italian = "イタリア語"
case hindi = "ヒンディー語"
var identifier: String {
switch self {
case .japanese:
return "ja_JP"
case .english:
return "en_US"
case .simplified:
return "zh_Hans"
case .traditional:
return "zh_Hant"
case .korean:
return "ko"
case .german:
return "de_DE"
case .italian:
return "it_IT"
case .hindi:
return "hi_IN"
}
}
}
| true
|
6d260d5ce6e8e8418edd2a331f144586c2f2dc6f
|
Swift
|
19CM0134/SampleSupport
|
/SampleSupport/View/ArchiveHeader.swift
|
UTF-8
| 2,020
| 2.625
| 3
|
[] |
no_license
|
//
// ArchiveHeader.swift
// ExhibitionSup
//
// Created by cmStudent on 2021/01/20.
//
import UIKit
class ArchiveHeader: UIView {
// MARK: - Properties
private var presenter: ExhibitionPresenter!
private var targetExhibition: [ExhibitionModel] = []
private let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 26)
label.textColor = .black
label.text = "履歴"
return label
}()
private let exhibitionTitle: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 17.5)
label.textColor = .black
return label
}()
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .white
addSubview(titleLabel)
titleLabel.anchor(top: topAnchor,
left: leftAnchor,
paddingTop: 20,
paddingLeft: 15)
addSubview(exhibitionTitle)
exhibitionTitle.anchor(top: titleLabel.bottomAnchor,
left: leftAnchor,
paddingTop: 10,
paddingLeft: 15)
setupExhibitionPresenter()
}
override func layoutSubviews() {
super.layoutSubviews()
exhibitionTitle.text = targetExhibition[0].exhibitionName
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Helpers
fileprivate func setupExhibitionPresenter() {
presenter = ExhibitionPresenter()
presenter.delegate = self
presenter.getExhibitionInfo()
}
}
// MARK: - ExhibitionPresenterDelegate
extension ArchiveHeader: ExhibitionPresenterDelegate {
func setExhibitionToScreen(_ exhibition: [ExhibitionModel]) {
targetExhibition = exhibition
}
}
| true
|
630a97cb6037198e1ee2e4eab0da4350e4640ac1
|
Swift
|
NFuego/st
|
/momoStore/momoStore/ConfigInteractor.swift
|
UTF-8
| 723
| 2.703125
| 3
|
[] |
no_license
|
//
// ConfigInteractor.swift
// Project: momoStore
//
// Module: Config
//
// MomoDidi 2016年
//
// MARK: Imports
import Foundation
import SwiftyVIPER
// MARK: Protocols
/// Should be conformed to by the `ConfigInteractor` and referenced by `ConfigPresenter`
protocol ConfigPresenterInteractorProtocol {
/// Requests the title for the presenter
func requestTitle()
}
// MARK: -
/// The Interactor for the Config module
struct ConfigInteractor {
// MARK: - Variables
weak var presenter: ConfigInteractorPresenterProtocol?
}
// MARK: - Config Presenter to Interactor Protocol
extension ConfigInteractor: ConfigPresenterInteractorProtocol {
func requestTitle() {
presenter?.set(title: "Config")
}
}
| true
|
b53249e2828f7fb7005dd5fc371d0174135bde0a
|
Swift
|
TaimoorSaeed/Social-App
|
/Social-App/Controller/SignInVC.swift
|
UTF-8
| 3,338
| 2.703125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Social-App
//
// Created by Asher Ahsan on 11/07/2018.
// Copyright © 2018 swift. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import Firebase
import FirebaseAuth
import SwiftKeychainWrapper
class SignInVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
if let _ = KeychainWrapper.standard.string(forKey: KEY_UID){
performSegue(withIdentifier: "goToFeed", sender: nil)
}
}
@IBOutlet weak var emailFeild: FancyFeild!
@IBOutlet weak var passwordFeild: FancyFeild!
@IBAction func fbBtnPressed(_ sender: Any) {
let facebookLogin = FBSDKLoginManager()
facebookLogin.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
if error != nil {
print("Unable to anuthenticate - \(String(describing: error))")
} else if result?.isCancelled == true {
print("User cancel facebook auth")
} else {
print("Sucessfullt authenticated with facebook")
let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
self.firebaseAuth(_credential: credential)
}
}
}
func firebaseAuth(_credential : AuthCredential) {
Auth.auth().signInAndRetrieveData(with: _credential) { (user, error) in
if error != nil {
print("Unable to authenticate with firebase - \(String(describing: error))")
} else {
print("Sucessfull authenicated with firebase")
if let user = user{
print(user.user.uid)
self.completeSignIn(id: user.user.uid)
}
}
}
}
@IBAction func signInTapped(_ sender: Any) {
if let email = emailFeild.text , let pwd = passwordFeild.text {
Auth.auth().signIn(withEmail: email, password: pwd, completion: { (user, error) in
if error == nil {
print("Email user authenticaed with firebase")
} else {
print(error?.localizedDescription)
Auth.auth().createUser(withEmail: email, password: pwd, completion: { (user, error) in
if error != nil {
print("Unable to authenticate with firebase using email")
print(error?.localizedDescription)
} else {
print("Sucessfully authenicated with firebase")
if let user = user {
self.completeSignIn(id: user.user.uid)
}
}
})
}
})
}
}
func completeSignIn(id: String) {
let keychaingResult = KeychainWrapper.standard.set(id, forKey: KEY_UID)
print("Data saved to keychain \(keychaingResult)")
performSegue(withIdentifier: "goToFeed", sender: nil)
}
}
| true
|
5b5e5554c5e54e97ec2b835d6aa85c0413e28775
|
Swift
|
ambrish018/MVVM-UnitTest-UITest-Swift
|
/MovieApp/View/MovieListPageVC.swift
|
UTF-8
| 2,344
| 2.546875
| 3
|
[] |
no_license
|
//
// MovieListPageVC.swift
// MovieApp
//
// Created by YASH COMPUTERS on 29/08/19.
// Copyright © 2019 ambrish. All rights reserved.
//
import UIKit
class MovieListPageVC: UIViewController {
@IBOutlet weak var movieTableView: UITableView!
enum MovieListType {
case popular
case nowPlaying
}
var viewModel : MovieListProtocol!
override func viewDidLoad() {
super.viewDidLoad()
viewModel.viewDidLoad()
// Do any additional setup after loading the view.
viewModel.callBack = { [weak self] in
DispatchQueue.main.async {
self?.movieTableView.reloadData()
}
}
}
}
extension MovieListPageVC : UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewModel.numberOfRows
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? MovieListTableViewCell else {
fatalError()
}
if viewModel.numberOfRows == indexPath.row + 1 {
self.callNextPage()
}
let model = self.viewModel.tableCellDataModelForIndexPath(indexPath)
cell.configureCell(model: model)
return cell
}
func callNextPage(){
viewModel.viewDidLoad()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 300
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let model = self.viewModel.tableCellDataModelForIndexPath(indexPath)
let detailVC = self.storyboard?.instantiateViewController(withIdentifier: "MovieDetailVC") as! MovieDetailVC
detailVC.detailUrl = model.movieDetailUrl
self.navigationController?.pushViewController(detailVC, animated: true)
}
}
extension MovieListPageVC {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
}
| true
|
89b65933abaeb58e425c5e64de5fabc64ae4247d
|
Swift
|
asproat/PurchaseAndConvert
|
/PurchaseAndConvert/CurrencyViewController.swift
|
UTF-8
| 6,163
| 2.578125
| 3
|
[] |
no_license
|
//
// CurrencyViewController.swift
// PurchaseAndConvert
//
// Created by Alan Sproat on 1/5/19.
// Copyright © 2019 Gary Sproat. All rights reserved.
//
import UIKit
class CurrencyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var convertedTotal: UILabel!
@IBOutlet weak var tableView: UITableView!
var currencies : [Currency]?
var totalUSD : Float = 0.00
let APIKey : String = "3322a128ce9574e8da21c690f981d76c"
override func viewDidLoad() {
super.viewDidLoad()
convertedTotal.text = "\(totalUSD) USD"
// Do any additional setup after loading the view.
tableView.dataSource = self
tableView.delegate = self
getCurrencies()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return currencies?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "currencyCell", for: indexPath) as UITableViewCell
cell.textLabel?.text = "\(currencies?[indexPath.row].currencyName ?? "")"
return cell
}
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
// get conversion
//http://apilayer.net/api/convert?from=EUR&to=GBP&amount=100
let url = URL(string: "http://apilayer.net/api/live?source=USD¤cies=\(currencies![indexPath.row].currencyCode ?? "USD")&amount=\(totalUSD)&access_key=\(APIKey)")
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.timeoutInterval = 5
let dataTask = URLSession.shared.dataTask(with: request)
{
(data, response, error) in
if let _ = error
{
let alert = UIAlertController(title: "Conversion Error", message: "Error Converting Total", preferredStyle: .alert )
let action1 = UIAlertAction(title: "OK", style: .default)
alert.addAction(action1)
self.present(alert, animated: true, completion: nil)
}
else
{
if let usableData = data
{
do
{
let jsonData = try JSONSerialization.jsonObject(with: usableData, options: .mutableContainers) as! [String: Any]
DispatchQueue.main.async
{
if jsonData["success"] as! Int == 1
{
let converted = (jsonData["quotes"]! as! [String:Any])["USD" + self.currencies![indexPath.row].currencyCode]! as! NSNumber
self.convertedTotal.text = "\(converted.floatValue * self.totalUSD) \(self.currencies?[indexPath.row].currencyCode ?? "")"
}
else
{
self.convertedTotal.text = "Error in conversion"
}
}
}
catch
{
DispatchQueue.main.async
{
let alert = UIAlertController(title: "Conversion Error", message: "Error Converting Total", preferredStyle: .alert )
let action1 = UIAlertAction(title: "OK", style: .default)
alert.addAction(action1)
self.present(alert, animated: true, completion: nil)
}
}
}
}
}
dataTask.resume()
}
func getCurrencies()
{
currencies = [Currency]()
let url = URL(string: "http://apilayer.net/api/list?access_key=\(APIKey)")
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.timeoutInterval = 5
let dataTask = URLSession.shared.dataTask(with: request)
{
(data, response, error) in
if let _ = error
{
print("error = \(String(describing: error))")
let alert = UIAlertController(title: "Currency Error", message: "Error Fetching Currencies", preferredStyle: .alert )
let action1 = UIAlertAction(title: "OK", style: .default)
alert.addAction(action1)
self.present(alert, animated: true, completion: nil)
}
else
{
if let usableData = data
{
do
{
let jsonData = try JSONSerialization.jsonObject(with: usableData, options: .mutableContainers) as! [String: Any]
for currency in jsonData["currencies"] as! [String:String]
{
self.currencies?.append(Currency(name: currency.value, code: currency.key))
}
self.currencies?.sort(by: { $0.currencyName < $1.currencyName } )
DispatchQueue.main.async
{
self.tableView.reloadData()
}
}
catch
{
DispatchQueue.main.async
{
let alert = UIAlertController(title: "Currency Fetch Error", message: "Error Fetching Currencies", preferredStyle: .alert )
let action1 = UIAlertAction(title: "OK", style: .default)
alert.addAction(action1)
self.present(alert, animated: true, completion: nil)
}
}
}
}
}
dataTask.resume()
}
}
| true
|
f22c8e907a6b0ae0d23ec228f91d23ba8eef90a5
|
Swift
|
a7ex/GenericApp
|
/GenericApp/Layers/Application/Validators/TextValidator.swift
|
UTF-8
| 1,330
| 3.40625
| 3
|
[] |
no_license
|
//
// TextValidator.swift
import Foundation
enum TextValidator: Validator {
case notEmpty
case minLength(length: Int)
case maxLength(length: Int)
case contains(subString: String)
case containsRegexp(regexp: String)
case validEmail
func validate(_ input: Any?) -> Bool {
let text = input as? String
switch self {
case .notEmpty:
guard let text = text,
!text.isEmpty else { return false }
return true
case .minLength(let length):
guard let text = text,
!text.isEmpty else { return false }
return text.characters.count >= length
case .maxLength(let length):
guard let text = text,
!text.isEmpty else { return true }
return text.characters.count <= length
case .contains(let subString):
return text?.contains(subString) ?? false
case .containsRegexp(let regexp):
guard text?.range(of: regexp,
options: [.regularExpression, .caseInsensitive],
range: nil,
locale: nil) != nil else { return false }
return true
case .validEmail:
return text?.contains("@") ?? false
}
}
}
| true
|
25666331446c2dd7b1defd48d36f0fa237cb44b3
|
Swift
|
jdkouris/ios-firebase-chat
|
/FirebaseChat/FirebaseChat/Model Controller/ChatRoomController.swift
|
UTF-8
| 1,968
| 2.78125
| 3
|
[] |
no_license
|
//
// ChatRoomController.swift
// FirebaseChat
//
// Created by John Kouris on 12/7/19.
// Copyright © 2019 John Kouris. All rights reserved.
//
import Foundation
import Firebase
import MessageKit
class ChatRoomController {
var chatRooms: [ChatRoom] = []
var dbRef: DatabaseReference = Database.database().reference()
func createChatRoom(with title: String) {
let chatRoomData: [String: Any] = ["title": title, "messages": [UUID().uuidString], "uid": UUID().uuidString]
dbRef.child("chats").child(chatRoomData["uid"] as! String).setValue(chatRoomData, withCompletionBlock: { error, ref in
if error == nil {
print("Sucess")
} else {
print("Error")
}
})
}
func getChatRooms(completion: @escaping () -> Void ) {
dbRef.child("chats").queryOrdered(byChild: "title").observe(.value) { (snapshot) in
let snapshots = snapshot.children.allObjects as! [DataSnapshot]
self.chatRooms.removeAll()
for snap in snapshots {
let chatRoomDictionary = snap.value as! [String: Any]
let uid = snap.key
let title = chatRoomDictionary["title"] as! String
// let messages = chatRoomDictionary["messages"] as! [Message]
// let messages = chatRoomDictionary["messages"]
let chatRoom = ChatRoom(uid: uid, title: title, messages: [Message(senderID: UUID().uuidString, text: "Welcome to your chat room!", author: "ChatBot")])
self.chatRooms.append(chatRoom)
}
completion()
}
}
func createMessage(in chatRoom: ChatRoom) {
let message = Message(senderID: "", text: "", author: "")
dbRef.child("chats").child(chatRoom.uid).child("messages").child("senderID").childByAutoId().setValue(message)
}
}
| true
|
5f196690243e5305d493efadac673ba8dd4f7247
|
Swift
|
andrespch/SwiftUIExperiments
|
/SwiftUIExperiment/ViewModels/PlaylistViewModel.swift
|
UTF-8
| 1,708
| 2.59375
| 3
|
[] |
no_license
|
import Foundation
import SwiftUI
import CoreData
class PlaylistViewModel: NSObject, ObservableObject {
private let context: NSManagedObjectContext
private let controller: NSFetchedResultsController<Track>
@Published var faults: [AnyObject] = []
private let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
return formatter
}()
func trackViewModel(for index: Int) -> TrackViewModel {
guard let track = controller.fetchedObjects?[index] else {
preconditionFailure("index out of bounds")
}
let viewModel = TrackViewModel(track: track, dateFormatter: dateFormatter)
return viewModel
}
private(set) var numberOfTracks: Int = 0
init(context: NSManagedObjectContext) {
self.context = context
let fetchRequest = NSFetchRequest<Track>(entityName: "Track")
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Track.releaseDate, ascending: true)]
fetchRequest.fetchBatchSize = 10
self.controller = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: context,
sectionNameKeyPath: nil,
cacheName: nil)
super.init()
do {
try controller.performFetch()
numberOfTracks = controller.fetchedObjects?.count ?? 0
} catch {
fatalError("Failed to fetch entities: \(error)")
}
}
}
| true
|
2974fe3b9d955ab6eb8a452858e57a8e17915d5b
|
Swift
|
jaimejazarenoiii/Lisztomania
|
/Lisztomania/Network/Services/PlaylistAgent.swift
|
UTF-8
| 404
| 2.640625
| 3
|
[] |
no_license
|
//
// PlaylistAgent.swift
// Lisztomania
//
// Created by Jaime Jazareno III on 1/24/21.
//
import Foundation
import Combine
struct PlaylistAgent {
private let agent = Agent()
func getMyPlaylist(limit: Int = 10) -> AnyPublisher<Playlists, Error> {
let request = URLRequest(router: PlaylistRouter.getAll, params: [:])
return agent.run(request).map(\.value).eraseToAnyPublisher()
}
}
| true
|
f85c3081384a3bf881ecb8f3d96bf6cb397399f8
|
Swift
|
danschultz/codepath_twitter
|
/twitter/User.swift
|
UTF-8
| 529
| 2.953125
| 3
|
[] |
no_license
|
//
// User.swift
// twitter
//
// Created by Dan Schultz on 9/28/14.
// Copyright (c) 2014 Dan Schultz. All rights reserved.
//
import UIKit
class User: NSObject {
var name: String
var screenName: String
var profileImageUrl: NSURL
var tagline: String?
init(values: NSDictionary) {
name = values["name"] as String
screenName = values["screen_name"] as String
profileImageUrl = NSURL(string: values["profile_image_url"] as String)
tagline = values["tagline"] as? String
}
}
| true
|
1207dc107848a3e3f26e0e94f2dfefd168ef7de8
|
Swift
|
Madi-KShino/Movie-List-Test3-
|
/TEST3(movieApi)/Model/Movie.swift
|
UTF-8
| 634
| 3.15625
| 3
|
[] |
no_license
|
//
// Movie.swift
// TEST3(movieApi)
//
// Created by Madison Kaori Shino on 6/28/19.
// Copyright © 2019 Madi S. All rights reserved.
//
import Foundation
//FIRST LEVEL
struct TopLevelMovieDictionary: Decodable {
let results: [Movie]
}
//SECOND LEVEL
struct Movie: Decodable {
let title: String
let rating: Double
let summary: String
let date: String
let image: String?
enum CodingKeys: String, CodingKey {
case title = "original_title"
case rating = "vote_average"
case summary = "overview"
case date = "release_date"
case image = "poster_path"
}
}
| true
|
3984bc0804de9bbd776385a74862c4dcbc98748e
|
Swift
|
AndreyAS73/ToDoList
|
/calendar/calendar/ModelNote.swift
|
UTF-8
| 1,178
| 3.28125
| 3
|
[] |
no_license
|
//
// ModelNote.swift
// calendar
//
// Created by Андрей Антонов on 15.03.2021.
// Copyright © 2021 Aspire. All rights reserved.
//
import Foundation
import UIKit
var ToDoItems = [Note]()
struct Note {
var id : Int
var startTime = Date()
var finishTime = Date()
var name : String
var description : String
func ToDoList(response: String) -> [Note] {
print("Starting to parse the file")
let data = Data(response.utf8)
do {
let myJson = try JSONSerialization.jsonObject(with: data) as! [[String: AnyObject]]
for item in myJson {
let id = item["id"] as! Int
let startTime = item["startTime"] as! Date
let finishTime = item["finishTime"] as! Date
let name = item["name"] as! String
let descrption = item["description"] as! String
let ToDoitems = Note(id: id, startTime: startTime, finishTime: finishTime, name: name, description: descrption)
ToDoItems.append(ToDoitems)
}
}
catch {
print("Error", error)
}
return ToDoItems
}
}
| true
|
c2a0a5939996d1b54894a59e85f88eb10f26ca77
|
Swift
|
villegaskpu/a4sysCore
|
/a4SysCoreIOS/Models/Parser/OffertsParser.swift
|
UTF-8
| 1,122
| 2.625
| 3
|
[] |
no_license
|
//
// OffertsParse.swift
// a4SysCoreIOS
//
// Created by David on 9/5/19.
// Copyright © 2019 Yopter. All rights reserved.
//
import Foundation
import ObjectMapper
class OffertsParser: BaseParser {
override func parse(JSONObject: Any) -> AnyObject? {
if let value = Mapper<Offer>().mapArray(JSONObject: JSONObject) {
var badge = 0
var tempArrOffers : [Offer] = []
for item in value {
if item.userRating.rating != 1.0 {
tempArrOffers.append(item)
}
}
tempArrOffers = tempArrOffers.filter{ $0.deleted == 0 }
tempArrOffers = tempArrOffers.map{ (offer : Offer) -> Offer in
let mutableOffer = offer
mutableOffer.isHome = true
mutableOffer.isFavorite = false
if offer.viewed == 0 {
badge = badge + 1
}
return mutableOffer
}
return value as AnyObject
}
return nil
}
}
| true
|
adfa28f9410670a48b0932f8cc19fc84b1718d6e
|
Swift
|
vandilsonlima/redux-swiftui
|
/Redux/states/library/LibraryReducer.swift
|
UTF-8
| 1,105
| 2.953125
| 3
|
[] |
no_license
|
//
// LibraryReducer.swift
// Redux
//
// Created by Vandilson Lima on 23/04/21.
//
import Foundation
func libraryReducer(_ state: LibraryState, action: LibraryAction) -> LibraryState {
switch action {
case .setArtists(let artists):
return LibraryState(artists: artists, isLoading: state.isLoading)
case .deleteArtist(let artistId):
return LibraryState(artists: state.artists.filter { $0.id != artistId }, isLoading: state.isLoading)
case .deleteAlbum(let artistId, let albumId):
return deleteAlbum(state, artistId, albumId)
case .loading(let isLoading):
return LibraryState(artists: state.artists, isLoading: isLoading)
}
}
private func deleteAlbum(_ state: LibraryState, _ artistId: UUID, _ albumId: UUID) -> LibraryState {
guard
let index = state.artists.firstIndex(where: { $0.id == artistId})
else { return state }
let artirst = state.artists[index]
var albums = artirst.albums
albums.removeAll(where: { $0.id == albumId })
var artists = state.artists
artists[index] = artirst.changing(albums: albums)
return LibraryState(artists: artists, isLoading: state.isLoading)
}
| true
|
ffc076b589f5ae81e7b5477f26c79591ddc570a8
|
Swift
|
drawde1/music-Store
|
/Music Store/LoginSignupViewController.swift
|
UTF-8
| 5,055
| 2.546875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Music Store
//
// Created by Rave Bizz on 6/21/21.
//
import UIKit
import CoreData
class LoginSignupViewController: UIViewController {
@IBOutlet weak var loginField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var signupButton: UIButton!
@IBAction func onSignup(_ sender: Any) {
if loginField.text != "" || passwordField.text != "" {
createUser(login: loginField.text ?? "user", password: passwordField.text ?? "123")
let alert = UIAlertController(title: "Success!", message: "Thanks for signing up! Please login now!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)
} else {
let alert = UIAlertController(title: "Error", message: "Login/Password cannot be empty", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)
}
}
@IBAction func onLogin(_ sender: Any) {
// deleteAllUsers()
if loginField.text != "" || passwordField.text != "" {
let fetchedUser = fetchUser(login: loginField.text!, password: passwordField.text!)
if fetchedUser != nil {
UserModel.shared.user = fetchedUser!
// GOTO PROFILE
let storyBoard : UIStoryboard = UIStoryboard(name: "Product", bundle:nil)
let profileViewController = storyBoard.instantiateViewController(withIdentifier: "ProfileView")
self.navigationController?.pushViewController(profileViewController, animated: true)
} else {
let alert = UIAlertController(title: "Error", message: "Login/Password are incorrect", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)
}
} else {
let alert = UIAlertController(title: "Error", message: "Login/Password cannot be empty", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)
}
fetchData()
}
override func viewDidLoad() {
super.viewDidLoad()
// createUser()
// fetchData()
// fetchOneData(with: "Mattt", and: "123")
// Do any additional setup after loading the view....
}
func createUser(login: String, password: String){
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let container = appDelegate?.persistentContainer
guard let viewContext = container?.viewContext else {return}
let user = User(context: viewContext)
user.password = password
user.name = login
user.currentPoint = 0
user.pointTreward = 0
let song = Song(context: viewContext)
song.name = "Fire"
song.price = 10
song.owner = user
print(song)
print(user)
try? viewContext.save()
}
func deleteAllUsers() {
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let container = appDelegate?.persistentContainer
guard let viewContext = container?.viewContext else {return}
let request: NSFetchRequest<NSFetchRequestResult> = User.fetchRequest()
let deleteRequest = NSBatchDeleteRequest(fetchRequest: request)
let result = try? viewContext.execute(deleteRequest)
}
func fetchData(){
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let container = appDelegate?.persistentContainer
guard let viewContext = container?.viewContext else {return}
let request: NSFetchRequest<User> = User.fetchRequest()
let result = try? viewContext.fetch(request)
print(result)
print("Count \(result?.count)")
}
func fetchUser(login: String, password: String) -> User? {
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let container = appDelegate?.persistentContainer
guard let viewContext = container?.viewContext else {return nil}
let request: NSFetchRequest<User> = User.fetchRequest()
request.predicate = NSPredicate(format: "name = %@ AND password = %@", login, password)
let result = try? viewContext.fetch(request)
if result?.count ?? 0 > 0 {
let loggedInModel = result?.first
// let loggedInModel = UserModel(login: "", password: "", currentSpent: 1.0, spendToReward: 1.0)
return loggedInModel
}
// print("Count \(result?.count)")
return nil
}
}
| true
|
eb9a0e0bd43e833692e202783bdc653748d7e5cf
|
Swift
|
navedrizvi/Fluent-Word-Journal
|
/Fluent Vocab Trainer/Models/Response.swift
|
UTF-8
| 1,039
| 2.796875
| 3
|
[] |
no_license
|
//
// Response.swift
// Fluent Vocab Trainer
//
// Created by Naved Rizvi on 8/5/19.
// Copyright © 2019 Naved Rizvi. All rights reserved.
//
import Foundation
import SwiftUI
import SwiftyJSON
//JSON parsing model
struct Response: Decodable {
var word: String?
var wordnikUrl: String?
var text: String?
var partOfSpeech: String?
var exampleUses: JSON? //server is ambiguous here
init(json: [String: Any]) {
word = json["word"] as? String ?? nil
wordnikUrl = json["wordnikUrl"] as? String ?? nil
if (json["text"] == nil){
text = nil
} else {
text = json["text"] as? String ?? nil
}
if (json["partOfSpeech"] == nil){
partOfSpeech = nil
} else {
partOfSpeech = json["partOfSpeech"] as? String ?? nil
}
if (json["exampleUses"] == nil){
exampleUses = nil
}
else {
exampleUses = json["exampleUses"] as? JSON ?? nil
}
}
}
| true
|
595de5ad88ad6c6fa54a479b14f6fdf274050c75
|
Swift
|
LoraKucher/TestProjects
|
/TestProject/FirstTab/Cells/EmployeeCell/EmployeeCell.swift
|
UTF-8
| 554
| 2.671875
| 3
|
[] |
no_license
|
//
// EmployeeCell.swift
// TestProject
//
// Created by Lora Kucher on 30.10.2019.
// Copyright © 2019 Lora Kucher. All rights reserved.
//
import UIKit
class EmployeeCell: UITableViewCell {
@IBOutlet weak var descriptionTextField: UITextField!
@IBOutlet weak var titleLabel: UILabel!
func configCell(with indexPath: IndexPath, type: EmployeeType) {
tag = indexPath.row
titleLabel.text = type.rows[indexPath.row]
descriptionTextField.placeholder = "Enter your \(type.rows[indexPath.row].lowercased())"
}
}
| true
|
9c6c8d2dd8066cee47e684ddb6cefe1ed92949a3
|
Swift
|
ekurutepe/Iguazu
|
/Sources/Iguazu/IGC/IGCWaypoint.swift
|
UTF-8
| 1,091
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
//
// IGCWaypoint.swift
// Charts
//
// Created by Engin Kurutepe on 17.01.20.
//
import Foundation
import CoreLocation
public struct IGCWaypoint: CustomStringConvertible {
public let title: String
public let coordinate: CLLocationCoordinate2D
public var description: String {
return "Waypoint: \(title) \(coordinate.latitude), \(coordinate.longitude)"
}
}
private let LatitudeOffset = 1
private let LongitudeOffset = 9
private let TitleOffset = 18
public extension IGCWaypoint {
init(with line: String) {
guard
let prefix = line.extractString(from: 0, length: 1), prefix == "C"
else {
fatalError("tried to initialize IGCWaypoint with a line that does NOT start with C: \(line)")
}
guard
let lat = line.extractLatitude(from: LatitudeOffset),
let lng = line.extractLongitude(from: LongitudeOffset)
else {
fatalError("could not extract lat lon from line: \(line)")
}
coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
title = line.extractString(from: TitleOffset, length: 0) ?? ""
}
}
| true
|
753e76668235e7701f295050f4af5d248fef4091
|
Swift
|
SuliacLEGUILLOU/swift_gallery
|
/d03/CustomCell.swift
|
UTF-8
| 2,590
| 2.796875
| 3
|
[] |
no_license
|
//
// CustomCell.swift
// d03
//
// Created by Suliac LE-GUILLOU on 3/30/18.
// Copyright © 2018 Suliac LE-GUILLOU. All rights reserved.
//
import UIKit
protocol ErrorDelegate: class {
func loadingError()
}
class CustomCell: UICollectionViewCell {
var item: String? {
didSet {
let url: URL = URL(string: item!)!
self.indicator.startAnimating()
DispatchQueue.global(qos: .userInitiated).async {
do {
let imageData:Data
try imageData = Data(contentsOf: url)
DispatchQueue.main.async {
self.imageView.image = UIImage(data: imageData)
self.indicator.stopAnimating()
}
} catch {
print("ERROR \(error)")
self.indicator.stopAnimating()
self.handleError()
}
}
}
}
weak var delegate: ErrorDelegate?
@objc func handleError() {
self.delegate?.loadingError()
}
private let imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
private let indicator: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView()
indicator.translatesAutoresizingMaskIntoConstraints = false
indicator.hidesWhenStopped = true
indicator.color = .black
return indicator
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imageView)
addSubview(indicator)
imageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
imageView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
imageView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
indicator.topAnchor.constraint(equalTo: topAnchor).isActive = true
indicator.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
indicator.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
indicator.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
layer.borderWidth = 1
layer.borderColor = UIColor.black.cgColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
54844e28a2c6eb32a187a254dc1a799a565fa0a2
|
Swift
|
DrewKiino/swift-app-foundation
|
/Sources/SwiftAppFoundation/Extensions/Foundation/NSAttributedString+Extensions.swift
|
UTF-8
| 1,089
| 2.875
| 3
|
[] |
no_license
|
//
// NSAttributedString+Extensions.swift
// AppFoundation
//
// Created by Andrew Aquino on 3/27/19.
//
import UIKit
extension TextAttributes {
public static func styled(
_ color: UIColor?,
font: UIFont?,
kern: NSNumber = 0.0,
lineSpacing: CGFloat = 0.0,
minimumLineHeight: CGFloat = 0.0,
maximumLineHeight: CGFloat = 0.0,
lineHeightMultiple: CGFloat = 1.0,
alignment: NSTextAlignment? = .left,
underline: Bool = false
) -> TextAttributes {
let style = NSMutableParagraphStyle()
style.lineBreakMode = .byWordWrapping
style.lineSpacing = lineSpacing
style.minimumLineHeight = minimumLineHeight
style.maximumLineHeight = maximumLineHeight
style.lineHeightMultiple = lineHeightMultiple
if let alignment = alignment {
style.alignment = alignment
}
var dict: Dictionary = [
.foregroundColor: color,
.font: font,
.kern: kern,
.paragraphStyle: style
].compactMapValues { $0 }
if underline {
dict[.underlineStyle ] = NSUnderlineStyle.single.rawValue
}
return dict
}
}
| true
|
eb69f17a36caae0731530a05789155b00add17f2
|
Swift
|
anji-plus/captcha
|
/view/ios/captcha_swift/captcha_swift/catchaview/UIView+Extension.swift
|
UTF-8
| 5,418
| 2.703125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// UIView+Extension.swift
// DanTang
//
// Created by 杨蒙 on 2017/3/24.
// Copyright © 2017年 hrscy. All rights reserved.
//
import UIKit
extension UIView {
/// 裁剪 view 的圆角
func clipRectCorner(direction: UIRectCorner, cornerRadius: CGFloat) {
let cornerSize = CGSize(width: cornerRadius, height: cornerRadius)
let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: direction, cornerRadii: cornerSize)
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.cgPath
layer.addSublayer(maskLayer)
layer.mask = maskLayer
}
//移除所有子view
func reoveAllSubView() {
for subView in self.subviews {
subView.removeFromSuperview()
}
}
/// x
var x: CGFloat {
get {
return frame.origin.x
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.origin.x = newValue
frame = tempFrame
}
}
/// y
var y: CGFloat {
get {
return frame.origin.y
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.origin.y = newValue
frame = tempFrame
}
}
var bottom: CGFloat {
get {
return self.y + self.height
}
set(newValue) {
self.y = newValue - self.height
}
}
var right: CGFloat {
get {
return self.x + self.width
}
set(newValue) {
self.x = newValue - self.width
}
}
/// height
var height: CGFloat {
get {
return frame.size.height
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.size.height = newValue
frame = tempFrame
}
}
/// width
var width: CGFloat {
get {
return frame.size.width
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.size.width = newValue
frame = tempFrame
}
}
/// size
var size: CGSize {
get {
return frame.size
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.size = newValue
frame = tempFrame
}
}
/// centerX
var centerX: CGFloat {
get {
return center.x
}
set(newValue) {
var tempCenter: CGPoint = center
tempCenter.x = newValue
center = tempCenter
}
}
/// centerY
var centerY: CGFloat {
get {
return center.y
}
set(newValue) {
var tempCenter: CGPoint = center
tempCenter.y = newValue
center = tempCenter;
}
}
}
extension Data {
static func getCurrentLogTime() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "YYYY-MM-dd HH:mm:ss:SSS"
let timerString: String = formatter.string(from: Date())
return timerString
}
}
extension CALayer {
/// 设置渐变色
/// - parameter colors: 渐变颜色数组
/// - parameter locations: 逐个对应渐变色的数组,设置颜色的渐变占比,nil则默认平均分配
/// - parameter startPoint: 开始渐变的坐标(控制渐变的方向),取值(0 ~ 1)
/// - parameter endPoint: 结束渐变的坐标(控制渐变的方向),取值(0 ~ 1)
public func setGradient(colors: [UIColor], locations: [NSNumber]? = nil, startPoint: CGPoint, endPoint: CGPoint) {
/// 设置渐变色
func _setGradient(_ layer: CAGradientLayer) {
var colorArr = [CGColor]()
for color in colors {
colorArr.append(color.cgColor)
}
CATransaction.begin()
CATransaction.setDisableActions(true)
layer.frame = self.bounds
CATransaction.commit()
layer.colors = colorArr
layer.locations = locations
layer.startPoint = startPoint
layer.endPoint = endPoint
}
let gradientLayer = CAGradientLayer()
self.insertSublayer(gradientLayer , at: 0)
_setGradient(gradientLayer)
return
}
}
extension UIColor {
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, _ alpha: CGFloat = 1.0) {
self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alpha)
}
class func randomColor() -> UIColor{
return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
}
convenience init(_ hexString:String, _ alpha: CGFloat = 1.0) {
let scanner:Scanner = Scanner(string:hexString)
var valueRGB:UInt32 = 0
if scanner.scanHexInt32(&valueRGB) == false {
self.init(red: 0,green: 0,blue: 0,alpha: 0)
}else{
self.init(
red:CGFloat((valueRGB & 0xFF0000)>>16)/255.0,
green:CGFloat((valueRGB & 0x00FF00)>>8)/255.0,
blue:CGFloat(valueRGB & 0x0000FF)/255.0,
alpha:CGFloat(alpha)
)
}
}
}
| true
|
b727f365dd5ce23b3aee281c0fe97558ac0c0db6
|
Swift
|
JamesPerlman/TexasLotto
|
/AutoLotto/HomeViewController.swift
|
UTF-8
| 1,236
| 2.71875
| 3
|
[] |
no_license
|
//
// HomeViewController.swift
// AutoLotto
//
// Created by James Perlman on 8/28/16.
// Copyright © 2016 James Perlman. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
@IBOutlet weak var dollarLabel:UILabel!
@IBOutlet weak var centLabel:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setNavigationBarHidden(false, animated: true)
navigationItem.hidesBackButton = true
navigationController?.navigationBar.barStyle = .BlackTranslucent
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
refreshMoneyLabels()
}
@IBAction func addMoney(sender: UIButton?) {
UserWallet.addMoney(50)
Alert(title: "Success!", message: "We added fifty bucks to your account, on the house. Go get 'em, cowboy.").showOkay()
refreshMoneyLabels()
}
@IBAction func logOut(sender: UIButton?) {
navigationController?.popViewControllerAnimated(true)
}
func refreshMoneyLabels() {
dollarLabel.text = UserWallet.getDollars() + "."
centLabel.text = UserWallet.getChange()
view.layoutIfNeeded()
}
}
| true
|
b61d5e71a10c045ceefef1dde3a8f946bf8520ac
|
Swift
|
a0188000/MyWeek
|
/MyWeek/Declarative/Declarative.swift
|
UTF-8
| 806
| 2.609375
| 3
|
[] |
no_license
|
//
// Declarative.swift
// MyHealthManagement
//
// Created by EVERTRUST on 2020/3/9.
// Copyright © 2020 Shen Wei Ting. All rights reserved.
//
import UIKit
protocol Declarative {
init()
}
extension NSObject: Declarative { }
extension Declarative where Self: NSObject {
init(_ configureHandler: (Self) -> Void) {
self.init()
configureHandler(self)
}
}
extension Declarative where Self: UIButton {
init(type: UIButton.ButtonType, _ configureHandler: (Self) -> Void) {
self.init(type: type)
configureHandler(self)
}
}
extension Declarative where Self: UICollectionView {
init(layout: UICollectionViewLayout, _ configureHandler: (Self) -> Void) {
self.init(frame: .zero, collectionViewLayout: layout)
configureHandler(self)
}
}
| true
|
cdee7242c36d1d3746dab031b143dd5eccce7cde
|
Swift
|
rudrankriyam/TonesChat
|
/TonesChat SwiftUI 3.0/End/TonesChat/Views/LoginHeaderView.swift
|
UTF-8
| 736
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// LoginHeaderView.swift
// TonesChat
//
// Created by Rudrank Riyam on 31/05/21.
//
import SwiftUI
struct LoginHeaderView: View {
var body: some View {
VStack {
Image("login_header_image")
.resizable()
.aspectRatio(contentMode: .fit)
Text("Welcome to Music Paradise!")
.fontWeight(.black)
.foregroundColor(.brand)
.font(.largeTitle)
.multilineTextAlignment(.center)
Text("Share your exceptional music taste with the world.")
.fontWeight(.light)
.multilineTextAlignment(.center)
.padding()
}
}
}
struct LoginHeaderView_Previews: PreviewProvider {
static var previews: some View {
LoginHeaderView()
}
}
| true
|
e64d7921ddaf6771173d9b91ec4feab7aec8e23a
|
Swift
|
macdoum1/Advent-Of-Code
|
/AdventOfCode.playground/Sources/Position.swift
|
UTF-8
| 707
| 3.96875
| 4
|
[] |
no_license
|
import Foundation
public struct Position: Hashable {
public let x: Int
public let y: Int
public init(x: Int, y: Int) {
self.x = x
self.y = y
}
public var left: Position {
return Position(x: x-1, y: y)
}
public var right: Position {
return Position(x: x+1, y: y)
}
public var below: Position {
return Position(x: x, y: y+1)
}
public var above: Position {
return Position(x: x, y: y-1)
}
public var isValid: Bool {
return x >= 0 && y >= 0
}
public func adding(_ position: Position) -> Position {
return Position(x: x+position.x, y: y+position.y)
}
}
| true
|
f75169ee4adc4018cd1db2ad6e23cc2c743a0cb4
|
Swift
|
CarlManster/swift_playground
|
/Kakao_SecretMap_20190525_01.playground/Contents.swift
|
UTF-8
| 1,144
| 3.484375
| 3
|
[] |
no_license
|
import UIKit
extension String {
func replacingOccurrences<Target, Replacement>(of targets: [Target], with replacements: [Replacement], options: CompareOptions = [], range searchRange: Range<Index>? = nil) -> String where Target : StringProtocol, Replacement : StringProtocol {
var result = self
zip(targets, replacements)
.forEach { result = result.replacingOccurrences(of: $0, with: $1, options: options, range: searchRange) }
return result
}
}
func decrypt(arr0: [Int], arr1: [Int]) -> [String] {
guard arr0.count == arr1.count else { return [] }
return zip(arr0, arr1)
.map { UInt8($0) | UInt8($1) }
.map { String($0, radix: 2) }
.map { $0.replacingOccurrences(of: ["0", "1"], with: [" ", "#"]) }
}
let first = [9, 20, 28, 18, 11]
let second = [30, 1, 21, 17, 28]
print(decrypt(arr0: first, arr1: second))
let third = [46, 33, 33 ,22, 31, 50]
let fourth = [27 ,56, 19, 14, 14, 10]
print(decrypt(arr0: third, arr1: fourth))
// ["#####", "# # #", "### #", "# ##", "#####"]
// ["######", "### #", "## ##", "#### ", "#####", "### # "]
| true
|
947e38a46ab5fcef6203f23f69623b019c70d406
|
Swift
|
minbaba/RXDemo
|
/miaomiao.v2/Base/UserTag/UserTagModel.swift
|
UTF-8
| 1,689
| 2.5625
| 3
|
[] |
no_license
|
//
// UserTagModel.swift
// miaomiao.v2
//
// Created by minbaba on 16/4/12.
// Copyright © 2016年 MiaoquTech Inc. All rights reserved.
//
//import UIKit
import Foundation
class UserTagModel {
var type:ModelType!
var text = ""
var rect = CGRectMake(0, 0, 35, 12)
var color:ColorConf.tag?
var image:String?
private init() {}
init(type:ModelType, text:String = "") {
self.type = type
self.text = text
color = [.Single, .Loving, .Married, .Female, .Male, .VIP, .Market][type.rawValue]
image = [nil, nil, nil, "tag_icon_女", "tag_icon_男", "tag_icon_vip", nil][type.rawValue]
if type == .Vip {
rect.size.width = 12
}
}
func tagButton() -> UIButton {
let button = UIButton(type: .System)
button.frame = rect
button.setTitle(text, forState: .Normal)
button.titleLabel?.font = UIFont.systemFontOfSize(12)
button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
if let img = image {
button.setImage(UIImage(named: img), forState: .Normal)
}
button.mq_setCornerRadius(1)
return button
}
func tagButton(origin:CGPoint) -> UIButton {
let button = tagButton()
var rect = self.rect
rect.origin = origin
button.frame = rect
return button
}
enum ModelType:Int {
case Alone = 0
case Loving = 1
case Married = 2
case FeMale = 3
case Male = 4
case Vip = 5
case Market = 6
}
}
| true
|
924be09611b0fb6321305d76e743f435ea34a701
|
Swift
|
JanRajtr/SwiftSky
|
/Sources/SwiftSky/Units.swift
|
UTF-8
| 5,806
| 3.0625
| 3
|
[
"MIT"
] |
permissive
|
//
// Units.swift
// SwiftSky
//
// Created by Luca Silverentand on 11/04/2017.
// Copyright © 2017 App Company.io. All rights reserved.
//
import Foundation
/// The unit used for `Temperature` values
public enum TemperatureUnit {
/// Represents the Fahrenheit unit [(wikipedia)](https://en.wikipedia.org/wiki/Fahrenheit)
case fahrenheit
/// Represents the Celsius unit [(wikipedia)](https://en.wikipedia.org/wiki/Celsius)
case celsius
/// Represents the Kelvin unit [(wikipedia)](https://en.wikipedia.org/wiki/Kelvin)
case kelvin
}
/// The unit used for `Distance` values
public enum DistanceUnit {
/// Represents the Mile unit [(wikipedia)](https://en.wikipedia.org/wiki/Mile)
case mile
/// Represents the Yard unit [(wikipedia)](https://en.wikipedia.org/wiki/Yard)
case yard
/// Represents the Kilometer unit [(wikipedia)](https://en.wikipedia.org/wiki/Kilometre)
case kilometer
/// Represents the Meter unit [(wikipedia)](https://en.wikipedia.org/wiki/Metre)
case meter
}
/// The unit used for `Speed` values
public enum SpeedUnit {
/// Represents the Miles per Hour unit [(wikipedia)](https://en.wikipedia.org/wiki/Miles_per_hour)
case milePerHour
/// Represents the Kilometer per Hour unit [(wikipedia)](https://en.wikipedia.org/wiki/Kilometres_per_hour)
case kilometerPerHour
/// Represents the Meter per Second unit [(wikipedia)](https://en.wikipedia.org/wiki/Metre_per_second)
case meterPerSecond
/// Represents the Knot unit [(wikipedia)](https://en.wikipedia.org/wiki/Knot_(unit))
case knot
/// Represents the Beaufort scale unit (wind only) [(wikipedia)](https://en.wikipedia.org/wiki/Beaufort_scale)
case beaufort
}
/// The unit used for `Pressure` values
public enum PressureUnit {
/// Represents the Millibar unit [(wikipedia)](https://en.wikipedia.org/wiki/Bar_(unit))
case millibar
/// Represents the Hecto Pascal unit [(wikipedia)](https://en.wikipedia.org/wiki/Pascal_(unit))
case hectopascal
/// Represents the Inches of Mercury unit [(wikipedia)](https://en.wikipedia.org/wiki/Inch_of_mercury)
case inchesOfMercury
}
/// The unit used for precipitation `Intensity` values
public enum PrecipitationUnit {
/// Represents the Inch unit [(wikipedia)](https://en.wikipedia.org/wiki/Inch)
case inch
/// Represents the Millimeter unit [(wikipedia)](https://en.wikipedia.org/wiki/Millimetre)
case millimeter
}
/// The unit used for precipitation `Accumulation` values
public enum AccumulationUnit {
/// Represents the Inch unit [(wikipedia)](https://en.wikipedia.org/wiki/Inch)
case inch
/// Represents the Centimeter unit [(wikipedia)](https://en.wikipedia.org/wiki/Centimetre)
case centimeter
}
/// Specifies the units to use for values in a `DataPoint`
public struct UnitProfile {
/// The unit to use for `Temperature` values
public var temperature : TemperatureUnit = .fahrenheit
/// The unit to use for `Distance` values
public var distance : DistanceUnit = .mile
/// The unit to use for `Speed` values
public var speed : SpeedUnit = .milePerHour
/// The unit to use for `Pressure` values
public var pressure : PressureUnit = .millibar
/// The unit to use for `Intensity` precipitation values
public var precipitation : PrecipitationUnit = .inch
/// The unit to use for `Accumulation` precipitation values
public var accumulation : AccumulationUnit = .inch
private let profiles = ["us","ca","uk2","si"]
var shortcode : String {
var matchID : String = "us"
var currentMatch : Int = 0
for id in profiles {
let apiProfile = ApiUnitProfile(id)
var matchCount : Int = 0
matchCount += (apiProfile.temperature == temperature ? 1 : 0)
matchCount += (apiProfile.distance == distance ? 1 : 0)
matchCount += (apiProfile.speed == speed ? 1 : 0)
matchCount += (apiProfile.pressure == pressure ? 1 : 0)
matchCount += (apiProfile.precipitation == precipitation ? 1 : 0)
matchCount += (apiProfile.accumulation == accumulation ? 1 : 0)
if matchCount > currentMatch {
currentMatch = matchCount
matchID = id
}
}
return matchID
}
}
struct ApiUnitProfile {
let shortcode : String
let temperature : TemperatureUnit
let distance : DistanceUnit
let speed : SpeedUnit
let pressure : PressureUnit
let precipitation : PrecipitationUnit
let accumulation : AccumulationUnit
init(_ string: String?) {
shortcode = string ?? "us"
switch string ?? "us" {
case "ca":
temperature = .celsius
distance = .kilometer
speed = .kilometerPerHour
pressure = .hectopascal
precipitation = .millimeter
accumulation = .centimeter
case "uk2":
temperature = .celsius
distance = .mile
speed = .milePerHour
pressure = .hectopascal
precipitation = .millimeter
accumulation = .centimeter
case "si":
temperature = .celsius
distance = .kilometer
speed = .meterPerSecond
pressure = .hectopascal
precipitation = .millimeter
accumulation = .centimeter
default:
temperature = .fahrenheit
distance = .mile
speed = .milePerHour
pressure = .millibar
precipitation = .inch
accumulation = .inch
}
}
}
| true
|
8a661c2ae0a021218acb453b40acf986848a1d2d
|
Swift
|
imbaggaarm/ios-chat-p2p-webrtc
|
/lab_mmt/View Models/FriendCellVM.swift
|
UTF-8
| 676
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// FriendCellVM.swift
// lab_mmt
//
// Created by Imbaggaarm on 10/31/19.
// Copyright © 2019 Tai Duong. All rights reserved.
//
import UIKit
struct FriendCellVM {
let imageURL: URL?
let name: String
let onlineStateColor: UIColor
init(imageURL: URL?, name: String, onlineState: P2POnlineState) {
self.imageURL = imageURL
self.name = name
switch onlineState {
case .online:
onlineStateColor = .green
case .idle:
onlineStateColor = .yellow
case .doNotDisturb:
onlineStateColor = .red
default: //offline
onlineStateColor = .gray
}
}
}
| true
|
b8981f46e6d12c4dacb52f41adeb9aaf3815ba0f
|
Swift
|
qgvc4/OO-Language-Comparison
|
/code/Swift/propertiesDemo.playground/Contents.swift
|
UTF-8
| 377
| 4.03125
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
class Square {
var length: Double
var area: Double {
return length * length
}
init(length: Double) {
self.length = length
}
}
var squareA = Square(length: 4.0)
print(squareA.length) // 4.0 this is a storeed property
print(squareA.area) // 16.0 this is a computed property
| true
|
dd4cf5f1ab6e79c6bd24cd938dc65003238efab5
|
Swift
|
JosipMarkovic20/Birthdays-App
|
/Birthdays App/Home/Models/HomeBaseItem.swift
|
UTF-8
| 430
| 2.515625
| 3
|
[] |
no_license
|
//
// HomeBaseItem.swift
// Birthdays App
//
// Created by Josip Marković on 26.06.2021..
//
import Foundation
import RxDataSources
public class HomeBaseItem: IdentifiableType, Equatable{
public static func ==(lhs: HomeBaseItem, rhs: HomeBaseItem) -> Bool {
lhs.identity == rhs.identity
}
public let identity: String
public init(identity: String){
self.identity = identity
}
}
| true
|
5b8b8d9e30aeeeb55e699dfc8f4ae5c0f1c0d05c
|
Swift
|
ashfurrow/Nimble-Snapshots
|
/Bootstrap/Bootstrap/DynamicTypeView.swift
|
UTF-8
| 2,131
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import UIKit
public final class DynamicTypeView: UIView {
public let label: UILabel
override public init(frame: CGRect) {
label = UILabel()
super.init(frame: frame)
backgroundColor = .white
translatesAutoresizingMaskIntoConstraints = false
label.font = .preferredFont(forTextStyle: .body)
label.text = "Example"
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
addSubview(label)
setNeedsUpdateConstraints()
#if swift(>=4.2)
let notName = UIContentSizeCategory.didChangeNotification
#else
let notName = NSNotification.Name.UIContentSizeCategoryDidChange
#endif
NotificationCenter.default.addObserver(self, selector: #selector(updateFonts),
name: notName,
object: nil)
}
private var createdConstraints = false
override public func updateConstraints() {
if !createdConstraints {
label.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
label.topAnchor.constraint(equalTo: topAnchor).isActive = true
}
super.updateConstraints()
}
@objc
func updateFonts(_ notification: Notification) {
#if swift(>=4.2)
let newValueKey = UIContentSizeCategory.newValueUserInfoKey
#else
let newValueKey = UIContentSizeCategoryNewValueKey
#endif
guard let category = notification.userInfo?[newValueKey] as? String else {
return
}
label.font = .preferredFont(forTextStyle: .body)
label.text = category.replacingOccurrences(of: "UICTContentSizeCategory", with: "")
}
@available(*, unavailable)
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
0fdd03744f2db0317f26f1b0e1dd9e163374afff
|
Swift
|
babakmuir/Bagation
|
/Bagation/Model/Chat.swift
|
UTF-8
| 957
| 2.734375
| 3
|
[] |
no_license
|
//
// Chat.swift
// Bagation
//
// Created by Pushpendra on 13/12/18.
// Copyright © 2018 IOSAppExpertise. All rights reserved.
//
import Foundation
import UIKit
class Chat {
var name:String! = ""
var senderName:String! = ""
var text:String! = ""
var receiverID:String! = ""
var userID:String! = ""
var date:String! = ""
var mediaType:messageType! = .text
init(chatDict:[String:Any]) {
self.name = chatDict["receiver_name"] as? String
self.senderName = chatDict["sender_name"] as? String
self.receiverID = chatDict["receiver_id"] as? String
self.text = chatDict["text"] as? String
self.userID = chatDict["user_id"] as? String
self.date = chatDict["date"] as? String
let type:String = chatDict["mediaType"] as! String
if type == "1" {
mediaType = .image
}else {
mediaType = .text
}
}
}
| true
|
143042e91264d427c25e7b9f8c3cfad30380d3a3
|
Swift
|
SCCapstone/Accountability-Pods
|
/AccountabilityPods/AccountabilityPods/ViewControllers/MyPod/OwnResourceVC.swift
|
UTF-8
| 9,909
| 2.59375
| 3
|
[] |
no_license
|
//
// OwnResourceVC.swift
// AccountabilityPods
//
// Created by duncan evans on 12/4/20.
// Copyright © 2020 CapstoneGroup. All rights reserved.
//
// Description: Manages the view that displays a users resource and allows the user to edit or delete the resource.
import UIKit
import Firebase
class OwnResourceVC: UIViewController {
// MARK: - Class Variables
/// The firestore database.
let db = Firestore.firestore()
/// Boolean value that changes if user is editing the resource.
var userIsEditing: Bool = false
/// The resource object with the post information passed from the table in which the post was tapped.
var resource: Resource = Resource()
/// If the account is an org or not
var isOrg: Int = 2
// MARK: - UI Connectors
/// The desciption of a post being viewed.
@IBOutlet weak var desc: UITextView!
/// The editable name of a post being viewed.
@IBOutlet weak var nameEdit: UITextField!
/// The uneditable name of a post being viewed.
@IBOutlet weak var nameLabel: UILabel!
/// The button that the user presses to edit the post content.
@IBOutlet weak var editButton: UIButton!
/// The button that for user to save edits.
@IBOutlet weak var doneButton: UIButton!
/// The user inputted image (org accounts only)
@IBOutlet weak var imgView: UIImageView!
/// The description of a post being viewed (org accounts)
@IBOutlet weak var orgDesc: UITextView!
// MARK: - Set up
override func viewDidLoad() {
super.viewDidLoad()
// set page to only work with light mode
overrideUserInterfaceStyle = .light
// set name and description
configureText()
}
/// Sets keyboard to hide when screen is tapped.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
/// Sets name and description to values in the passed resource object.
func configureText()
{
desc.text = resource.desc
orgDesc.text = resource.desc
nameLabel.text = resource.name
// initially hide done button
doneButton.isHidden = true
let usersRef = db.collection("organizations")
let directories = resource.path.split(separator: "/")
usersRef.getDocuments() {(querySnapshot, err) in
if let err = err {
print("Error: \(err)")
}
else {
for document in querySnapshot!.documents {
if document.documentID == directories[1] {
self.isOrg = 1
}
else {
self.isOrg = 0
}
}
}
print(self.isOrg)
print(directories[1])
if(self.isOrg == 1) {
print("0a")
self.imgView.isHidden = false
self.desc.isHidden = true
self.orgDesc.isHidden = false
self.setImgField()
} else {
print("1a")
self.imgView.isHidden = true
self.desc.isHidden = false
self.orgDesc.isHidden = true
}
}
}
func setImgField() {
let directories = resource.path.split(separator: "/")
var imgUrl = ""
let usrName = "" + directories[1]
var orgDocID = ""
if(imgView.isHidden == false) {
print("0x")
let findDocID = db.collection("organizations").document(usrName).collection("POSTEDRESOURCES")
print("1x")
findDocID.getDocuments() {(QuerySnapshot, err) in
if let err = err {
print("Error: \(err)")
}
else {
for document in QuerySnapshot!.documents {
print("2x")
if (document.get("resourceName") as? String == self.nameLabel.text) {
print("3x")
orgDocID = (document.documentID as String)
}
}
}
}
}
print("4x")
let usersRef = db.collection("organizations").document(usrName).collection("POSTEDRESOURCES")
usersRef.getDocuments() {(QuerySnapshot, err) in
if let err = err {
print("Error: \(err)")
}
else {
for document in QuerySnapshot!.documents {
if(document.documentID == orgDocID) {
imgUrl = document.get("imageLink") as! String
print("\n\n\n\n" + imgUrl + "\n\n\n\n\n")
}
}
}
let urls = URL(string: imgUrl)!
let session = URLSession(configuration: .default)
let downloadPic = session.dataTask(with: urls) { Data,URLResponse,Error in
if let e = Error {
print("Error downloading picture: \(e)")
} else {
if let res = URLResponse as? HTTPURLResponse {
print("Downloaded picture with response: \(res.statusCode)")
if let imageData = Data {
let imageDown = UIImage(data: imageData)
print("work")
DispatchQueue.main.async {
self.imgView.image = imageDown
}
print("works")
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get a response code")
}
}
}
downloadPic.resume()
}
}
// MARK: - UI Functionality
/// Allows user to edit resource name and description with edit button is pressed.
///
/// - Parameter sender: the edit button that was tapped
@IBAction func editResource(_ sender: Any) {
// sends notification to own post display that a resource has been edited.
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "OnEditResource"), object: nil)
// sets interface to light mode
overrideUserInterfaceStyle = .light
// change editing value
userIsEditing = true
nameLabel.isHidden = true
// enable correct buttons
editButton.isHidden = true
doneButton.isHidden = false
desc.isEditable = true
nameEdit.text = nameLabel.text
nameLabel.isEnabled = false
nameEdit.isEnabled = true
nameEdit.isUserInteractionEnabled = true
nameEdit.isHidden = false
// cosmetically edit the the text views and fields
desc.layer.cornerRadius = 10
desc.layer.backgroundColor = UIColor.systemGray6.resolvedColor(with: self.traitCollection).cgColor
nameEdit.layer.borderWidth = 0
nameEdit.layer.cornerRadius = 5
}
/// Updates text fields and views, and the database with the edited post.
@IBAction func onDone(_ sender: Any) {
// Update text fields to finish editing
overrideUserInterfaceStyle = .light
nameEdit.isHidden = true
nameLabel.isHidden = false
userIsEditing = false
editButton.isHidden = false
doneButton.isHidden = true
editButton.tintColor = .black
desc.isEditable = false
nameLabel.text = nameEdit.text
nameLabel.isEnabled = true
nameEdit.isEnabled = false
nameEdit.isUserInteractionEnabled = false
desc.layer.backgroundColor = UIColor.white.cgColor
// Update resource information in the database
db.document(resource.path).setData(["resourceName" : nameLabel.text ?? "", "resourceDesc" : desc.text ?? ""]) {err in
if let err = err {
print(err)
}
}
}
/// Deletes resource from database when delete button is pressed.
///
/// - Parameter sender: the delete button that was pressed
@IBAction func onDelete(_ sender: Any) {
let alertController = UIAlertController(title: "Delete Post", message: "Would you like to delete your post?", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
do {
self.dismiss(animated:true, completion: {
let docID = self.db.document(self.resource.path).documentID
self.db.collection("users").document(Constants.User.sharedInstance.userID).collection("POSTEDRESOURCES").document((docID)).delete()
if(self.isOrg == 1) {
self.db.collection("organization").document(Constants.User.sharedInstance.userID).collection("POSTEDRESOURCES").document((docID)).delete()
}
// send notication to the users own post resource display that a resources have changed
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "OnEditResource"), object: nil)
// close the opened display because post has been deleted
self.dismiss(animated: true)
})
}
}))
alertController.addAction(UIAlertAction(title:"No", style: .default, handler: nil))
self.present(alertController, animated: true)
}
}
| true
|
362325951eddf063e387e73964f99c836c7140e2
|
Swift
|
ooper-shlab/OpenCLNBodySim-Swift
|
/Sources/Model/NBody/UI/Meters/Mediator/NBodyMeters.swift
|
UTF-8
| 3,372
| 2.5625
| 3
|
[] |
no_license
|
//
// NBodyMeters.swift
// OpenCL_NBody_Simulation
//
// Translated by OOPer in cooperation with shlab.jp, on 2015/12/29.
//
//
/*
<codex>
<abstract>
Mediator object for managing multiple hud objects for n-body simulators.
</abstract>
</codex>
*/
import Cocoa
import OpenGL.GL
@objc(NBodyMeters)
class NBodyMeters: NSObject {
//MARK: -
private var _index: NBody.MeterType
private var _count: Int
private var mpMeters: [NBodyMeter] = []
private var mpMeter: NBodyMeter!
init(count: Int) {
assert(count > 0)
_index = NBody.MeterType(rawValue: 0)!
_count = count
super.init()
mpMeters.reserveCapacity(_count)
for _ in 0..<_count {
mpMeters.append(NBodyMeter())
}
mpMeter = mpMeters[_index.rawValue]
}
func reset() {
for pMeter in mpMeters {
pMeter.value = 0.0
pMeter.reset()
}
}
func resize(_ size: NSSize) {
for pMeter in mpMeters {
pMeter.frame = size
}
}
func show(_ doShow: Bool) {
for pMeter in mpMeters {
pMeter.visible = doShow
}
}
func acquire() -> Bool {
return mpMeter.acquire()
}
func toggle() {
mpMeter.toggle()
}
func update() {
mpMeter.update()
}
func draw() {
mpMeter.draw()
}
func draw(_ positions: [NSPoint]) {
for (i, position) in positions.enumerated() {
let pMeter = mpMeters[i]
pMeter.point = position
pMeter.update()
pMeter.draw()
}
}
var bound: Int {
get {return mpMeter.bound}
set {
mpMeter.bound = newValue
}
}
var frame: CGSize {
get {return mpMeter.frame}
set {
mpMeter.frame = newValue
}
}
var useTimer: Bool {
get {return mpMeter.useTimer}
set {
mpMeter.useTimer = newValue
}
}
var useHostInfo: Bool {
get {return mpMeter.useHostInfo}
set {
mpMeter.useHostInfo = newValue
}
}
var index: NBody.MeterType {
get {return _index}
set {
_index = (newValue.rawValue < _count) ? newValue : NBody.MeterType(rawValue: 0)!
mpMeter = mpMeters[_index.rawValue]
}
}
var visible: Bool {
get {return mpMeter.visible}
set {
mpMeter.visible = newValue
}
}
var label: String {
get {return mpMeter.label}
set {
mpMeter.label = newValue
}
}
var max: Int {
get {return mpMeter.max}
set {
mpMeter.max = newValue
}
}
var point: CGPoint {
get {return mpMeter.point}
set {
mpMeter.point = newValue
}
}
var speed: GLfloat {
get {return mpMeter.speed}
set {
mpMeter.speed = newValue
}
}
var value: GLdouble {
get {return mpMeter.value}
set {
mpMeter.value = newValue
}
}
}
| true
|
a684367dbbb90f42109a3506e900a6b5d8730ef7
|
Swift
|
a-eliora/BrainTech2021
|
/BrainTech/Views/OBIntroView.swift
|
UTF-8
| 1,186
| 2.953125
| 3
|
[] |
no_license
|
//
// OBIntroView.swift
// BrainTech
//
// Created by Alejandro Aguirre on 2021-08-13.
//
import SwiftUI
struct OBIntroView: View {
var body: some View {
VStack {
Spacer()
Text("To get started, please help us better tailor your personal recommendations by answering a few short questions.")
.foregroundColor(.body)
Spacer()
NavigationLink(destination: ContentView()) {
Text("Continue")
.font(.headline)
.fontWeight(.semibold)
.foregroundColor(.white)
.frame(width: 220, height: 60, alignment: .center)
.background(Color.lightBlue)
.cornerRadius(100)
}
Spacer()
}
.navigationBarTitle("Questions")
.padding(.horizontal)
}
}
struct OBIntroView_Previews: PreviewProvider {
static var previews: some View {
OBIntroView()
}
}
| true
|
88bb078bc9a20ac370265cfeb9a7fd7f3f1bb1a1
|
Swift
|
henrique-a/UITableViewDemo
|
/Contatos/ContactCell.swift
|
UTF-8
| 755
| 2.546875
| 3
|
[] |
no_license
|
//
// ContactCell.swift
// Contatos
//
// Created by Ada 2018 on 26/04/18.
// Copyright © 2018 Academy. All rights reserved.
//
import UIKit
class ContactCell: UITableViewCell {
@IBOutlet weak var name: UILabel!
@IBOutlet weak var phone: UILabel!
@IBOutlet weak var photo: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.photo.layer.masksToBounds = false
self.photo.layer.cornerRadius = self.photo.frame.size.width/2
self.photo.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| true
|
a0f0a50168b172df167a68046c9cb8612d3b95a5
|
Swift
|
gklei/lookback_ios
|
/UIKit ViewControllers/CalendarWeekdayHeaderViewController.swift
|
UTF-8
| 4,769
| 2.71875
| 3
|
[] |
no_license
|
//
// CalendarWeekdayHeaderViewController.swift
// Streaks
//
// Created by Gregory Klein on 12/25/17.
// Copyright © 2017 Gregory Klein. All rights reserved.
//
import UIKit
class CalendarWeekdayHeaderViewController: UIViewController {
class Cell: UICollectionViewCell {
static var reuseID = "CalendarWeekdayHeader.Cell"
static var df: DateFormatter {
let df = DateFormatter()
df.dateFormat = "MM/dd"
return df
}
static func register(collectionView cv: UICollectionView) {
cv.register(self, forCellWithReuseIdentifier: reuseID)
}
static func dequeueCell(with collectionView: UICollectionView, at indexPath: IndexPath) -> Cell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseID, for: indexPath) as! Cell
cell.configure(with: indexPath.row)
return cell
}
fileprivate lazy var _label: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 12, weight: .semibold)
return label
}()
required init?(coder aDecoder: NSCoder) { fatalError() }
override init(frame: CGRect) {
super.init(frame: frame)
_label.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(_label)
NSLayoutConstraint.activate([
_label.centerXAnchor.constraint(equalTo: centerXAnchor),
_label.centerYAnchor.constraint(equalTo: centerYAnchor)
])
}
func configure(with dayIndex: Int) {
let symbol = Calendar.current.veryShortWeekdaySymbols[dayIndex]
_label.text = symbol
}
}
fileprivate var _cv: UICollectionView!
fileprivate var _spacingFraction: CGFloat = 0.032
let calendar: Calendar
required init?(coder aDecoder: NSCoder) { fatalError() }
init(calendar: Calendar, spacingFraction: CGFloat) {
self.calendar = calendar
_spacingFraction = spacingFraction
super.init(nibName: nil, bundle: nil)
}
override func loadView() {
let view = UIView()
let layout = UICollectionViewFlowLayout()
_cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
_cv.dataSource = self
_cv.delegate = self
_cv.showsHorizontalScrollIndicator = false
_cv.backgroundColor = .clear
Cell.register(collectionView: _cv)
_cv.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(_cv)
NSLayoutConstraint.activate([
_cv.leadingAnchor.constraint(equalTo: view.leadingAnchor),
_cv.topAnchor.constraint(equalTo: view.topAnchor),
_cv.trailingAnchor.constraint(equalTo: view.trailingAnchor),
_cv.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
self.view = view
}
}
extension CalendarWeekdayHeaderViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 7
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = Cell.dequeueCell(with: collectionView, at: indexPath)
return cell
}
}
extension CalendarWeekdayHeaderViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let sidePadding = collectionView.bounds.width * _spacingFraction
return UIEdgeInsets(top: 0, left: sidePadding, bottom: 0, right: sidePadding)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemsPerRow = CGFloat(7)
let spacing: CGFloat = collectionView.bounds.width * _spacingFraction
let totalSpacing = (itemsPerRow + 1) * spacing
let size = (collectionView.bounds.size.width - totalSpacing) / CGFloat(7)
return CGSize(width: size, height: collectionView.bounds.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return collectionView.bounds.width * _spacingFraction
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return collectionView.bounds.width * _spacingFraction
}
}
| true
|
016456d9d5e3d11e7e442fae9969d7aaac0bf3cc
|
Swift
|
KentaMaeda0916/CustomTabView
|
/CastomTabView/ContentView.swift
|
UTF-8
| 2,502
| 3.328125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// CastomTabView
//
// Created by まえけん on 2021/04/18.
// Copyright © 2021 maeken. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State var selected = 0
var body: some View {
VStack {
weekTabView(selected: $selected)
Spacer()
if selected == 0 {
Text("Monday")
} else if selected == 1 {
Text("Tuesday")
} else if selected == 2 {
Text("Wednesday")
} else if selected == 3 {
Text("Thursday")
} else if selected == 4 {
Text("Friday")
} else if selected == 5 {
Text("Suresday")
} else if selected == 6 {
Text("Sunday")
}
Spacer()
}
}
}
struct weekTabView: View {
@Binding var selected: Int
var body: some View {
VStack(alignment: .center, spacing: 40) {
HStack {
weekTabButtonView(selectedRow: 0,weekButtonLable: "月",selected: $selected)
weekTabButtonView(selectedRow: 1,weekButtonLable: "火",selected: $selected)
weekTabButtonView(selectedRow: 2,weekButtonLable: "水",selected: $selected)
weekTabButtonView(selectedRow: 3,weekButtonLable: "木",selected: $selected)
weekTabButtonView(selectedRow: 4,weekButtonLable: "金",selected: $selected)
weekTabButtonView(selectedRow: 5,weekButtonLable: "土",selected: $selected)
weekTabButtonView(selectedRow: 6,weekButtonLable: "日",selected: $selected)
}
.frame(height: 40)
}
}
}
struct weekTabButtonView: View{
var selectedRow: Int
@State var weekButtonLable: String
@Binding var selected: Int
var body: some View {
HStack(alignment: .center) {
Button(action: {
self.selected = self.selectedRow
}) {
Text(weekButtonLable)
.fontWeight(.semibold)
.foregroundColor(self.selected == selectedRow ? .black: Color.gray.opacity(0.5))
}
.frame(width:UIScreen.main.bounds.width / 8,
height: 40)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
3c6eab95c134270c978c89fb319c1d1068a95a26
|
Swift
|
Enchappolis/weatherapp---combine-version
|
/weatherapp/ViewControllers/CitySearchViewController.swift
|
UTF-8
| 6,479
| 2.5625
| 3
|
[] |
no_license
|
//
// CitySearchViewController.swift
// weatherapp
//
// Created by Enchappolis on 7/26/20.
// Copyright © 2020 Enchappolis. All rights reserved.
// https://github.com/Enchappolis
/*
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.
Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
distribute, sublicense, create a derivative work, and/or sell copies of the
Software in any work that is designed, intended, or marketed for pedagogical or
instructional purposes related to programming, coding, application development,
or information technology. Permission for such use, copying, modification,
merger, publication, distribution, sublicensing, creation of derivative works,
or sale is expressly withheld.
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
protocol CitySearchViewControllerDelegate: AnyObject {
// State is not returned by API => We need WACity so that we have the state.
func citySearchViewControllerDidSearch(city: WACity)
}
class CitySearchViewController: UIViewController {
// MARK: - Outlets
@IBOutlet weak var citySearchTableView: UITableView!
// MARK: - Private Variables
private var cityListFiltered = [WACity]()
private let searchController = UISearchController()
// MARK: - Public Variables
weak var delegate: CitySearchViewControllerDelegate?
// MARK: - Private Methods
private func setupSearchController() {
self.navigationItem.searchController = searchController
self.navigationItem.hidesSearchBarWhenScrolling = false
self.searchController.obscuresBackgroundDuringPresentation = false
self.searchController.searchBar.placeholder = "City"
self.searchController.searchBar.returnKeyType = .default
self.searchController.searchBar.autocorrectionType = .no
self.searchController.definesPresentationContext = true
// For didPresentSearchController() of UISearchControllerDelegate.
self.searchController.delegate = self
self.searchController.searchBar.delegate = self
}
private func reloadTableView(searchText: String = "") {
// x in searchbar tapped.
if searchText.isEmpty {
self.cityListFiltered = []
}
else {
self.cityListFiltered = WACityListComplete.data.filter {
$0.name.lowercased().starts(with: searchText.lowercased())
}
}
self.citySearchTableView.reloadData()
}
private func searchControllerBecomeFirstResponder() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.searchController.searchBar.becomeFirstResponder()
}
}
// MARK: - View Load
override func viewDidLoad() {
super.viewDidLoad()
citySearchTableView.delegate = self
citySearchTableView.dataSource = self
citySearchTableView.keyboardDismissMode = .onDrag
setupSearchController()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.searchController.isActive = true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
// MARK: - UITableViewDataSource
extension CitySearchViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cityListFiltered.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let citySearchTableViewCell = tableView.dequeueReusableCell(withIdentifier: CitySearchTableViewCell.tableViewCellName) as? CitySearchTableViewCell {
let city = cityListFiltered[indexPath.row]
citySearchTableViewCell.configure(city: city)
return citySearchTableViewCell
}
return UITableViewCell()
}
}
// MARK: - UITableViewDelegate
extension CitySearchViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.citySearchViewControllerDidSearch(city: cityListFiltered[indexPath.row])
}
}
// MARK: - UISearchBarDelegate
extension CitySearchViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
reloadTableView(searchText: searchText)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.dismiss(animated: true, completion: nil)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.searchController.searchBar.endEditing(true)
}
}
// MARK: - UISearchControllerDelegate
extension CitySearchViewController: UISearchControllerDelegate {
// Needs isActive = true in viewDidAppear().
func didPresentSearchController(_ searchController: UISearchController) {
self.searchControllerBecomeFirstResponder()
}
}
| true
|
43b528691477a3a0da6c5850f4b4050311be1d2f
|
Swift
|
danielvega7/masterChwefRemote
|
/Cafe Mini App/ViewController.swift
|
UTF-8
| 3,255
| 3
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Cafe Mini App
//
// Created by DANIEL VEGA on 9/10/21.
//
import UIKit
class SuperMegaVariables{
static var menuFood = ["rice", "steak", "winter rolls", "pasta"]
static var menuPrice = [2.50, 5.00, 3.00, 4.00]
static var daFood = ["shopping"]
static var daPrice = [0.0]
static var count = 0
static var menuCount = 3
}
class ViewController: UIViewController, UITextFieldDelegate{
@IBOutlet weak var foodTextField: UITextField!
@IBOutlet weak var priceTextField: UITextField!
@IBOutlet weak var cartLabel: UILabel!
@IBOutlet weak var cartTextView: UITextView!
var hereCount = 0
override func viewDidLoad() {
super.viewDidLoad()
foodTextField.delegate = self
priceTextField.delegate = self
// Do any additional setup after loading the view.
}
@IBAction func addToCart(_ sender: UIButton) {
if foodTextField.text == "" || priceTextField.text == "" || Double(priceTextField.text!) == nil{
cartLabel.text = "one or both of the textfields empty"
}
else{
var jason = 0
while(jason <= SuperMegaVariables.count){
if foodTextField.text == SuperMegaVariables.menuFood[SuperMegaVariables.count]{
if nil != priceTextField.text {
if Double(priceTextField.text!) != nil{
if Double(priceTextField.text!) == SuperMegaVariables.menuPrice[SuperMegaVariables.count]{
SuperMegaVariables.daFood.append(foodTextField.text!)
SuperMegaVariables.daPrice.append(Double(priceTextField.text!)!)
hereCount += 1
SuperMegaVariables.count += 1
cartLabel.text = "food: \(SuperMegaVariables.daFood[SuperMegaVariables.count]) price: \(SuperMegaVariables.daPrice[SuperMegaVariables.count])"
//textview
var jamal = 0
var addedString = ""
while(jamal <= SuperMegaVariables.count){
addedString += "\(jamal + 1).) food: \(SuperMegaVariables.daFood[jamal]) \t price: \(SuperMegaVariables.daPrice[jamal]) \n"
jamal += 1
}
cartTextView.text = "Shopping Cart \n" + addedString
}
else{
cartLabel.text = "prices don't match menu"
}
}
else{
cartLabel.text = "fix syntax rn"
}
}
else{
cartLabel.text = "type something or else"
}
}
else{
cartLabel.text = "food doesn't match any on menu"
}
jason += 1
}
}
foodTextField.resignFirstResponder()
priceTextField.resignFirstResponder()
}
}
| true
|
c6350ff3e286d6130a16b37213c4d452aa8c4969
|
Swift
|
Sharafutdinova705/CustomTransitions
|
/Animations/Second/View/View.swift
|
UTF-8
| 294
| 2.515625
| 3
|
[] |
no_license
|
//
// View.swift
// Animations
//
// Created by Гузель on 29/04/2019.
// Copyright © 2019 Гузель. All rights reserved.
//
import UIKit
class View: UIView {
var imageView: UIImageView!
func setImage(image: UIImage) {
self.imageView.image = image
}
}
| true
|
7df4a18c3f8a24b79dcdee4fadfa35736e23b897
|
Swift
|
ChangeNOW-lab/ChangeNow_Integration_iOS
|
/CNIntegration/Basic/Extensions/UITextField+Extension.swift
|
UTF-8
| 2,538
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
//
// UITextField+Additions.swift
// CNIntegration
//
// Created by Pavel Pronin on 06/01/2017.
// Copyright © 2017 Pavel Pronin. All rights reserved.
//
extension UITextField {
func replaceCharactersOfFormattedStringInRange(_ range: NSRange,
withString string: String,
normalizedCharacters: CharacterSet,
formatting: (String) -> String) {
let (formattedString, offset) = (text ?? "")
.replaceCharactersOfFormattedStringInRange(range,
withString: string,
normalizedCharacters: normalizedCharacters,
formatting: formatting)
restoreCursorPositionInFormattedString(formattedString,
normalizedOffset: offset,
normalizedCharacters: normalizedCharacters)
}
func restoreCursorPositionInFormattedString(_ formattedString: String,
normalizedOffset: Int,
normalizedCharacters: CharacterSet) {
var cursorOffset = normalizedOffset
for (index, character) in formattedString.enumerated() {
guard index <= cursorOffset else { break }
if character.unicodeScalars.filter(normalizedCharacters.contains).isEmpty {
cursorOffset += 1 // incrementing offset each time we encounter formatting character
}
}
if let restoredCursorPosition = position(from: beginningOfDocument, offset: cursorOffset) {
let newSelectedRange = textRange(from: restoredCursorPosition, to: restoredCursorPosition)
selectedTextRange = newSelectedRange
}
}
}
extension UITextField {
/// Moves the caret to the correct position by removing the trailing whitespace
func fixCaretPosition() {
// Moving the caret to the correct position by removing the trailing whitespace
// http://stackoverflow.com/questions/14220187/uitextfield-has-trailing-whitespace-after-securetextentry-toggle
let beginning = beginningOfDocument
selectedTextRange = textRange(from: beginning, to: beginning)
let end = endOfDocument
selectedTextRange = textRange(from: end, to: end)
}
}
| true
|
02b3c00d7e3eb904cd5463a3f5d5538e3e92edb1
|
Swift
|
LucasBlackP/TableViewDataSource
|
/Demo/AppleHistory/AppleHistory/MacOSDataSource.swift
|
UTF-8
| 1,162
| 2.734375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// MacOSDataSource.swift
// AppleHistory
//
// Created by Dmytro Anokhin on 27/05/2018.
// Copyright © 2018 Dmytro Anokhin. All rights reserved.
//
import UIKit
import TableViewDataSource
class MacOSDataSource: TableViewDataSource {
let generations = [
[ "Kodiak" ],
[ "Cheetah", "Puma", "Jaguar", "Panther", "Tiger", "Leopard", "Snow Leopard", "Lion", "Mountain Lion" ],
[ "Mavericks", "Yosemite", "El Capitan", "Sierra", "High Sierra"]
]
override var numberOfSections: Int {
return generations.count
}
override func registerReusableViews(with tableView: UITableView) {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return generations[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = generations[indexPath.section][indexPath.row]
return cell
}
}
| true
|
5a88fefd2cad591c6590958ea4dbcf828ea5c005
|
Swift
|
opikpunezio/kiwari-ios-test
|
/TestChat/Model/Member.swift
|
UTF-8
| 500
| 2.59375
| 3
|
[] |
no_license
|
//
// User.swift
// TestChat
//
// Created by Taufik Rohmat on 11/03/20.
// Copyright © 2020 Taufik. All rights reserved.
//
import Foundation
import FirebaseFirestore
struct Member{
var id: String?
var displayName: String?
var picture: String?
init(document: QueryDocumentSnapshot) {
let data = document.data()
id = document.documentID
displayName = data["displayName"] as? String
picture = data["picture"] as? String
}
}
| true
|
8ebbdd3c096fb50993b446ff0bad4559539b4c3d
|
Swift
|
pallavtrivedi03/H-Bazaar
|
/H-Bazaar/ResponseModels/Variants.swift
|
UTF-8
| 613
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
struct VariantsResponseModel : Codable {
let id : Int?
let color : String?
let size : Int?
let price : Int?
enum CodingKeys: String, CodingKey {
case id = "id"
case color = "color"
case size = "size"
case price = "price"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decodeIfPresent(Int.self, forKey: .id)
color = try values.decodeIfPresent(String.self, forKey: .color)
size = try values.decodeIfPresent(Int.self, forKey: .size)
price = try values.decodeIfPresent(Int.self, forKey: .price)
}
}
| true
|
a3d8ffa4d998fb4e9e49ee364a41c0bdebb2ee28
|
Swift
|
jeed2424/SnapFish
|
/SnapFish/SelectUserViewController.swift
|
UTF-8
| 2,239
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// SelectUserViewController.swift
// SnapFish
//
// Created by Mac Owner on 2/6/17.
// Copyright © 2017 Shashank. All rights reserved.
//
import UIKit
import FirebaseDatabase
import FirebaseAuth
class SelectUserViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var users : [User] = []
var imageURL = ""
var descrip = ""
var uuid = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tableView.dataSource = self
self.tableView.delegate = self
FIRDatabase.database().reference().child("users").observe(FIRDataEventType.childAdded, with: {(snapshot) in
print(snapshot)
// Here something is changed from previous version .... value is considered to be type id so we have to describe it to NSDictionary and run following steps
let user = User()
let snapshotValue = snapshot.value as? NSDictionary
user.Username = (snapshotValue?["username"] as? String)!
user.uid = snapshot.key
self.users.append(user)
self.tableView.reloadData()
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let user = users[indexPath.row]
cell.textLabel?.text = user.Username
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user = users[indexPath.row]
let snap = ["from":user.Username, "description":descrip, "imageURL":imageURL, "uuid":uuid] as [String : Any]
FIRDatabase.database().reference().child("users").child(user.uid).child("snaps").childByAutoId().setValue(snap)
navigationController!.popToRootViewController(animated: true)
}
}
| true
|
b82dd88ff950241e93eace16e724be99cfa48e04
|
Swift
|
team-nutee/NUTEE_iOS
|
/NUTEE/Global/Utils/MenuBar/MenuBarCVCell.swift
|
UTF-8
| 1,895
| 2.578125
| 3
|
[] |
no_license
|
//
// MenuBarCVCell.swift
// NUTEE
//
// Created by Hee Jae Kim on 2021/01/23.
// Copyright © 2021 Nutee. All rights reserved.
//
import UIKit
class MenuBarCVCell: UICollectionViewCell {
// MARK: - UI components
let menuTitle = UILabel()
// MARK: - Life Cycle
override init(frame: CGRect) {
super.init(frame: frame)
initCell()
makeConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Helper
func initCell() {
_ = menuTitle.then {
$0.font = .systemFont(ofSize: 15)
$0.textColor = .gray
}
}
func makeConstraints() {
contentView.addSubview(menuTitle)
menuTitle.snp.makeConstraints {
$0.centerX.equalTo(contentView)
$0.centerY.equalTo(contentView)
}
}
// MARK: - Override Function
override var isHighlighted: Bool {
didSet {
if isSelected == true {
_ = menuTitle.then {
$0.font = .boldSystemFont(ofSize: 18)
$0.textColor = .nuteeGreen
}
} else {
_ = menuTitle.then {
$0.font = .systemFont(ofSize: 15)
$0.textColor = .gray
}
}
}
}
override var isSelected: Bool {
didSet {
if isSelected == true {
_ = menuTitle.then {
$0.font = .boldSystemFont(ofSize: 18)
$0.textColor = .nuteeGreen
}
} else {
_ = menuTitle.then {
$0.font = .systemFont(ofSize: 15)
$0.textColor = .gray
}
}
}
}
}
| true
|
a6eb89115df252f64053464bf4e8381a2bff4006
|
Swift
|
alexandrevale/HACKATRUCK
|
/StackViews/StackViews/ViewController.swift
|
UTF-8
| 697
| 2.828125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// StackViews
//
// Created by Student on 01/11/17.
// Copyright © 2017 Alexandre do Vale. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var middleName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var fullName: UILabel!
@IBAction func sayMyName(_ sender: Any) {
fullName.text = firstName.text! + " " + middleName.text! + " " + lastName.text!
}
@IBAction func clear(_ sender: Any) {
firstName.text = ""
middleName.text = ""
lastName.text = ""
fullName.text = "Full name"
}
}
| true
|
a493193a5ae3cb0363bf54cd59f33400887e6f31
|
Swift
|
hmorales27/jenkinsTest
|
/Classes/Data Structure/SDCollapseButton.swift
|
UTF-8
| 2,478
| 2.59375
| 3
|
[] |
no_license
|
//
// CollapseButton.swift
// JBSM-iOS
//
// Created by Sharkey, Justin (ELS-CON) on 5/12/16.
// Copyright © 2016 Elsevier, Inc. All rights reserved.
//
import Foundation
protocol SectionDataCollapseButtonDelegate: class {
func sectionDataCollapseButtonDidToggle(collapse: Bool)
}
extension SectionsData {
class CollapseButton: UIButton {
weak var delegate: SectionDataCollapseButtonDelegate?
var buttonSaysCollapseAll = true
init() {
super.init(frame: CGRect.zero)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup() {
setTitleColor(UIColor.darkGray, for: UIControlState())
titleLabel?.font = AppConfiguration.DefaultBoldFont
layer.borderColor = UIColor.darkGray.cgColor
layer.borderWidth = 1
layer.cornerRadius = 4
backgroundColor = UIColor.veryLightGray()
setTitle("Collapse All", for: UIControlState())
accessibilityLabel = "collapse all articles"
addTarget(self, action: #selector(userDidSelectButton), for: .touchUpInside)
}
func updateButton(collapse: Bool) {
if collapse == true {
delegate?.sectionDataCollapseButtonDidToggle(collapse: true)
setTitle("Expand All", for: UIControlState())
accessibilityLabel = "expand all articles"
buttonSaysCollapseAll = false
} else {
delegate?.sectionDataCollapseButtonDidToggle(collapse: false)
setTitle("Collapse All", for: UIControlState())
accessibilityLabel = "collapse all articles"
buttonSaysCollapseAll = true
}
}
func updateState(collapsed: Bool) {
if collapsed == true {
setTitle("Expand All", for: UIControlState())
buttonSaysCollapseAll = false
} else {
setTitle("Collapse All", for: UIControlState())
buttonSaysCollapseAll = true
}
}
func userDidSelectButton() {
if buttonSaysCollapseAll == true {
updateButton(collapse: true)
} else {
updateButton(collapse: false)
}
}
}
}
| true
|
7a76e1e1780317c54910774438497824049a2721
|
Swift
|
apple-avadhesh/oop_design_patterns_swift
|
/decorator_pattern/DecoratorPattern.playground/Contents.swift
|
UTF-8
| 1,486
| 4.21875
| 4
|
[] |
no_license
|
import UIKit
//A simple example for Decorator pattern
//wrap a object dynamically
protocol WebPage {
func display()
}
final class BasicWebPage: WebPage {
func display() {
print("Basic WEB page")
}
}
class WebPageDecorator: WebPage {
private var decoratedWebPage: WebPage
init(webpage: WebPage) {
self.decoratedWebPage = webpage
}
func display() {
decoratedWebPage.display()
}
}
final class AuthenticatedWebPage: WebPageDecorator {
override init(webpage: WebPage) {
super.init(webpage: webpage)
}
override func display() {
if authenticateUser() == true {
super.display()
} else {
print("Authenticate failed!")
}
}
func authenticateUser()-> Bool {
print("Authetication done")
return true
}
}
final class AuthorizedWebPage: WebPageDecorator {
override init(webpage: WebPage) {
super.init(webpage: webpage)
}
override func display() {
if authorizedUser() == true {
super.display()
} else {
print("Authorization failed!")
}
}
func authorizedUser()-> Bool {
print("Authorization done")
return true
}
}
//Test
let page = AuthenticatedWebPage.init(webpage: AuthorizedWebPage.init(webpage: BasicWebPage.init()))
page.display()
//Output
/*
Authetication done
Authorization done
Basic WEB page
*/
| true
|
d440a1f4addc765d743f5a7a0c2b831ca20632d0
|
Swift
|
yumi48/NationalFlag
|
/NationalFlag/ViewController.swift
|
UTF-8
| 2,623
| 3
| 3
|
[] |
no_license
|
//
// ViewController.swift
// NationalFlag
//
// Created by 木村由美 on 2020/02/22.
// Copyright © 2020 木村由美. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var myTV: UITableView!
@IBOutlet weak var myIV: UIImageView!
//国名の一覧
var country: [String] = ["アメリカ","日本","韓国","イギリス","フランス","ドイツ","イタリア","カナダ","中国","ジャマイカ"]
//国旗の画像ファイル名一覧
var flags: [String] = ["America.png","Japan.png","Korea.png","Britain.png","France.png","Germany.png","Italy.png","Canada.png","China.png","Jamaica.png"]
override func viewDidLoad() {
super.viewDidLoad()
//デリゲート・データソースの移譲の設定
myTV.delegate = self
myTV.dataSource = self
// Do any additional setup after loading the view.
}
//テーブルビューに表示するセルの数を返すメソッド
//国名の配列が増えた場合にも柔軟に対応するため、「配列countryの要素の数」を返しています。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return country.count
}
//テーブルビューに表示するセルを返すメソッド
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//ストーリーボード上のセル「myCell」を上で指定したセル数の分だけ量産して、
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath as IndexPath)
//そのセルのラベルのテキストに国名の配列を1つずつはめ込んでいきます。
cell.textLabel?.text = country[indexPath.row]
//同様にしてセルのイメージビューの画像に、各国の画像ファイル名で指定した画像を1つずつはめ込んでいきます。
cell.imageView?.image = UIImage(named: flags[indexPath.row])
//出来上がったセルを戻り値に指定しておしまい。
return cell
}
//セルがタップされた際の動画を実装するメソッド
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//Outlet接続したmyIVの画像(image)を、配列flagsの画像ファイル名のものに変更する
myIV.image = UIImage(named: flags[indexPath.row])
}
}
| true
|
6383cc9083cd91c90b060d3a7a73d1bab57d4dde
|
Swift
|
AmarvirSingh/Bank-App
|
/BankApp/BankApp/detailCell.swift
|
UTF-8
| 551
| 2.65625
| 3
|
[] |
no_license
|
//
// detailCell.swift
// BankApp
//
// Created by Amarvir Mac on 26/11/20.
// Copyright © 2020 Amarvir Mac. All rights reserved.
//
import UIKit
class detailCell: UITableViewCell {
@IBOutlet weak var AccountDetails: UILabel!
func setDetails (c:Accounts){
AccountDetails.text = " Name : \(c.name) \n Age : \(c.age) \n Address : \(c.Address) \n Contact : \(c.contact) \n Balance : \(c.balance) Dollars \n Account Type : \(c.type)"
}
func setnoDetails(){
AccountDetails.text = "Sorry No Account found"
}
}
| true
|
df45272ec2e38fd7036c8e1476f3c52bbb2675e0
|
Swift
|
YohanAvishke/unit-converter
|
/UnitConverter/Models/Converters/Speed.swift
|
UTF-8
| 2,378
| 3.703125
| 4
|
[] |
no_license
|
//
// Speed.swift
// UnitConverter
//
// Created by Yohan Avishke Ediriweera on 2021-03-16.
//
import Foundation
enum SpeedUnit: CaseIterable {
case knot
case ms
case mih
case kmh
}
class Speed {
var unit: SpeedUnit
var value: Double
var decimalPlaces: Int
init(unit: SpeedUnit, value: String, decimalPlaces: Int) {
self.unit = unit
self.value = Double(value)!
self.decimalPlaces = decimalPlaces
}
}
class SpeedConverter {
var speed: Speed
init(speed: Speed) {
self.speed = speed
}
/**
Convert `speed.value` from `speed.unit` to `to`
- Parameters: `SpeedUnit` type that `value` is converted to
- Returns: `String` containing the converted value
*/
func convert(unit to: SpeedUnit) -> String {
var output = 0.0
switch speed.unit {
case .knot:
if to == .ms {
output = speed.value / 1.944
} else if to == .kmh {
output = speed.value * 1.852
} else if to == .mih {
output = speed.value * 1.151
}
case .ms:
if to == .kmh {
output = speed.value * 3.6
} else if to == .mih {
output = speed.value * 2.237
} else if to == .knot {
output = speed.value * 1.944
}
case .kmh:
if to == .ms {
output = speed.value / 3.6
} else if to == .mih {
output = speed.value / 1.609
} else if to == .knot {
output = speed.value / 1.852
}
case .mih:
if to == .ms {
output = speed.value / 2.237
} else if to == .kmh {
output = speed.value * 1.609
} else if to == .knot {
output = speed.value / 1.151
}
}
// Check if output has a decimal part. And if true then round it off
let deciamlPart = output.truncatingRemainder(dividingBy: 1)
if deciamlPart > 0 {
output = output.rounded(toPlaces: speed.decimalPlaces)
} else {
return String(Int(output))
}
if output == 0.0 {
return ""
}
return String(output)
}
}
| true
|
efafffe5eb62c996fc12762a061009428eabd5a4
|
Swift
|
huangboju/Moots
|
/UICollectionViewLayout/CollectionKit-master/Examples/GridExample/GridViewController.swift
|
UTF-8
| 1,584
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// GridViewController.swift
// CollectionKitExample
//
// Created by Luke Zhao on 2016-06-05.
// Copyright © 2016 lkzhao. All rights reserved.
//
import UIKit
import CollectionKit
let kGridCellSize = CGSize(width: 50, height: 50)
let kGridSize = (width: 20, height: 20)
let kGridCellPadding:CGFloat = 10
class GridViewController: CollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
let dataProvider = ArrayDataProvider(data: Array(1...kGridSize.width * kGridSize.height), identifierMapper: { (_, data) in
return "\(data)"
})
let layout = Closurelayout(
frameProvider: { (i: Int, data: Int, _) in
CGRect(x: CGFloat(i % kGridSize.width) * (kGridCellSize.width + kGridCellPadding),
y: CGFloat(i / kGridSize.width) * (kGridCellSize.height + kGridCellPadding),
width: kGridCellSize.width,
height: kGridCellSize.height)
}
)
collectionView.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
let provider = CollectionProvider(
dataProvider: dataProvider,
viewUpdater: { (view: UILabel, data: Int, index: Int) in
view.backgroundColor = UIColor(hue: CGFloat(index) / CGFloat(kGridSize.width * kGridSize.height),
saturation: 0.68, brightness: 0.98, alpha: 1)
view.textColor = .white
view.textAlignment = .center
view.text = "\(data)"
}
)
provider.layout = layout
provider.presenter = WobblePresenter()
self.provider = provider
}
}
| true
|
d45fbd795042002270b0af550b97912d622bb9bc
|
Swift
|
imvenj/Walt
|
/Walt/Source/CMSampleBuffer+ImageConvertible.swift
|
UTF-8
| 1,512
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// CMSampleBuffer+ImageConvertible.swift
// Pods
//
// Created by Gonzalo Nunez on 10/7/16.
//
//
#if os(macOS)
import AppKit
public typealias WTImage = NSImage
#else
import UIKit
public typealias WTImage = UIImage
#endif
import CoreMedia
public protocol ImageConvertible {
func toImage() -> WTImage?
}
extension CMSampleBuffer: ImageConvertible {
public func toImage() -> WTImage? {
guard let imageBuffer = CMSampleBufferGetImageBuffer(self) else {
return nil
}
CVPixelBufferLockBaseAddress(imageBuffer, [])
let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
let width = CVPixelBufferGetWidth(imageBuffer)
let height = CVPixelBufferGetHeight(imageBuffer)
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let context = CGContext(data: baseAddress, width: width, height: height,
bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace,
bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)
else {
return nil
}
guard let cgImage = context.makeImage() else {
return nil
}
CVPixelBufferUnlockBaseAddress(imageBuffer, [])
#if os(macOS)
return NSImage(cgImage: cgImage, size: CGSize.init(width: width, height: height))
#else
return UIImage(cgImage: cgImage)
#endif
}
}
| true
|
944ec56a78dc9c5a425eaa780cbe65e6127145c2
|
Swift
|
V-Marco/miscellaneous
|
/snakesAndLadders/snakesAndLadders/GridTools.swift
|
UTF-8
| 1,788
| 3.5
| 4
|
[] |
no_license
|
//
// GridTools.swift
// snakesAndLadders
//
// Created by Vladimir Omelyusik on 26/08/2019.
// Copyright © 2019 Vladimir Omelyusik. All rights reserved.
//
import UIKit
func genTenTenGrid(fromView view: UIView) -> (Array<Double>, Array<Double>) {
// generates 10x10 grid placed on a view's bounds
// returns a tuple with two arrays: with x coordinates (first) and y coordinates (second)
// of a top-left corner of the grid's cells
let width = view.bounds.size.width
let height = view.bounds.size.height
let lowerRightPoint = CGPoint(x: view.bounds.origin.x + width,
y: view.bounds.origin.y + height)
let cellWidth = width / 10
let cellHeight = height / 10
// get x-s
var xs = [Double]()
var i = lowerRightPoint.x
repeat {
xs.append(Double(i - cellWidth))
i -= cellWidth
} while i > lowerRightPoint.x - width
// get y-s
var ys = [Double]()
var j = lowerRightPoint.y
repeat {
ys.append(Double(j - cellHeight))
j -= cellWidth
} while j > lowerRightPoint.y - height
return (xs.reversed(), ys.reversed())
}
func getGridCoordinateFromCellNumber(cellNumber: Int, coordinates: (Array<Double>, Array<Double>)) -> CGPoint {
// returns the coordinates for cell of a given number (in a 10x10 grid the cells are number 0-99 with
// 0-9 in the first row (from right to left),
// 10-19 in the second row (from left to right),
// 20-29 in the third row (from right to left) and so on.
let row = cellNumber / coordinates.0.count
var column = cellNumber - coordinates.0.count * row
if row % 2 != 0 {
column = coordinates.0.count - 1 - column
}
return CGPoint(x: coordinates.0[column], y: coordinates.1[row])
}
| true
|
01e4b5d7b026613f9a451baa223950583f13d22c
|
Swift
|
cyhunter/Geometria
|
/Tests/GeometriaTests/Generalized/AABBTests.swift
|
UTF-8
| 48,687
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
import XCTest
import Geometria
class AABBTests: XCTestCase {
typealias Box = AABB2D
func testCodable() throws {
let sut = Box(minimum: .init(x: 1, y: 2),
maximum: .init(x: 3, y: 4))
let encoder = JSONEncoder()
let decoder = JSONDecoder()
let data = try encoder.encode(sut)
let result = try decoder.decode(Box.self, from: data)
XCTAssertEqual(sut, result)
}
func testInitWithMinimumMaximum() {
let sut = Box(minimum: .init(x: 1, y: 2),
maximum: .init(x: 3, y: 4))
XCTAssertEqual(sut.minimum, .init(x: 1, y: 2))
XCTAssertEqual(sut.maximum, .init(x: 3, y: 4))
}
func testLocation() {
let sut = Box(minimum: .init(x: 1, y: 2),
maximum: .init(x: 3, y: 4))
XCTAssertEqual(sut.location, .init(x: 1, y: 2))
}
}
// MARK: BoundableType Conformance
extension AABBTests {
func testBounds() {
let sut = Box(minimum: .init(x: 1, y: 2),
maximum: .init(x: 3, y: 6))
let result = sut.bounds
XCTAssertEqual(result.minimum, .init(x: 1, y: 2))
XCTAssertEqual(result.maximum, .init(x: 3, y: 6))
}
}
// MARK: Equatable Conformance
extension AABBTests {
func testEquality() {
XCTAssertEqual(Box(minimum: .init(x: 1, y: 2),
maximum: .init(x: 3, y: 4)),
Box(minimum: .init(x: 1, y: 2),
maximum: .init(x: 3, y: 4)))
}
func testUnequality() {
XCTAssertNotEqual(Box(minimum: .init(x: 999, y: 2),
maximum: .init(x: 3, y: 4)),
Box(minimum: .init(x: 1, y: 2),
maximum: .init(x: 3, y: 4)))
XCTAssertNotEqual(Box(minimum: .init(x: 1, y: 999),
maximum: .init(x: 3, y: 4)),
Box(minimum: .init(x: 1, y: 2),
maximum: .init(x: 3, y: 4)))
XCTAssertNotEqual(Box(minimum: .init(x: 1, y: 2),
maximum: .init(x: 999, y: 4)),
Box(minimum: .init(x: 1, y: 2),
maximum: .init(x: 3, y: 4)))
XCTAssertNotEqual(Box(minimum: .init(x: 1, y: 2),
maximum: .init(x: 3, y: 999)),
Box(minimum: .init(x: 1, y: 2),
maximum: .init(x: 3, y: 4)))
}
func testIsSizeZero_zeroArea() {
let sut = Box(minimum: .init(x: 0, y: 0), maximum: .init(x: 0, y: 0))
XCTAssertTrue(sut.isSizeZero)
}
func testIsSizeZero_zeroWidth() {
let sut = Box(minimum: .init(x: 0, y: 0), maximum: .init(x: 0, y: 1))
XCTAssertFalse(sut.isSizeZero)
}
func testIsSizeZero_zeroHeight() {
let sut = Box(minimum: .init(x: 0, y: 0), maximum: .init(x: 1, y: 0))
XCTAssertFalse(sut.isSizeZero)
}
func testIsSizeZero_nonZeroArea() {
let sut = Box(minimum: .init(x: 0, y: 0), maximum: .init(x: 1, y: 1))
XCTAssertFalse(sut.isSizeZero)
}
}
// MARK: VectorComparable Conformance
extension AABBTests {
func testIsValid() {
XCTAssertTrue(Box(minimum: .zero, maximum: .zero).isValid)
XCTAssertTrue(Box(minimum: .zero, maximum: .one).isValid)
XCTAssertTrue(Box(minimum: .zero, maximum: .init(x: 0, y: 1)).isValid)
XCTAssertTrue(Box(minimum: .zero, maximum: .init(x: 1, y: 0)).isValid)
XCTAssertFalse(Box(minimum: .init(x: 0, y: 1), maximum: .zero).isValid)
XCTAssertFalse(Box(minimum: .init(x: 1, y: 0), maximum: .zero).isValid)
XCTAssertFalse(Box(minimum: .one, maximum: .zero).isValid)
}
func testInitOfPoints_2Points() {
let result = Box(of: .init(x: -5, y: 6), .init(x: 3, y: -2))
XCTAssertEqual(result.minimum, .init(x: -5, y: -2))
XCTAssertEqual(result.maximum, .init(x: 3, y: 6))
}
func testInitOfPoints_3Points() {
let result =
Box(of: .init(x: -5, y: 4),
.init(x: 3, y: -2),
.init(x: 2, y: 6)
)
XCTAssertEqual(result.minimum, .init(x: -5, y: -2))
XCTAssertEqual(result.maximum, .init(x: 3, y: 6))
}
func testInitOfPoints_4Points() {
let result =
Box(of: .init(x: -5, y: 4),
.init(x: 3, y: -2),
.init(x: 1, y: 3),
.init(x: 2, y: 6)
)
XCTAssertEqual(result.minimum, .init(x: -5, y: -2))
XCTAssertEqual(result.maximum, .init(x: 3, y: 6))
}
func testExpandToIncludePoint() {
var sut = Box.zero
sut.expand(toInclude: .init(x: -1, y: 2))
sut.expand(toInclude: .init(x: 3, y: -5))
XCTAssertEqual(sut.minimum, .init(x: -1, y: -5))
XCTAssertEqual(sut.maximum, .init(x: 3, y: 2))
}
func testExpandToIncludePoints() {
var sut = Box.zero
sut.expand(toInclude: [.init(x: -1, y: 2), .init(x: 3, y: -5)])
XCTAssertEqual(sut.minimum, .init(x: -1, y: -5))
XCTAssertEqual(sut.maximum, .init(x: 3, y: 2))
}
func testClamp_outOfBounds() {
let sut = Box(minimum: .init(x: 2, y: 3), maximum: .init(x: 7, y: 11))
XCTAssertEqual(sut.clamp(.init(x: 0, y: 0)), .init(x: 2, y: 3))
XCTAssertEqual(sut.clamp(.init(x: 12, y: 12)), .init(x: 7, y: 11))
XCTAssertEqual(sut.clamp(.init(x: 0, y: 5)), .init(x: 2, y: 5))
XCTAssertEqual(sut.clamp(.init(x: 5, y: 1)), .init(x: 5, y: 3))
}
func testClamp_withinBounds() {
let sut = Box(minimum: .init(x: 2, y: 3), maximum: .init(x: 7, y: 11))
XCTAssertEqual(sut.clamp(.init(x: 3, y: 5)), .init(x: 3, y: 5))
}
func testContainsPoint() {
let sut = Box(minimum: .init(x: 0, y: 1), maximum: .init(x: 5, y: 8))
XCTAssertTrue(sut.contains(.init(x: 0, y: 1)))
XCTAssertTrue(sut.contains(.init(x: 5, y: 1)))
XCTAssertTrue(sut.contains(.init(x: 5, y: 7)))
XCTAssertTrue(sut.contains(.init(x: 5, y: 1)))
XCTAssertTrue(sut.contains(.init(x: 3, y: 3)))
XCTAssertFalse(sut.contains(.init(x: -1, y: 1)))
XCTAssertFalse(sut.contains(.init(x: 6, y: 1)))
XCTAssertFalse(sut.contains(.init(x: 6, y: 7)))
XCTAssertFalse(sut.contains(.init(x: 5, y: 0)))
}
}
// MARK: SelfIntersectableRectangleType Conformance
extension AABBTests {
func testContainsAABB() {
let sut = Box(x: 0, y: 1, width: 5, height: 7)
XCTAssertTrue(sut.contains(Box(x: 1, y: 2, width: 3, height: 4)))
XCTAssertFalse(sut.contains(Box(x: -1, y: 2, width: 3, height: 4)))
XCTAssertFalse(sut.contains(Box(x: 1, y: -2, width: 3, height: 4)))
XCTAssertFalse(sut.contains(Box(x: 1, y: 2, width: 5, height: 4)))
XCTAssertFalse(sut.contains(Box(x: 1, y: 2, width: 3, height: 7)))
}
func testContainsAABB_returnsTrueForEqualBox() {
let sut = Box(x: 0, y: 1, width: 5, height: 7)
XCTAssertTrue(sut.contains(sut))
}
func testIntersectsAABB() {
let sut = Box(x: 0, y: 0, width: 3, height: 3)
XCTAssertTrue(sut.intersects(Box(x: -1, y: -1, width: 2, height: 2)))
XCTAssertFalse(sut.intersects(Box(x: -3, y: 0, width: 2, height: 2)))
XCTAssertFalse(sut.intersects(Box(x: 0, y: -3, width: 2, height: 2)))
XCTAssertFalse(sut.intersects(Box(x: 4, y: 0, width: 2, height: 2)))
XCTAssertFalse(sut.intersects(Box(x: 0, y: 4, width: 2, height: 2)))
}
func testIntersectsAABB_edgeIntersections() {
let sut = Box(x: 0, y: 0, width: 3, height: 3)
XCTAssertTrue(sut.intersects(Box(x: -2, y: -2, width: 2, height: 2)))
XCTAssertTrue(sut.intersects(Box(x: -2, y: 3, width: 2, height: 2)))
XCTAssertTrue(sut.intersects(Box(x: 3, y: -2, width: 2, height: 2)))
XCTAssertTrue(sut.intersects(Box(x: 3, y: 3, width: 2, height: 2)))
}
func testUnion() {
let sut = Box(x: 1, y: 2, width: 3, height: 5)
let result = sut.union(.init(x: 7, y: 13, width: 17, height: 19))
XCTAssertEqual(result.location, .init(x: 1, y: 2))
XCTAssertEqual(result.size, .init(x: 23, y: 30))
}
func testIntersection_sameAABB() {
let rect = Box(x: 1, y: 2, width: 3, height: 4)
let result = rect.intersection(rect)
XCTAssertEqual(result, rect)
}
func testIntersection_overlappingAABB() {
let rect1 = Box(x: 1, y: 2, width: 3, height: 4)
let rect2 = Box(x: -1, y: 1, width: 3, height: 4)
let result = rect1.intersection(rect2)
XCTAssertEqual(result, Box(x: 1, y: 2, width: 1, height: 3))
}
func testIntersection_edgeOnly() {
let rect1 = Box(x: 1, y: 2, width: 3, height: 4)
let rect2 = Box(x: -2, y: 2, width: 3, height: 4)
let result = rect1.intersection(rect2)
XCTAssertEqual(result, Box(x: 1, y: 2, width: 0, height: 4))
}
func testIntersection_cornerOnly() {
let rect1 = Box(x: 1, y: 2, width: 3, height: 4)
let rect2 = Box(x: -2, y: -2, width: 3, height: 4)
let result = rect1.intersection(rect2)
XCTAssertEqual(result, Box(x: 1, y: 2, width: 0, height: 0))
}
func testIntersection_noIntersection() {
let rect1 = Box(x: 1, y: 2, width: 3, height: 4)
let rect2 = Box(x: -3, y: -3, width: 3, height: 4)
let result = rect1.intersection(rect2)
XCTAssertNil(result)
}
}
// MARK: VectorAdditive Conformance
extension AABBTests {
func testSize() {
let sut = Box(minimum: .init(x: 0, y: 1), maximum: .init(x: 2, y: 4))
XCTAssertEqual(sut.size, .init(x: 2, y: 3))
}
func testIsZero() {
XCTAssertTrue(Box(minimum: .zero, maximum: .zero).isZero)
XCTAssertFalse(Box(minimum: .zero, maximum: .one).isZero)
XCTAssertFalse(Box(minimum: .zero, maximum: .init(x: 0, y: 1)).isZero)
XCTAssertFalse(Box(minimum: .zero, maximum: .init(x: 1, y: 0)).isZero)
XCTAssertFalse(Box(minimum: .init(x: 0, y: 1), maximum: .zero).isZero)
XCTAssertFalse(Box(minimum: .init(x: 1, y: 0), maximum: .zero).isZero)
XCTAssertFalse(Box(minimum: .one, maximum: .zero).isZero)
}
func testAsRectangle() {
let sut = Box(minimum: .init(x: 0, y: 1), maximum: .init(x: 2, y: 4))
let result = sut.asRectangle
XCTAssertEqual(result, NRectangle(x: 0, y: 1, width: 2, height: 3))
}
func testInitEmpty() {
let sut = Box()
XCTAssertEqual(sut.minimum, .zero)
XCTAssertEqual(sut.maximum, .zero)
}
func testInitWithLocationSize() {
let sut = Box(location: .init(x: 1, y: 2), size: .init(x: 3, y: 4))
XCTAssertEqual(sut.minimum, .init(x: 1, y: 2))
XCTAssertEqual(sut.maximum, .init(x: 4, y: 6))
}
}
// MARK: VectorAdditive & VectorComparable Conformance
extension AABBTests {
func testInitOfPoints_variadic() {
let result =
Box(of: .init(x: -5, y: 4),
.init(x: 3, y: -2),
.init(x: 1, y: 3),
.init(x: 2, y: 1),
.init(x: 2, y: 6)
)
XCTAssertEqual(result.minimum, .init(x: -5, y: -2))
XCTAssertEqual(result.maximum, .init(x: 3, y: 6))
}
func testInitPoints() {
let result = Box(points: [
.init(x: -5, y: 4),
.init(x: 3, y: -2),
.init(x: 1, y: 3),
.init(x: 2, y: 1),
.init(x: 2, y: 6)
])
XCTAssertEqual(result.minimum, .init(x: -5, y: -2))
XCTAssertEqual(result.maximum, .init(x: 3, y: 6))
}
func testInitPoints_empty() {
let result = Box(points: [])
XCTAssertEqual(result.minimum, .zero)
XCTAssertEqual(result.maximum, .zero)
}
}
// MARK: Vector: VectorMultiplicative Conformance
extension AABBTests {
func testCenter() {
let sut = Box(x: 1, y: 2, width: 3, height: 5)
XCTAssertEqual(sut.center, .init(x: 2.5, y: 4.5))
}
func testCenter_set() {
var sut = Box(x: 1, y: 2, width: 3, height: 5)
sut.center = .init(x: 11, y: 13)
XCTAssertEqual(sut.location, .init(x: 9.5, y: 10.5))
XCTAssertEqual(sut.size, .init(x: 3, y: 5))
}
func testInflatedByVector() {
let sut = Box(x: 1, y: 2, width: 3, height: 5)
let result = sut.inflatedBy(.init(x: 7, y: 11))
XCTAssertEqual(result.location, .init(x: -2.5, y: -3.5))
XCTAssertEqual(result.size, .init(x: 10, y: 16))
}
func testInflatedByVector_maintainsCenter() {
let sut = Box(x: 1, y: 2, width: 3, height: 5)
let result = sut.inflatedBy(.init(x: 7, y: 11))
XCTAssertEqual(result.center, sut.center)
}
func testInsetByVector() {
let sut = Box(x: 1, y: 2, width: 7, height: 11)
let result = sut.insetBy(.init(x: 3, y: 5))
XCTAssertEqual(result.location, .init(x: 2.5, y: 4.5))
XCTAssertEqual(result.size, .init(x: 4, y: 6))
}
func testInsetByVector_maintainsCenter() {
let sut = Box(x: 1, y: 2, width: 7, height: 11)
let result = sut.insetBy(.init(x: 3, y: 5))
XCTAssertEqual(result.center, sut.center)
}
func testMovingCenterToVector() {
let sut = Box(x: 1, y: 2, width: 7, height: 11)
let result = sut.movingCenter(to: .init(x: 5, y: 13))
XCTAssertEqual(result.location, .init(x: 1.5, y: 7.5))
XCTAssertEqual(result.size, .init(x: 7, y: 11))
}
}
// MARK: Vector: VectorMultiplicative Tests
extension AABBTests {
func testUnit() {
let sut = Box.unit
XCTAssertEqual(sut.minimum, .zero)
XCTAssertEqual(sut.maximum, .one)
}
}
// MARK: - ConvexType Conformance
// MARK: 2D
extension AABBTests {
// MARK: intersects(line:)
func testIntersectsLine_2d_line() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 2, y1: 9, x2: 15, y2: 5)
XCTAssertTrue(sut.intersects(line: line))
}
func testIntersectsLine_2d_line_alongEdge_returnsTrue() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 0, y1: 3, x2: 1, y2: 3)
XCTAssertTrue(sut.intersects(line: line))
}
func testIntersectsLine_2d_line_outsideLineLimits_returnsTrue() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 0, y1: 9, x2: 1, y2: 8)
XCTAssertTrue(sut.intersects(line: line))
}
func testIntersectsLine_2d_line_noIntersection_bottom_returnsFalse() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 12, y1: 9, x2: 13, y2: 9)
XCTAssertFalse(sut.intersects(line: line))
}
func testIntersectsLine_2d_line_noIntersection_returnsFalse() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 9, y1: 9, x2: 15, y2: 7)
XCTAssertFalse(sut.intersects(line: line))
}
func testIntersectsLine_2d_lineSegment_outsideLineLimits_returnsFalse() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = LineSegment2D(x1: 0, y1: 9, x2: 1, y2: 8)
XCTAssertFalse(sut.intersects(line: line))
}
func testIntersectsLine_2d_lineSegment_alongEdge_returnsTrue() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = LineSegment2D(x1: 1, y1: 3, x2: 13, y2: 3)
XCTAssertTrue(sut.intersects(line: line))
}
func testIntersectsLine_2d_lineSegment_alongEdge_startsAfterEdge_returnsFalse() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = LineSegment2D(x1: 12, y1: 3, x2: 13, y2: 3)
XCTAssertFalse(sut.intersects(line: line))
}
func testIntersectsLine_2d_ray() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Ray2D(x1: 2, y1: 9, x2: 15, y2: 5)
XCTAssertTrue(sut.intersects(line: line))
}
func testIntersectsLine_2d_ray_intersectsBeforeRayStart_returnsFalse() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Ray2D(x1: 2, y1: 10, x2: 15, y2: 11)
XCTAssertFalse(sut.intersects(line: line))
}
func testIntersectsLine_2d_ray_intersectsAfterRayStart_returnsTrue() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Ray2D(x1: 0, y1: 0, x2: 1, y2: 1)
XCTAssertTrue(sut.intersects(line: line))
}
func testIntersectsLine_2d_ray_startsWithinAABB_returnsTrue() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Ray2D(x1: 3, y1: 4, x2: 4, y2: 5)
XCTAssertTrue(sut.intersects(line: line))
}
func testIntersectsLine_2d_ray_alongEdge_returnsTrue() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Ray2D(x1: 0, y1: 3, x2: 1, y2: 3)
XCTAssertTrue(sut.intersects(line: line))
}
func testIntersectsLine_2d_directionalRay_intersectsBeforeRayStart_returnsFalse() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = DirectionalRay2D(x1: 2, y1: 10, x2: 15, y2: 11)
XCTAssertFalse(sut.intersects(line: line))
}
func testIntersectsLine_2d_directionalRay_intersectsAfterRayStart_returnsTrue() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = DirectionalRay2D(x1: 0, y1: 0, x2: 1, y2: 1)
XCTAssertTrue(sut.intersects(line: line))
}
func testIntersectsLine_2d_directionalRay_startsWithinAABB_returnsTrue() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = DirectionalRay2D(x1: 3, y1: 4, x2: 4, y2: 5)
XCTAssertTrue(sut.intersects(line: line))
}
func testIntersectsLine_2d_directionalRay_alongEdge_returnsTrue() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 1, y1: 3, x2: 13, y2: 3)
XCTAssertTrue(sut.intersects(line: line))
}
// MARK: intersection(with:)
func testIntersectionWith_2d_line_across_horizontal() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 0, y1: 5, x2: 12, y2: 5)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 2.0, y: 5.0),
normal: .init(x: -1.0, y: 0)
),
PointNormal(
point: .init(x: 11.0, y: 5.0),
normal: .init(x: -1.0, y: 0)
)
)
)
}
func testIntersectionWith_2d_line_contained_horizontal() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 3, y1: 5, x2: 7, y2: 5)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 2.0, y: 5.0),
normal: .init(x: -1.0, y: 0)
),
PointNormal(
point: .init(x: 11.0, y: 5.0),
normal: .init(x: -1.0, y: 0)
)
)
)
}
func testIntersectionWith_2d_line_fromTop_pointingDown() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 5, y1: 0, x2: 5, y2: 1)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 5.0, y: 3.0),
normal: .init(x: 0.0, y: -1.0)
),
PointNormal(
point: .init(x: 5.0, y: 7.0),
normal: .init(x: 0.0, y: -1.0)
)
)
)
}
func testIntersectionWith_2d_line_fromTop_pointingUp() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 5, y1: 1, x2: 5, y2: 0)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 5.0, y: 7.0),
normal: .init(x: 0.0, y: 1.0)
),
PointNormal(
point: .init(x: 5.0, y: 3.0),
normal: .init(x: 0.0, y: 1.0)
)
)
)
}
func testIntersectionWith_2d_line_fromLeft_pointingRight() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 0, y1: 5, x2: 1, y2: 5)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 2.0, y: 5.0),
normal: .init(x: -1.0, y: 0.0)
),
PointNormal(
point: .init(x: 11.0, y: 5.0),
normal: .init(x: -1.0, y: 0.0)
)
)
)
}
func testIntersectionWith_2d_line_fromLeft_pointingLeft() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 1, y1: 5, x2: 0, y2: 5)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 11.0, y: 5.0),
normal: .init(x: 1.0, y: 0)
),
PointNormal(
point: .init(x: 2.0, y: 5.0),
normal: .init(x: 1.0, y: 0)
)
)
)
}
func testIntersectionWith_2d_line_fromRight_pointingLeft() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 13, y1: 5, x2: 12, y2: 5)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 11.0, y: 5.0),
normal: .init(x: 1.0, y: 0)
),
PointNormal(
point: .init(x: 2.0, y: 5.0),
normal: .init(x: 1.0, y: 0)
)
)
)
}
func testIntersectionWith_2d_line_fromRight_pointingRight() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 12, y1: 5, x2: 13, y2: 5)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 2.0, y: 5.0),
normal: .init(x: -1, y: 0)
),
PointNormal(
point: .init(x: 11.0, y: 5.0),
normal: .init(x: -1, y: 0)
)
)
)
}
func testIntersectionWith_2d_line_fromBottom_pointingUp() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 5, y1: 9, x2: 5, y2: 8)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 5.0, y: 7.0),
normal: .init(x: 0.0, y: 1.0)
),
PointNormal(
point: .init(x: 5.0, y: 3.0),
normal: .init(x: 0.0, y: 1.0)
)
)
)
}
func testIntersectionWith_2d_line_fromBottom_pointingDown() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 5, y1: 8, x2: 5, y2: 9)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 5.0, y: 3.0),
normal: .init(x: 0.0, y: -1.0)
),
PointNormal(
point: .init(x: 5.0, y: 7.0),
normal: .init(x: 0.0, y: -1.0)
)
)
)
}
func testIntersectionWith_2d_line_outsideLineLimits() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 0, y1: 8, x2: 1, y2: 7)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 2.0, y: 6.0),
normal: .init(x: -1.0, y: 0.0)
),
PointNormal(
point: .init(x: 5.0, y: 3.0),
normal: .init(x: 0.0, y: 1.0)
)
)
)
}
func testIntersectionWith_2d_line_noIntersection() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 9, y1: 9, x2: 15, y2: 7)
assertEqual(sut.intersection(with: line), .noIntersection)
}
func testIntersectionWith_2d_line_noIntersection_top_horizontal() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 3, y1: 2, x2: 5, y2: 2)
assertEqual(sut.intersection(with: line), .noIntersection)
}
func testIntersectionWith_2d_line_noIntersection_top_horizontal_long_line() {
let sut = Box(left: 2, top: 3, right: 4, bottom: 7)
let line = Line2D(x1: -50, y1: 2.5, x2: 50, y2: 2.5)
assertEqual(sut.intersection(with: line), .noIntersection)
}
func testIntersectionWith_2d_line_noIntersection_left_vertical() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 1, y1: 2, x2: 1, y2: 3)
assertEqual(sut.intersection(with: line), .noIntersection)
}
func testIntersectionWith_2d_line_noIntersection_right_vertical() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 12, y1: 2, x2: 12, y2: 3)
assertEqual(sut.intersection(with: line), .noIntersection)
}
func testIntersectionWith_2d_line_noIntersection_bottom_horizontal() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 3, y1: 9, x2: 5, y2: 9)
assertEqual(sut.intersection(with: line), .noIntersection)
}
func testIntersectionWith_2d_line_noIntersection_bottomRight_horizontal() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 12, y1: 9, x2: 13, y2: 9)
assertEqual(sut.intersection(with: line), .noIntersection)
}
func testIntersectionWith_2d_line_alongEdge() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 1, y1: 3, x2: 13, y2: 3)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 2.0, y: 3.0),
normal: .init(x: -1.0, y: 0.0)
),
PointNormal(
point: .init(x: 11.0, y: 3.0),
normal: .init(x: -1.0, y: 0.0)
)
)
)
}
func testIntersectionWith_2d_lineSegment_outsideLineLimits() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = LineSegment2D(x1: 0, y1: 9, x2: 1, y2: 8)
assertEqual(sut.intersection(with: line), .noIntersection)
}
func testIntersectionWith_2d_lineSegment_exitOnly() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = LineSegment2D(x1: 5, y1: 4, x2: 12, y2: 4)
assertEqual(
sut.intersection(with: line),
.exit(
PointNormal(
point: .init(x: 11.0, y: 4.0),
normal: .init(x: -1.0, y: 0.0)
)
)
)
}
func testIntersectionWith_2d_lineSegment_endsWithinAABB() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = LineSegment2D(x1: 2, y1: 4, x2: 5, y2: 4)
assertEqual(
sut.intersection(with: line),
.enter(
PointNormal(
point: .init(x: 2.0, y: 4.0),
normal: .init(x: -1.0, y: 0.0)
)
)
)
}
func testIntersectionWith_2d_lineSegment_alongEdge() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Line2D(x1: 1, y1: 3, x2: 13, y2: 3)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 2.0, y: 3.0),
normal: .init(x: -1.0, y: 0.0)
),
PointNormal(
point: .init(x: 11.0, y: 3.0),
normal: .init(x: -1.0, y: 0.0)
)
)
)
}
func testIntersectionWith_2d_line_contained() {
let sut = Box(left: 0, top: 0, right: 20, bottom: 20)
let line = LineSegment2D(start: .one, end: .init(x: 10, y: 10))
assertEqual(sut.intersection(with: line), .contained)
}
func testIntersectionWith_2d_ray() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Ray2D(x1: 2, y1: 9, x2: 15, y2: 5)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 8.5, y: 7.0),
normal: .init(x: 0.0, y: 1.0)
),
PointNormal(
point: .init(x: 11.0, y: 6.230769230769231),
normal: .init(x: -1.0, y: 0.0)
)
)
)
}
func testIntersectionWith_2d_ray_intersectsBeforeRayStart() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Ray2D(x1: 10, y1: 10, x2: 15, y2: 11)
assertEqual(sut.intersection(with: line), .noIntersection)
}
func testIntersectionWith_2d_ray_intersectsAfterRayStart() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Ray2D(x1: 0, y1: 0, x2: 1, y2: 1)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 3.0, y: 3.0),
normal: .init(x: 0.0, y: -1.0)
),
PointNormal(
point: .init(x: 7.0, y: 7.0),
normal: .init(x: 0.0, y: -1.0)
)
)
)
}
func testIntersectionWith_2d_ray_startsWithinAABB() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Ray2D(x1: 3, y1: 4, x2: 4, y2: 5)
assertEqual(
sut.intersection(with: line),
.exit(
PointNormal(
point: .init(x: 6.0, y: 7.0),
normal: .init(x: 0.0, y: -1.0)
)
)
)
}
func testIntersectionWith_2d_ray_alongEdge() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = Ray2D(x1: 0, y1: 3, x2: 1, y2: 3)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 2.0, y: 3.0),
normal: .init(x: -1.0, y: 0.0)
),
PointNormal(
point: .init(x: 11.0, y: 3.0),
normal: .init(x: -1.0, y: 0.0)
)
)
)
}
func testIntersectionWith_2d_directionalRay_intersectsBeforeRayStart() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = DirectionalRay2D(x1: 2, y1: 10, x2: 15, y2: 11)
assertEqual(sut.intersection(with: line), .noIntersection)
}
func testIntersectionWith_2d_directionalRay_intersectsAfterRayStart() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = DirectionalRay2D(x1: 0, y1: 0, x2: 1, y2: 1)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 3.0, y: 3.0),
normal: .init(x: 0.0, y: -1.0)
),
PointNormal(
point: .init(x: 6.999999999999999, y: 6.999999999999999),
normal: .init(x: 0.0, y: -1.0)
)
)
)
}
func testIntersectionWith_2d_directionalRay_startsWithinAABB() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = DirectionalRay2D(x1: 3, y1: 4, x2: 4, y2: 5)
assertEqual(
sut.intersection(with: line),
.exit(
PointNormal(
point: .init(x: 6.0, y: 7.0),
normal: .init(x: 0.0, y: -1.0)
)
)
)
}
func testIntersectionWith_2d_directionalRay_alongEdge() {
let sut = Box(left: 2, top: 3, right: 11, bottom: 7)
let line = DirectionalRay2D(x1: 0, y1: 3, x2: 1, y2: 3)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 2.0, y: 3.0),
normal: .init(x: -1.0, y: 0.0)
),
PointNormal(
point: .init(x: 11.0, y: 3.0),
normal: .init(x: -1.0, y: 0.0)
)
)
)
}
// MARK: -
func testIntersectionWith_2d_lineSegment_bug1() {
// Verify that the intersection point containment check doesn't fail due
// to rounding errors in the produced intersection points
let sut = Box(left: 162.5, top: 135.0, right: 237.5, bottom: 165.0)
let line = LineSegment2D(x1: 101.01359554152113, y1: 164.20182144594258,
x2: 298.9864044584789, y2: 145.79817855405742)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 162.5, y: 158.4860171567055),
normal: .init(x: -1.0, y: 0.0)
),
PointNormal(
point: .init(x: 237.50000000000003, y: 151.5139828432945),
normal: .init(x: -1.0, y: 0.0)
)
)
)
}
}
// MARK: 3D
extension AABBTests {
typealias AABB3 = AABB3D
// MARK: intersects(line:)
func testIntersectsLine_3d_line_acrossTopQuadrant() {
let sut = AABB3(minimum: .init(x: 0, y: 0, z: 0), maximum: .init(x: 10, y: 10, z: 10))
let line = Line3D(x1: -5, y1: 5, z1: 7, x2: 15, y2: 5, z2: 7)
XCTAssertTrue(sut.intersects(line: line))
}
// MARK: intersection(with:)
// MARK: X - Positive
func testIntersectionWith_3d_line_acrossTopQuadrant_xPositive() {
// Run a line on a rectangular-shaped AABB of dimensions (x30 y20 z10),
// along the X coordinate through the top (Y: 10, Z: 7) quadrant.
let sut = AABB3(minimum: .init(x: 0, y: 0, z: 0), maximum: .init(x: 30, y: 20, z: 10))
let line = Line3D(x1: -5, y1: 10, z1: 7, x2: 40, y2: 10, z2: 7)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: -2.7755575615628914e-16, y: 10.0, z: 7.0),
normal: .init(x: -1.0, y: 0.0, z: 0.0)
),
PointNormal(
point: .init(x: 30.0, y: 10.0, z: 7.0),
normal: .init(x: -1.0, y: 0.0, z: 0.0)
)
)
)
}
func testIntersectionWith_3d_line_acrossFarQuadrant_xPositive() {
// Run a line on a rectangular-shaped AABB of dimensions (x30 y20 z10),
// along the X coordinate through the far (Y: 12, Z: 10) quadrant.
let sut = AABB3(minimum: .init(x: 0, y: 0, z: 0), maximum: .init(x: 30, y: 20, z: 10))
let line = Line3D(x1: -5, y1: 12, z1: 5, x2: 40, y2: 12, z2: 5)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: -2.7755575615628914e-16, y: 12, z: 5.0),
normal: .init(x: -1.0, y: 0.0, z: 0.0)
),
PointNormal(
point: .init(x: 30.0, y: 12, z: 5.0),
normal: .init(x: -1.0, y: 0.0, z: 0.0)
)
)
)
}
func testIntersectionWith_3d_line_acrossBottomQuadrant_xPositive() {
// Run a line on a rectangular-shaped AABB of dimensions (x30 y20 z10),
// along the X coordinate through the bottom (Y: 10, Z: 3) quadrant.
let sut = AABB3(minimum: .init(x: 0, y: 0, z: 0), maximum: .init(x: 30, y: 20, z: 10))
let line = Line3D(x1: -5, y1: 10, z1: 3, x2: 40, y2: 10, z2: 3)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: -2.7755575615628914e-16, y: 10.0, z: 3.0),
normal: .init(x: -1.0, y: 0.0, z: 0.0)
),
PointNormal(
point: .init(x: 30.0, y: 10.0, z: 3.0),
normal: .init(x: -1.0, y: 0.0, z: 0.0)
)
)
)
}
func testIntersectionWith_3d_line_acrossNearQuadrant_xPositive() {
// Run a line on a rectangular-shaped AABB of dimensions (x30 y20 z10),
// along the X coordinate through the near (Y: 7, Z: 10) quadrant.
let sut = AABB3(minimum: .init(x: 0, y: 0, z: 0), maximum: .init(x: 30, y: 20, z: 10))
let line = Line3D(x1: -5, y1: 7, z1: 5, x2: 40, y2: 7, z2: 5)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: -2.7755575615628914e-16, y: 7, z: 5.0),
normal: .init(x: -1.0, y: 0.0, z: 0.0)
),
PointNormal(
point: .init(x: 30.0, y: 7, z: 5.0),
normal: .init(x: -1.0, y: 0.0, z: 0.0)
)
)
)
}
// MARK: X - Negative
func testIntersectionWith_3d_line_acrossTopQuadrant_xNegative() {
// Run a line on a rectangular-shaped AABB of dimensions (x30 y20 z10),
// along the X coordinate through the top (Y: 10, Z: 7) quadrant.
let sut = AABB3(minimum: .init(x: 0, y: 0, z: 0), maximum: .init(x: 30, y: 20, z: 10))
let line = Line3D(x1: 40, y1: 10, z1: 7, x2: -5, y2: 10, z2: 7)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 30.0, y: 10.0, z: 7.0),
normal: .init(x: 1.0, y: 0.0, z: 0.0)
),
PointNormal(
point: .init(x: 2.220446049250313e-15, y: 10.0, z: 7.0),
normal: .init(x: 1.0, y: 0.0, z: 0.0)
)
)
)
}
func testIntersectionWith_3d_line_acrossFarQuadrant_xNegative() {
// Run a line on a rectangular-shaped AABB of dimensions (x30 y20 z10),
// along the X coordinate through the far (Y: 12, Z: 10) quadrant.
let sut = AABB3(minimum: .init(x: 0, y: 0, z: 0), maximum: .init(x: 30, y: 20, z: 10))
let line = Line3D(x1: 40, y1: 12, z1: 5, x2: -5, y2: 12, z2: 5)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 30.0, y: 12, z: 5.0),
normal: .init(x: 1.0, y: 0.0, z: 0.0)
),
PointNormal(
point: .init(x: 2.220446049250313e-15, y: 12.0, z: 5.0),
normal: .init(x: 1.0, y: 0.0, z: 0.0)
)
)
)
}
func testIntersectionWith_3d_line_acrossBottomQuadrant_xNegative() {
// Run a line on a rectangular-shaped AABB of dimensions (x30 y20 z10),
// along the X coordinate through the bottom (Y: 10, Z: 3) quadrant.
let sut = AABB3(minimum: .init(x: 0, y: 0, z: 0), maximum: .init(x: 30, y: 20, z: 10))
let line = Line3D(x1: 40, y1: 10, z1: 3, x2: -5, y2: 10, z2: 3)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 30.0, y: 10.0, z: 3.0),
normal: .init(x: 1.0, y: 0.0, z: 0.0)
),
PointNormal(
point: .init(x: 2.220446049250313e-15, y: 10.0, z: 3.0),
normal: .init(x: 1.0, y: 0.0, z: 0.0)
)
)
)
}
func testIntersectionWith_3d_line_acrossNearQuadrant_xNegative() {
// Run a line on a rectangular-shaped AABB of dimensions (x30 y20 z10),
// along the X coordinate through the near (Y: 7, Z: 10) quadrant.
let sut = AABB3(minimum: .init(x: 0, y: 0, z: 0), maximum: .init(x: 30, y: 20, z: 10))
let line = Line3D(x1: 40, y1: 7, z1: 5, x2: -5, y2: 7, z2: 5)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 30.0, y: 7.0, z: 5.0),
normal: .init(x: 1.0, y: 0.0, z: 0.0)
),
PointNormal(
point: .init(x: 2.220446049250313e-15, y: 7.0, z: 5.0),
normal: .init(x: 1.0, y: 0.0, z: 0.0)
)
)
)
}
// MARK: Y - Positive - Angled
func testIntersectionWith_3d_ray_acrossTopQuadrant_yPositiveAngled() {
// Run a line on a rectangular-shaped AABB of dimensions (x30 y20 z10),
// along the Y coordinate through the near (X: 20, Z: 7) quadrant, with
// a downard slope that cuts to the far bottom (X: 20, Z: 3) quadrant.
let sut = AABB3(minimum: .init(x: 0, y: 0, z: 0), maximum: .init(x: 30, y: 20, z: 10))
let line = DirectionalRay3D(x1: 20, y1: -5, z1: 7, x2: 20, y2: 25, z2: 3)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 20.0, y: 1.67257683684584e-16, z: 6.333333333333333),
normal: .init(x: 0.0, y: -1.0, z: 0.0)
),
PointNormal(
point: .init(x: 20.0, y: 20.0, z: 3.666666666666667),
normal: .init(x: 0.0, y: -1.0, z: 0.0)
)
)
)
}
func testIntersectionWith_3d_ray_offset_acrossTopQuadrant_yPositiveAngled() {
// Run a line on a rectangular-shaped AABB of dimensions (x30 y20 z10)
// with an offset from origin of (x2, y3, z4), along the Y coordinate
// through the near (X: 20, Z: 7) quadrant, with a downard slope that
// cuts to the bottom far (Y: 17, Z: 4) quadrant.
let sut = AABB3(minimum: .init(x: 2, y: 3, z: 4), maximum: .init(x: 30, y: 20, z: 10))
let line = DirectionalRay3D(x1: 20, y1: -5, z1: 7, x2: 20, y2: 25, z2: 3)
assertEqual(
sut.intersection(with: line),
.enterExit(
PointNormal(
point: .init(x: 20.0, y: 2.999999999999999, z: 5.933333333333334),
normal: .init(x: 0.0, y: -1.0, z: 0.0)
),
PointNormal(
point: .init(x: 20.0, y: 17.5, z: 4.0),
normal: .init(x: 0.0, y: 0.0, z: 1.0)
)
)
)
}
#if canImport(simd)
func testIntersectionWith_3d_ray_normalBug1() {
// From GeometriaApp commit 8bf1b3021ef3fd133c46ca6c3e959c90a84df2f5
// at pixel coord: (x: 174, y: 160)
// Original AABB:
// AABB(minimum: .init(x: -20.0, y: 110.0, z: 80.0),
// maximum: .init(x: 60.0, y: 90.0, z: 95.0))
//
// Issue turned out to be the inverted Y min-max axis above, but we leave
// the test here to reference it in the future just in case.
//
typealias Vector = SIMD3<Double>
let sut = AABB<Vector>(minimum: .init(x: -20.0, y: 90.0, z: 80.0),
maximum: .init(x: 60.0, y: 110.0, z: 95.0))
let ray = DirectionalRay<Vector>(
start: .init(x: -7.8, y: 0.0, z: 87.0),
direction: .init(
x: -0.08629543594487392,
y: 0.995716568594699,
z: -0.03319055228648997
)
)
assertEqual(
sut.intersection(with: ray),
.enterExit(
PointNormal(
point: .init(x: -15.6, y: 90.0, z: 84.0),
normal: .init(x: 0.0, y: -1.0, z: 0.0)
),
PointNormal(
point: .init(x: -17.333333333333332, y: 110.0, z: 83.33333333333333),
normal: .init(x: 0.0, y: -1.0, z: 0.0)
)
)
)
}
#endif
}
// MARK: SignedDistanceMeasurableType Conformance
extension AABBTests {
func testSignedDistanceTo_center() {
let sut = Box(minimum: .init(x: 1, y: 2), maximum: .init(x: 5, y: 7))
XCTAssertEqual(sut.signedDistance(to: sut.center), -2.0)
}
func testSignedDistanceTo_onEdge_left() {
let sut = Box(minimum: .init(x: 1, y: 2), maximum: .init(x: 5, y: 7))
XCTAssertEqual(sut.signedDistance(to: .init(x: 1, y: 5)), 0.0)
}
func testSignedDistanceTo_onEdge_top() {
let sut = Box(minimum: .init(x: 1, y: 2), maximum: .init(x: 5, y: 7))
XCTAssertEqual(sut.signedDistance(to: .init(x: 3, y: 7)), 0.0)
}
func testSignedDistanceTo_onEdge_right() {
let sut = Box(minimum: .init(x: 1, y: 2), maximum: .init(x: 5, y: 7))
XCTAssertEqual(sut.signedDistance(to: .init(x: 5, y: 5)), 0.0)
}
func testSignedDistanceTo_onEdge_bottom() {
let sut = Box(minimum: .init(x: 1, y: 2), maximum: .init(x: 5, y: 7))
XCTAssertEqual(sut.signedDistance(to: .init(x: 3, y: 2)), 0.0)
}
func testSignedDistanceTo_outside_bottomEdge() {
let sut = Box(minimum: .init(x: 1, y: 2), maximum: .init(x: 5, y: 7))
XCTAssertEqual(sut.signedDistance(to: .init(x: 3, y: 0)), 2.0)
}
func testSignedDistanceTo_outside_rightEdge() {
let sut = Box(minimum: .init(x: 1, y: 2), maximum: .init(x: 5, y: 7))
XCTAssertEqual(sut.signedDistance(to: .init(x: 7, y: 5)), 2.0)
}
func testSignedDistanceTo_outside_bottomLeftEdge() {
let sut = Box(minimum: .init(x: 1, y: 2), maximum: .init(x: 5, y: 7))
XCTAssertEqual(sut.signedDistance(to: .init(x: 0, y: 0)), 2.23606797749979)
}
}
| true
|
003f004e01cd0c88accffedaf4b5091d98176b8a
|
Swift
|
henryhudson/Physics
|
/Physics/2 Basic Physics/Quantum physics.swift
|
UTF-8
| 813
| 3.203125
| 3
|
[] |
no_license
|
//
// Quantum physics.swift
// Feynman Physics
//
// Created by Henry Hudson on 15/06/2020.
// Copyright © 2020 Henry Hudson. All rights reserved.
//
import SwiftUI
private var QM = "at higher fequencyies waves behave much like particles"
private var EinstienQM = "Einstein changed the concept of space-time from a seperate concept of space and time into a combintation of the two Space-Time and then further in to a a curved space-time which represents graviation"
private var theUncertantyOfMomentumAndPosition = "deltaX deltaP >= planks constant/ 2"
struct Quantum_physics: View {
var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
}
}
struct Quantum_physics_Previews: PreviewProvider {
static var previews: some View {
Quantum_physics()
}
}
| true
|
25435bc3c2fc9c6acaadcaeb346f4d832674d6cc
|
Swift
|
darthpelo/LookAround
|
/LookAround/LookAround/Scenes/Map/VenueDetailPresenter.swift
|
UTF-8
| 1,031
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// VenueDetailPresenter.swift
// LookAround
//
// Created by Alessio Roberto on 25/06/2019.
// Copyright © 2019 Alessio Roberto. All rights reserved.
//
import Foundation
protocol VenueDetailPresentable {
func getVenueDetail(venueId: String)
}
protocol VenueDetailView {
func updateVenue(name: String, and address: String?)
}
struct VenueDetailPresenter: VenueDetailPresentable {
typealias Dependencies = HasFoursquareClientable
private var dependencies: Dependencies?
private var view: VenueDetailView?
init(view: VenueDetailView, dependencies: Dependencies = AppDependencies()) {
self.view = view
self.dependencies = dependencies
}
func getVenueDetail(venueId: String) {
dependencies?.foursquareClientable.getDetail(venueID: venueId) { detail in
if let detail = detail {
DispatchQueue.main.async {
self.view?.updateVenue(name: detail.name, and: detail.location.address)
}
} else {}
}
}
}
| true
|
b86357d7d2cfe7d287e2fed5c53d0f08d4b77c59
|
Swift
|
Zuping/LeetCode-swift
|
/LeetCode/Trie.swift
|
UTF-8
| 2,387
| 3.484375
| 3
|
[] |
no_license
|
//
// Trie.swift
// LeetCode
//
// Created by zuping on 11/11/18.
// Copyright © 2018 zuping. All rights reserved.
//
import Cocoa
class Trie: NSObject {
let root = TrieNode()
/** Initialize your data structure here. */
override init() { }
/** Inserts a word into the trie. */
func insert(_ word: String) {
let chars = word.utf16.map({ Int($0) })
var node = root
for i in 0 ..< chars.count {
var child = node.chars[chars[i]]
if child == nil {
child = TrieNode()
}
node.chars[chars[i]] = child
node = child!
}
node.end = true
}
/** Returns if the word is in the trie. */
func search(_ word: String) -> Bool {
let chars = word.utf16.map({ Int($0) })
var node = root
for i in 0 ..< chars.count {
guard let child = node.chars[chars[i]] else {
return false
}
node = child
}
return node.end
}
/** Returns if there is any word in the trie that starts with the given prefix. */
func startsWith(_ prefix: String) -> Bool {
let chars = prefix.utf16.map({ Int($0) })
var node = root
for i in 0 ..< chars.count {
guard let child = node.chars[chars[i]] else {
return false
}
node = child
}
return true
}
func fuzzySearch(_ word: String) -> Bool {
let chars = word.utf16.map({ Int($0) })
return fuzzySearchRecusion(0, chars, root)
}
func fuzzySearchRecusion( _ idx: Int, _ chars: [Int], _ node: TrieNode) -> Bool {
if idx == chars.count {
return node.end
}
if chars[idx] == 46 {
for i in 0 ..< node.chars.count {
if let child = node.chars[i] {
if fuzzySearchRecusion(idx + 1, chars, child) {
return true
}
}
}
return false
} else {
if let child = node.chars[chars[idx]] {
return fuzzySearchRecusion(idx + 1, chars, child)
} else {
return false
}
}
}
}
class TrieNode {
var end = false
var chars: [TrieNode?] = Array(repeating: nil, count: 129)
}
| true
|
8353e3128ec2c423a60e0785f9fb5333b17e682c
|
Swift
|
NatashaTheRobot/WatchOS2WatchConnectivityDemos
|
/sendMessage/WatchOS2CounterSwiftStarter/WatchOS2CounterSwift/ViewController.swift
|
UTF-8
| 1,021
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// WatchOS2CounterSwift
//
// Created by Thai, Kristina on 6/20/15.
// Copyright © 2015 Kristina Thai. All rights reserved.
//
import UIKit
import WatchConnectivity
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var mainTableView: UITableView!
var counterData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.mainTableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return counterData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CounterCell"
let cell = self.mainTableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
let counterValueString = self.counterData[indexPath.row]
cell.textLabel?.text = counterValueString
return cell
}
}
| true
|
356e6a9a4a465214527754f83fce243f41a173c4
|
Swift
|
LeonAgmonNacht/LCV-Image-Proccesing
|
/Operators.swift
|
UTF-8
| 594
| 3.3125
| 3
|
[] |
no_license
|
//
// Operators.swift
// VisionMacApp
//
// Created by לאון אגמון נכט on 31/05/2016.
// Copyright © 2016 Leon. All rights reserved.
//
import Foundation
// MARK: - Vector Operators
/**
sums the two given tuples
- returns: (first.0 + second.0, first.1 + second.1)
*/
func +(first:(Int, Int), second: (Int, Int)) -> (Int, Int) {
return (first.0 + second.0, first.1 + second.1)
}
/**
mult the two given tuples, component by scalar
- returns: (first.0*scalar, first.1*scalar)
*/
func *(first:(Int, Int), scalar: Int) -> (Int, Int) {
return (first.0*scalar, first.1*scalar)
}
| true
|
d0ed34f11b2fa5870a988007f4cc44173f2cf950
|
Swift
|
kamedono/HALTeacher
|
/HALTeacher/MainViewController.swift
|
UTF-8
| 1,965
| 2.53125
| 3
|
[] |
no_license
|
////
//// ViewController.swift
//// SlideMenuControllerSwift
////
//// Created by Yuji Hato on 12/3/14.
////
//
//import UIKit
//
//class MainViewController: UIViewController {
//
// let notificationCenter = NSNotificationCenter.defaultCenter()
//
// @IBOutlet weak var testButton: UIButton!
// @IBOutlet weak var controllerButton: ControllerBadgeButtonView!
//
// override func viewDidLoad() {
// super.viewDidLoad()
// //デリゲートの取得
// ControllerBadgeButtonController.controllerBadgeButtonControllerInstance.delegate = self.controllerButton
//
//// //学生データの初期設定
//// //学生の名前
//// let studentName:[String] = ["弓削太郎","弓削二郎","弓削三郎","弓削四郎","弓削五郎"]
//// let defaultStudentState:[Bool] = [true,false,false,true,false]
//// for(var i=0; studentName.count>i; i++){
//// StudentInfoBox.studentInfoBoxInstance.studentInfoBox.append(StudentInfo(userName: studentName[i], userID: "i"+String(i+1), idNumber: i+1, absent: defaultStudentState[i], lock:false))
//// }
// }
//
// //+をおした時
// @IBAction func plusBadgeNumber(sender: AnyObject) {
// println("+をおした")
// ControllerBadgeButtonController.controllerBadgeButtonControllerInstance.addBadgeNumber()
// rigahtTablesViewReload()
// }
//
//
//
//
// override func viewWillAppear(animated: Bool) {
// super.viewWillAppear(animated)
// }
//
// @IBAction func puchNextView(sender: AnyObject) {
// performSegueWithIdentifier("goToNextView", sender: nil)
// }
//
// override func didReceiveMemoryWarning() {
// super.didReceiveMemoryWarning()
// }
//
// /*
// 制御テーブルビューを出す
// */
// @IBAction func openRightMenu(sender: AnyObject) {
// self.toggleRight()
// }
//
//}
//
| true
|
babc1f1264b851c1583aac286d9846b15c2954ad
|
Swift
|
rendyhk/MovieGallery
|
/MovieGallery/Classes/ViewController/MovieDetailViewController.swift
|
UTF-8
| 5,809
| 2.609375
| 3
|
[] |
no_license
|
//
// MovieDetailViewController.swift
// MovieGallery
//
// Created by Rendy Hananta on 08/10/17.
// Copyright © 2017 Rendy Hananta. All rights reserved.
//
import UIKit
import Alamofire
enum MovieDetailCellType: Int {
case header = 0
case headerDetail = 1
case synopsis = 2
static let total = 3
}
class MovieDetailViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var movieID = "" {
didSet {
loadData()
}
}
var movieTitle = ""
var movieDetail: MovieDetail = MovieDetail(dictionary:[:]) {
didSet {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
private func setupView() {
title = movieTitle
tableView.register(MovieDetailHeaderTableViewCell.nib(), forCellReuseIdentifier: Constant.Identifier.Cell.movieDetailHeader)
tableView.register(MovieDetailHeaderDetailTableViewCell.nib(), forCellReuseIdentifier: Constant.Identifier.Cell.movieDetailHeaderDescription)
tableView.register(MovieDetailSynopsisTableViewCell.nib(), forCellReuseIdentifier: Constant.Identifier.Cell.movieDetailSynopsis)
tableView.tableFooterView = UIView()
}
private func loadData() {
requestDetail()
}
private func requestDetail() {
let queryItems = [URLQueryItem(name: Constant.API.RequestKey.apiKey, value: Constant.API.Value.apiKey)
]
let urlComps = NSURLComponents(string: Constant.API.URL.movieDetailURLString + movieID)
urlComps?.queryItems = queryItems
guard let movieDetailURL = urlComps?.url else {
return
}
Alamofire.request(URLRequest(url: movieDetailURL)).responseJSON(queue: DispatchQueue.global(), options: .allowFragments, completionHandler: { (response) in
switch response.result {
case .success(_):
guard let responseDictionary = response.result.value as? [String: AnyObject] else {
return
}
print("xxx \(responseDictionary)")
self.movieDetail = MovieDetail(dictionary: responseDictionary)
case .failure(_):
return
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK: UITableViewDataSource
extension MovieDetailViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return MovieDetailCellType.total
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell.init(style: .default, reuseIdentifier: "defaultCell")
switch indexPath.row {
case MovieDetailCellType.header.rawValue:
let cell = tableView.dequeueReusableCell(withIdentifier: Constant.Identifier.Cell.movieDetailHeader) as! MovieDetailHeaderTableViewCell
cell.imageURLString = self.movieDetail.posterURL
return cell
case MovieDetailCellType.headerDetail.rawValue:
let cell = tableView.dequeueReusableCell(withIdentifier: Constant.Identifier.Cell.movieDetailHeaderDescription) as! MovieDetailHeaderDetailTableViewCell
cell.duration = "\(self.movieDetail.runtime) minutes"
cell.title = movieDetail.title
cell.popularity = movieDetail.voteAverage
cell.vote = movieDetail.voteAverage
cell.languages = movieDetail.spokenLanguage.map { lang in
return lang.name
}
cell.genres = movieDetail.genres.map { genre in
return genre.name
}
cell.delegate = self
return cell
case MovieDetailCellType.synopsis.rawValue:
let cell = tableView.dequeueReusableCell(withIdentifier: Constant.Identifier.Cell.movieDetailSynopsis) as! MovieDetailSynopsisTableViewCell
cell.overview = movieDetail.overview
return cell
default:
break
}
return cell
}
}
//MARK: UITableViewDelegate
extension MovieDetailViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.row {
case MovieDetailCellType.header.rawValue:
return 200
case MovieDetailCellType.headerDetail.rawValue:
return 130
case MovieDetailCellType.synopsis.rawValue:
return UITableViewAutomaticDimension
default:
break
}
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.row {
case MovieDetailCellType.header.rawValue:
return 200
case MovieDetailCellType.headerDetail.rawValue:
return 130
case MovieDetailCellType.synopsis.rawValue:
return 100
default:
break
}
return 44
}
}
//MARK: MovieDetailHeaderDetailTableViewCellDelegate
extension MovieDetailViewController: MovieDetailHeaderDetailTableViewCellDelegate {
func movieDetailHeaderDetailTableViewCell(cell: MovieDetailHeaderDetailTableViewCell, didTap sender: UIButton) {
let webVC = WebViewController(nibName: "WebViewController", bundle: nil)
navigationController?.pushViewController(webVC, animated: true)
}
}
| true
|
fa15bae60036b5c6bd63e2d938ed8e3812563a83
|
Swift
|
mrainka/post-reader
|
/PostReader/Models/Page.swift
|
UTF-8
| 1,340
| 3.25
| 3
|
[] |
no_license
|
//
// Page.swift
// PostReader
//
// Created by Marcin Rainka @Home on 23/03/2019.
// Copyright © 2019 Marcin Rainka. All rights reserved.
//
private extension KeyedDecodingContainer {
private func conversionError(
of inputType: Any.Type,
to outputType: Any.Type,
forKey key: KeyedDecodingContainer.Key)
-> Error
{
let description = "Failed to convert \(String(describing: inputType)) to \(String(describing: outputType))."
return DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: description)
}
func decode(_ type: String.Type, forKey key: KeyedDecodingContainer.Key) throws -> Int {
let input = try decode(type, forKey: key) as String
guard let output = Int(input) else { throw conversionError(of: type, to: Int.self, forKey: key) }
return output
}
}
struct Page {
private enum CodingKeys: String, CodingKey {
case limit, offset
}
var isFirst: Bool { return offset == 0 }
let limit: Int
let offset: Int
}
extension Page: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
limit = try container.decode(String.self, forKey: .limit)
offset = try container.decode(String.self, forKey: .offset)
}
}
| true
|
f717e15b6a6670a9d94f1183ceb74ba6fc9336fd
|
Swift
|
ramcneal13/SecondIOEngine
|
/SecondIOEngine/ParseINI.swift
|
UTF-8
| 3,518
| 2.703125
| 3
|
[] |
no_license
|
//
// Config.swift
// FirstIOEngine
//
// Created by Richard McNeal on 11/2/17.
// Copyright © 2017 Richard McNeal. All rights reserved.
//
import Foundation
import Cocoa
typealias sectionData = [String:String]
extension UInt8 {
var char: Character {
return Character(UnicodeScalar(self))
}
}
public class ParseINIConfig {
private var fileName:String = ""
private var handle:FileHandle?
private var currentLine:String = ""
private var configStrings:[String]
private var sections:[String:sectionData] = [:]
private var verbose = false
private let GlobalSection = "global"
init(_ file:URL) throws {
configStrings = [String]()
do {
try handle = FileHandle(forReadingFrom: file)
} catch {
throw FileErrors.openFailure(name: "Oops, failed to open FileHandle for '\(file)'", error_num: 0)
}
}
private func appendToCurrent(b:UInt8) {
if b.char == "\n" {
configStrings.append(currentLine)
currentLine.removeAll()
} else {
currentLine.append(b.char)
}
}
private func boundedName(str:String, beg:String, end:String) -> String? {
if str.hasPrefix(beg) && str.hasSuffix(end) {
let startIdx = str.index(str.startIndex, offsetBy: 1)
let endIdx = str.index(str.endIndex, offsetBy: -1)
let strRange = Range(uncheckedBounds: (lower: startIdx, upper: endIdx))
return String(str[strRange])
} else {
return nil
}
}
func enableParseDisplay() { verbose = true }
func isValid() -> Bool { return handle != nil }
func parse() -> Bool {
if handle == nil {
return false
}
let d = handle?.readDataToEndOfFile()
var workingSection = "FUBAR"
d?.forEach { byte in appendToCurrent(b: byte) }
if currentLine.count != 0 {
configStrings.append(currentLine)
}
for l in configStrings {
if let sec = boundedName(str: l, beg: "[", end: "]") {
switch sec {
case GlobalSection:
workingSection = sec
default:
let possibleJob = sec.split(separator: " ")
if possibleJob.count == 2 {
if let jobSection = boundedName(str: String(possibleJob[1]),
beg: "\"", end: "\"") {
workingSection = jobSection
} else {
return false
}
} else {
return false
}
}
sections[workingSection] = sectionData()
} else if l != "" {
let opts = l.split(separator: "=")
if opts.count == 2 {
sections[workingSection]![String(opts[0])] = String(opts[1])
} else {
sections[workingSection]![String(opts[0])] = "true"
}
}
}
if verbose {
print("---- Dumping results of config ----")
for (k, v) in sections {
print("Section: \(k)")
for (d, v1) in v {
print(" \(d)" + " = " + "\(v1)")
}
}
}
return true
}
func setParam(_ section:String, _ param:String, process: ((String) -> Void)) {
if let p = requestParam(section: section, param: param) {
process(p)
}
}
private func requestParam(section:String, param:String) -> String? {
if let s = sections[section] {
if let p = s[param] {
return p
} else {
// If the request isn't in the current section see
// if the global section has the parameter set and if
// so return that one.
if let p = sections[GlobalSection]![param] {
return p
}
}
}
return nil
}
func jobNameValid(_ name:String) -> Bool {
if sections[name] != nil {
return true
} else {
return false
}
}
func requestJobs() -> [String] {
var rval = [String]()
for (k, _) in sections {
if k != GlobalSection {
rval.append(k)
}
}
return rval
}
}
| true
|
ab805ef79e10946cc3ee8f5d81c8edb5d75262f4
|
Swift
|
mrainka/japanese-numbers
|
/JapaneseNumbers/UserInterface/Views/JapaneseNumbers/JapaneseNumbersTableViewDataSourceAndDelegate.swift
|
UTF-8
| 1,789
| 2.90625
| 3
|
[] |
no_license
|
//
// JapaneseNumbersTableViewDataSourceAndDelegate.swift
// JapaneseNumbers
//
// Created by Marcin Rainka on 23/06/2018.
// Copyright © 2018 Marcin Rainka. All rights reserved.
//
import UIKit
final class JapaneseNumbersTableViewDataSourceAndDelegate: NSObject {
private(set) var model: JapaneseNumbersViewModel?
}
extension JapaneseNumbersTableViewDataSourceAndDelegate: ModelConfigurable {
func configure(with model: JapaneseNumbersViewModel) {
self.model = model
}
}
extension JapaneseNumbersTableViewDataSourceAndDelegate: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
model?.selectItem(forCellAt: indexPath)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let item = model?.item(forCellAt: indexPath) else { return }
cell.configureIfPossible(with: item)
}
// MARK: Highlighting Row
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.isHighlighted = true
}
func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.isHighlighted = false
}
}
extension JapaneseNumbersTableViewDataSourceAndDelegate: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let item = model?.item(forCellAt: indexPath) else { return .init() }
return tableView.dequeueReusableCell(with: item, for: indexPath)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model?.numberOfItems ?? 0
}
}
| true
|
ff69066e82f05550e20ab9835e2dd43e79d77f6d
|
Swift
|
robinrob/swift
|
/practice/practice/Combinations.swift
|
UTF-8
| 1,507
| 3.90625
| 4
|
[] |
no_license
|
//
// Combinations.swift
// practice
//
// Created by Robin Smith on 03/12/2017.
// Copyright © 2017 Robin Smith. All rights reserved.
//
import Foundation
class Combinations {
static func multiplyIntArrays() {
let A = Array(1...4)
let B = Array(5...8)
let C = Array(9...12)
let result = ArrayMultiplier<Int>().multiply([A, B, C])
print(result)
}
static func multiplyStringArrays() {
let A = ["A", "B", "C", "D"]
let B = ["E", "F", "G", "H"]
let C = ["I", "J", "k", "L"]
let result = ArrayMultiplier<String>().multiply([A, B, C])
print(result)
}
static func run() {
multiplyIntArrays()
print()
multiplyStringArrays()
}
}
class ArrayMultiplier<T> {
func multiply(_ listOfArrays: [[T]]) -> [[T]] {
var result: [[T]] = []
for array in listOfArrays {
result = self.multiply(listOfArrays: result, by: array)
}
return result
}
private func multiply(listOfArrays: [[T]], by multiplyingArray: [T]) -> [[T]] {
var result: [[T]] = []
if listOfArrays.count > 0 {
for array in listOfArrays {
for item in multiplyingArray {
result.append(array + [item])
}
}
} else {
for item in multiplyingArray {
result.append([item])
}
}
return result
}
}
| true
|
214465d45b452b2d07818a763888a565e154cd89
|
Swift
|
adamkaplan/swifter
|
/Swifter/Tree.swift
|
UTF-8
| 2,569
| 3.3125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Tree.swift
// Swifter
//
// Created by Daniel Hanggi on 7/22/14.
// Copyright (c) 2014 Yahoo!. All rights reserved.
//
import Foundation
/** A generic, immutable binary tree. */
class Tree<T> {
func fold<L>(leafValue: L, f: (L,T,L) -> L) -> L {
return leafValue
}
func node() -> T? {
return nil
}
func isEmpty() -> Bool {
return self.fold(true) {
(_, _, _) -> Bool in
return false
}
}
func map<S>(f: (T) -> S) -> Tree<S> {
return self.fold(Leaf()) {
(left: Tree<S>, node: T, right: Tree<S>) -> Tree<S> in
return Node(left, f(node), right)
}
}
func contains(value: T, eq: ((T,T) -> Bool)) -> Bool {
return self.fold(false) {
(left: Bool, node: T, right: Bool) -> Bool in
return left || eq(node, value) || right
}
}
func count() -> Int {
return self.fold(0) {
(left: Int, _, right: Int) -> Int in
return left + 1 + right
}
}
func equal(other: Tree<T>, eq: (T,T) -> Bool) -> Bool {
return other.isEmpty()
}
func leftSubtree() -> Tree<T>? {
return nil
}
func rightSubtree() -> Tree<T>? {
return nil
}
}
class Leaf<T> : Tree<T> {}
class Node<T> : Tree<T> {
typealias Data = (Tree<T>, T, Tree<T>)
let data: Data
init(_ left: Tree<T>, _ node: T, _ right: Tree<T>) {
self.data = (left, node, right)
}
override func fold<L>(leafValue: L, f: (L,T,L) -> L) -> L {
let (left, node, right) = self.data
return f(left.fold(leafValue, f), node, right.fold(leafValue, f))
}
override func node() -> T? {
let (_, node, _) = self.data
return node
}
override func equal(other: Tree<T>, eq: (T,T) -> Bool) -> Bool {
let (sLeft, sNode, sRight) = self.data
if let (oLeft, oNode, oRight) = (other as? Node)?.data {
return sLeft.equal(oLeft, eq) && eq(sNode, oNode) && sRight.equal(oRight, eq)
} else {
return false
}
}
override func leftSubtree() -> Tree<T>? {
let (left, _, _) = self.data
return left
}
override func rightSubtree() -> Tree<T>? {
let (_, _, right) = self.data
return right
}
}
extension Tree : Printable {
var description: String {
get {
return self.fold(".") { "[\($0)^\($1)^\($2)]" }
}
}
}
| true
|
511c6626a65354532f5dfcf5b870e5a830df2f5d
|
Swift
|
yunchiri/SpyLanguageTraining
|
/SpyLanguageTraining/QuizCollectionViewController.swift
|
UTF-8
| 1,840
| 2.84375
| 3
|
[] |
no_license
|
//
// QuizCollectionViewController.swift
// SpyLanguageTraining
//
// Created by yunchiri on 2016. 5. 25..
// Copyright © 2016년 youngchill. All rights reserved.
//
import UIKit
import TisprCardStack
class QuizCollectionViewController: TisprCardStackViewController,TisprCardStackViewControllerDelegate {
private var countOfCards: Int = 60
override func viewDidLoad() {
super.viewDidLoad()
//set animation speed
setAnimationSpeed(5)
//set size of cards
let size = CGSizeMake(view.bounds.width - 40, view.bounds.height/2)
setCardSize(size)
cardStackDelegate = self
//configuration of stacks
layout.topStackMaximumSize = 40
layout.bottomStackMaximumSize = 10
layout.bottomStackCardHeight = 45
}
//method to add new card
@IBAction func addNewCards(sender: AnyObject) {
countOfCards += 1
newCardWasAdded()
}
override func numberOfCards() -> Int {
return countOfCards
}
override func card(collectionView: UICollectionView, cardForItemAtIndexPath indexPath: NSIndexPath) -> TisprCardStackViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("QuizCellIdentifier", forIndexPath: indexPath) as! QuizCell
// cell.backgroundColor = colors[indexPath.item % colors.count]
// cell.text.text = "Card - \(indexPath.item)"
return cell
}
@IBAction func moveUP(sender: AnyObject) {
// moveCardUp()
}
@IBAction func moveCardDown(sender: AnyObject) {
moveCardDown()
}
func cardDidChangeState(cardIndex: Int) {
print("card with index - \(cardIndex) changed position")
}
}
| true
|
f8a73793f94d253c31048e2342a791224b62c228
|
Swift
|
apphud/Apphud-App
|
/ApphudIntentHandler/IntentHandler.swift
|
UTF-8
| 1,195
| 2.5625
| 3
|
[] |
no_license
|
//
// IntentHandler.swift
// ApphudIntentHandler
//
// Created by Alexander Selivanov on 06.10.2020.
//
import Intents
class IntentHandler: INExtension {
override func handler(for intent: INIntent) -> Any {
switch intent {
case is ConfigurationIntent:
return Handler()
default:
return self
}
}
}
class BaseIntentHandler: NSObject {
func prepareAppsObjects() -> INObjectCollection<IntentApp>? {
let apps = AppsManager.shared.getIntentApps()
let intentApps = apps.map({ (app) -> IntentApp in
app.intentApp
})
return INObjectCollection(items: intentApps)
}
@objc(defaultAppForConfiguration:) func defaultApp(for intent: ConfigurationIntent) -> IntentApp? {
guard let app = SessionStore().currentApp else { return nil }
return IntentApp(identifier: app.id, display: app.name)
}
}
class Handler: BaseIntentHandler, ConfigurationIntentHandling {
func provideAppOptionsCollection(for intent: ConfigurationIntent, with completion: @escaping (INObjectCollection<IntentApp>?, Error?) -> Void) {
completion(prepareAppsObjects(), nil)
}
}
| true
|
239ae9461145140c792e6e2b91d937c07214f2da
|
Swift
|
joaoipiraja/FAMA-App-IOS
|
/FAMAApp/Model/Artist.swift
|
UTF-8
| 318
| 2.84375
| 3
|
[] |
no_license
|
//
// Artist.swift
// FAMAApp
//
// Created by João Pedro Aragão on 26/04/19.
// Copyright © 2019 FAMA. All rights reserved.
//
import Foundation
struct Artist: Codable {
var name: String
var number: Int
var isPresenting: Bool
var eventName: String {
return "Atração \(number) - \(name)"
}
}
| true
|
2d904899131b1a4af319023ff8d2ddca52cd4616
|
Swift
|
hubertdaryanto/RollingKnight
|
/Rolling Knight/Scenes/MenuScene.swift
|
UTF-8
| 1,528
| 3
| 3
|
[] |
no_license
|
//
// MenuScene.swift
// Rolling Knight
//
// Created by Hubert Daryanto on 12/06/20.
// Copyright © 2020 Hubert Daryanto. All rights reserved.
//
import UIKit
import GameplayKit
class MenuScene: SKScene {
let homeLabel = SKLabelNode(text: "You are in home!. Tap to play!")
override func didMove(to view: SKView) {
backgroundColor = UIColor.yellow
addLabel()
}
func addLabel()
{
homeLabel.fontSize = 50
homeLabel.fontColor = UIColor.black
homeLabel.position = CGPoint(x: frame.midX, y: frame.midY)
addChild(homeLabel)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
if let node = self.nodes(at: touch.location(in: self)).first as? SKSpriteNode {
if node == homeLabel
{
playTheGame()
}
}
playTheGame()
}
func playTheGame()
{
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
}
| true
|
ca132ebc240aa5aef2bcb1d2a43a6893e8c0af9f
|
Swift
|
godrm/SidebarProject
|
/SidebarProject/SecondViewController.swift
|
UTF-8
| 2,789
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// OtherViewController.swift
// PRBoard
//
// Created by JK on 2021/02/18.
//
import UIKit
class SecondViewController: UICollectionViewController {
static let storyboardID = "SecondView"
static func instantiateFromStoryboard() -> SecondViewController? {
let storyboard = UIStoryboard(name: "Main", bundle: .main)
return storyboard.instantiateViewController(identifier: storyboardID) as? SecondViewController
}
var objects = [Any]()
override func viewDidLoad() {
super.viewDidLoad()
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:)))
navigationItem.rightBarButtonItem = addButton
}
override func viewWillAppear(_ animated: Bool) {
clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
@objc
func insertNewObject(_ sender: Any) {
objects.insert(NSDate(), at: 0)
let indexPath = IndexPath(row: 0, section: 0)
collectionView.insertItems(at: [indexPath])
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = collectionView.indexPathsForSelectedItems?.first {
let object = objects[indexPath.row] as! NSDate
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return objects.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TitleViewCell.reuseIdentifier, for: indexPath) as! TitleViewCell
let object = objects[indexPath.row] as! NSDate
cell.titleLabel.text = object.description
return cell
}
}
extension SecondViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 365, height: 55)
}
}
| true
|
aa72d8715102c55d85438611287926584c4a1475
|
Swift
|
Asavarkhul/DeezerExercice
|
/DeezerExerciceTests/Artists/Models/AlbumTests.swift
|
UTF-8
| 634
| 2.59375
| 3
|
[] |
no_license
|
//
// AlbumTests.swift
// DeezerExerciceTests
//
// Created by Bertrand BLOC'H on 22/05/2019.
// Copyright © 2019 bblch. All rights reserved.
//
import XCTest
@testable import DeezerExercice
final class AlbumTests: XCTestCase {
func testGivenATrack_WhenInitializedWithAnAlbumTrackResponse_ItsCorrectlyInitialized() {
let track = Track(position: 1, title: "Europa", previewURLString: "url")
let response = AlbumTrackResponse(data: [track])
let album = Album(title: "Santana", albumTrackResponse: response)
XCTAssertEqual(album.title, "Santana")
XCTAssertEqual(album.tracks.count, 1)
}
}
| true
|
28d63c8e4400b8246b3f9450c75cbbc2db31fabd
|
Swift
|
mohsinalimat/ZVRefreshing
|
/ZVRefreshing/Footer/ZVRefreshFooter.swift
|
UTF-8
| 1,573
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// ZRefreshFooter.swift
//
// Created by ZhangZZZZ on 16/3/31.
// Copyright © 2016年 ZhangZZZZ. All rights reserved.
//
import UIKit
open class ZVRefreshFooter: ZVRefreshComponent {
/// 忽略的UIScrollView.contentInset.bottom
public var ignoredScrollViewContentInsetBottom: CGFloat = 0.0
/// 是否自动隐藏
public var isAutomaticallyHidden: Bool = true
override open func willMove(toSuperview newSuperview: UIView?) {
// 判断superview是否为nil
guard let superview = newSuperview as? UIScrollView else { return }
super.willMove(toSuperview: superview)
if superview.isKind(of: UITableView.classForCoder()) ||
superview.isKind(of: UICollectionView.classForCoder()) {
superview.reloadDataHandler = { totalCount in
if self.isAutomaticallyHidden {
self.isHidden = (totalCount == 0)
}
}
}
}
/// 设置组件是否为RefreshState.noMoreData
public var isNoMoreData: Bool = false {
didSet {
if self.isNoMoreData {
self.state = .noMoreData
} else {
self.state = .idle
}
}
}
}
extension ZVRefreshFooter {
public func endRefreshingWithNoMoreData() {
self.state = .noMoreData
}
public func resetNoMoreData() {
self.state = .idle
}
}
extension ZVRefreshFooter {
override open func prepare() {
self.height = Component.Footer.height
}
}
| true
|
6ce58b22efebfa5a424153e257c6855291542c1c
|
Swift
|
cocoabagel/BitriseDemo
|
/BitriseDemo/CoreDataStack.swift
|
UTF-8
| 4,258
| 2.546875
| 3
|
[] |
no_license
|
//
// CoreDataStack.swift
// BitriseDemo
//
// Created by Kazutoshi Baba on 1/12/16.
// Copyright © 2016 Kazutoshi Baba. All rights reserved.
//
import Foundation
import CoreData
open class CoreDataStack {
public init() {
}
deinit {
NotificationCenter.default.removeObserver(self)
}
public var managedObjectModel: NSManagedObjectModel = {
var modelPath = Bundle.main.path(forResource: "BitriseDemo", ofType: "momd")
var modelURL = URL(fileURLWithPath: modelPath!)
var model = NSManagedObjectModel(contentsOf: modelURL)!
return model
}()
var applicationDocumentsDirectory: URL = {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1] as URL
}()
public lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
print("Providing SQLite persistent store coordinator")
let url = self.applicationDocumentsDirectory.appendingPathComponent("BitriseDemo.sqlite")
var options = [NSInferMappingModelAutomaticallyOption: true, NSMigratePersistentStoresAutomaticallyOption: true]
var psc = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
do {
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName:nil, at: url, options: options)
} catch {
print("Error when creating persistent store \(error)")
fatalError()
}
return psc
}()
public lazy var rootContext: NSManagedObjectContext = {
let context: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
context.persistentStoreCoordinator = self.persistentStoreCoordinator
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return context
}()
public lazy var mainContext: NSManagedObjectContext = {
let mainContext: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
mainContext.parent = self.rootContext
mainContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
NotificationCenter.default.addObserver(self, selector: #selector(CoreDataStack.mainContextDidSave(_:)), name: NSNotification.Name.NSManagedObjectContextDidSave, object: mainContext)
return mainContext
}()
public func newDerivedContext() -> NSManagedObjectContext {
let context: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
context.parent = self.mainContext
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return context
}
public func saveContext(_ context: NSManagedObjectContext) {
if context.parent === self.mainContext {
self.saveDerivedContext(context)
return
}
context.perform() {
do {
try context.obtainPermanentIDs(for: Array(context.insertedObjects))
} catch {
print("Error obtaining permanent IDs for \(context.insertedObjects), \(error)")
}
do {
try context.save()
} catch {
print("Unresolved core data error: \(error)")
abort()
}
}
}
public func saveDerivedContext(_ context: NSManagedObjectContext) {
context.perform() {
do {
try context.obtainPermanentIDs(for: Array(context.insertedObjects))
} catch {
print("Error obtaining permanent IDs for \(context.insertedObjects), \(error)")
}
do {
try context.save()
} catch {
print("Unresolved core data error: \(error)")
abort()
}
self.saveContext(self.mainContext)
}
}
@objc func mainContextDidSave(_ notification: Notification) {
self.saveContext(self.rootContext)
}
}
| true
|
df91ce6b593a9d79d3504f6fae5241eefb013428
|
Swift
|
dinotrnka/swiftui-blueprint-template
|
/Blueprint/Code/Utilities/EnvironmentObjects/FeatureToggles.swift
|
UTF-8
| 1,576
| 3.203125
| 3
|
[] |
no_license
|
import SwiftUI
enum FeatureToggle: String, CaseIterable {
case redBackground = "Red Background"
case goWild = "Go Wild"
case bossMode = "Boss Mode"
}
class FeatureToggles: ObservableObject {
static let shared = FeatureToggles()
@Published var enabled: [FeatureToggle] = []
var buttons: [ActionSheet.Button] {
var buttons = FeatureToggle.allCases.map { featureToggle in
Alert.Button.default(
Text(FeatureToggles.shared.presentable(featureToggle: featureToggle))) {
FeatureToggles.shared.toggle(featureToggle: featureToggle)
}
}
buttons.append(Alert.Button.cancel())
return buttons
}
func presentable(featureToggle: FeatureToggle) -> String {
return "\(featureToggle.rawValue): \(isOn(featureToggle: featureToggle) ? "On" : "Off")"
}
func isOn(featureToggle: FeatureToggle) -> Bool {
return enabled.contains(featureToggle)
}
func toggle(featureToggle: FeatureToggle) {
if isOn(featureToggle: featureToggle) {
setOff(featureToggle: featureToggle)
} else {
setOn(featureToggle: featureToggle)
}
}
func setOn(featureToggle: FeatureToggle) {
guard !isOn(featureToggle: featureToggle) else {
return
}
enabled.append(featureToggle)
}
func setOff(featureToggle: FeatureToggle) {
guard isOn(featureToggle: featureToggle) else {
return
}
enabled.removeAll { $0 == featureToggle }
}
}
| true
|
e83fe1d016e4e47647cd945121cac1dbc6611b0e
|
Swift
|
inSummertime/SExtensions
|
/Tests/Swift/String/StringWordsTests.swift
|
UTF-8
| 2,495
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
//
// StringWordsTests.swift
// SExtensionsTests
//
// Created by Ray on 2018/5/30.
// Copyright © 2018年 Ray. All rights reserved.
//
@testable import SExtensions
import XCTest
final class StringWordsTests: XCTestCase {
func testWords() {
XCTAssertEqual("hi".words, ["hi"])
XCTAssertEqual("hiThere!".words, ["hi", "there!"])
XCTAssertEqual("hi There!".words, ["hi", "there!"])
XCTAssertEqual("hi There!*2".words, ["hi", "there!*2"])
XCTAssertEqual("2 hi There!".words, ["2", "hi", "there!"])
XCTAssertEqual("hi_there".words, ["hi_there"])
XCTAssertEqual("hi-there".words, ["hi-there"])
XCTAssertEqual("hi-There".words, ["hi-", "there"])
XCTAssertEqual("".words, [])
XCTAssertEqual(" \n".words, [])
XCTAssertEqual("hi\nthere".words, ["hi", "there"])
}
func testWordCount() {
XCTAssertEqual("hi".wordCount, 1)
XCTAssertEqual("hiThere!".wordCount, 2)
XCTAssertEqual("hi There!".wordCount, 2)
XCTAssertEqual("hi There!*2".wordCount, 2)
XCTAssertEqual("2 hi There!".wordCount, 3)
XCTAssertEqual("hi_there".wordCount, 1)
XCTAssertEqual("hi-there".wordCount, 1)
XCTAssertEqual("hi-There".wordCount, 2)
XCTAssertEqual("".wordCount, 0)
XCTAssertEqual(" \n".wordCount, 0)
XCTAssertEqual("hi\nthere".wordCount, 2)
}
func testWordsReversed() {
XCTAssertEqual("Hello world !".wordsReversed, "! world Hello")
XCTAssertEqual("hello".wordsReversed, "hello")
XCTAssertEqual("".wordsReversed, "")
}
func testIsAnagram() {
XCTAssertTrue("abc".isAnagram(with: "acb"))
XCTAssertFalse("ab".isAnagram(with: "a"))
XCTAssertTrue("a".isAnagram(with: "a"))
XCTAssertTrue("".isAnagram(with: ""))
XCTAssertTrue(" ".isAnagram(with: " "))
}
func testLongestPalindrome() {
XCTAssertEqual("".longestPalindrome, "")
XCTAssertEqual("a".longestPalindrome, "a")
XCTAssertEqual("ab".longestPalindrome, "b")
XCTAssertEqual("aa".longestPalindrome, "aa")
XCTAssertEqual("aba".longestPalindrome, "aba")
XCTAssertEqual("abab".longestPalindrome, "bab")
XCTAssertEqual("ababc".longestPalindrome, "bab")
XCTAssertEqual("ababa".longestPalindrome, "ababa")
XCTAssertEqual("abaabc".longestPalindrome, "baab")
XCTAssertEqual("abaaba".longestPalindrome, "abaaba")
}
}
| true
|
1506144638a013c743da79d3679229d5c16ed215
|
Swift
|
anar-d/Accommodation
|
/Accommodation/Services/Geocoder.swift
|
UTF-8
| 1,050
| 2.6875
| 3
|
[] |
no_license
|
//
// Geocoder.swift
// Accommodation
//
// Created by Anar on 16.08.2020.
// Copyright © 2020 Commodo. All rights reserved.
//
import YandexMapKit
class Geocoder {
static func start(for point: YMKPoint, closure: @escaping (String) -> ()) {
guard let url = URL(string: "https://geocode-maps.yandex.ru/1.x/?apikey=\(YANDEX_GEOCODER_KEY)&format=json&geocode=\(point.longitude),\(point.latitude)") else { return }
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let data = data,
let yandexGeoResponse = try? JSONDecoder().decode(YandexGeoResponse.self, from: data)
else { return }
if let response = yandexGeoResponse.response, let pointName = response.GeoObjectCollection.featureMember.first {
closure(pointName.debugDescription)
Accommodation.location = MapPoint(latitude: point.latitude,
longitude: point.longitude)
} else {
closure(#"¯\_(ツ)_/¯"#)
}
}.resume()
}
}
| true
|
9bcd27c68cfb431305773954115cdd84f7b37836
|
Swift
|
danielaparra/ios-sprint8-challenge
|
/Message BoardUITests/ThreadDetailTableViewControllerPage.swift
|
UTF-8
| 1,966
| 2.53125
| 3
|
[] |
no_license
|
//
// ThreadDetailTableViewControllerPage.swift
// Message BoardUITests
//
// Created by Daniela Parra on 10/19/18.
// Copyright © 2018 Lambda School. All rights reserved.
//
import XCTest
struct ThreadDetailTableViewControllerPage: TestPage {
// MARK: - Interactions
// Go back to threads TVC
@discardableResult func goBackToThreads() -> ThreadsTableViewControllerPage {
backButtonToThreads.tap()
return threadsTableViewControllerPage
}
// Click add button
@discardableResult func clickAddButton() -> MessageDetailViewControllerPage {
addMessageButton.tap()
return MessageDetailViewControllerPage(testCase: self.testCase, threadDetailTableViewControllerPage: self)
}
// MARK: - Verifications
// See messages
@discardableResult func verifyMessageExists(at index: Int) -> ThreadDetailTableViewControllerPage {
testCase.expect(true: cell(0).isHittable, file: #file, line: #line)
return self
}
// Arrived to correct thread
@discardableResult func atCorrectThread(of name: String) -> ThreadDetailTableViewControllerPage {
let navigationTitle = titleFor(threadName: name)
testCase.expect(exists: navigationTitle, file: #file, line: #line)
return self
}
// MARK: - Elements
// Title
func titleFor(threadName: String) -> XCUIElement {
return app.navigationBars["\(threadName)"]
}
// Cell at index by
func cell(_ index: Int) -> XCUIElement {
return app.tables.cells.element(boundBy: index)
}
// Back button
var backButtonToThreads: XCUIElement {
return app.navigationBars.buttons["λ Message Board"]
}
// Add button
var addMessageButton: XCUIElement {
return app.navigationBars.buttons["Add"]
}
var testCase: XCTestCase
var threadsTableViewControllerPage: ThreadsTableViewControllerPage
}
| true
|
d444a23c48a328575deb6c14048f759523cef766
|
Swift
|
DanielHJA/Working-PDF-Context
|
/Uiviewswitch/AnimationManager.swift
|
UTF-8
| 896
| 2.6875
| 3
|
[] |
no_license
|
//
// AnimationManager.swift
// Uiviewswitch
//
// Created by Daniel Hjärtström on 2016-11-30.
// Copyright © 2016 Daniel Hjärtström. All rights reserved.
//
import UIKit
class AnimationManager: NSObject {
func animate(view: UIView, time: Double, animateTo: CGFloat, completion: @escaping ()->()) {
UIView.animate(withDuration: time, animations: {
view.center.x = animateTo
}) { (Bool) in
completion()
}
}
func animateWithSpring(view: UIView, time: Double, animateTo: CGFloat){
UIView.animate(withDuration: time, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: [], animations: {
view.center.x = animateTo
}, completion: { (Bool) in
})
}
}
| true
|
56aa9038ec1a90fe50a0601b1919feb833ad6b8c
|
Swift
|
ipran/HelloMindvalley
|
/Demo/MindValleyDemoApp/MindValleyDemoApp/Source/ViewControllers/ViewController.swift
|
UTF-8
| 2,316
| 2.65625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// MindValleyDemoApp
//
// Created by Pranil on 2/12/19.
// Copyright © 2019 pranil. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: - Outlet Connection
@IBOutlet weak var tableView: UITableView!
// Declarations
var listOfData: [ServerResponse] = []
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Register NoDataTableViewCell Xib file
self.tableView.register(UINib(nibName: "NoDataTableViewCell", bundle: nil), forCellReuseIdentifier: "NoDataTableViewCell")
showActivityIndicator()
configureView()
loadData()
}
}
// MARK: - General Functions
extension ViewController {
func loadData() {
// Load data from server
DataManager.shared.fetchServerData { (status, message, serverResponse) in
if status {
self.listOfData = serverResponse
self.refresh()
}
}
}
func configureView() {
navigationItem.title = "Users"
}
func refresh() {
hideActivityIndicator()
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
// MARK: - Tableview Related
extension ViewController: UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if listOfData.count > 0 {
return listOfData.count
}
else {
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if listOfData.count > 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: HomeTableViewCell.identifier) as! HomeTableViewCell
var user = UserModel()
user.name = listOfData[indexPath.row].user?.name
user.id = listOfData[indexPath.row].user?.id
user.profile_image = listOfData[indexPath.row].user?.profile_image
cell.data = user
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: NoDataTableViewCell.identifier) as! NoDataTableViewCell
return cell
}
}
}
| true
|
8115491e79c851c458ef314e9bcfda9b46406d2b
|
Swift
|
Hariiiiii/Behavior-Therapy
|
/hsh/ComplianceTraining.swift
|
UTF-8
| 2,567
| 2.71875
| 3
|
[] |
no_license
|
//
// ComplianceTraining.swift
// hsh
//
// Created by Harinarayanan Janardhanan on 4/20/18.
// Copyright © 2018 Harinarayanan Janardhanan. All rights reserved.
//
import UIKit
class ComplianceTraining: UIViewController {
@IBOutlet weak var content: UITextView!
var archiveFlag:Int!
override func viewDidLoad() {
super.viewDidLoad()
//Dismiss Keyboard Tap gesture
let tap = UITapGestureRecognizer(target: self.view, action: Selector("endEditing:"))
tap.cancelsTouchesInView = false
self.view.addGestureRecognizer(tap)
let contentText = "The goal for this week is to get in the habit of giving effective commands, and get your child in the habit of following them.Your child needs frequent, repeated opportunities to earn your praise for completing instructions.Praise makes it more likely that your child will want to do these instructions!.To give your child a chance to practice, we encourage you to engage in a “compliance trial” each day.Select a 15-20-minute interval each day, and deliver up to five clear, simple (single-step) instructions.For these practice times, select easy commands they are likely to follow, so that there is a greater likelihood you will be able to praise them.Good example commands for compliance trials might include.• Please hand me the remote.• Alex, I dropped my pen. Please hand me the pen.• Amy, I need you to flip on the fan.• Remember to praise as soon as your child starts moving to complete the task, and again when they complete the task"
var alignedContent = contentText.replacingOccurrences(of: ".", with: "\n")
alignedContent = alignedContent.replacingOccurrences(of: ":", with: "\n \n")
content.text = alignedContent
content.sizeToFit()
content.isScrollEnabled = false
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "complainceData") {
let vc = segue.destination as! ComplianceTrainingLog
vc.archiveFlag = 1
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
5d234761f8e302f00fa504f710e6cd7f8ad0caf0
|
Swift
|
dronusoid/my-favorite-movies
|
/MyFavoriteMovies/FavoriteMovieCell.swift
|
UTF-8
| 1,837
| 2.734375
| 3
|
[] |
no_license
|
//
// movieCell.swift
// MyFavoriteMovies
//
// Created by Андрей Тиньков on 11.03.17.
// Copyright © 2017 Udacity. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class FavoriteMovieCell: UITableViewCell {
static let identifier = "FavoriteTableViewCell"
let disposeBag = DisposeBag()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
func configure(with movie: Movie) {
//Cell configuration
self.textLabel?.text = movie.title
loadMoviePoster(from: movie.posterPath)
}
private func loadMoviePoster(from posterPath: String?) {
// Get the poster image, then populate the image view
// check that posterPath is not nil
guard let posterPath = posterPath, posterPath != "" else {
print("Poster path is empty")
return
}
/* 1. Set the parameters */
// There are none...
/* 2. Build the URL */
let baseURL = URL(string: appDelegate.config.baseImageURLString)!
let url = baseURL.appendingPathComponent("w154")
.appendingPathComponent(posterPath)
/* 3. Configure the request */
let request = URLRequest(url: url)
/* 4. Make the request */
let loadPoster = appDelegate.sharedSession.rx.data(request: request)
loadPoster.subscribe(onNext: {
data in
/* 5. Parse the data */
// No need, the data is already raw image data.
/* 6. Use the data! */
if let image = UIImage(data: data) {
performUIUpdatesOnMain {
self.imageView?.image = image
}
} else {
print("Could not create image from \(data)")
}
}
, onError: {
error in
print("There was an error with image request: \(error)")
})
.addDisposableTo(disposeBag)
}
}
| true
|
58398f1921b4ddf2af378044874704d9d85a710f
|
Swift
|
jsdu/PersonalityQuiz
|
/PersonalityQuiz/Data/QuestionManager.swift
|
UTF-8
| 12,169
| 3.296875
| 3
|
[] |
no_license
|
//
// QuestionManager.swift
// PersonalityQuiz
//
// Created by Jing Song Du on 2020-01-11.
// Copyright © 2020 Jing Song Du. All rights reserved.
//
import Foundation
struct QuestionManager {
// Questions from https://ipip.ori.org/newMultipleconstructs.htm
var possibleExtrovertQuestions = [
Question(question: "Am the life of the party.", questionType: .extrovert, isPositive: true),
Question(question: "Feel comfortable around people.", questionType: .extrovert, isPositive: true),
Question(question: "Start conversations.", questionType: .extrovert, isPositive: true),
Question(question: "Talk to a lot of different people at parties.", questionType: .extrovert, isPositive: true),
Question(question: "Don't mind being the center of attention.", questionType: .extrovert, isPositive: true),
Question(question: "Make friends easily.", questionType: .extrovert, isPositive: true),
Question(question: "Take charge.", questionType: .extrovert, isPositive: true),
Question(question: "Know how to captivate people.", questionType: .extrovert, isPositive: true),
Question(question: "Feel at ease with people.", questionType: .extrovert, isPositive: true),
Question(question: "Am skilled in handling social situations.", questionType: .extrovert, isPositive: true),
Question(question: "Find it difficult to approach others.", questionType: .extrovert, isPositive: false),
Question(question: "Often feel uncomfortable around others.", questionType: .extrovert, isPositive: false),
Question(question: "Bottle up my feelings.", questionType: .extrovert, isPositive: false),
Question(question: "Am a very private person.", questionType: .extrovert, isPositive: false),
Question(question: "Wait for others to lead the way.", questionType: .extrovert, isPositive: false),
Question(question: "Don't talk a lot.", questionType: .extrovert, isPositive: false),
Question(question: "Keep in the background.", questionType: .extrovert, isPositive: false),
Question(question: "Have little to say.", questionType: .extrovert, isPositive: false),
Question(question: "Don't like to draw attention to myself.", questionType: .extrovert, isPositive: false),
Question(question: "Am quiet around strangers.", questionType: .extrovert, isPositive: false)
]
var possibleIntuitiveQuestions = [
Question(question: "Have a rich vocabulary.", questionType: .intuitive, isPositive: true),
Question(question: "Have a vivid imagination.", questionType: .intuitive, isPositive: true),
Question(question: "Have excellent ideas.", questionType: .intuitive, isPositive: true),
Question(question: "Am quick to understand things.", questionType: .intuitive, isPositive: true),
Question(question: "Use difficult words.", questionType: .intuitive, isPositive: true),
Question(question: "Spend time reflecting on things.", questionType: .intuitive, isPositive: true),
Question(question: "Am full of ideas.", questionType: .intuitive, isPositive: true),
Question(question: "Carry the conversation to a higher level.", questionType: .intuitive, isPositive: true),
Question(question: "Catch on to things quickly.", questionType: .intuitive, isPositive: true),
Question(question: "Can handle a lot of information.", questionType: .intuitive, isPositive: true),
Question(question: "Love to think up new ways of doing things.", questionType: .intuitive, isPositive: true),
Question(question: "Love to read challenging material.", questionType: .intuitive, isPositive: true),
Question(question: "Am good at many things.", questionType: .intuitive, isPositive: true),
Question(question: "Have difficulty understanding abstract ideas.",
questionType: .intuitive, isPositive: false),
Question(question: "Am not interested in abstract ideas.", questionType: .intuitive, isPositive: false),
Question(question: "Do not have a good imagination.", questionType: .intuitive, isPositive: false),
Question(question: "Try to avoid complex people.", questionType: .intuitive, isPositive: false),
Question(question: "Have difficulty imagining things.", questionType: .intuitive, isPositive: false),
Question(question: "Avoid difficult reading material.", questionType: .intuitive, isPositive: false),
Question(question: "Will not probe deeply into a subject.", questionType: .intuitive, isPositive: false)
]
var possibleFeelingQuestions = [
Question(question: "Am interested in people.", questionType: .feeling, isPositive: true),
Question(question: "Sympathize with others' feelings.", questionType: .feeling, isPositive: true),
Question(question: "Have a soft heart.", questionType: .feeling, isPositive: true),
Question(question: "Take time out for others.", questionType: .feeling, isPositive: true),
Question(question: "Feel others' emotions.", questionType: .feeling, isPositive: true),
Question(question: "Make people feel at ease.", questionType: .feeling, isPositive: true),
Question(question: "Inquire about others' well-being.", questionType: .feeling, isPositive: true),
Question(question: "Know how to comfort others.", questionType: .feeling, isPositive: true),
Question(question: "Love children.", questionType: .feeling, isPositive: true),
Question(question: "Am on good terms with nearly everyone.", questionType: .feeling, isPositive: true),
Question(question: "Have a good word for everyone.", questionType: .feeling, isPositive: true),
Question(question: "Show my gratitude.", questionType: .feeling, isPositive: true),
Question(question: "Think of others first.", questionType: .feeling, isPositive: true),
Question(question: "Love to help others.", questionType: .feeling, isPositive: true),
Question(question: "Am not really interested in others.", questionType: .feeling, isPositive: false),
Question(question: "Insult people.", questionType: .feeling, isPositive: false),
Question(question: "Am not interested in other people's problems.", questionType: .feeling, isPositive: false),
Question(question: "Feel little concern for others.", questionType: .feeling, isPositive: false),
Question(question: "Am hard to get to know.", questionType: .feeling, isPositive: false),
Question(question: "Am indifferent to the feelings of others.", questionType: .feeling, isPositive: false)
]
var possibleJudgingQuestions = [
Question(question: "Am always prepared.", questionType: .judging, isPositive: true),
Question(question: "Pay attention to details.", questionType: .judging, isPositive: true),
Question(question: "Get chores done right away.", questionType: .judging, isPositive: true),
Question(question: "Like order.", questionType: .judging, isPositive: true),
Question(question: "Follow a schedule.", questionType: .judging, isPositive: true),
Question(question: "Am exacting in my work.", questionType: .judging, isPositive: true),
Question(question: "Do things according to a plan.", questionType: .judging, isPositive: true),
Question(question: "Continue until everything is perfect.", questionType: .judging, isPositive: true),
Question(question: "Make plans and stick to them.", questionType: .judging, isPositive: true),
Question(question: "Love order and regularity.", questionType: .judging, isPositive: true),
Question(question: "Like to tidy up.", questionType: .judging, isPositive: true),
Question(question: "Leave my belongings around.", questionType: .judging, isPositive: false),
Question(question: "Make a mess of things.", questionType: .judging, isPositive: false),
Question(question: "Often forget to put things back in their proper place.",
questionType: .judging, isPositive: false),
Question(question: "Shirk my duties.", questionType: .judging, isPositive: false),
Question(question: "Neglect my duties.", questionType: .judging, isPositive: false),
Question(question: "Waste my time.", questionType: .judging, isPositive: false),
Question(question: "Do things in a half-way manner.", questionType: .judging, isPositive: false),
Question(question: "Find it difficult to get down to work.", questionType: .judging, isPositive: false),
Question(question: "Leave a mess in my room.", questionType: .judging, isPositive: false)
]
var possibleAssertiveQuestions = [
Question(question: "Am relaxed most of the time.", questionType: .assertive, isPositive: true),
Question(question: "Seldom feel blue.", questionType: .assertive, isPositive: true),
Question(question: "Am not easily bothered by things.", questionType: .assertive, isPositive: true),
Question(question: "Rarely get irritated.", questionType: .assertive, isPositive: true),
Question(question: "Seldom get mad.", questionType: .assertive, isPositive: true),
Question(question: "Get stressed out easily.", questionType: .assertive, isPositive: false),
Question(question: "Worry about things.", questionType: .assertive, isPositive: false),
Question(question: "Am easily disturbed.", questionType: .assertive, isPositive: false),
Question(question: "Get upset easily.", questionType: .assertive, isPositive: false),
Question(question: "Change my mood a lot.", questionType: .assertive, isPositive: false),
Question(question: "Have frequent mood swings.", questionType: .assertive, isPositive: false),
Question(question: "Get irritated easily.", questionType: .assertive, isPositive: false),
Question(question: "Often feel blue.", questionType: .assertive, isPositive: false),
Question(question: "Get angry easily.", questionType: .assertive, isPositive: false),
Question(question: "Panic easily.", questionType: .assertive, isPositive: false),
Question(question: "Feel threatened easily.", questionType: .assertive, isPositive: false),
Question(question: "Get overwhelmed by emotions.", questionType: .assertive, isPositive: false),
Question(question: "Take offense easily.", questionType: .assertive, isPositive: false),
Question(question: "Get caught up in my problems.", questionType: .assertive, isPositive: false),
Question(question: "Grumble about things.", questionType: .assertive, isPositive: false)
]
mutating func getQuestions() -> [Question] {
var quiz: [Question] = []
getQuestions(questions: &quiz, possibleQuestions: &possibleExtrovertQuestions)
getQuestions(questions: &quiz, possibleQuestions: &possibleIntuitiveQuestions)
getQuestions(questions: &quiz, possibleQuestions: &possibleFeelingQuestions)
getQuestions(questions: &quiz, possibleQuestions: &possibleJudgingQuestions)
getQuestions(questions: &quiz, possibleQuestions: &possibleAssertiveQuestions)
quiz.shuffle()
return quiz
}
mutating func getAdditionalQuestions() -> [Question] {
var additionalQuiz: [Question] = []
additionalQuiz.append(contentsOf: possibleExtrovertQuestions)
additionalQuiz.append(contentsOf: possibleIntuitiveQuestions)
additionalQuiz.append(contentsOf: possibleFeelingQuestions)
additionalQuiz.append(contentsOf: possibleJudgingQuestions)
additionalQuiz.append(contentsOf: possibleAssertiveQuestions)
additionalQuiz.shuffle()
return additionalQuiz
}
fileprivate func getQuestions(questions: inout [Question], possibleQuestions: inout [Question]) {
for _ in 0 ..< 10 {
let randomIndex = Int(arc4random_uniform(UInt32(possibleQuestions.count)))
questions.append(possibleQuestions[randomIndex])
possibleQuestions.remove(at: randomIndex)
}
}
}
| true
|
335fac7b5ab04ffb988990cad5bf4389921a6113
|
Swift
|
square/workflow-swift
|
/Samples/ModalContainer/Sources/ModalContainerScreen.swift
|
UTF-8
| 2,220
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import WorkflowUI
/// A `ModalContainerScreen` displays a base screen and optionally one or more modals on top of it.
public struct ModalContainerScreen<BaseScreen: Screen>: Screen {
/// The base screen to show underneath any modally presented screens.
public let baseScreen: BaseScreen
/// Modally presented screens
public let modals: [ModalContainerScreenModal]
public init(baseScreen: BaseScreen, modals: [ModalContainerScreenModal]) {
self.baseScreen = baseScreen
self.modals = modals
}
public func viewControllerDescription(environment: ViewEnvironment) -> ViewControllerDescription {
return ModalContainerViewController.description(for: self, environment: environment)
}
}
/// Represents a single screen to be displayed modally
public struct ModalContainerScreenModal {
public enum Style: Equatable {
// full screen modal presentation
case fullScreen
// formsheet or pagesheet like modal presentation
case sheet
}
/// The screen to be displayed
public var screen: AnyScreen
/// A bool used to specify whether presentation should be animated
public var animated: Bool
/// The style in which the screen should be presented
public var style: Style
/// A key used to differentiate modal screens during updates
public var key: AnyHashable
public init<Key: Hashable>(screen: AnyScreen, style: Style = .fullScreen, key: Key, animated: Bool = true) {
self.screen = screen
self.style = style
self.key = AnyHashable(key)
self.animated = animated
}
}
| true
|
d2c6b64c3a2523a938dd2741db782f7bb2206a7d
|
Swift
|
tdscientist/ChargingIndicator
|
/Charging Animation/GradientBackgroundView.swift
|
UTF-8
| 1,179
| 2.765625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// GradientBackgroundView.swift
// Charging Animation
//
// Created by Adeyinka Adediji on 01/06/2018.
// Copyright © 2018 Adeyinka Adediji. All rights reserved.
//
import UIKit
@IBDesignable
class GradientBackgroundView: UIView {
public override init(frame: CGRect) {
super.init(frame: frame)
updateView()
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
updateView()
}
override func layoutSubviews() {
super.layoutSubviews()
updateView()
}
override class var layerClass: AnyClass {
return CAGradientLayer.self
}
private func updateView() {
if let sublayers = self.layer.sublayers {
for layer in sublayers {
layer.removeFromSuperlayer()
}
}
let colorLayer = CAGradientLayer()
colorLayer.frame = frame
colorLayer.colors = [UIColor.DARK_TURQUOISE.cgColor, UIColor.BLUE_VIOLET.cgColor]
colorLayer.startPoint = CGPoint(x: 1.0, y: 0.5)
colorLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
layer.addSublayer(colorLayer)
}
}
| true
|
609c0b199b2fe3c14697587c9765088fac2400eb
|
Swift
|
aBloomingTree/CaiyunWeather
|
/Sources/CaiyunWeather/Extensions.swift
|
UTF-8
| 2,049
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
//
// Extensions.swift
//
//
// Created by 袁林 on 2021/6/13.
//
import Foundation
extension String {
public func localized(comment: String? = nil) -> String {
return NSLocalizedString(self, bundle: Bundle.module, comment: comment ?? "")
}
}
extension DateFormatter {
static let serverType: DateFormatter = {
// Credit: https://stackoverflow.com/questions/35700281/date-format-in-swift
let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mmZZZZZ"
return formatter
}()
}
// Credit: https://stackoverflow.com/a/59292570/14640876
extension Range where Bound: AdditiveArithmetic & ExpressibleByIntegerLiteral {
init(center: Bound, tolerance: Bound) {
self.init(uncheckedBounds: (lower: center - tolerance, upper: center + tolerance))
}
}
extension ClosedRange where Bound: AdditiveArithmetic {
init(center: Bound, tolerance: Bound) {
self.init(uncheckedBounds: (lower: center - tolerance, upper: center + tolerance))
}
}
// Credit: https://stackoverflow.com/a/35407213/14640876
extension String {
func convertToTimeInterval() -> TimeInterval {
guard self != "" else { return 0 }
var interval: Double = 0
let parts = self.components(separatedBy: ":")
for (index, part) in parts.reversed().enumerated() {
interval += (Double(part) ?? 0) * pow(60, Double(index + 1))
}
return interval
}
}
// Credit: https://stackoverflow.com/a/28872601/14640876
extension TimeInterval {
func convertToString() -> String {
let time = Int(self.rounded(.towardZero))
// let milliseconds = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
// let seconds = time % 60
let minutes = (time / 60) % 60
let hours = (time / 3600)
// return String(format: "%0.2d:%0.2d:%0.2d.%0.3d", hours, minutes, seconds, milliseconds)
return String(format: "%0.2d:%0.2d", hours, minutes)
}
}
| true
|
6f32477739c79e48659e0967e9d7419670013ab5
|
Swift
|
CS3217-GroupX-Challo/Challo-iOS
|
/Challo/Challo/Persistence/Repositories/LocalStorageRetriever.swift
|
UTF-8
| 567
| 2.953125
| 3
|
[] |
no_license
|
//
// EntityRepositoryProtocol.swift
// Challo
//
// Created by Tan Le Yang on 17/4/21.
//
protocol LocalStorageRetriever {
associatedtype Model
associatedtype LocalStore: StoreProtocol where LocalStore.Model == Model
var localStore: LocalStore { get }
func retrieveFromLocalStore() -> [Model]
func saveToLocalStore(models: [Model])
}
extension LocalStorageRetriever {
func retrieveFromLocalStore() -> [Model] {
localStore.getAll()
}
func saveToLocalStore(models: [Model]) {
localStore.save(models: models)
}
}
| true
|
1497adb5f59d0b9949d3b3dd54adb0fff7aeb989
|
Swift
|
rseonp/Twitter
|
/Twitter/TweetCell.swift
|
UTF-8
| 2,877
| 2.703125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// TweetCell.swift
// Twitter
//
// Created by Victor Li Wang on 2/21/16.
// Copyright © 2016 Victor Li Wang. All rights reserved.
//
import UIKit
class TweetCell: UITableViewCell {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var tweetLabel: UILabel!
@IBOutlet weak var retweetCountLabel: UILabel!
@IBOutlet weak var favoriteCountLabel: UILabel!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var favoriteButton: UIButton!
var tweet: Tweet! {
didSet {
usernameLabel.text = tweet.user?.name
profileImageView.setImageWithURL((tweet.user?.profileUrl)!)
let formatter = NSDateFormatter()
formatter.dateStyle = .ShortStyle
formatter.timeStyle = .ShortStyle
let dateString = formatter.stringFromDate((tweet.timestamp)!)
timestampLabel.text = dateString
tweetLabel.text = tweet.text
retweetCountLabel.text = "\(tweet.retweetCount)"
// favoriteCountLabel.text = "\(tweet.favoritesCount)"
if(tweet.retweeted == true) {
retweetButton.setImage(UIImage(named: "retweet-action-on.png"), forState: .Normal)
// retweetButton.selected = true
// print("retweetselected = true in TweetCell")
} else {
retweetButton.setImage(UIImage(named: "retweet-action.png"), forState: .Normal)
// retweetButton.selected = false
// print("retweetselected = false in TweetCell")
}
if(tweet.favorited == true) {
favoriteButton.setImage(UIImage(named: "like-action-on.png"), forState: .Normal)
// favoriteButton.selected = true
// print("favoriteselected = true in TweetCell")
} else {
favoriteButton.setImage(UIImage(named: "like-action.png"), forState: .Normal)
// favoriteButton.selected = false
// print("favoriteselected = false in TweetCell")
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
profileImageView.layer.cornerRadius = 3
profileImageView.clipsToBounds = true
usernameLabel.preferredMaxLayoutWidth = usernameLabel.frame.size.width
}
override func layoutSubviews() {
super.layoutSubviews()
usernameLabel.preferredMaxLayoutWidth = usernameLabel.frame.size.width
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| true
|
6916afea7a09bba39e0c9448fd931d41bcb2e1a4
|
Swift
|
mohshaat1990/project-structure
|
/project-structure/Views/Scenes/Authorizations/RegisterViewController.swift
|
UTF-8
| 1,247
| 2.609375
| 3
|
[] |
no_license
|
//
// RegisterViewController.swift
// project-structure
//
// Created by Mohamed Shaat on 8/26/19.
// Copyright © 2019 shaat. All rights reserved.
//
import UIKit
class RegisterViewController: UIViewController {
typealias ViewModelType = RegisterViewModel
private var viewModel: ViewModelType!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension RegisterViewController: ControllerType {
func configure(with viewModel: RegisterViewModel) {
}
static func create(with viewModel: RegisterViewModel) -> UIViewController? {
let storyboard = UIStoryboard(name: "Authorizations", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "RegisterViewController") as? RegisterViewController
return controller
}
}
| true
|
0e08adabf91f2bf6d3928dd55bf9e3cb6c54af0e
|
Swift
|
damodarnamala/GoContacts
|
/GoContacts/Components/ContactList/ContactListView.swift
|
UTF-8
| 4,523
| 2.53125
| 3
|
[] |
no_license
|
import UIKit
final class ContactListView: UIViewController {
@IBOutlet weak var tableContactList: UITableView!
var presenter: ContactListPresenterProtocol?
var loader : Loader!
lazy var count : Int = { return 0 }()
var contacts:[Contact]!
var sectionTiles = [String]()
var indexList = [Character: [Contact]]()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
presenter?.onViewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.isHidden = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
func setupViews() {
let leftBarButton = UIBarButtonItem(title: BarButtonTitle.group, style: .plain, target: self, action: #selector(leftBarButtonAction))
let rightBarButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(rightBarButtonAction))
self.navigationItem.leftBarButtonItem = leftBarButton
self.navigationItem.rightBarButtonItem = rightBarButton
tableContactList.separatorColor = Color.borderColor
self.loader = Loader(view: self.view)
self.toggleTableView(true)
}
@objc func leftBarButtonAction() {
}
@objc func rightBarButtonAction() {
self.presenter?.showAddContact(on: self.navigationController!)
}
func toggleTableView(_ show: Bool) {
self.tableContactList.isHidden = show
}
func createListAndUpdateTable() {
let nameAscendingSorted = self.contacts.sorted { (initial, next) -> Bool in
return initial.first_name!.compare(next.first_name!) == .orderedAscending
}
self.indexList = Dictionary(grouping: nameAscendingSorted, by: { $0.first_name!.lowercased().first! })
sectionTiles = Array(self.indexList.keys).map {
return String($0)
}
sectionTiles = sectionTiles.sorted()
DispatchQueue.main.async {
self.toggleTableView(false)
self.loader.hide()
self.tableContactList!.sectionIndexColor = Color.gray
self.tableContactList!.sectionIndexBackgroundColor = Color.clear
self.tableContactList.reloadData()
}
}
func getContactsForKey(section: NSInteger)->[Contact] {
let key = self.sectionTiles [section]
let ch = key[key.startIndex]
return self.indexList[ch]!
}
}
extension ContactListView: ContactListViewProtocol {
func didRecieved(contacts: [Contact]) {
self.count = contacts.count
self.contacts = contacts
createListAndUpdateTable()
DispatchQueue.main.async {
self.view.showBanner(.success, "User details updated")
}
}
func didFailedWith(eror: String) {
self.loader.hide()
self.view.showBanner(.failed, "Please try after some time")
}
func showLoader() {
self.loader?.show()
}
}
extension ContactListView : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let contacts = getContactsForKey(section: section)
return contacts.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return sectionTiles.count
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return self.sectionTiles
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionTiles[section]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:ContactListCell.identifier) as! ContactListCell
let contacts = getContactsForKey(section: indexPath.section)
let contact = contacts[indexPath.row]
cell.configure(contact)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let contacts = getContactsForKey(section: indexPath.section)
let selectedContact = contacts[indexPath.row]
self.presenter?.showDetail(self.navigationController!, with: selectedContact)
}
}
| true
|
ce667850da98455d871cb37f956ef7451b508b27
|
Swift
|
tdlinton/Try_Firebase1
|
/Try_Firebase1/AppDelegate.swift
|
UTF-8
| 6,310
| 2.53125
| 3
|
[] |
no_license
|
//
// AppDelegate.swift
// Try_Firebase1
//
// Created by Thomas Linton on 3/15/18.
// Copyright © 2018 Thomas Linton. All rights reserved.
//
import UIKit
import Firebase
struct Constants {
static let AnalyticsEnabled = "firebase_analytics_collection_enabled"
static let CrashlyticsEnabled = "firebase_crashlytics_collection_enabled"
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// METHOD A
/*
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
setDefaultsFromSettingsBundle()
// Initialize Firebase Analytics
FirebaseApp.configure()
let enableAnalytics = UserDefaults.standard.bool(forKey: Constants.AnalyticsEnabled)
AnalyticsConfiguration.shared().setAnalyticsCollectionEnabled(enableAnalytics)
// Initialize Crashlytics
if UserDefaults.standard.bool(forKey: Constants.CrashlyticsEnabled)
{
Fabric.with([Crashlytics.self])
}
// Print out settings
if UserDefaults.standard.bool(forKey: Constants.AnalyticsEnabled)
{
print("analytics enabled")
} else {
print("analytics disabled")
}
if UserDefaults.standard.bool(forKey: Constants.CrashlyticsEnabled)
{
print("crashlytics enabled")
} else {
print("crashlytics disabled")
}
return true
}
*/
// METHOD B [need to add CrashlyticsDelegation protocol to AppDelegate]
/*
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
setDefaultsFromSettingsBundle()
// Initialize Firebase Analytics
FirebaseApp.configure()
let enableAnalytics = UserDefaults.standard.bool(forKey: Constants.AnalyticsEnabled)
AnalyticsConfiguration.shared().setAnalyticsCollectionEnabled(enableAnalytics)
Crashlytics.sharedInstance().delegate = self
// Print out settings
if UserDefaults.standard.bool(forKey: Constants.AnalyticsEnabled)
{
print("analytics enabled")
} else {
print("analytics disabled")
}
if UserDefaults.standard.bool(forKey: Constants.CrashlyticsEnabled)
{
print("crashlytics enabled")
} else {
print("crashlytics disabled")
}
return true
}
// for METHOD B:
func crashlyticsDidDetectReport_B(forLastExecution report: CLSReport, completionHandler: @escaping (Bool) -> Void)
{
let shouldSendCrashReport = UserDefaults.standard.bool(forKey: Constants.CrashlyticsEnabled)
completionHandler(shouldSendCrashReport)
}
*/
// METHOD C - crashes on startup in call to Fabric.with
/*
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
setDefaultsFromSettingsBundle()
// Print out settings
if UserDefaults.standard.bool(forKey: Constants.AnalyticsEnabled)
{
print("analytics enabled")
} else {
print("analytics disabled")
}
if UserDefaults.standard.bool(forKey: Constants.CrashlyticsEnabled)
{
print("crashlytics enabled")
} else {
print("crashlytics disabled")
}
// NO Firebase Analytics
// Initialize Crashlytics
if UserDefaults.standard.bool(forKey: Constants.CrashlyticsEnabled)
{
Fabric.with([Crashlytics.self])
}
return true
}
*/
// Method E: turn on Crashlytics + Analytics together - WORKS
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
setDefaultsFromSettingsBundle()
// Print out settings
if UserDefaults.standard.bool(forKey: Constants.AnalyticsEnabled)
{
print("analytics enabled")
} else {
print("analytics disabled")
}
if UserDefaults.standard.bool(forKey: Constants.CrashlyticsEnabled)
{
print("crashlytics enabled")
} else {
print("crashlytics disabled")
}
// Switch for Analytics + Crashlytics together
if UserDefaults.standard.bool(forKey: Constants.CrashlyticsEnabled)
{
FirebaseApp.configure()
AnalyticsConfiguration.shared().setAnalyticsCollectionEnabled(true)
Fabric.with([Crashlytics.self])
}
return true
}
func setDefaultsFromSettingsBundle() {
//Read PreferenceSpecifiers from Root.plist in Settings.Bundle
if let settingsURL = Bundle.main.url(forResource: "Root", withExtension: "plist", subdirectory: "Settings.bundle"),
let settingsPlist = NSDictionary(contentsOf: settingsURL),
let preferences = settingsPlist["PreferenceSpecifiers"] as? [NSDictionary] {
for prefSpecification in preferences {
if let key = prefSpecification["Key"] as? String, let value = prefSpecification["DefaultValue"] {
//If key doesn't exists in userDefaults then register it, else keep original value
if UserDefaults.standard.value(forKey: key) == nil {
UserDefaults.standard.set(value, forKey: key)
NSLog("registerDefaultsFromSettingsBundle: Set following to UserDefaults - (key: \(key), value: \(value), type: \(type(of: value)))")
}
}
}
} else {
NSLog("registerDefaultsFromSettingsBundle: Could not find Settings.bundle")
}
}
}
| true
|
e911e6c67947046a167883ad3e8babe96c4198d1
|
Swift
|
GCIntesa/Pokeapp
|
/Pokeapp/Pokeapp/App/Detail/DetailCoordinator.swift
|
UTF-8
| 979
| 2.703125
| 3
|
[] |
no_license
|
//
// DetailCoordinator.swift
// Pokeapp
//
// Created by Gionatan Cernusco on 19/01/21.
//
import Foundation
import UIKit
final class DetailCoordinator {
private let navigationController: SwipeBackNavigationController
private let viewModel: DetailViewModel
init(navigationController: SwipeBackNavigationController, pokemonModel: PokemonModel){
self.navigationController = navigationController
viewModel = DetailViewModel(pokemonModel: pokemonModel)
}
func start(){
viewModel.coordinator = self
let vc = DetailViewController()
vc.config(detailViewModel: viewModel)
navigationController.pushViewController(vc, animated: true)
}
func onBackDidTap() {
navigationController.popViewController(animated: true)
}
func onImageDidTap(pokemonModel: PokemonModel){
ImageViewerCoordinator(navigationController: navigationController, pokemonModel: pokemonModel).start()
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.