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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d76a5f52e849b8bd5f0deb6449a45e27995a8c11
|
Swift
|
ebarquin/starWars
|
/StarWars/UniverseViewControllerTableViewController.swift
|
UTF-8
| 3,176
| 2.828125
| 3
|
[] |
no_license
|
//
// UniverseViewControllerTableViewController.swift
// StarWars
//
// Created by Eugenio Barquín on 23/1/17.
// Copyright © 2017 Eugenio Barquín. All rights reserved.
//
import UIKit
class UniverseViewControllerTableViewController: UITableViewController {
//MARK: - Properties
let model : StarWarsUniverse
//MARK: - Initialization
init(model: StarWarsUniverse){
self.model = model
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
//Incomplete implementation, return the number of sections
return model.affiliationCount
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Incomplete implementation, return the number of rows
return model.characterCount(forAffiliation: getAffiliation(forSection: section))
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return model.affiliationName(getAffiliation(forSection: section))
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//Definir un id para el tipo de celda
let cellId = "StarWarsCell"
//Averiguar la afiliación
let aff = getAffiliation(forSection: indexPath.section)
//Averiguar quien es el personaje
let char = model.character(atIndex: indexPath.row, forAffiliation: aff)
//Crear la celda
var cell = tableView.dequeueReusableCell(withIdentifier: cellId)
if cell == nil{
//El opcional está vacio y toca crear la celda desde cero
cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
}
//Configurarla
cell?.imageView?.image = char.photo
cell?.textLabel?.text = char.alias
cell?.detailTextLabel?.text = char.name
//Devolverla
return cell!
}
//MARK: - Utils
func getAffiliation(forSection section: Int) ->StarWarsAffiliation{
var aff: StarWarsAffiliation = .unknow
switch section {
case 0:
aff = .galacticEmpire
case 1:
aff = .rebelAlliance
case 2:
aff = .jabbaCriminalEmpire
case 3:
aff = .firstOrder
default:
aff = .unknow
}
return aff
}
}
| true
|
4cc31198688cb9a62d482f09b37a8f5f7935669c
|
Swift
|
AitoApps/WhatAmIEating
|
/WhatAmIEating/ViewControllers/InformMealViewController.swift
|
UTF-8
| 2,100
| 2.65625
| 3
|
[] |
no_license
|
//
// InformMealViewController.swift
// WhatAmIEating
//
// Created by Bárbara Ferreira on 08/04/2018.
// Copyright © 2018 Barbara Ferreira. All rights reserved.
//
import UIKit
import FirebaseAuth
import FirebaseDatabase
class InformMealViewController: UIViewController {
var meals: [Meal] = [ ]
var mealTypes = [ "BREAKFAST", "LUNCH", "SNACK", "DINNER" ]
var mealType: String = ""
@IBOutlet weak var tt_page: UIImageView!
@IBAction func logOut(_ sender: Any) {
let authentication = Auth.auth()
do{
try authentication.signOut()
self.performSegue(withIdentifier: "backTo", sender: self)
dismiss(animated: true, completion: nil)
} catch {
print("Error while trying to log user out!")
}
}
@IBAction func breakfastOption(_ sender: Any) {
self.mealType = "BREAKFAST" //mealTypes[0]
//createMeal(mealType: mealType)
}
@IBAction func lunchOption(_ sender: Any) {
self.mealType = "LUNCH" //mealTypes[1]
//createMeal(mealType: mealType)
}
@IBAction func snackOption(_ sender: Any) {
self.mealType = "SNACK"
}
@IBAction func dinnerOption(_ sender: Any) {
self.mealType = "DINNER" //mealTypes[3]
//createMeal(mealType: mealType)
}
override func viewDidLoad() {
super.viewDidLoad()
self.mealType = "SNACK"
self.tt_page.image = #imageLiteral(resourceName: "add meal")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "breakfastType" || segue.identifier == "lunchType" || segue.identifier == "dinnerType" || segue.identifier == "snackType" {
let photoMealViewController = segue.destination as! PhotoViewController
photoMealViewController.mealType = self.mealType
}
}
}
| true
|
537b4166107b918c7f6a253163c505715d1e24e9
|
Swift
|
Charlisim/TicketToRide-Swift
|
/TicketToRideRules/Models/CardType.swift
|
UTF-8
| 456
| 2.921875
| 3
|
[] |
no_license
|
//
// CardType.swift
// TicketToRideRules
//
// Created by Carlos Simon on 05/05/2019.
// Copyright © 2019 AltApps. All rights reserved.
//
import Foundation
public enum CardType: String, CaseIterable, CustomStringConvertible{
case red
case white
case yellow
case green
case locomotive
case black
case blue
case orange
case pink
public var description: String{
return self.rawValue.capitalized
}
}
| true
|
b64bcbc53e6b14390f0fb72bba5d99f33d871190
|
Swift
|
dimaosa/ReduxNotes-Coordinators
|
/ReduxNotes/Coordinators/Menu/NotesTableViewController/AllNotesTableViewController.swift
|
UTF-8
| 2,471
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// AllNotesTableViewController.swift
// ReduxNotes
//
// Created by Dima Osadchy on 13/08/2019.
// Copyright © 2019 Alexey Demedeckiy. All rights reserved.
//
import UIKit
final class AllNotesTableViewController: UITableViewController {
struct Props {
let title: String
let notes: [Note]
let addNewNote: Command
let endObserving: Command
struct Note {
let title: String
let select: Command
let delete: Command
}
}
override func viewDidLoad() {
super.viewDidLoad()
registerCells()
addTabBarItems()
}
deinit {
props.endObserving.perform()
}
private var props = Props(title: "Notes", notes: [], addNewNote: .nop, endObserving: .nop)
func render(props: Props) {
self.props = props
self.tableView.reloadData()
view.setNeedsLayout()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
title = props.title
}
@IBAction func unwindToNotesList(segue: UIStoryboardSegue) {}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return props.notes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: NoteTableViewCell.reuseIdentifier) as! NoteTableViewCell
cell.textLabel?.text = props.notes[indexPath.row].title
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
props.notes[indexPath.row].select.perform()
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
props.notes[indexPath.row].delete.perform()
}
}
private func registerCells() {
tableView.register(NoteTableViewCell.self, forCellReuseIdentifier: NoteTableViewCell.reuseIdentifier)
}
private func addTabBarItems() {
navigationItem.setRightBarButton(UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNewNote)), animated: false)
}
@objc private func addNewNote() {
props.addNewNote.perform()
}
}
| true
|
38f129a8f1e7ba0f0bd491dd6f8527a03b62885b
|
Swift
|
mlitman/codr
|
/CodrBE/uxVarExpression.swift
|
UTF-8
| 469
| 2.6875
| 3
|
[] |
no_license
|
//
// uxVarExpression.swift
// CodrBE
//
// Created by Michael Litman on 4/19/15.
// Copyright (c) 2015 awesomefat. All rights reserved.
//
import UIKit
class uxVarExpression: uxExpression
{
var name:String!
override init()
{
self.name = ""
}
override func toJSON() -> String
{
return "{\"type\":\"var-exp\",\"name\":\"\(self.name)\"}"
}
override func displayValue() -> String
{
return name!
}
}
| true
|
646a01cec71d68b6f424ecf6d1e80760db2371b2
|
Swift
|
WeZZard/TrieCollections
|
/TrieCollections/Dictionary/KeysView/TrieDictionaryKeysIterator.swift
|
UTF-8
| 1,063
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// TrieDictionaryKeysIterator.swift
// TrieCollections
//
// Created on 30/10/2018.
//
public struct TrieDictionaryKeysIterator<K: TriePrefixInterpretable, V>:
IteratorProtocol
{
public typealias Key = K
public typealias Value = V
public typealias Element = Key
internal typealias _KeyValueContainer = _TrieKeyValueContainer<K, V>
internal typealias _Impl = _TrieDepthFirstIteratorImpl<_KeyValueContainer>
internal var _impl: _Impl
public init(view: TrieDictionaryKeys<K, V>) {
self = .init(trieDictionary: view._trieDictionary)
}
public init(trieDictionary: TrieDictionary<K, V>) {
_impl = .init(storage: trieDictionary._storage)
}
internal mutating func _withDedicatedImpl<R>(_ closure: (_Impl) -> R)
-> R
{
if !isKnownUniquelyReferenced(&_impl) {
_impl = .init(impl: _impl)
}
return closure(_impl)
}
public mutating func next() -> Element? {
return _withDedicatedImpl({$0.next()?.key})
}
}
| true
|
f96ae6da9bad6cb29774ca44dd50a9dc5ba4f429
|
Swift
|
Anvics/AmberExample
|
/TestAmberTests/Amber/Feed/FeedReducerTests.swift
|
UTF-8
| 1,442
| 2.546875
| 3
|
[] |
no_license
|
//
// FeedFeedReducerTests.swift
// TestAmber
//
// Created by Nikita Arkhipov on 11/10/2017.
// Copyright © 2017 Anvics. All rights reserved.
//
import XCTest
import ReactiveKit
class NoFeedItemsLoader: FeedItemLoaderProtocol {
func load(completion: @escaping ([FeedItem]) -> Void){
completion([])
}
}
class FeedReducerTests: XCTestCase{
let store = AmberStore(reducer: FeedReducer(loader: NoFeedItemsLoader()),
router: FeedRouter(),
requiredData: ())
func testAction() {
let item = FeedItem(id: 0, title: "Test", image: nil)
assert(.itemsLoaded([item]), .like(item)) { state in
state.feedItems.count == 1 && state.feedItems[0].isLiked
}
}
func assert(_ actions: FeedAction..., meetsCondition: (FeedState) -> Bool){
actions.forEach(store.perform)
XCTAssert(meetsCondition(store.currentState()))
}
func assert(timeOut: TimeInterval, actions: FeedAction..., meetsCondition: @escaping (FeedState) -> Bool){
let expect = expectation(description: "FeedTest expectation for \(actions)")
actions.forEach(store.perform)
waitForExpectations(timeout: timeOut, handler: nil)
let bag = DisposeBag()
store.state.observeNext { state in
if meetsCondition(state) { expect.fulfill() }
bag.dispose()
}.dispose(in: bag)
}
}
| true
|
3fe722d45710208e2310f077fc33e87b9b53e3bd
|
Swift
|
kevinvanderlugt/Exercism-Solutions
|
/swift/exercism-test-runner/exercism-test-runnerTests/BobTest.swift
|
UTF-8
| 3,779
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
import UIKit
import XCTest
class BobTests: XCTestCase {
func testStatingSomething() {
let input = "Tom-ay-to, tom-aaaah-to."
let expected = "Whatever."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testShouting() {
let input = "WATCH OUT!"
let expected = "Woah, chill out!"
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testAskingAQustion() {
let input = "Does this cryogenic chamber make me look fat?"
let expected = "Sure."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testTalkingForcefully() {
let input = "Let's go make out behind the gym!"
let expected = "Whatever."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testUsingAcronyms() {
let input = "It's OK if you don't want to go to the DMV."
let expected = "Whatever."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testForcefulQuestions() {
let input = "WHAT THE HELL WERE YOU THINKING?"
let expected = "Woah, chill out!"
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testShoutingNumbers() {
let input = "1, 2, 3 GO!"
let expected = "Woah, chill out!"
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testOnlyNumbers() {
let input = "1, 2, 3."
let expected = "Whatever."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testQuestionWithOnlyNumbers() {
let input = "4?"
let expected = "Sure."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testShoutingWithSpecialCharacters() {
let input = "ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!"
let expected = "Woah, chill out!"
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testShoutingWithUmlautsCharacters() {
let input = "ÄMLÄTS!"
let expected = "Woah, chill out!"
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testShoutingWithAccentCharacters() {
let input = "ÂÜ!"
let expected = "Woah, chill out!"
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testCalmlySpeakingAboutUmlauts() {
let input = "ÄMLäTS!"
let expected = "Whatever."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testShoutingWithNoExclamationmark() {
let input = "I HATE YOU"
let expected = "Woah, chill out!"
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testStatementContainingQuestionsMark() {
let input = "Ending with a ? means a question."
let expected = "Whatever."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testPrattlingOn() {
let input = "Wait! Hang on. Are you going to be OK?"
let expected = "Sure."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testSilence() {
let input = ""
let expected = "Fine, be that way."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
func testProlongedSilence() {
let input = " "
let expected = "Fine, be that way."
let result = Bob.hey(input)
XCTAssertEqual(expected, result)
}
}
| true
|
bb2bf638268e4284129f2902b7be97d6f75274ce
|
Swift
|
cesar-paiva/mvvm_with_tdd
|
/LoginForm/LoginForm/LoginFormTests/LoginViewModelTests.swift
|
UTF-8
| 9,088
| 2.515625
| 3
|
[] |
no_license
|
//
// LoginViewModelTests.swift
// LoginFormTests
//
// Created by Cesar Paiva on 11/11/19.
// Copyright © 2019 Cesar Paiva. All rights reserved.
//
import XCTest
@testable import LoginForm
class LoginViewModelTests: XCTestCase {
fileprivate var mockLoginViewController: MockLoginViewController!
fileprivate var sut: LoginViewModel!
fileprivate var validUserName = "abcdefghij"
fileprivate var invalidUserName = "a"
fileprivate var validPassword = "D%io7AFn9Y"
fileprivate var invalidPassword = "123"
override func setUp() {
super.setUp()
mockLoginViewController = MockLoginViewController()
sut = LoginViewModel(view: mockLoginViewController!)
}
override func tearDown() {
super.tearDown()
mockLoginViewController = nil
sut = nil
}
}
// MARK: initialization tests
extension LoginViewModelTests {
func testInit_ValidView_InstantiatesObject() {
XCTAssertNotNil(sut)
}
func testInit_ValidView_CopiesViewToIvar() {
if let lhs = mockLoginViewController, let rhs = sut.view as? MockLoginViewController {
XCTAssertTrue(lhs === rhs)
}
}
}
// MARK: performInitialViewSetup tests
extension LoginViewModelTests {
func testPerformInitialViewSetup_Calls_ClearUserNameField_OnViewController() {
let expectation = self.expectation(description: "expected clearUserNameField() to be called")
mockLoginViewController!.expectationForClearUserNameField = expectation
sut.performInitialViewSetup()
waitForExpectations(timeout: 1.0, handler: nil)
}
func testPerformInitialViewSetup_Calls_ClearPasswordField_OnViewController() {
let expectation = self.expectation(description: "expected clearPasswordField() to be called")
mockLoginViewController!.expectationForClearPasswordField = expectation
sut.performInitialViewSetup()
waitForExpectations(timeout: 1.0, handler: nil)
}
func testPerformInitialViewSetup_Calls_DisablesLoginButton_OnViewController() {
let expectation = self.expectation(description: "expected enableLoginButton(false) to be called")
mockLoginViewController!.expectationForEnableLoginButton = (expectation, false)
sut.performInitialViewSetup()
waitForExpectations(timeout: 1.0, handler: nil)
}
func testPerformInitialViewSetup_Calls_EnableCreateAccountButton_OnViewController() {
let expectation = self.expectation(description: "expected enableCreateAccountButton(true) to be called")
mockLoginViewController!.expectationForCreateAccountButton = (expectation, true)
sut.performInitialViewSetup()
waitForExpectations(timeout: 1.0, handler: nil)
}
}
// MARK: didEndOnExit tests
extension LoginViewModelTests {
func testUserNameDidEndOnExit_Calls_HideKeyboard_OnViewController() {
let expectation = self.expectation(description: "expected hideKeyboard() to be called")
mockLoginViewController!.expectationForHideKeyboard = expectation
sut.userNameDidEndOnExit()
waitForExpectations(timeout: 1.0, handler: nil)
}
func testPasswordDidOnExit_Calls_HideKeyboard_OnViewController() {
let expectation = self.expectation(description: "expected hideKeyboard() to be called")
mockLoginViewController!.expectationForHideKeyboard = expectation
sut.passwordDidEndOnExit()
waitForExpectations(timeout: 1.0, handler: nil)
}
}
// MARK: userNameUpdated tests
extension LoginViewModelTests {
func testUserNameUpdated_Calls_Validate_OnUserNameValidator() {
let expectation = self.expectation(description: "expected validate() to be called")
sut.userNameValidator = MockUserNameValidator(expectation, expectedValue: validUserName)
sut.userNameUpdated(validUserName)
waitForExpectations(timeout: 1.0, handler: nil)
}
func testUserNameUpdated_ValidUserName_PasswordValidated_EnablesLoginButton_OnViewController() {
let expectation = self.expectation(description: "expected enableLogin(true) to be called")
mockLoginViewController!.expectationForEnableLoginButton = (expectation, true)
sut.passwordValidated = true
sut.userNameUpdated(validUserName)
waitForExpectations(timeout: 1.0, handler: nil)
}
func testUserNameUpdated_ValidUserName_PasswordNotValidated_DisablesLoginButton_OnViewController() {
let expectation = self.expectation(description: "expected enableLogin(false) to be called")
mockLoginViewController!.expectationForEnableLoginButton = (expectation, false)
sut.passwordValidated = false
sut.userNameUpdated(validUserName)
waitForExpectations(timeout: 1.0, handler: nil)
}
func testUserNameUpdated_InvalidUserName_PasswordValidated_DisablesLoginButton_OnViewController() {
let expectation = self.expectation(description: "expected enableLogin(false) to be called")
mockLoginViewController.expectationForEnableLoginButton = (expectation, false)
sut.passwordValidated = true
sut.userNameUpdated(invalidUserName)
waitForExpectations(timeout: 1.0, handler: nil)
}
func testUserNameUpdated_InvalidUserName_PasswordNotValidated_DisablesLoginButton_OnViewController() {
let expectation = self.expectation(description: "expected enableLogin(false) to be called")
mockLoginViewController.expectationForEnableLoginButton = (expectation, false)
sut.passwordValidated = false
sut.userNameUpdated(invalidUserName)
waitForExpectations(timeout: 1.0, handler: nil)
}
}
// MARK: passwordUpdated tests
extension LoginViewModelTests {
func testPasswordUpdated_Calls_Validate_OnPasswordValidator() {
let expectation = self.expectation(description: "expected validate() to be called")
sut.passwordValidator = MockPasswordValidator(expectation, expectedValue: validPassword)
sut.passwordUpdated(validPassword)
waitForExpectations(timeout: 1.0, handler: nil)
}
func testPasswordUpdated_ValidPassword_UserNameValidated_EnablesLoginButton_OnViewController() {
let expectation = self.expectation(description: "expected enableLogin(true) to be called")
mockLoginViewController.expectationForEnableLoginButton = (expectation, true)
sut.userNameValidated = true
sut.passwordUpdated(validPassword)
waitForExpectations(timeout: 1.0, handler: nil)
}
func testPasswordUpdated_ValidPassword_UserNameNotValidated_DisablesLoginButton_OnViewController() {
let expectation = self.expectation(description: "expected enableLogin(false) to be called")
mockLoginViewController.expectationForEnableLoginButton = (expectation, false)
sut.userNameValidated = false
sut.passwordUpdated(validPassword)
waitForExpectations(timeout: 1.0, handler: nil)
}
func testPasswordUpdated_InvalidPassword_UserNameValidated_DisablesLoginButton_OnViewController() {
let expectation = self.expectation(description: "expected enableLogin(false) to be called")
mockLoginViewController.expectationForEnableLoginButton = (expectation, false)
sut.userNameValidated = true
sut.passwordUpdated(invalidPassword)
waitForExpectations(timeout: 1.0, handler: nil)
}
func testPasswordUpdated_InvalidPassword_UserNameNotValidated_DisablesLoginButton_OnViewController() {
let expectation = self.expectation(description: "expected enableLogin(false) to be called")
mockLoginViewController.expectationForEnableLoginButton = (expectation, false)
sut.userNameValidated = false
sut.passwordUpdated(invalidPassword)
waitForExpectations(timeout: 1.0, handler: nil)
}
}
// MARK: login tests
extension LoginViewModelTests {
func testLogin_ValidParameters_Calls_doLogin_OnLoginController() {
let expectation = self.expectation(description: "expected doLogin() to be called")
let mockLoginController = MockLoginController(expectation, expectedUserName: validUserName, expectedPassword: validPassword)
mockLoginController.shouldReturnTrueOnLogin = true
sut.loginController = mockLoginController
mockLoginController.loginControllerDelegate = sut
sut.login(userName: validUserName, password: validPassword)
waitForExpectations(timeout: 1.0, handler: nil)
}
}
| true
|
f34d9288f82a3a08fe5efdcfb0269564a185a2c7
|
Swift
|
KadyPei/iOS-Application
|
/User.swift
|
UTF-8
| 395
| 2.890625
| 3
|
[] |
no_license
|
//
// Uswer.swift
// Eater
//
// Created by Kady Pei on 12/12/19.
// Copyright © 2019 nyu.edu. All rights reserved.
//
import Foundation
class User {
var uid: String
var email: String?
var displayName: String?
init(uid: String, displayName: String?, email: String?) {
self.uid = uid
self.email = email
self.displayName = displayName
}
}
| true
|
e72e024c9d99e6968b66ea89c76dc849f28505e4
|
Swift
|
28th-BE-SOPT-iOS-Part/KimSeungChan
|
/KaKao/KaKaoClone/KaKaoClone/VC/Friend2ViewController.swift
|
UTF-8
| 1,786
| 2.578125
| 3
|
[] |
no_license
|
//
// Friend2ViewController.swift
// KaKaoClone
//
// Created by 김승찬 on 2021/04/16.
//
import UIKit
class Friend2ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let gestureRecognizer = UIPanGestureRecognizer(target: self,
action: #selector(panGestureRecognizerHandler(_:)))
view.addGestureRecognizer(gestureRecognizer)
}
@IBAction func panGestureRecognizerHandler(_ sender: UIPanGestureRecognizer) {
let touchPoint = sender.location(in: view?.window)
var initialTouchPoint = CGPoint.zero
switch sender.state {
case .began:
initialTouchPoint = touchPoint
case .changed:
if touchPoint.y > initialTouchPoint.y {
view.frame.origin.y = touchPoint.y - initialTouchPoint.y
}
case .ended, .cancelled:
if touchPoint.y - initialTouchPoint.y > 200 {
dismiss(animated: true, completion: nil)
} else {
UIView.animate(withDuration: 0.2, animations: {
self.view.frame = CGRect(x: 0,
y: 0,
width: self.view.frame.size.width,
height: self.view.frame.size.height)
})
}
case .failed, .possible:
break
func backButton(_ sender: UIButton) {
guard (self.storyboard?.instantiateViewController(identifier: "Friend1ViewController")
as? Friend1ViewController) != nil else { return }
self.dismiss(animated: true, completion: nil)
}
}
}
}
| true
|
408d13423ae22838f9a4f91f0a8c78497718f01a
|
Swift
|
nimblehq/NimbleExtension
|
/NimbleExtension/Sources/Extensions/UIKit/UIView+RoundedCorners.swift
|
UTF-8
| 532
| 2.578125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
//
// UIView+RoundedCorners.swift
// NimbleExtension
//
// Created by Jason Nam on 5/9/19.
// Copyright © 2019 Nimble. All rights reserved.
//
import UIKit
public extension UIView {
func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(
roundedRect: bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius)
)
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}
| true
|
b6348cfca5ad730a0c9e373aae5eced241937c7f
|
Swift
|
SarooshNasir/Shapify-UIBezierpath
|
/Shapify/TriangleDemo.swift
|
UTF-8
| 998
| 3.125
| 3
|
[] |
no_license
|
//
// TriangleDemo.swift
// Shapify
//
// Created by IT on 11/30/20.
// Copyright © 2020 IT. All rights reserved.
//
import UIKit
class TriangleDemo: UIView {
var path: UIBezierPath!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func createTriangle() {
path = UIBezierPath()
path.move(to: CGPoint(x: self.frame.width/2, y: 0.0))
path.addLine(to: CGPoint(x: 0.0, y: self.frame.size.height))
path.addLine(to: CGPoint(x: self.frame.size.width, y: self.frame.size.height))
path.close()
}
override func draw(_ rect: CGRect) {
self.createTriangle()
// Specify the fill color and apply it to the path.
UIColor.orange.setFill()
path.fill()
// Specify a border (stroke) color.
UIColor.purple.setStroke()
path.stroke()
}
}
| true
|
1c7bbc895030c63d63e23bc563a32234b306017a
|
Swift
|
mizozobu/Project3
|
/Project 3 Sou Mizobuchi/Model/ScriptureRenderer.swift
|
UTF-8
| 4,848
| 2.640625
| 3
|
[] |
no_license
|
//
// ScriptureRenderer.swift
// Map Scriptures
//
// Created by Steve Liddle on 11/7/14.
// Copyright (c) 2014 IS 543. All rights reserved.
//
import Foundation
// MARK: - ScriptureRenderer class
class ScriptureRenderer {
// MARK: - Constants
struct Constant {
static let baseUrl = "http://scriptures.byu.edu/mapscrip/"
static let footnoteVerse = 1000
static let renderLongTitles = true
}
// MARK: - Properties
// Note how I've made this property private and now return a tuple from htmlForBookId() so as
// to eliminate the "code smell" of having MapViewController depend on state of this singleton.
// Many software engineers would point to the previous public version of this property as an
// example of a classic anti-pattern (a bad thing).
private var collectedGeocodedPlaces = [GeoPlace]()
// MARK: - Singleton
// See http://bit.ly/1tdRybj for a discussion of this singleton pattern.
static let sharedRenderer = ScriptureRenderer()
private init() {
// This guarantees that code outside this file can't instantiate a ScriptureRenderer.
// So others must use the sharedRenderer singleton.
}
// MARK: - Helpers
func htmlForBookId(_ bookId: Int, chapter: Int) -> (String, [GeoPlace]) {
let book = GeoDatabase.sharedGeoDatabase.bookForId(bookId)
var title = ""
var heading1 = ""
var heading2 = ""
title = titleForBook(book, chapter, Constant.renderLongTitles)
heading1 = book.webTitle
if !isSupplementary(book) {
heading2 = book.heading2
if heading2 != "" {
heading2 = "\(heading2)\(chapter)"
}
}
let stylePath = Bundle.main.path(forResource: "scripture", ofType: "css")!
let scriptureStyle = try? NSString(contentsOfFile: stylePath, encoding: String.Encoding.utf8.rawValue)
var page = "<!doctype html>\n<html><head><title>\(title)</title>\n"
if let style = scriptureStyle {
page += "<style type=\"text/css\">\n\(style)\n</style>\n"
}
page += "<meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=NO\" />\n"
page += "</head>\n<body>"
page += "<div class=\"heading1\">\(heading1)</div>"
page += "<div class=\"heading2\">\(heading2)</div>"
page += "<div class=\"chapter\">"
collectedGeocodedPlaces = [GeoPlace]()
for scripture in GeoDatabase.sharedGeoDatabase.versesForScriptureBookId(bookId, chapter) {
var verseClass = "verse"
if scripture.flag == "H" {
verseClass = "headVerse"
}
page += "<a name=\"\(scripture.verse)\"><div class=\"\(verseClass)\">"
if scripture.verse > 1 && scripture.verse < Constant.footnoteVerse {
page += "<span class=\"verseNumber\">\(scripture.verse)</span>"
}
page += geocodedTextForVerseText(scripture.text, scripture.id)
page += "</div>"
}
let scriptPath = Bundle.main.path(forResource: "geocode", ofType: "js")!
let script = try! NSString(contentsOfFile: scriptPath, encoding: String.Encoding.utf8.rawValue)
page += "</div></body><script type=\"text/javascript\">\(script)</script></html>"
return (page.convertToHtmlEntities(), collectedGeocodedPlaces)
}
// MARK: - Private helpers
private func geocodedTextForVerseText(_ verseText: String, _ scriptureId: Int) -> String {
var verseText = verseText
for (geoplace, geotag) in GeoDatabase.sharedGeoDatabase.geoTagsForScriptureId(scriptureId) {
let startIndex = verseText.index(verseText.startIndex, offsetBy: geotag.startOffset)
let endIndex = verseText.index(startIndex, offsetBy: geotag.endOffset - geotag.startOffset)
collectedGeocodedPlaces.append(geoplace)
// Insert hyperlink for geotag in this verse at the given offsets
verseText = """
\(verseText[..<startIndex])\
<a href="\(Constant.baseUrl)\(geoplace.id)">\
\(verseText[startIndex ..< endIndex])</a>\
\(verseText[endIndex...])
"""
}
return verseText
}
private func isSupplementary(_ book: Book) -> Bool {
return book.numChapters == nil && book.parentBookId != nil;
}
private func titleForBook(_ book: Book, _ chapter: Int, _ renderLongTitles: Bool) -> String {
var title = renderLongTitles ? book.citeFull : book.citeAbbr
let numChapters = book.numChapters ?? 0
if chapter > 0 && numChapters > 1 {
title += " \(chapter)"
}
return title
}
}
| true
|
acfbb354ce888c29f611087114b7b8aa229d5c87
|
Swift
|
cshcshan/TableView-swift
|
/TableView-swift/AutoLayout/AutoLayoutViewController.swift
|
UTF-8
| 1,802
| 2.796875
| 3
|
[] |
no_license
|
//
// AutoLayoutViewController.swift
// TableView-swift
//
// Created by Han Chen on 2019/1/6.
// Copyright © 2019 cshan. All rights reserved.
//
import Foundation
import UIKit
class AutoLayoutViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
private var dataArray: [[String]] = []
override func viewDidLoad() {
super.viewDidLoad()
setupDataArray()
setupTableView()
}
private func setupDataArray() {
dataArray = []
for index in 0..<20 {
var data: [String] = []
data.append("\(index + 1)")
var data1 = ""
var data2 = ""
for _ in 0..<index + 1 {
data1 += "\(Int.random(in: 0..<1000))"
data2 += "\(Int.random(in: 0..<1000))\n"
}
data.append("\(data1)")
data.append("\(data2)")
dataArray.append(data)
}
}
private func setupTableView() {
tableView.register(UINib(nibName: String(describing: AutoLayoutTableViewCell.self), bundle: nil), forCellReuseIdentifier: "CELL")
tableView.dataSource = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 50
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CELL", for: indexPath) as! AutoLayoutTableViewCell
let data = dataArray[indexPath.row]
cell.bind(one: data[0], two: data[1], three: data[2])
return cell
}
}
| true
|
3163a04ff354eb226adbc1c7aedea17abb5cb44a
|
Swift
|
david-sobeski/ReefLifeTV
|
/ReefLifeTV/Ux/Species/SpecieDetailsViewController.swift
|
UTF-8
| 4,337
| 2.59375
| 3
|
[] |
no_license
|
//
// SpecieDetailsViewController.swift
// ReefLifeTV
//
// Created by David Sobeski on 11/4/18.
// Copyright © 2018 David Sobeski. All rights reserved.
//
import UIKit
class SpecieDetailsViewController: UIViewController, DetailsDelegate {
// ---------------------------------------------------------------------------------------------
// MARK: - Public Properties
public var specieId: Int = -1
// ---------------------------------------------------------------------------------------------
// MARK: - Internal Properties
private var specieDetail: SpecieDetailModel = SpecieDetailModel()
private var speciePhotos: Array<SpeciePhotoModel> = [SpeciePhotoModel]()
// ---------------------------------------------------------------------------------------------
// MARK: - IBOutlets
@IBOutlet var specieImageView: UIImageView!
@IBOutlet var detailsTextView: UITextView!
@IBOutlet var proertiesView: UIView!
// ---------------------------------------------------------------------------------------------
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
//
// Fetch the details for our specie.
//
self.specieDetail = RLDatabase.shared.getSpecieDetail(specieId)
//
// Fetch the photos for our specie.
//
self.speciePhotos = RLDatabase.shared.getSpeciePhotos(specieId)
//
// Set all of our properties and details.
//
if self.speciePhotos.count == 0 {
self.specieImageView.image = UIImage(named: Resource.UnknownImage)//?.resizeTo(self.specieImageView.bounds)
} else {
self.specieImageView.image = UIImage(named: self.speciePhotos[0].name)//?.resizeTo(self.specieImageView.bounds)
}
//
// We need our UIImageView to support the ability to be tapped or clicked. Therefore,
// we need to enable user interaction.
//
self.specieImageView.isUserInteractionEnabled = true
self.specieImageView.adjustsImageWhenAncestorFocused = true
//
// We need our UITextView to have the ability to be selectable and scrollable.
//
self.detailsTextView.text = self.specieDetail.details
self.detailsTextView.isSelectable = true
self.detailsTextView.isUserInteractionEnabled = true
self.detailsTextView.panGestureRecognizer.allowedTouchTypes = [UITouch.TouchType.indirect.rawValue] as [NSNumber]
}
//
// Notifies the view controller that a segue is about to be performed. Note, the default
// implementation does nothing, so there is no need to call the super class.
//
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier! == Resource.SegueProperties {
if let propertiesViewController = segue.destination as? PropertiesViewController {
propertiesViewController.delegate = self
}
}
}
// ---------------------------------------------------------------------------------------------
// MARK: - DetailsDelegate
func getSpecieDetails() -> SpecieDetailModel {
return self.specieDetail
}
// ---------------------------------------------------------------------------------------------
// MARK: - IBActions
@IBAction func onTap(_ sender: UITapGestureRecognizer) {
//
// Since we can not add a touch to a UIImageView in Interface Builder, have to programmatically
// disply our view controller that is used to display our full image. We get the
// Storyboard ID for our detailed picture controller and we present it. We need to
// pass the ID of the specie to our detailed photo viewer so it can display the
// appropriate photo.
//
let photoViewController = UIStoryboard(name: Resource.StoryboardPhoto, bundle: nil).instantiateInitialViewController() as? PhotoViewController
photoViewController?.photoModel = self.speciePhotos[0]
//
// Show our new controller.
//
self.present(photoViewController!, animated: true, completion: nil)
}
}
| true
|
42476b7c49f8fccadcffd381a152b07fc017b8c3
|
Swift
|
hendoware/ios-sprint4-challenge
|
/MyMovies/MyMovies/Model Controllers/MovieController.swift
|
UTF-8
| 8,015
| 3.015625
| 3
|
[] |
no_license
|
import Foundation
import CoreData
class MovieController {
init() { fetchMoviesFromServer() }
static var shared = MovieController()
private let apiKey = "4cc920dab8b729a619647ccc4d191d5e"
private let baseURL = URL(string: "https://api.themoviedb.org/3/search/movie")!
private let firebaseURL = URL(string: "https://mymovies-5e431.firebaseio.com/")!
func searchForMovie(with searchTerm: String, completion: @escaping (Error?) -> Void) {
var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: true)
let queryParameters = ["query": searchTerm,
"api_key": apiKey]
components?.queryItems = queryParameters.map({URLQueryItem(name: $0.key, value: $0.value)})
guard let requestURL = components?.url else {
completion(NSError())
return
}
URLSession.shared.dataTask(with: requestURL) { (data, _, error) in
if let error = error {
NSLog("Error searching for movie with search term \(searchTerm): \(error)")
completion(error)
return
}
guard let data = data else {
NSLog("No data returned from data task")
completion(NSError())
return
}
do {
let movieRepresentations = try JSONDecoder().decode(MovieRepresentations.self, from: data).results
self.searchedMovies = movieRepresentations
completion(nil)
} catch {
NSLog("Error decoding JSON data: \(error)")
completion(error)
}
}.resume()
}
// MARK: - Properties
var searchedMovies: [MovieRepresentation] = []
}
// Core Data
extension MovieController {
// Create a new movie in the managed object context & save it to persistent store
func addMovie(with title: String, hasWatched: Bool = false, context: NSManagedObjectContext = CoreDataStack.shared.mainContext) {
let movie = Movie(title: title, hasWatched: hasWatched, context: context)
do {
try CoreDataStack.shared.save(context: context)
} catch {
NSLog("Error saving movie: \(error)")
}
put(movie: movie)
}
// Update an existing movie in the managed object context and save it to persistent store
func update(movie: Movie) {
movie.hasWatched = !movie.hasWatched
put(movie: movie)
}
// Delete a movie in the managed object context and save the new managed object context
// to persistent store
func delete(movie: Movie) {
deleteMovieFromServer(movie: movie)
let moc = CoreDataStack.shared.mainContext
moc.delete(movie)
do {
try CoreDataStack.shared.save(context: moc)
} catch {
moc.reset()
NSLog("Error saving moc after deleting movie: \(error)")
}
}
func movie(for identifier: String, in context: NSManagedObjectContext) -> Movie? {
guard let identifier = UUID(uuidString: identifier) else { return nil }
let fetchRequest: NSFetchRequest<Movie> = Movie.fetchRequest()
let predicate = NSPredicate(format: "identifier == %@", identifier as NSUUID)
fetchRequest.predicate = predicate
var result: Movie? = nil
context.performAndWait {
do {
result = try context.fetch(fetchRequest).first
} catch {
NSLog("Error fetching movie with UUID: \(identifier): \(error)")
}
}
return result
}
}
// Networking
extension MovieController {
// Typealias for completion handler
typealias CompletionHandler = (Error?) -> Void
func fetchMoviesFromServer(completion: @escaping CompletionHandler = { _ in }) {
let requestURL = firebaseURL.appendingPathExtension("json")
URLSession.shared.dataTask(with: requestURL) { (data, _, error) in
if let error = error {
NSLog("Error fetching movies: \(error)")
completion(error)
}
guard let data = data else {
NSLog("No data returned from Firebase.")
completion(NSError())
return
}
do {
let movieRepresentations = try JSONDecoder().decode([String: MovieRepresentation].self, from: data).map({ $0.value })
let backgroundContext = CoreDataStack.shared.container.newBackgroundContext()
backgroundContext.performAndWait {
for movieRep in movieRepresentations {
guard let identifier = movieRep.identifier?.uuidString else
{ return }
if let _ = self.movie(for: identifier, in: backgroundContext) {} else {
let _ = Movie(movieRepresentation: movieRep, context: backgroundContext)
}
}
do {
try CoreDataStack.shared.save(context: backgroundContext)
} catch {
NSLog("Error saving background context: \(error)")
}
}
completion(nil)
} catch {
NSLog("Error decoding Movie representations: \(error)")
completion(error)
return
}
}.resume()
}
func put(movie: Movie, completion: @escaping CompletionHandler = { _ in }) {
let identifier = movie.identifier ?? UUID()
let requestURL = firebaseURL.appendingPathComponent(identifier.uuidString).appendingPathExtension("json")
var request = URLRequest(url: requestURL)
request.httpMethod = "PUT"
do {
guard var movieRepresentation = movie.movieRepresentation else {
completion(NSError())
return
}
movieRepresentation.identifier = identifier
movie.identifier = identifier
try CoreDataStack.shared.save()
request.httpBody = try JSONEncoder().encode(movieRepresentation)
} catch {
NSLog("Error encoding Movie representation: \(error)")
completion(error)
return
}
URLSession.shared.dataTask(with: request) { (data, _, error) in
if let error = error {
NSLog("Error PUTing Movie: \(error)")
completion(error)
return
}
completion(nil)
}.resume()
}
func deleteMovieFromServer(movie: Movie, completion: @escaping CompletionHandler = { _ in }) {
guard let identifier = movie.identifier else {
NSLog("No identifier for Movie to delete")
completion(NSError())
return
}
let requestURL = firebaseURL.appendingPathComponent(identifier.uuidString).appendingPathExtension("json")
var request = URLRequest(url: requestURL)
request.httpMethod = "DELETE"
URLSession.shared.dataTask(with: request) { (data, _, error) in
completion(error)
}.resume()
}
}
| true
|
b7ad311e834bf8bc781d06e1e3d5aff402c990fe
|
Swift
|
freddyholland/Demograph
|
/Demograph/Classes/Util/Account.swift
|
UTF-8
| 10,245
| 2.625
| 3
|
[] |
no_license
|
//
// Auth.swift
// Demograph
//
// Created by Frederick Holland on 24/04/20.
// Copyright © 2020 Frederick Holland. All rights reserved.
//
import Foundation
import FirebaseAuth
import FirebaseFirestore
class Account {
public static func create(email: String, password: String, local_tag: String, name: String, platforms: [Platform], completionHandler: @escaping (_ success: Bool, _ error: Error?) -> Void) {
Auth.auth().createUser(withEmail: email, password: password, completion: {
(result, error) in
guard let user = result?.user, error == nil else {
// There was an error generating an account
completionHandler(false, error)
print(error!)
return
}
let profile = Profile(id: user.uid, local_tag: local_tag.lowercased(), name: name, picture: Placeholders.picture!, banner: Placeholders.banner!, platforms: [], bio: "", supporting: [], supporters: [], clips: [])
saveProfile(profile: profile, completion: {
success in
if success {
print("account successfully created")
/*updateUsername(profile: profile, tag: local_tag, completion: {
success in
if !success {
print("An error occurred updating the created profile's username to the userbase.")
}
})*/
} else {
completionHandler(false, error)
}
})
let emailData = ["email":email]
Firestore.firestore().collection("users").document(user.uid).setData(emailData, merge: true)
//Firestore.firestore().collection("users").document(user.uid).setValue(email, forKey: "email")
completionHandler(true, error)
})
}
public static func updateSupporting(profile: Profile)
{
let id = profile.id
let supporting = profile.supporting!
Firestore.firestore().collection("users").document(id).setData(["supporting":supporting], merge: true)
//Firestore.firestore().collection("users").document(id).setValue(supporting, forKey: "supporting")
}
/*public static func updateUsername(profile: Profile, tag: String, completion: @escaping (_ success: Bool) -> Void) {
print("attempting to download userbase document")
Firestore.firestore().collection("info").document("userbase").getDocument
{ (snapshot, error) in
print("updating userbase")
if let error = error {
print("An error occurred: \(error)")
completion(false)
return
}
print("no errors, downloading data")
var data = snapshot?.data() as? [String:String] ?? [:]
if (data[profile.local_tag] != nil) {
data.removeValue(forKey: profile.local_tag)
}
data[tag] = profile.id
Firestore.firestore().collection("info").document("userbase").setData(data)
completion(true)
}
}*/
public static func attemptLogin(email: String, password: String, completionHandler: @escaping (_ success: Bool, _ error: Error?) -> Void) {
Auth.auth().signIn(withEmail: email, password: password, completion: {
(result, error) in
guard let _ = result?.user, error == nil else {
// There was an error generating an account
completionHandler(false, error)
print(error!)
return
}
completionHandler(true, error)
})
}
public static func userTagExists(user_tag: String, completionHandler: @escaping (_ success: Bool) -> Void) {
Firestore.firestore().collection("users").whereField("local_tag", in: [user_tag])
Firestore.firestore().collection("users").getDocuments(completion: {
(snapshot, error) in
if let error = error {
print(error)
} else {
for document in snapshot!.documents {
if(!document.exists) {
continue
}
if(document.get("local_tag") == nil) {
continue
}
let local_tag: String = document.get("local_tag") as! String
if local_tag.lowercased() == user_tag.lowercased() {
completionHandler(true)
return
}
}
completionHandler(false)
}
})
}
/*public static func getProfileUID(tag: String, completion: @escaping (_ uid: String) -> Void) {
Firestore.firestore().collection("info").document("userbase").getDocument
{ (snapshot, error) in
if let error = error {
print("An error occurred: \(error)")
return
}
print("Data: \(snapshot?.data())")
print("Tag: \(tag)")
let userList = snapshot?.data()! as? [String:String] ?? [:]
if !userList[tag.lowercased()].isEmpty {
completion(userList[tag.lowercased()]!)
} else {
completion("")
}
}
}*/
public static func getProfile(userID: String, completion: @escaping (_ user: Profile) -> Void) {
let profile = Profile(id: userID, local_tag: "", name: "", picture: UIImage(), banner: UIImage(), platforms: [], bio: "", supporting: [], supporters: [], clips: [])
print("attempting to get profile")
Firestore.firestore().collection("users").document(userID).getDocument(completion: {
(snapshot, error) in
if let error = error {
print(error)
print("there was an aerror")
return
}
print("checking for local_tag")
if (snapshot?.get("local_tag") != nil)
&& (snapshot?.get("name") != nil)
&& (snapshot?.get("email") != nil) {
// All necessary fields are available.
print("Stage 1 pass")
profile.local_tag = snapshot?.get("local_tag") as! String
profile.name = snapshot?.get("name") as! String
if snapshot?.get("bio") != nil {
profile.bio = snapshot?.get("bio") as! String as String
}
if snapshot?.get("platforms") != nil {
let platformArrays = snapshot?.get("platforms") as! [[String:String]]
var platforms:[Platform] = []
for platformArray in platformArrays {
platforms.append(Platform.getPlatform(from: platformArray))
}
profile.platforms = platforms
}
if snapshot?.get("supporting") != nil {
let supporting = snapshot?.get("supporting") as! [String]
profile.supporting = supporting
} else {
profile.supporting = []
}
if snapshot?.get("clips") != nil {
let clips = snapshot?.get("clips") as! [Int]
profile.clips = clips
} else {
profile.clips = []
}
Bucket.getUserPicture(id: userID, completion: {
image in
profile.picture = image
Bucket.getUserBanner(id: userID, completion: {
image in
profile.banner = image
completion(profile)
})
})
}
})
}
public static func saveProfile(profile: Profile, completion: @escaping (_ success: Bool) -> Void) {
print("### Recieved request to save Profile")
let id = profile.id
var data: [String:Any] = [
"local_tag":profile.local_tag.lowercased(),
"name":profile.name,
"bio":profile.bio!,
"clips":profile.clips!,
"supporting":profile.supporting!
]
print(profile.id)
/*if profile.clips?.count != 0 {
data["clips"] = profile.clips
//ref.setValue(profile.clips, forKey: "clips")
}*/
if profile.platforms?.count != 0 {
var platforms:[[String:String]] = []
for platform in profile.platforms! {
platforms.append(Platform.getDictionary(from: platform))
}
data["platforms"] = platforms
//ref.setValue(platforms, forKey: "platforms")
} else {
data["platforms"] = []
}
Firestore.firestore().collection("users").document(id).setData(data, merge: true) { err in
if let err = err {
print("### Error writing document: \(err)")
completion(false)
} else {
print("### Document successfully written!")
/*updateUsername(profile: profile, tag: profile.local_tag, completion: {
success in
if !success {
print("An error occurred updating the value of the users local_tag in the userbase.")
}
})*/
completion(true)
}
}
Bucket.saveUserPicture(profile: profile)
Bucket.saveUserBanner(profile: profile)
}
}
| true
|
8dccee595c1dd406647eae01bd56e22b605031c8
|
Swift
|
ZuopanYao/swift-utils
|
/Sources/Utils/geom/context/gradient/GraphicsGradientKind.swift
|
UTF-8
| 1,261
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
//typealias GraphicsGradientKind = GraphicsGradientKind
public protocol GraphicsGradientKind {
var cgGradient:CGGradient {get}
var colors:[CGColor]{get set}
var locations:[CGFloat]{get set}/*same as color stops*/
var transformation:CGAffineTransform?{get set}
}
extension GraphicsGradientKind{
/**
* Convert
*/
func gradient()->GradientKind{
switch self{
case let gradient as LinearGraphicsGradient:
return gradient.linearGradient()
case let gradient as RadialGraphicsGradient:
return gradient.radialGradient()
default:
fatalError("type not supported")
}
}
}
public protocol GraphicsGradientDecoratable:GraphicsGradientKind {
var gradient:GraphicsGradient {get set}
}
extension GraphicsGradientDecoratable{
public var colors:[CGColor]{get{return gradient.colors} set{gradient.colors = newValue}}
public var locations:[CGFloat]{get{return gradient.locations} set{gradient.locations = newValue}}/*same as color stops*/
public var transformation:CGAffineTransform?{get{return gradient.transformation} set{gradient.transformation = newValue}}
public var cgGradient:CGGradient {return self.gradient.cgGradient}
}
| true
|
6e4eac7ea1209421fbf4bb938288262070427f05
|
Swift
|
scott-lydon/ParkMyWheels
|
/SFMotorcycleParking/LocationManagerAuth.swift
|
UTF-8
| 703
| 2.546875
| 3
|
[] |
no_license
|
import CoreLocation
import UIKit
import GoogleMaps
import GooglePlaces
extension ViewController: CLLocationManagerDelegate {
//Handles authorization
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted:
print("Location access was restricted.")
case .denied:
print("User denied access to location.")
mapView.isHidden = false
case .notDetermined:
print("Location status not determined.")
case .authorizedAlways: fallthrough
case .authorizedWhenInUse:
print("Location status is OK.")
}
}
}
| true
|
5a8f2ba4080f23e9cfa02a4a269ca5db062229f4
|
Swift
|
Vinogradov7511339/GitHubClient
|
/GitHub Client/Data/Network/Models/GithubApi/ReleaseResponseDTO.swift
|
UTF-8
| 841
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// ReleaseResponseDTO.swift
// GitHub Client
//
// Created by Alexander Vinogradov on 11.08.2021.
//
import Foundation
struct ReleaseResponseDTO: Codable {
let id: Int
let htmlUrl: URL
let url: URL
let tagName: String
let targetCommitish: String
let reactions: Reactions?
let name: String
let body: String
let createdAt: String
let publishedAt: String
let author: UserResponseDTO
func toDomain() -> Release {
.init(id: id,
tagName: tagName,
targetCommitish: targetCommitish,
name: name,
body: body,
createdAt: createdAt.toDate(),
publishedAt: publishedAt.toDate(),
author: author.toDomain(),
reactions: reactions,
url: url,
htmlUrl: htmlUrl)
}
}
| true
|
aeec825454978a5db8779843db5ce569e7e31a0f
|
Swift
|
mrtymcln/FilmNotes
|
/FilmNotes/Attribute Views/AttributeFormView.swift
|
UTF-8
| 2,418
| 2.640625
| 3
|
[] |
no_license
|
import SwiftUI
struct AttributeFormView: View {
@Binding var textName: String
@Binding var textOrder: String
var body: some View {
Section(header: Text("")) {
VStack {
HStack {
Text("Order")
.foregroundColor(.gray)
Spacer()
}
TextField("", text: self.$textOrder)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
VStack {
HStack {
Text("Date taken").foregroundColor(.gray)
DatePicker(selection: /*@START_MENU_TOKEN@*/.constant(Date())/*@END_MENU_TOKEN@*/, label: { Text("") })
}
}
}
Section(header: Text("")) {
VStack {
HStack {
Text("Aperture")
.foregroundColor(.gray)
Spacer()
}
TextField("f/", text: self.$textName)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
VStack {
HStack {
Text("Shutter speed")
.foregroundColor(.gray)
Spacer()
}
TextField("", text: self.$textName)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
VStack {
HStack {
Text("Compensation")
.foregroundColor(.gray)
Spacer()
}
TextField("", text: self.$textName)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
VStack {
HStack {
Text("Notes")
.foregroundColor(.gray)
Spacer()
}
TextField("", text: self.$textName)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
}
}
}
#if DEBUG
struct AttributeFormView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
Form {
AttributeFormView(textName: .constant(""), textOrder: .constant(""))
}
}
}
}
#endif
| true
|
8455b1daae4cd72f8525728c7d9501c4ce4700ae
|
Swift
|
DavidDuarte22/VeritranTest
|
/Example/Tests/TestsTransfer.swift
|
UTF-8
| 5,683
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// TestsTransfer.swift
// VeritranSDK_Tests
//
// Created by itsupport on 12/01/2021.
// Copyright © 2021 CocoaPods. All rights reserved.
//
import XCTest
import VeritranSDK
class TestsTransfer: XCTestCase {
var mockusers: [User]!
var mockInterface: UserApiInterface!
var sdkInstance: VeritranSDK!
// NOTE: userUSDAccount have the same pointer address that user's USDAccount so we can test using a var of that account. Making changes in one impact in the other
var franciscoUser: User!
var matiasUser: User!
var franciscoUserUSDAccount: Account!
var matiasUserUSDAccount: Account!
override func setUp() {
super.setUp()
mockusers = [
User(identifier: "francisco", name: "Francisco Dominguez", accounts: [.USD: Account(type: Currency.USD, ammount: 100)]),
User(identifier: "matias", name: "Matias Fernandez", accounts: [.USD: Account(type: Currency.USD, ammount: 100)])
]
mockInterface = UserApiImpl(usersDb: mockusers)
sdkInstance = VeritranSDK(interface: mockInterface)
franciscoUser = sdkInstance.usersAPI.getUserById(id: "francisco")
matiasUser = sdkInstance.usersAPI.getUserById(id: "matias")
self.setUSDAccounts()
}
// Transfer
func testTransfer(){
// Check USD accounts are created.
guard self.franciscoUserUSDAccount != nil else { return }
guard self.matiasUserUSDAccount != nil else { return }
self.franciscoUserUSDAccount.withdrawAmmount(ammountTo: 10) { [weak self] result in
switch result {
case .success(_):
self?.matiasUserUSDAccount.increaseAmmount(ammountTo: 10) { result in
switch result {
case .success(_):
XCTAssertEqual(self?.franciscoUserUSDAccount.getAmmount(), 90)
XCTAssertEqual(self?.matiasUserUSDAccount.getAmmount(), 110)
case .failure(_):
XCTFail("Failed depositing money")
}
}
case .failure(_):
XCTFail("Failed withdrawing money")
}
self?.expectation(description: "transfer").fulfill()
self?.waitForExpectations(timeout: 5, handler: nil)
}
}
func testTransferFailedWithdrawError(){
// Check USD accounts are created.
guard self.franciscoUserUSDAccount != nil else { return }
guard self.matiasUserUSDAccount != nil else { return }
self.franciscoUserUSDAccount.withdrawAmmount(ammountTo: 101) { [weak self] result in
switch result {
case .success(_):
self?.matiasUserUSDAccount.increaseAmmount(ammountTo: 10) { result in
switch result {
case .success(_):
XCTFail("Shouldn't reach this point")
case .failure(_):
XCTFail("Shouldn't reach this point")
}
}
case .failure(_):
XCTAssertEqual(self?.franciscoUserUSDAccount.getAmmount(), 100)
}
self?.expectation(description: "transfer").fulfill()
self?.waitForExpectations(timeout: 5, handler: nil)
}
}
func testTransferDepositFailed(){
// Check USD accounts are created.
guard self.franciscoUserUSDAccount != nil else { return }
guard self.matiasUserUSDAccount != nil else { return }
self.franciscoUserUSDAccount.withdrawAmmount(ammountTo: 10) { [weak self] result in
switch result {
case .success(_):
//force error
self?.matiasUserUSDAccount.increaseAmmount(ammountTo: -10) { result in
switch result {
case .success(_):
XCTFail("Shouldn't reach this point")
case .failure(_):
// depositing the money again to the first user
self?.franciscoUserUSDAccount.increaseAmmount(ammountTo: 10) { result in
switch result {
case .success(_):
XCTAssertEqual(self?.franciscoUserUSDAccount.getAmmount(), 100)
XCTAssertEqual(self?.matiasUserUSDAccount.getAmmount(), 100)
case .failure(_):
XCTFail("Failed depositing money")
}
}
}
}
case .failure(_):
XCTFail("Failed withdrawing money")
}
self?.expectation(description: "transfer").fulfill()
self?.waitForExpectations(timeout: 5, handler: nil)
}
}
}
//MARK: Utils for tests
extension TestsTransfer {
func setUSDAccounts () {
franciscoUser.getAccountByCurrency(currency: .USD) { result in
switch result {
case .success(let account):
self.franciscoUserUSDAccount = account
case .failure(_):
break
}
}
matiasUser.getAccountByCurrency(currency: .USD) { result in
switch result {
case .success(let account):
self.matiasUserUSDAccount = account
case .failure(_):
break
}
}
}
}
| true
|
6bdd48a1f79ab9ccbf840bc234f842173bb8d9f6
|
Swift
|
hosamasd/MST-XD-using-swiftui
|
/MST XD/view/about us/SettingsRowView.swift
|
UTF-8
| 1,382
| 3.046875
| 3
|
[] |
no_license
|
//
// SettingsRowView.swift
// MST XD
//
// Created by hosam on 3/18/21.
//
import SwiftUI
struct SettingsRowView: View {
let name:String
var rightName = ""
var noValue = false
@Binding var show:Bool
// @Binding var shows:Bool
var body: some View {
VStack {
Spacer()
.frame(height:8)
HStack {
Text(name)
Spacer()
if noValue {
Spacer()
}else
if rightName == "" {
Image(systemName: "chevron.forward")
.foregroundColor(.gray)
}else
if rightName == "?" {
Toggle("", isOn: $show)
}
else {
Text(rightName)
.font(.system(size: 14))
}
}
Divider()
}
.padding(.horizontal)
.background(Color.white)
}
}
struct SettingsRowView_Previews: PreviewProvider {
static var previews: some View {
SettingsRowView(name: "about us", rightName: "?", show: .constant(true))
}
}
| true
|
5bd363c2fb7cf28f049ed966044216613286146e
|
Swift
|
alanturker/TradeList-FirebaseRealtimeDatabase
|
/TradeList/Controller/ItemController/ItemListUITableViewCell.swift
|
UTF-8
| 944
| 2.578125
| 3
|
[] |
no_license
|
//
// ItemListUITableViewCell.swift
// TradeList
//
// Created by Türker on 13.10.2021.
//
import UIKit
class ItemListUITableViewCell: UITableViewCell {
@IBOutlet private weak var productName: UILabel!
@IBOutlet private weak var productCategory: UILabel!
@IBOutlet private weak var productPrice: UILabel!
@IBOutlet private weak var productDescription: UILabel!
@IBOutlet private weak var productDate: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func configureCellOutlets(model: Item) {
productName.text = model.title
productDate.text = model.dateItem
productPrice.text = model.price
productDescription.text = model.descriptionItem
productCategory.text = model.category
}
}
| true
|
c05097271a7a5c51aee5f5b4d70f3116b38fca89
|
Swift
|
adamnemecek/PointOfView
|
/PointOfView/Extensions/simd.swift
|
UTF-8
| 3,748
| 3.03125
| 3
|
[] |
no_license
|
import simd
extension float3 {
static let xAxis = float3(x: 1, y: 0, z: 0)
static let yAxis = float3(x: 0, y: 1, z: 0)
static let zAxis = float3(x: 0, y: 0, z: 1)
init(xy: float2, z: Float) {
self.init(x: xy.x, y: xy.y, z: z)
}
func transformed(by matrix: float4x4) -> float3 {
let homogenous = matrix * float4(xyz: self, w: 1)
return homogenous.xyz / homogenous.w
}
func rotated(about axis: float3, by angle: Float) -> float3 {
return self.transformed(by: float4x4.rotation(about: axis, by: angle))
}
}
extension float4 {
init(xyz: float3, w: Float) {
self.init(x: xyz.x, y: xyz.y, z: xyz.z, w: w)
}
var xyz: float3 {
get {
return float3(x: x, y: y, z: z)
}
set {
x = newValue.x
y = newValue.y
z = newValue.z
}
}
init(x: Float, yzw: float3) {
self.init(x: x, y: yzw.x, z: yzw.y, w: yzw.z)
}
init(x: Float, y: Float, zw: float2) {
self.init(x: x, y: y, z: zw.x, w: zw.y)
}
init(xy: float2, z: Float, w: Float) {
self.init(x: xy.x, y: xy.y, z: z, w: w)
}
init(xy: float2, zw: float2) {
self.init(x: xy.x, y: xy.y, z: zw.x, w: zw.y)
}
func transformed(by matrix: float4x4) -> float4 {
return matrix * self
}
}
extension float4x4 {
static var identity: float4x4 {
return .init(diagonal: .init(1))
}
static func translation(by vector: float3) -> float4x4 {
return .identity + .init(columns: (.init(0), .init(0), .init(0), .init(xyz: vector, w: 0)))
}
static func scaling(by vector: float3) -> float4x4 {
return .init(diagonal: .init(xyz: vector, w: 1))
}
static func rotation(about axis: float3, by angle: Float) -> float4x4 {
return float4x4(columns: (
float4(
x: cos(angle) + axis.x * axis.x * (1 - cos(angle)),
y: axis.x * axis.y * (1 - cos(angle)) + axis.z * sin(angle),
z: axis.x * axis.z * (1 - cos(angle)) - axis.y * sin(angle),
w: 0
),
float4(
x: axis.x * axis.y * (1 - cos(angle)) - axis.z * sin(angle),
y: cos(angle) + axis.y * axis.y * (1 - cos(angle)),
z: axis.y * axis.z * (1 - cos(angle)) + axis.x * sin(angle),
w: 0
),
float4(
x: axis.x * axis.z * (1 - cos(angle)) + axis.y * sin(angle),
y: axis.y * axis.z * (1 - cos(angle)) - axis.x * sin(angle),
z: cos(angle) + axis.z * axis.z * (1 - cos(angle)),
w: 0
),
float4(xyz: .init(0), w: 1)
))
}
static func lookat(forward: float3, up: float3) -> float4x4 {
let normalizedForward = normalize(forward)
let right = normalize(cross(up, forward))
let orthogonalizedUp = normalize(cross(forward, right))
return float4x4(columns: (
float4(x: right.x, y: orthogonalizedUp.x, z: normalizedForward.x, w: 0),
float4(x: right.y, y: orthogonalizedUp.y, z: normalizedForward.y, w: 0),
float4(x: right.z, y: orthogonalizedUp.z, z: normalizedForward.z, w: 0),
float4(xyz: .init(0), w: 1)
))
}
static func infinitePerspective(fovy: Float, nearDistance: Float, aspectRatio: Float) -> float4x4 {
return float4x4(columns: (
float4(x: 1 / tan(fovy / 2) / aspectRatio, yzw: .init(0)),
float4(x: 0, y: 1 / tan(fovy / 2), zw: .init(0)),
float4(xy: .init(0), zw: .init(1)),
float4(xy: .init(0), z: -2 * nearDistance, w: 0)
))
}
}
| true
|
ac0338158e78c0beeb19902443b573719c3219e7
|
Swift
|
GridsDev/swiftui-MenuApp
|
/swiftui-MenuApp/swiftui-MenuApp/SkyView.swift
|
UTF-8
| 2,345
| 2.796875
| 3
|
[] |
no_license
|
//
// SkyView.swift
// swiftui-MenuApp
//
// Created by Grids Jivapong on 17/2/2564 BE.
//
import SwiftUI
struct SkyView: View {
@AppStorage("isNight") var isNight = false
var body: some View {
VStack {
if isNight {
LinearGradient(gradient: Gradient(colors: [Color(#colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)), Color(#colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1))]), startPoint: .top, endPoint: .bottom)
.ignoresSafeArea()
} else {
ZStack {
LinearGradient(gradient: Gradient(colors: [Color(#colorLiteral(red: 0.004859850742, green: 0.09608627111, blue: 0.5749928951, alpha: 1)), Color(#colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1))]), startPoint: .top, endPoint: .bottom)
.ignoresSafeArea()
VStack {
Spacer()
Stars()
Stars()
.rotationEffect(.degrees(90))
.offset(x: 120)
Spacer()
}
Stars()
.rotationEffect(.degrees(-90))
.offset(x: -120, y: -200)
}
}
}
.frame(width: UIScreen.main.bounds.width)
.overlay(Button(action: { isNight.toggle() }, label: {
Image(systemName: isNight ? "moon.fill" : "sun.max.fill")
.font(.title)
.foregroundColor(.white)
.padding(.trailing, 32)
}), alignment: .topTrailing)
}
}
struct SkyView_Previews: PreviewProvider {
static var previews: some View {
SkyView()
}
}
struct Stars: View {
let offsets = [12, 72, -18, 42, 120, 0, 8, -55, 100]
var body: some View {
HStack {
ForEach(offsets, id: \.self) { cloudOffset in
Image(systemName: "star.fill")
.font(.caption)
.foregroundColor(.white)
.padding(18)
.offset(y: CGFloat(cloudOffset))
}
}
}
}
| true
|
bc25c01c05a1b74335ddc1ee50e769f3e05dbf63
|
Swift
|
loyihsu/fun-with-leetcode-in-swift
|
/Solutions/01 - Easy/1880. Check if Word Equals Summation of Two Words.swift
|
UTF-8
| 456
| 3.5625
| 4
|
[] |
no_license
|
// Problem: https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/
class Solution {
func code(for str: String) -> Int {
var temp = str.unicodeScalars.reduce("") {
$0 + "\($1.value - 97)"
}
return Int(temp)!
}
func isSumEqual(_ firstWord: String, _ secondWord: String, _ targetWord: String) -> Bool {
code(for: firstWord) + code(for: secondWord) == code(for: targetWord)
}
}
| true
|
708da5a1ef5bd0a117de5409c3465407ddc57aa0
|
Swift
|
vmagaziy/Articles
|
/Articles/HTTPClient.swift
|
UTF-8
| 1,947
| 3.046875
| 3
|
[] |
no_license
|
import Foundation
protocol URLSessionProtocol {
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
}
final class HTTPClient {
private let session: URLSessionProtocol
enum Error: Swift.Error, Equatable {
case HTTPStatus(Int, Data?)
}
init(session: URLSessionProtocol = URLSession.shared) {
self.session = session
}
static func parse(_ data: Data?, _ response: URLResponse?, _ error: Swift.Error?) -> Result<Data, Swift.Error> {
let statusCode = (response as? HTTPURLResponse)?.statusCode
if let statusCode = statusCode, !(200..<400).contains(statusCode) {
return .failure(Error.HTTPStatus(statusCode, data))
} else if let error = error {
return .failure(error)
} else {
return .success(data ?? Data())
}
}
func load(url: URL) -> Future<Data> {
return load(request: URLRequest(url: url))
}
func load(request: URLRequest) -> Future<Data> {
let promise = Promise<Data>()
let task = session.dataTask(with: request) { data, response, error in
let result = HTTPClient.parse(data, response, error)
switch result {
case let .failure(error):
if !error.isHTTPCancelError {
print("Failed to load \"\(request.url!)\": \(error)")
}
promise.reject(with: error)
case .success(let data):
promise.resolve(with: data)
}
}
task.resume()
return promise
}
}
private extension Error {
var isHTTPCancelError: Bool {
let nsError = self as NSError
return nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorCancelled
}
}
extension URLSession: URLSessionProtocol {
}
| true
|
3fc604c1b2680b4a9de76a783ee3ba869d32c698
|
Swift
|
talspektor/Coupons-System
|
/Coupons-System/Models/CouponsByCategory.swift
|
UTF-8
| 358
| 2.734375
| 3
|
[] |
no_license
|
//
// CouponsByCategory.swift
// CouponSystem
//
// Created by Tal talspektor on 21/01/2021.
//
import Foundation
struct CategoryCoupons: Codable, Identifiable, Equatable {
static func == (lhs: CategoryCoupons, rhs: CategoryCoupons) -> Bool {
return lhs.id == rhs.id
}
let id: Int
let category: Category
var coupons: [Coupon]
}
| true
|
9acdf731ef74f7c5253da622e0f8c4d21e443919
|
Swift
|
mehadi07/CodeFights-2
|
/solutions/ada_number.swift
|
UTF-8
| 2,864
| 3.0625
| 3
|
[] |
no_license
|
func adaNumber(line: String) -> Bool {
var chars = line.lowercaseString.characters.map({String($0)})
if chars[0] == "-" {
chars.removeAtIndex(0)
}
for base in 2...16 {
if parseNumWithHead(base, chars) != nil {
return true
}
}
if parseNum(10, chars) != nil {
return true
}
return false
}
func parseNumWithHead(base: Int, _ chars: [String]) -> Int? {
var first = -1
for i in 0..<chars.count {
if chars[i] == "#" {
first = i
break
}
}
if first == -1 || first == 0 || first == chars.count - 1 || first == chars.count - 2 {
return nil
}
if chars[chars.count - 1] != "#" {
return nil
}
var newChars: [String] = []
for i in 0..<first {
newChars.append(chars[i])
}
if base != parseNum(10, newChars) {
return nil
}
newChars = []
for i in (first + 1)..<(chars.count - 1) {
newChars.append(chars[i])
}
return parseNum(base, newChars)
}
func parseNum(base: Int, _ chars: [String]) -> Int? {
var end = baseToEnd(base), result = 0
for i in 0..<chars.count {
let char = chars[i]
if char == "_" {
if i == 0 {
return nil
}
if i == chars.count - 1 {
return nil
}
if (i + 1) < chars.count && chars[i + 1] == "_" {
return nil
}
continue
}
if base <= 10 {
if "0" <= char && char <= end {
result = result &* base &+ stringToInt(char)!
continue
}
} else {
if "0" <= char && char <= "9" {
result = result &* base &+ stringToInt(char)!
continue
}
if "a" <= char && char <= end {
result = result &* base &+ stringToInt(char)!
continue
}
}
return nil
}
return result
}
func stringToInt(string: String) -> Int? {
if "0" <= string && string <= "9" {
return Int(string)!
} else {
switch string {
case "a":
return 10
case "b":
return 11
case "c":
return 12
case "d":
return 13
case "e":
return 14
case "f":
return 15
default:
return nil
}
}
}
func baseToEnd(base: Int) -> String {
var end = ""
switch base {
case 2, 3, 4, 5, 6, 7, 8, 9, 10:
end = String(base - 1)
case 11:
end = "a"
case 12:
end = "b"
case 13:
end = "c"
case 14:
end = "d"
case 15:
end = "e"
case 16:
end = "f"
default:
end = ""
}
return end
}
| true
|
9a24a3a41292cef578b828ef389027397ca0977b
|
Swift
|
dennysplettlinger/swift-chucknorris-jokes
|
/chucknorris-jokes/chucknorris-jokes/chucknorris-jokes/ViewController.swift
|
UTF-8
| 1,768
| 2.953125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// chucknorris-jokes
//
// Created by dennys Plettlinger on 13.05.20.
// Copyright © 2020 dennysplettlinger. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var jokesTableView: UITableView!
var jokes = [Joke]()
override func viewDidLoad() {
super.viewDidLoad()
jokesTableView.dataSource = self
jokesTableView.delegate = self
fetchData()
}
func fetchData(){
DispatchQueue.global(qos: .background).async {
let jsonUrlString = "http://api.icndb.com/jokes"
let url = URL(string: jsonUrlString)!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
let responseJsonObject = try! JSONDecoder().decode(JokeResponse.self, from: data)
self.jokes = responseJsonObject.value
DispatchQueue.main.async {
self.jokesTableView.reloadData()
}
}
task.resume()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return jokes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let jokeCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let joke = self.jokes[indexPath.row]
jokeCell.textLabel?.text = joke.joke
return jokeCell
}
}
| true
|
cfaf9238e71e3f621fbe43b62e1c7f98cd92e701
|
Swift
|
LpsBanik/Swift_LufthansaApp
|
/Swift_LufthansaApp/Models/Country+CoreDataClass.swift
|
UTF-8
| 689
| 2.5625
| 3
|
[] |
no_license
|
//
// Country+CoreDataClass.swift
// Swift_LufthansaApp
//
// Created by Сергей Кохан on 08.12.2017.
// Copyright © 2017 Siarhei Kokhan. All rights reserved.
//
//
import Foundation
import CoreData
@objc(Country)
public class Country: NSManagedObject {
func inititial(serverResponse responseObject: [String: Any]) {
countryCode = responseObject["CountryCode"] as? String ?? ""
if let names = responseObject["Names"] as? [String:Any] {
if let name = names["Name"] as? [String:Any] {
if let countryName = name["$"] as? String {
self.countryName = countryName
}
}
}
}
}
| true
|
48ee984e1c54e9983dfdeb10bd62a3cec4bcd76a
|
Swift
|
alvintu/FaceOff
|
/FaceOff/Extras/FoundationExtras.swift
|
UTF-8
| 486
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// FoundationExtras.swift
// FaceOff
//
// Created by John Scalo.
// Copyright © 2018 Made by Windmill. All rights reserved.
//
import Foundation
extension Array {
func randomItem() -> Element? {
if isEmpty { return nil }
let index = Int(arc4random_uniform(UInt32(self.count)))
return self[index]
}
}
extension Int {
static func randomInt(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
}
| true
|
981ff3c494c95178976d5dc67f6f8aaf9bebfabe
|
Swift
|
DarthXander/class-times
|
/Class Times/TimeLeftView.swift
|
UTF-8
| 1,786
| 3.046875
| 3
|
[] |
no_license
|
//
// TimeLeftView.swift
// Class Times
//
// Created by Xander Clair on 11/9/16.
// Copyright © 2016 Xander Clair. All rights reserved.
//
import UIKit
protocol TimeLeftDataSource: class {
func getFilledAngle() -> CGFloat?
}
@IBDesignable
class TimeLeftView: UIView {
var dataSource: TimeLeftDataSource? {
didSet {
setNeedsDisplay()
}
}
private var color: UIColor = UIColor.red {
didSet {
color.set()
setNeedsDisplay()
}
}
private var countdownCenter: CGPoint {
return CGPoint(x: bounds.width/2.0, y: bounds.height/2.0)
}
private var radius: CGFloat {
return min(bounds.width/2.0, bounds.height/2.0)*CGFloat(0.9)
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
if let source = dataSource, let angle = source.getFilledAngle() {
color = UIColor.red
//let path = UIBezierPath(arcCenter: countdownCenter, radius: radius, startAngle: 0.0, endAngle: angle, clockwise: true)
let offset = CGFloat(-M_PI/2.0)
let path = UIBezierPath(arcCenter: countdownCenter, radius: radius, startAngle: offset, endAngle: offset + angle, clockwise: true)
path.addLine(to: CGPoint(x: countdownCenter.x, y: countdownCenter.y))
path.close()
path.fill()
}
else {
color = UIColor.gray
let offset = CGFloat(M_PI/2.0)
let path = UIBezierPath(arcCenter: countdownCenter, radius: radius, startAngle: offset, endAngle: offset + CGFloat(2.0*M_PI), clockwise: true)
path.fill()
}te
}
}
| true
|
5e8734388d3617cee1c1aedf3ebe46f31eefc066
|
Swift
|
EtsTest-iOSApps/ARISES
|
/ARISES/Display/ChartBGView.swift
|
UTF-8
| 1,713
| 3.25
| 3
|
[] |
no_license
|
//
// ChartBGView.swift
// ARISES
//
// Created by Xiaoyu Ma on 17/05/2018.
// Copyright © 2018 Ryan Armiger. All rights reserved.
//
//this view acts as chart BG color holder, does not contain range bar
import UIKit
/**
* This class is a subclass of UIView used to create the three bands of the 'safe' range for the background of the chart using it's
* methods.
*/
class ChartBGView: UIView {
//MARK: Methods
/**
The draw method is called on the instantiation of the ChartBGView. It calls methods to create the 3 bands that show the 'safe'
range of blood glucose measurements.
- Paramater rect: CGRect, the bounds of the View.
*/
override func draw(_ rect: CGRect) {
let path = UIBezierPath(rect: bounds)
path.addClip()
drawMiddleBand()
drawTopBand()
}
///Creates a rectangle of colour White from the mid-point of the CustomView (~10 on graph to ~4) to create the 'safe' region.
private func drawMiddleBand(){
let middleRect = CGRect(
origin: CGPoint(x: 0.0, y: bounds.height/2),
size: CGSize(width: frame.width, height: frame.height * 0.3)
)
#colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 1).set()
UIRectFill(middleRect)
}
///Creates a rectangle with a size of the top half of the CustomView giving the top band (between 10 and 20 on the graph).
private func drawTopBand(){
let topRect = CGRect(
origin: bounds.origin,
size: CGSize(width: frame.width, height: frame.height / 2))
#colorLiteral(red: 1, green: 0.5781051517, blue: 0, alpha: 1).set()
UIRectFill(topRect)
}
}
| true
|
a1b535384572c8696ee390779d0b1a340c294f2f
|
Swift
|
GNRaju9160/iOS
|
/TableViewH&F/TableViewH&F/HeaderandFooter.swift
|
UTF-8
| 3,370
| 2.734375
| 3
|
[] |
no_license
|
//
// HeaderandFooter.swift
// TableViewH&F
//
// Created by Training on 26/09/19.
// Copyright © 2019 Training. All rights reserved.
//
import UIKit
class HeaderandFooter: UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var tblData: UITableView!
let sectionsArr = ["HOLLYWOOD","BOLLYWOOD","TOLLYWOOD"]
let itemsArr = [
["Avatar","Titanic","Harryporter","Avangers","The Hulk","Thore","Captain America"], // TOLLYWOOD
["Krish","Dhoom","Ek Tha Tiger","Koi Milgaya","Chennai Express","Padmavathi","3Idiots","Golmal","Oh My God"], // BOLLYWOOD
["Bahubali","Magadeera","Saho","Syira Narasimha Reddy","Valmiki","Chalo","Orange","DJ","Bunny","Balu"], // TOLLYWOOD
]
let titleArr = ["English","Hindi","Telugu"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func numberOfSections(in tableView: UITableView) -> Int {
return sectionsArr.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemsArr[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HandFCell", for: indexPath) as! HandFCell
cell.lblText!.text = itemsArr [indexPath.section][indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let vwHeader = UIView(frame: CGRect(x: 0, y: 50, width: tableView.frame.size.width, height: 18))
let label = UILabel(frame: CGRect(x: 150, y: 5, width: tableView.frame.size.width, height: 18))
label.text = sectionsArr[section]
label.textColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
vwHeader.addSubview(label)
return vwHeader
}
// func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
// if section == 0 {
// return "English"
// }else if section == 1 {
// return "Hindi"
// }else{
// return "Telugu"
// }
// }
// func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// return self.sectionsArr[section]
// }
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let vwHeader = UIView(frame: CGRect(x: 0, y: 50, width: tableView.frame.size.width, height: 20))
let lblText = UILabel(frame: CGRect(x: 180, y: 5, width: 200, height: 20))
lblText.text = titleArr[section]
lblText.textColor = #colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1)
vwHeader.addSubview(lblText)
return vwHeader
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 100
}
}
| true
|
52e50eabed0cf7564c72d303660d36b63e1605d2
|
Swift
|
diefthyntis/petdagogie
|
/extension.playground/Contents.swift
|
UTF-8
| 1,341
| 3.890625
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
extension Int {
func ConvertirEnSring() -> String {
return String(self)
}
}
var j: Int
j = 7
print(j.ConvertirEnSring())
var mafamille = ["alan": 45, "axelle": 67, "minette": 5]
mafamille["jmj"] = 58
print(mafamille)
extension String {
func Imprimer() {
print(self)
}
func CodeAscii() -> Int {
if self.count == 1 {
var _caracteres = [String:Int]()
var _symbole: String
var _code: Int
for _code in (33...126) {
_symbole = String(UnicodeScalar(_code)!)
_caracteres[_symbole] = _code
//print(_symbole)
}
//print(_caracteres)
return _caracteres[self]!
}
else {
return 0
}
}
}
var char = "j"
print(char.CodeAscii())
char.Imprimer()
/*
func CodeAscii(pSymbole: String) -> Int {
//var attr = [String : AnyObject]()
var _caracteres = [String:Int]()
var _symbole: String
var _code: Int
for _code in (33...126) {
_symbole = String(UnicodeScalar(_code)!)
_caracteres[_symbole] = _code
print(_symbole)
}
_code = (_caracteres[pSymbole])!
return _code
}
var char = "A"
print (CodeAscii(pSymbole: char))
*/
| true
|
fabf20448b1a1b795096f3fc09952b34b2001917
|
Swift
|
Nagashi-A-A/SwiftLearning
|
/TPUnitTesting/TPUnitTestingTests/TPUnitTestingTests.swift
|
UTF-8
| 2,417
| 2.703125
| 3
|
[] |
no_license
|
//
// Project39UnitTestingTests.swift
// Project39UnitTestingTests
//
// Created by Anton Yaroshchuk on 01.07.2021.
//
import XCTest
@testable import TPUnitTesting
class TPUnitTestingTests: XCTestCase {
// override func setUpWithError() throws {
// // Put setup code here. This method is called before the invocation of each test method in the class.
// }
//
// override func tearDownWithError() throws {
// // Put teardown code here. This method is called after the invocation of each test method in the class.
// }
//
// func testExample() throws {
// // This is an example of a functional test case.
// // Use XCTAssert and related functions to verify your tests produce the correct results.
// }
//
// func testPerformanceExample() throws {
// // This is an example of a performance test case.
// self.measure {
// // Put the code you want to measure the time of here.
// }
// }
func testAllWordsLoaded(){
let playData = PlayData()
XCTAssertEqual(playData.allWords.count, 18440, "allWords must be 0")
}
func testWordCountsAreCorrect(){
let playData = PlayData()
XCTAssertEqual(playData.wordCounts.count(for: "story"), 35, "story does not appear 35 times.")
XCTAssertEqual(playData.wordCounts.count(for: "pray"), 316, "pray does not appear 316 times.")
XCTAssertEqual(playData.wordCounts.count(for: "men"), 304, "men does not appear 304 times.")
}
func testWordsLoadQuickly(){
measure{
_ = PlayData()
}
}
func testUserFilterWorks(){
let playData = PlayData()
playData.applyUserFilter("100")
XCTAssertEqual(playData.filteredWords.count, 495)
playData.applyUserFilter("1000")
XCTAssertEqual(playData.filteredWords.count, 55)
playData.applyUserFilter("10000")
XCTAssertEqual(playData.filteredWords.count, 1)
playData.applyUserFilter("test")
XCTAssertEqual(playData.filteredWords.count, 56)
playData.applyUserFilter("swift")
XCTAssertEqual(playData.filteredWords.count, 7)
playData.applyUserFilter("objective-c")
XCTAssertEqual(playData.filteredWords.count, 0, "Something goes wrong, Shakespeare do not like to write in objective-c at all!")
}
}
| true
|
043ab514e78aa4f311018c0df452b971925f47c9
|
Swift
|
HateganOana/WhatsCooking
|
/WhatsCooking/API.swift
|
UTF-8
| 770
| 2.875
| 3
|
[] |
no_license
|
import UIKit
class API {
private let httpClient: HTTPClient;
private let persistenceManager: PersistenceManager
class var sharedInstance: API {
struct Singleton {
static let instance = API();
}
return Singleton.instance;
}
init() {
httpClient = HTTPClient();
persistenceManager = PersistenceManager()
}
func loadRecipes(){
self.httpClient.loadRecipes()
}
func insertRecipe(id: String, title: String, imgURL: String, author: String){
self.persistenceManager.insertRecipe(id, title: title, imgURL: imgURL, author: author)
}
func deleteRecipes(){
self.persistenceManager.deleteRecipes()
}
}
| true
|
6515274069c2b27813d3ff90dbebc3b757fbdd53
|
Swift
|
rohanaurora/Photo-Tagger
|
/Sources/API/NetworkingService.swift
|
UTF-8
| 1,043
| 3
| 3
|
[
"MIT"
] |
permissive
|
// Copyright © 2018 Hootsuite. All rights reserved.
import Foundation
/// Representing a Requests protocol
protocol Requests {
var url: URL { get }
}
/// Representing a Service protocol
protocol Service {
func get(request: Requests, completion: @escaping (Result<Data>) -> Void)
}
/// Networking Service
final class NetworkService: Service {
/// Get request
///
/// parameter: Takes a `Requests` object
/// completion: `Result` of data or errors
func get(request: Requests, completion: @escaping (Result<Data>) -> Void) {
URLSession.shared.dataTask(with: request.url) { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(ServiceError.invalidData))
return
}
completion(.success(data))
}.resume()
}
}
/// Client service error
enum ServiceError: Error {
case invalidData
}
| true
|
b5d67e60bd74e50caac3b537dfa528de107d8daa
|
Swift
|
mckaykerksiek/stockmarket
|
/StockMarket/Views/Helper Views/PlayerRowView.swift
|
UTF-8
| 980
| 3.25
| 3
|
[] |
no_license
|
//
// PlayerRowView.swift
// StockMarket
//
// Created by McKay Michaelis on 9/21/21.
//
import SwiftUI
struct PlayerRowView: View {
@ObservedObject var player: Player
var place: Int
var body: some View {
if place == 1 {
placeView()
.frame(maxWidth: .infinity)
.font(.title)
} else {
placeView()
}
}
@ViewBuilder func placeView() -> some View {
HStack {
Text("\(place)")
.multilineTextAlignment(.leading)
.frame(width: 50)
Text(player.name)
.multilineTextAlignment(.leading)
Spacer()
Text("\(player.totalScore)")
.multilineTextAlignment(.center)
.frame(minWidth: 50)
}
}
}
struct PlayerRowView_Previews: PreviewProvider {
static var previews: some View {
PlayerRowView(player: Player(name: "mckay"), place: 1)
}
}
| true
|
6796b1e91f46871e95f1cefa3789dc78460d6433
|
Swift
|
yamazaki-sensei/Attention
|
/client/Attention/GeoLocationSearchBar.swift
|
UTF-8
| 894
| 2.71875
| 3
|
[] |
no_license
|
//
// GeoLocationSearchBar.swift
// Attension
//
// Created by Hiraku Ohno on 2016/04/07.
// Copyright © 2016年 Hiraku Ohno. All rights reserved.
//
import UIKit
class GeoLocationSearchBar: UISearchBar {
var searchHandler: ((UISearchBar) -> Void)?
var startHandler: ((UISearchBar) -> Void)?
var determineHandler: ((UISearchBar) -> Void)?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
}
}
extension GeoLocationSearchBar: UISearchBarDelegate {
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
startHandler?(searchBar)
searchHandler?(searchBar)
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
searchHandler?(searchBar)
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
determineHandler?(searchBar)
}
}
| true
|
2689e569dbc248b94f4020c84a9415f027890c5a
|
Swift
|
nathaneidelson/CS52Demo
|
/CS51-Demo/Models/PhotoLog.swift
|
UTF-8
| 4,603
| 3.125
| 3
|
[] |
no_license
|
//
// Photo.swift
// CS51-Demo
//
// Created by Nathan Eidelson on 3/26/17.
// Copyright © 2017 Nathan Eidelson. All rights reserved.
//
import UIKit
import Alamofire
// While we implement PhotoLogs here, this is fairly basic as a model. Let's consider a User model, which may have the following methods...
// "User" class methods:
// get(id: string)
// login(email: string, password: string, ...)
// register(email: string, password: string, ...)
// etc...
// "User" instance methods:
// logout()
// delete()
// updateEmail()
// updateProfilePicture()
// etc...
class PhotoLog: NSObject {
// REPLACE THIS with your Airtable base + table url
static let airtableAPIUrl = "https://api.airtable.com/v0/appS4dWugwqgIushs/Photos"
// What are the advantages of keeping this as class variable?
// You can copy the array in other view controllers, and this will always remain an accurate
// source of truth.
static var photoLogs: [PhotoLog] = []
// Required variables
var id: String;
var name: String;
var url: String;
var image: UIImage;
// Optional variables
var notes: String?;
init?(recordJSON: [String: Any]) {
// You should NEVER assume anything about the server response.
// All response handling code on the client should not crash due to missing/extra data.
// 1. Avoid using the <Type>! (e.g. String!) variable type declaration... this allows nil upon
// initialization, but will crash upon access if it is still nil. It's confusing and often avoidable.
// 2. Avoid using as!... this will crash the client if the server response is malformed. as? allows
// the cast to fail, and causes the gaurded control flow to execute the else statement.
guard
let id = recordJSON["id"] as? String,
let fields = recordJSON["fields"] as? [String: Any],
let name = fields["name"] as? String,
let notes = fields["notes"] as? String?,
let file = fields["file"] as? [[String: Any]],
let url = file[0]["url"] as? String
else {
// If ANY of the above fail, we fail to construct the photoLog and return nil.
return nil
}
self.id = id
self.name = name
self.url = url
self.notes = notes
guard
// After setting the url of the file, we actually fetch the data
let nsurl = NSURL(string: self.url) as URL?,
let data = NSData(contentsOf: nsurl) as Data?,
let image = UIImage(data: data)
else {
return nil
}
self.image = image
}
class func fetchAll(callback: @escaping (Bool) -> Void) {
// Much of this code is stolen from the Alamofire docs... check them out if you're interested.
Alamofire.request(
airtableAPIUrl,
// The default http method is GET, but it's always good to be explicit
method: .get,
parameters: ["view": "Grid"], // REPLACE THIS with your Airtable view name
encoding: URLEncoding.default,
headers: ["Authorization": "Bearer keyRnHAoFhP36pWoC"] // REPLACE THIS with your Airtable API key
).responseJSON { response in
guard response.result.isSuccess else {
print("Error while fetching photo logs: \(String(describing: response.result.error))")
callback(false)
return
}
guard let value = response.result.value as? [String: Any],
let records = value["records"] as? [[String: Any]] else {
print("Malformed data received from fetchAllRooms service")
callback(false)
return
}
PhotoLog.photoLogs = []
for record in records {
if let photoLog = PhotoLog(recordJSON: record) {
PhotoLog.photoLogs.append(photoLog)
}
}
callback(true)
}
}
class func create(image: UIImage, name: String, notes: String) {
// I left this for you to on your own time, if interested.
// Note that the Airtable API allows you to create new records, but the attachment field
// only takes urls so you'll need to find a Cocoapod (or use alamofire + another API) that
// will upload this UIImage and return a url, which you can then POST to Airtable.
}
}
| true
|
8059c2d4492a54ad9d09c510f73ca2511bab3124
|
Swift
|
PavansOrganization/ImageListPOC
|
/ImageListPOC/ImageListPOC/MVVM/VIew/CustomCollectionViewCell/ImageCollectionViewCell.swift
|
UTF-8
| 3,521
| 2.5625
| 3
|
[] |
no_license
|
//
// ImageCollectionViewCell.swift
// ImageListPOC
//
// Created by test on 15/01/19.
// Copyright © 2019 test. All rights reserved.
//
import Foundation
import SnapKit
import SDWebImage
class ImageCollectionViewCell: UICollectionViewCell {
static let ID = ImageCollectionViewCell.description()
// MARK: UI Components
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let titleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.boldSystemFont(ofSize: label.font.pointSize)
return label
}()
let descriptionLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.font = .systemFont(ofSize: 17)
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var width: NSLayoutConstraint = {
let width = contentView.widthAnchor.constraint(equalToConstant: bounds.size.width)
width.isActive = true
return width
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.translatesAutoresizingMaskIntoConstraints = false
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
width.constant = bounds.size.width
return contentView.systemLayoutSizeFitting(CGSize(width: targetSize.width, height: 1))
}
// MARK: View Setup
fileprivate func setupViews() {
contentView.addSubview(imageView)
imageView.snp.remakeConstraints { (make) in
make.top.equalTo(contentView.safeAreaLayoutGuide.snp.top).offset(10)
make.centerX.equalTo(contentView.safeAreaLayoutGuide.snp.centerX)
make.width.equalTo(100)
make.height.equalTo(100)
}
contentView.addSubview(titleLabel)
titleLabel.snp.remakeConstraints { (make) in
make.top.equalTo(imageView.snp.bottom).offset(10)
make.left.equalTo(contentView.safeAreaLayoutGuide.snp.left)
make.right.equalTo(contentView.safeAreaLayoutGuide.snp.right)
}
contentView.addSubview(descriptionLabel)
descriptionLabel.snp.remakeConstraints { (make) in
make.top.equalTo(titleLabel.snp.bottom).offset(10)
make.left.equalTo(titleLabel.snp.left)
make.right.equalTo(titleLabel.snp.right)
make.bottom.equalTo(contentView.snp.bottom)
}
}
}
// MARK: Cell Configuration method
extension ImageCollectionViewCell {
func configureCell(viewModel: ImageDataViewModel) {
self.imageView.image = AppConstants.placeholderImage
self.titleLabel.text = viewModel.getImageTitle()
self.descriptionLabel.text = viewModel.getImageDescription()
guard let url = viewModel.getImageURL() else {
return
}
self.imageView.sd_setImage(with: url, placeholderImage: AppConstants.placeholderImage)
}
}
| true
|
0c8e3b2e4e32a4ab564532babc4ed69c37044cca
|
Swift
|
csuttner/scratchbook-ios
|
/bd_appdelegate_stb/CanvasView.swift
|
UTF-8
| 1,855
| 2.671875
| 3
|
[] |
no_license
|
//
// CanvasView.swift
// bd_appdelegate_stb
//
// Created by Clay Suttner on 11/25/19.
// Copyright © 2019 skite. All rights reserved.
//
import UIKit
import PencilKit
let π = CGFloat(Double.pi)
class CanvasView: UIImageView {
private let defaultLineWidth: CGFloat = 6
private var drawColor: UIColor = UIColor.black
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
image?.draw(in: bounds)
drawStroke(context: context, touch: touch)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
private func drawStroke(context: CGContext?, touch: UITouch) {
let previousLocation = touch.previousLocation(in: self)
let location = touch.location(in: self)
let lineWidth = lineWidthForDrawing(context: context, touch: touch)
drawColor.setStroke()
context?.setLineWidth(lineWidth)
context?.setLineCap(.round)
context?.move(to: previousLocation)
context?.addLine(to: location)
context?.strokePath()
}
private func lineWidthForDrawing(context: CGContext?, touch: UITouch) -> CGFloat {
let lineWidth = defaultLineWidth
return lineWidth
}
func clearCanvas(animated: Bool) {
if animated {
UIView.animate(withDuration: 0.5, animations: {
self.alpha = 0
}, completion: { finished in
self.alpha = 1
self.image = nil
})
} else {
image = nil
}
}
}
| true
|
1d03aae97cea65939b955c1f00b177941cb947d1
|
Swift
|
Renatdz/ScalableMonorepo
|
/Modules/Services/NetworkServiceAPI/NetworkServiceAPI/Sources/Network/ContentType.swift
|
UTF-8
| 218
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
public enum ContentType {
case applicationJson
public var rawValue: String {
switch self {
case .applicationJson:
return "application/json"
}
}
}
| true
|
fc9ab943a04f79cce32e682c5cf4fec4babde8f9
|
Swift
|
HiddenKill/Algorithm
|
/Algo/Algo/LinkedList/Topic4.swift
|
UTF-8
| 1,821
| 3.6875
| 4
|
[
"Apache-2.0"
] |
permissive
|
//
// Topic4.swift
// Algo
//
// Created by cxz on 2020/3/6.
// Copyright © 2020 cxz. All rights reserved.
//
import Foundation
/*
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
示例 2:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
/*
解题思路:
1. 将链表的尾结点指向头结点形成闭环
2. 在形成闭环的过程中同时遍历了一遍,拿到了链表的长度length
3. 根据链表长度和右旋转次数在遍历一次将第count-1-k个节点的next致为nil打破闭环即可
*/
public class Solution4 {
public static func rotateRight(_ head: ListNode?, _ k: Int) -> ListNode? {
if head == nil || k < 0 {
return nil
}
var nail: ListNode? = head
var count: Int = 1
while nail?.next != nil {
nail = nail?.next
count += 1
}
debugPrint(count)
var kk = k
if k >= count {
kk = (k%count)
}
debugPrint(kk)
nail?.next = head
var cur = head
var newHead = head
for _ in 0..<count-1-kk {
cur = cur?.next
}
newHead = cur?.next
cur?.next = nil
return newHead
}
}
| true
|
fa8c2bd6e8732f1cfb2f991538a3717c785be40f
|
Swift
|
sparklyhiking/bitcoin-kit-ios
|
/HSBitcoinKit/HSBitcoinKit/Network/Peer/PeerTask/RequestTransactionsTask.swift
|
UTF-8
| 1,073
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
class RequestTransactionsTask: PeerTask {
private var hashes: [Data]
var transactions = [Transaction]()
init(hashes: [Data]) {
self.hashes = hashes
}
override func start() {
let items = hashes.map { hash in
InventoryItem(type: InventoryItem.ObjectType.transaction.rawValue, hash: hash)
}
requester?.getData(items: items)
}
override func handle(transaction: Transaction) -> Bool {
guard let index = hashes.index(where: { $0 == transaction.dataHash }) else {
return false
}
hashes.remove(at: index)
transactions.append(transaction)
if hashes.isEmpty {
delegate?.handle(completedTask: self)
}
return true
}
override func isRequestingInventory(hash: Data) -> Bool {
return hashes.contains(hash)
}
func equalTo(_ task: RequestTransactionsTask?) -> Bool {
guard let task = task else {
return false
}
return hashes == task.hashes
}
}
| true
|
73439c9e432ea1069bc25c85a09f5cc6170c9863
|
Swift
|
cotkjaer/Silverback
|
/Silverback/UICollectionView.swift
|
UTF-8
| 10,707
| 2.75
| 3
|
[] |
no_license
|
//
// UICollectionView.swift
// Silverback
//
// Created by Christian Otkjær on 22/10/15.
// Copyright © 2015 Christian Otkjær. All rights reserved.
//
import UIKit
// MARK: - CustomDebugStringConvertible
extension UICollectionViewScrollDirection : CustomDebugStringConvertible, CustomStringConvertible
{
public var description : String { return debugDescription }
public var debugDescription : String
{
switch self
{
case .Vertical: return "Vertical"
case .Horizontal: return "Horizontal"
}
}
}
//MARK: - IndexPaths
extension UICollectionView
{
// public func visibleCells() -> [UICollectionViewCell]
// {
// return indexPathsForVisibleItems().flatMap{ self.cellForItemAtIndexPath($0) }
// }
public func indexPathForLocation(location : CGPoint) -> NSIndexPath?
{
for cell in visibleCells()
{
if cell.bounds.contains(location.convert(fromView: self, toView: cell))
{
return indexPathForCell(cell)
}
}
return nil
}
public func indexPathForView(view: UIView) -> NSIndexPath?
{
let superviews = view.superviews
if let myIndex = superviews.indexOf(self)
{
if let cell = Array(superviews[myIndex..<superviews.count]).cast(UICollectionViewCell).first
{
return indexPathForCell(cell)
}
}
return nil
}
}
public class LERPCollectionViewLayout: UICollectionViewLayout
{
public enum Alignment
{
case Top, Bottom, Left, Right
}
public var alignment = Alignment.Left { didSet { if oldValue != alignment { invalidateLayout() } } }
public enum Axis
{
case Vertical, Horizontal
}
public var axis = Axis.Horizontal { didSet { if oldValue != axis { invalidateLayout() } } }
public enum Distribution
{
case Fill, Stack
}
public var distribution = Distribution.Fill { didSet { if oldValue != distribution { invalidateLayout() } } }
private var attributes = Array<UICollectionViewLayoutAttributes>()
override public func prepareLayout()
{
super.prepareLayout()
attributes.removeAll()
if let sectionCount = collectionView?.numberOfSections()
{
for section in 0..<sectionCount
{
if let itemCount = collectionView?.numberOfItemsInSection(section)
{
for item in 0..<itemCount
{
let indexPath = NSIndexPath(forItem: item, inSection: section)
if let attrs = layoutAttributesForItemAtIndexPath(indexPath)
{
attributes.append(attrs)
}
}
}
}
}
}
override public func collectionViewContentSize() -> CGSize
{
if var frame = attributes.first?.frame
{
for attributesForItemAtIndexPath in attributes
{
frame.unionInPlace(attributesForItemAtIndexPath.frame)
}
return CGSize(width: frame.right, height: frame.top)
}
return CGSizeZero
}
override public func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool
{
return collectionView?.bounds != newBounds
}
override public func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]?
{
var attributesForElementsInRect = [UICollectionViewLayoutAttributes]()
for attributesForItemAtIndexPath in attributes
{
if CGRectIntersectsRect(attributesForItemAtIndexPath.frame, rect)
{
attributesForElementsInRect.append(attributesForItemAtIndexPath)
}
}
return attributesForElementsInRect
}
func factorForIndexPath(indexPath: NSIndexPath) -> CGFloat
{
if let itemCount = collectionView?.numberOfItemsInSection(indexPath.section)
{
let factor = itemCount > 1 ? CGFloat(indexPath.item) / (itemCount - 1) : 0
return factor
}
return 0
}
func zIndexForIndexPath(indexPath: NSIndexPath) -> Int
{
if let selectedItem = collectionView?.indexPathsForSelectedItems()?.first?.item,
let itemCount = collectionView?.numberOfItemsInSection(indexPath.section)
{
return itemCount - abs(selectedItem - indexPath.item)
}
return 0
}
override public func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?
{
if let collectionView = self.collectionView
// let attrs = super.layoutAttributesForItemAtIndexPath(indexPath)
{
let attrs = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
let factor = factorForIndexPath(indexPath)
let l = ceil(min(collectionView.bounds.height, collectionView.bounds.width))
let l_2 = l / 2
var lower = collectionView.contentOffset + CGPoint(x: l_2, y: l_2)
var higher = lower//CGPoint(x: l_2, y: l_2)
switch axis
{
case .Horizontal:
higher.x += collectionView.bounds.width - l
case .Vertical:
higher.y += collectionView.bounds.height - l
}
switch alignment
{
case .Top, .Left:
break
case .Bottom:
swap(&higher.y, &lower.y)
case .Right:
swap(&higher.x, &lower.x)
}
attrs.frame = CGRect(center: lerp(lower, higher, factor), size: CGSize(widthAndHeight: l))
attrs.zIndex = zIndexForIndexPath(indexPath)
return attrs
}
return nil
}
}
//MARK: - FlowLayout
extension UICollectionViewController
{
public var flowLayout : UICollectionViewFlowLayout? { return collectionViewLayout as? UICollectionViewFlowLayout }
}
//MARK: - batch updates
public extension UICollectionView
{
public func performBatchUpdates(updates: (() -> Void)?)
{
performBatchUpdates(updates, completion: nil)
}
public func reloadSection(section: Int)
{
if section >= 0 && section < numberOfSections()
{
self.reloadSections(NSIndexSet(index: section))
}
}
}
//MARK: refresh
public extension UICollectionView
{
public func refreshVisible(animated: Bool = true, completion: ((Bool) -> ())? = nil)
{
let animations = { self.reloadItemsAtIndexPaths(self.indexPathsForVisibleItems()) }
if animated
{
performBatchUpdates(animations, completion: completion)
}
else
{
animations()
completion?(true)
}
}
}
// MARK: - Index Paths
public extension UICollectionView
{
var lastIndexPath : NSIndexPath?
{
let section = numberOfSections() - 1
if section >= 0
{
let item = numberOfItemsInSection(section) - 1
if item >= 0
{
return NSIndexPath(forItem: item, inSection: section)
}
}
return nil
}
var firstIndexPath : NSIndexPath?
{
if numberOfSections() > 0
{
if numberOfItemsInSection(0) > 0
{
return NSIndexPath(forItem: 0, inSection: 0)
}
}
return nil
}
}
// MARK: - TODO: Move to own file
class PaginationCollectionViewFlowLayout: UICollectionViewFlowLayout
{
init(flowLayout: UICollectionViewFlowLayout)
{
super.init()
itemSize = flowLayout.itemSize
sectionInset = flowLayout.sectionInset
minimumLineSpacing = flowLayout.minimumLineSpacing
minimumInteritemSpacing = flowLayout.minimumInteritemSpacing
scrollDirection = flowLayout.scrollDirection
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder:aDecoder)
}
func applySelectedTransform(attributes: UICollectionViewLayoutAttributes?) -> UICollectionViewLayoutAttributes?
{
return attributes
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]?
{
if let layoutAttributesList = super.layoutAttributesForElementsInRect(rect)
{
return layoutAttributesList.flatMap( self.applySelectedTransform )
}
return nil
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?
{
let attributes = super.layoutAttributesForItemAtIndexPath(indexPath)
return applySelectedTransform(attributes)
}
// Mark : - Pagination
var pageWidth : CGFloat { return itemSize.width + minimumLineSpacing }
let flickVelocity : CGFloat = 0.3
override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint
{
var contentOffset = proposedContentOffset
if let collectionView = self.collectionView
{
let rawPageValue = collectionView.contentOffset.x / pageWidth
let currentPage = velocity.x > 0 ? floor(rawPageValue) : ceil(rawPageValue)
let nextPage = velocity.x > 0 ? ceil(rawPageValue) : floor(rawPageValue);
let pannedLessThanAPage = abs(1 + currentPage - rawPageValue) > 0.5
let flicked = abs(velocity.x) > flickVelocity
if pannedLessThanAPage && flicked
{
contentOffset.x = nextPage * pageWidth
}
else
{
contentOffset.x = round(rawPageValue) * pageWidth
}
}
return contentOffset
}
}
| true
|
22a3b62c7aa3e96abc576852199a078c20a917ca
|
Swift
|
ginnigarg/VirtualTourist
|
/VirtualTourist/CollectionCellFile.swift
|
UTF-8
| 871
| 2.734375
| 3
|
[] |
no_license
|
//
// CollectionCellFile.swift
// VirtualTourist
//
// Created by Guneet Garg on 21/04/18.
// Copyright © 2018 Guneet Garg. All rights reserved.
//
import Foundation
import UIKit
class CollectionCell:UICollectionViewCell{
@IBOutlet weak var imageView: UIImageView!
func initWithPhoto(recievedPhotoInstance : Photo){
if recievedPhotoInstance.data == nil {
let imageURL = URL(string: recievedPhotoInstance.url!)
URLSession.shared.dataTask(with: imageURL!){data,response,error in
if error==nil{
DispatchQueue.main.async {
self.imageView.image = UIImage(data: data! as Data)
}
}
}.resume()
} else {
imageView.image = UIImage(data: recievedPhotoInstance.data!)
}
}
}
| true
|
c841517a2d9fdadf5e5f8f095a409b075297f4c4
|
Swift
|
Sleyva1991/ios-afternoon-project-swift-fundamentals-iii
|
/CurrencyConverter/CurrencyConverterViewController.swift
|
UTF-8
| 1,962
| 3.25
| 3
|
[] |
no_license
|
//
// CurrencyConverterViewController.swift
// CurrencyConverter
//
// Created by Steven Leyva on 7/10/19.
// Copyright © 2019 Lambda School. All rights reserved.
//
import UIKit
class CurrencyConverterViewController: UIViewController {
@IBOutlet weak var fromCurrencyTextField: UITextField!
@IBOutlet weak var toCurrencyTextField: UITextField!
@IBOutlet weak var toCurrencyLabel: UILabel!
@IBOutlet weak var cadButton: UIButton!
@IBOutlet weak var pesoButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func convertButtonPressed(_ sender: UIButton) {
guard let currencyString = fromCurrencyTextField.text,
let currencyAmount = Double(currencyString) else { return }
let result = convert(dollars: currencyAmount , to: currencyType)
toCurrencyTextField.text = "\(result)"
}
@IBAction func cadButtonPressed(_ sender: UIButton) {
sender.isSelected.toggle()
if pesoButton.isSelected {
pesoButton.isSelected.toggle()
}
toCurrencyLabel.text = "Currency (CAD)"
currencyType = .cad
}
@IBAction func pesoButtonPressed(_ sender: UIButton) {
sender.isSelected.toggle()
if cadButton.isSelected {
cadButton.isSelected.toggle()
}
toCurrencyLabel.text = "Currency (Peso)"
currencyType = .peso
}
var currencyType: CurrencyType = .cad
func convert(dollars: Double, to unit: CurrencyType) -> Double {
// get the dollar amount to cad
let canadianAmount = 1.31 * dollars
if unit == .cad {
return canadianAmount
} else {
let pesoAmount = 19.15 * dollars
return pesoAmount
}
}
}
enum CurrencyType {
case cad
case peso
}
| true
|
eb929b4d533af8fb93d153ae73bcf85d89cf9993
|
Swift
|
alenaCod/weather
|
/iWeather/iWeather/Extension/Date+Extension.swift
|
UTF-8
| 973
| 3.140625
| 3
|
[] |
no_license
|
//
// DayWeek.swift
// iWeather
//
// Created by Mac on 7/26/18.
// Copyright © 2018 Alona Moiseyenko. All rights reserved.
//
import Foundation
extension Date {
func dayOfWeek() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")! as TimeZone
dateFormatter.dateFormat = "EE"
return dateFormatter.string(from: self).capitalized
}
func dateOfWeekAndMonth() -> String {
let dateFormate = DateFormatter()
dateFormate.timeZone = NSTimeZone(abbreviation: "UTC")! as TimeZone
dateFormate.dateFormat = "EE, d MMMM"
return dateFormate.string(from: self).capitalized
}
func day() -> String {
let dateFormate = DateFormatter()
dateFormate.timeZone = NSTimeZone(abbreviation: "UTC")! as TimeZone
dateFormate.dateFormat = "yyyy-MM-dd" //2018-08-01
return dateFormate.string(from: self).capitalized
}
}
| true
|
bbb11015c5ccb20a16a8e5a0b8d29f3028f00efd
|
Swift
|
brentlecomte/NHL-STATS-APP
|
/NHL APP/UI/Components/ViewControllerProvider.swift
|
UTF-8
| 2,857
| 2.59375
| 3
|
[] |
no_license
|
//
// ViewControllerProvider.swift
// NHL APP
//
// Created by Brent Le Comte on 17/12/2020.
// Copyright © 2020 Brent Le Comte. All rights reserved.
//
import Foundation
import UIKit
class ViewControllerProvider {
enum Storyboard: String {
case Main
case TodaysGames
case TeamsOverview
}
static let sharedInstance = ViewControllerProvider()
var dataProviders: DataProviders?
// MARK: - TodaysGames
func todaysGamesViewController() -> UIViewController {
let viewController = initialViewControllerFromStoryboard(.TodaysGames)!
if let viewController = viewController.children.first as? TodaysGamesViewController {
viewController.gamesDataProvider = dataProviders?.gamesDataProvider
}
return viewController
}
func liveFeedViewController(liveFeedLink: String, teams: Team) -> UIViewController {
guard let viewController = viewControllerNamed(LiveFeedViewController.storyBoardID, from: .TodaysGames) as? LiveFeedViewController else {return UIViewController()}
viewController.gamesDataProvider = dataProviders?.gamesDataProvider
viewController.liveFeedLink = liveFeedLink
viewController.teams = teams
return viewController
}
func liveFeedDetailViewController(play: AllPlays) -> UINavigationController {
guard let navigationController = viewControllerNamed("FeedDetailNavigationController", from: .TodaysGames) as? UINavigationController,
let viewController = viewControllerNamed(FeedDetailViewController.storyBoardID, from: .TodaysGames) as? FeedDetailViewController
else {
return UINavigationController()
}
viewController.play = play
navigationController.addChild(viewController)
navigationController.viewControllers = [viewController]
return navigationController
}
// MARK: - TeamsOverview
func teamsOverviewViewController() -> UIViewController {
let viewController = initialViewControllerFromStoryboard(.TeamsOverview)!
if let viewController = viewController.children.first as? TeamsOverviewViewController {
viewController.teamsDataProvider = dataProviders?.teamsDataProvider
}
return viewController
}
}
private extension ViewControllerProvider {
func initialViewControllerFromStoryboard(_ storyboard: Storyboard) -> UIViewController? {
return UIStoryboard(name: storyboard.rawValue, bundle: nil).instantiateInitialViewController()
}
func viewControllerNamed(_ name: String, from storyboard: Storyboard) -> UIViewController? {
return UIStoryboard(name: storyboard.rawValue, bundle: nil).instantiateViewController(withIdentifier: name)
}
}
| true
|
4a54d0dce141908654984d21d5b6ba15a3c11d4c
|
Swift
|
nyannya0328/UI-169
|
/UI-169/View/CustomShape.swift
|
UTF-8
| 1,018
| 2.90625
| 3
|
[] |
no_license
|
//
// CustomShape.swift
// UI-169
//
// Created by にゃんにゃん丸 on 2021/04/28.
//
import SwiftUI
struct CustomShape2: Shape {
func path(in rect: CGRect) -> Path {
return Path{path in
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: 0, y: rect.height))
let midWith = rect.width / 2
path.addLine(to: CGPoint(x: midWith - 80, y: rect.height))
path.addLine(to: CGPoint(x: midWith - 70, y: rect.height - 50))
path.addLine(to: CGPoint(x: midWith + 70, y: rect.height-50))
path.addLine(to: CGPoint(x: midWith + 80, y: rect.height))
path.addLine(to: CGPoint(x: rect.width, y: rect.height))
path.addLine(to: CGPoint(x: rect.width, y: 0))
}
}
}
struct CustomShape_Previews: PreviewProvider {
static var previews: some View {
TripView()
}
}
| true
|
d11d7ad3fc57e58add44899ce10593ba282f7613
|
Swift
|
ai-sho-app/onigiri-go-swift
|
/onigiri-go-swift/App/Workout/PrepareWorkoutViewController.swift
|
UTF-8
| 2,391
| 2.546875
| 3
|
[] |
no_license
|
//
// PrepareViewController.swift
// onigiri-go-swift
//
// Created by Sho Kawasaki on 2019/09/16.
// Copyright © 2019 Sho Kawasaki. All rights reserved.
//
import Foundation
import UIKit
class PrepareWorkoutViewController: UIViewController {
let MAX_COUNT = 3
var workoutTimer: Timer?
lazy var timerCount: Int = {
return MAX_COUNT
}()
lazy var timerText: UITextView = {
let textview = UITextView()
textview.frame = CGRect(x:0, y:0, width:100, height:100)
textview.backgroundColor = UIColor.themeOrange
textview.center = self.view.center
textview.text = String(timerCount)
return textview
}()
lazy var backButton: UIButton = {
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "btn_workout"), for: .normal)
button.frame = CGRect(x:0, y:0, width:100, height:100)
button.center = self.view.center
button.setTitle("back!", for: .normal)
button.addTarget(self, action: #selector(back(sender:)), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
// timer start
workoutTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(countTimer), userInfo: nil, repeats: true)
// TODO: view design
self.view.backgroundColor = UIColor.themeOrange
// TODO: replace text to image
view.addSubview(timerText)
// TODO: button design
view.addSubview(backButton)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc private func back(sender: UIButton) {
print("Press back button from \(sender)")
self.dismiss(animated: true, completion: nil)
self.workoutTimer?.invalidate()
}
@objc private func countTimer() {
print("Count timer. timerCount: \(timerCount)")
timerCount -= 1
if timerCount >= 0 {
timerText.text = String(timerCount)
}
if timerCount == 0 {
print("Start workout!")
self.workoutTimer?.invalidate()
timerCount = MAX_COUNT
let workoutVC = WorkoutViewController()
workoutVC.modalTransitionStyle = .crossDissolve
self.present(workoutVC, animated: true, completion: nil)
}
}
}
| true
|
b42167dca140e2904a08b2d4988e233afd7baf96
|
Swift
|
markd2/ssoutliner
|
/SSOutliner/helpers.swift
|
UTF-8
| 379
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// helpers.swift
// SSOutliner
//
// Created by Michael L. Ward on 1/26/17.
// Copyright © 2017 Michael L. Ward. All rights reserved.
//
import Foundation
func printUsage() {
print("\nusage: ssoutliner [-r] file")
print("flags:")
print(" -r, --rounded")
print(" Round the corners. Suitable for window screenshots.")
print("\nOutput overwrites input file.\n")
}
| true
|
39a0c492f46641416272d999dc1521194db905eb
|
Swift
|
Threee-s/LEDSignalDetector
|
/App/iOS/LEDSignalDetector/AirService.swift
|
UTF-8
| 3,540
| 2.609375
| 3
|
[] |
no_license
|
//
// AirService.swift
// AirCommCamera
//
// Created by 文光石 on 2015/12/17.
// Copyright © 2015年 Threees. All rights reserved.
//
import Foundation
protocol AirServiceDelegate {
func serviceDidSend(service: AirService)
func service(service: AirService, didReceiveData data: AnyObject)
}
protocol AirService {
func connect()
func setDelegate(delegate: AirServiceDelegate)
func send(data: CollectionData)
func sendBlockData(blockData: [CollectionData])
func disconnect()
}
class AirServiceHeroku: AirService {
//static let servUrls = "https://led.herokuapp.com/api/v1/capabilities"
static let servUrl = "http://led.herokuapp.com/api/v1/capabilities"
class func uploadMovie(path: String) {
AirNetworkManager.uploadMovieWithUrl(servUrl, path: path) { (result) -> Void in
print(result)
}
}
func connect() {
}
func setDelegate(delegate: AirServiceDelegate) {
}
func send(data: CollectionData) {
}
func sendBlockData(blockData: [CollectionData]) {
}
func disconnect() {
}
}
class AirServiceDropbox: AirService {
func connect() {
}
func setDelegate(delegate: AirServiceDelegate) {
}
func send(data: CollectionData) {
}
func sendBlockData(blockData: [CollectionData]) {
}
func disconnect() {
}
}
class AirServiceMilkcocoa: NSObject, AirService, LEDMQTTClientDelegate {
private var client: LEDMQTTClient!
private var path: String = ""
private var connected: Bool = false
private var delegate: AirServiceDelegate!
var isConnected: Bool {
return self.connected
}
convenience override init() {
//super.init()
//self.client = LEDMQTTClient()
//self.client?.delegate = self
self.init(path: "")
}
init(path: String) {
super.init()
self.path = path
self.client = LEDMQTTClient()
self.client.delegate = self
//self.client.connect()
}
deinit {
print("deinit")
self.client.disconnect()
}
// MARK: - AirServiceDelegate protocol
func connect() {
if !self.connected {
self.client.connect()
}
}
func setDelegate(delegate: AirServiceDelegate) {
self.delegate = delegate
}
func send(data: CollectionData) {
if self.connected {
self.client.push(self.path, data: data)
}
}
func sendBlockData(blockData: [CollectionData]) {
if self.connected {
self.client.push(self.path, blockData: blockData)
}
}
func disconnect() {
if self.connected {
self.client.disconnect()
}
}
// MARK: - LEDMQTTClientDelegate protocol
func ledMqttClientDidConnect(client: LEDMQTTClient) {
print("ledMqttClientDidConnect")
self.connected = true
}
func ledMqttClientDidSend(client: LEDMQTTClient) {
if (self.delegate != nil) {
self.delegate.serviceDidSend(self)
}
}
func ledMqttClient(client: LEDMQTTClient, didReceiveCollectionData data: CollectionData) {
}
func ledMqttClientDidDisconnect(client: LEDMQTTClient, withError err: NSError?) {
print("ledMqttClientDidDisconnect")
self.connected = false
}
}
| true
|
230504cb437b8fd3f7e90655b33ca43b5bc5d872
|
Swift
|
reloni/SimpleTodo
|
/Aika/Common/Extensions/Date+Extensions.swift
|
UTF-8
| 7,321
| 3.1875
| 3
|
[] |
no_license
|
//
// Date+Extensions.swift
// Aika
//
// Created by Anton Efimenko on 22.12.2017.
// Copyright © 2017 Anton Efimenko. All rights reserved.
//
import Foundation
extension Locale {
var is24HourFormat: Bool {
return !(DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: self)?.contains("a") ?? false)
}
var timeFormat: Date.DateFormat {
if is24HourFormat {
return .time24
} else {
return .time12
}
}
static let posix: Locale = Locale(identifier: "en_US_POSIX")
}
extension Calendar {
static let gregorianPosix: Calendar = {
var calendar = Calendar(identifier: .gregorian)
calendar.locale = Locale.posix
return calendar
}()
var lastWeekday: Int {
let tmp = 1 - firstWeekday
return tmp < 0 ? abs(tmp) : tmp + 7
}
var weekdaySymbolsPosix: [String] {
return Calendar.gregorianPosix.weekdaySymbols.map { $0.capitalized }
}
var shortWeekdaySymbolsPosix: [String] {
return Calendar.gregorianPosix.shortWeekdaySymbols.map { $0.capitalized }
}
}
extension Date {
enum DateFormat: String {
case dateFull = "E d MMM yyyy"
case dateWithoutYear = "E d MMM"
case time24 = "HH:mm"
case time12 = "h:mm a"
case dayOfWeek = "EEEE"
}
enum DisplayDateType {
case full(withTime: Bool)
case relative(withTime: Bool)
var withTime: Bool {
switch self {
case .full(let withTime): return withTime
case .relative(let withTime): return withTime
}
}
}
enum DateType {
case todayPast
case todayFuture
case yesterday
case tomorrow
case future
case past
}
func type(in calendar: Calendar) -> DateType {
if isToday(in: calendar) {
return isInPast ? .todayPast : .todayFuture
} else if isTomorrow(in: calendar) {
return .tomorrow
} else if isYesterday(in: calendar) {
return .yesterday
} else if isBeforeYesterday(in: calendar) {
return .past
} else {
return .future
}
}
func setting(_ component: Calendar.Component, value: Int, in calendar: Calendar) -> Date {
return calendar.date(bySetting: component, value: value, of: self)!
}
func adding(_ component: Calendar.Component, value: Int, in calendar: Calendar) -> Date {
return calendar.date(byAdding: component, value: value, to: self)!
}
public func beginningOfWeek(in calendar: Calendar) -> Date {
return calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
}
public func beginningOfMonth(in calendar: Calendar) -> Date {
let components = calendar.dateComponents([.year, .month], from: self)
return calendar.date(from: components)!
}
func beginningOfDay(in calendar: Calendar) -> Date {
return calendar.date(bySettingHour: 0, minute: 0, second: 0, of: self)!
}
func beginningOfYear(in calendar: Calendar) -> Date {
return calendar.date(bySettingHour: 0, minute: 0, second: 0, of: self)!.setting(.month, value: 1, in: calendar).setting(.day, value: 1, in: calendar)
}
func endingOfDay(in calendar: Calendar) -> Date {
return calendar.date(bySettingHour: 23, minute: 59, second: 59, of: self)!
}
func value(for component: Calendar.Component, in calendar: Calendar) -> DateComponents {
return calendar.dateComponents([component], from: self)
}
func weekday(in calendar: Calendar) -> Int? {
return value(for: .weekday, in: calendar).weekday
}
func dayOfMonth(in calendar: Calendar) -> Int? {
return value(for: .day, in: calendar).day
}
func month(in calendar: Calendar) -> Int? {
return value(for: .month, in: calendar).month
}
var isInPast: Bool { return self < Date() }
var isInFuture: Bool { return self < Date() }
func isToday(in calendar: Calendar) -> Bool {
return calendar.isDateInToday(self)
}
func isTomorrow(in calendar: Calendar) -> Bool {
return calendar.isDateInTomorrow(self)
}
func isYesterday(in calendar: Calendar) -> Bool {
return calendar.isDateInYesterday(self)
}
func isWithinCurrentYear(in calendar: Calendar) -> Bool {
return calendar.component(.year, from: self) == calendar.component(.year, from: Date())
}
func isWithinNext7Days(in calendar: Calendar) -> Bool {
let begin = Date().beginningOfDay(in: calendar)
let end = Date().adding(.day, value: 7, in: calendar).endingOfDay(in: calendar)
return self > begin && self < end
}
func isWithinCurrentWeek(is calendar: Calendar) -> Bool {
let begin = Date().beginningOfWeek(in: calendar)
let end = begin.adding(.day, value: 7, in: calendar)
return self > begin && self < end
}
func isBeforeYesterday(in calendar: Calendar) -> Bool {
let yesterday = Date().adding(.day, value: -1, in: calendar).beginningOfDay(in: calendar)
return self < yesterday
}
func isAfterTomorrow(in calendar: Calendar) -> Bool {
let tomorrow = Date().adding(.day, value: 1, in: calendar).beginningOfDay(in: calendar)
return self > tomorrow
}
static let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
return dateFormatter
}()
static let relativeDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale.current
formatter.dateStyle = .medium
formatter.doesRelativeDateFormatting = true
return formatter
}()
static let serverDateFormatter: DateFormatter = {
let formatter = DateFormatter()
//2017-01-05T21:55:57.001+00
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSxx"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
func toServerDateString() -> String {
return Date.serverDateFormatter.string(from: self)
}
func toRelativeDate(dateFormatter formatter: DateFormatter = Date.relativeDateFormatter, in calendar: Calendar) -> String? {
switch type(in: calendar) {
case .todayFuture, .todayPast, .yesterday, .tomorrow:
return formatter.string(from: self)
default: return nil
}
}
static func fromServer(string: String) -> Date? {
return Date.serverDateFormatter.date(from: string)
}
func toString(format: DisplayDateType, in calendar: Calendar, dateFormatter formatter: DateFormatter = Date.dateFormatter, relativeDateFormatter: DateFormatter = Date.relativeDateFormatter) -> String {
if case .relative = format, let spelled = toRelativeDate(dateFormatter: relativeDateFormatter, in: calendar) {
formatter.dateFormat = formatter.locale.timeFormat.rawValue
return format.withTime ? "\(spelled) \(formatter.string(from: self))" : spelled
}
if isWithinNext7Days(in: calendar) {
formatter.dateFormat = format.withTime ? "\(DateFormat.dayOfWeek.rawValue) \(formatter.locale.timeFormat.rawValue)" : DateFormat.dayOfWeek.rawValue
return formatter.string(from: self)
}
if isWithinCurrentYear(in: calendar) {
formatter.dateFormat = format.withTime ? "\(DateFormat.dateWithoutYear.rawValue) \(formatter.locale.timeFormat.rawValue)" : DateFormat.dateWithoutYear.rawValue
} else {
formatter.dateFormat = format.withTime ? "\(DateFormat.dateFull.rawValue) \(formatter.locale.timeFormat.rawValue)" : DateFormat.dateFull.rawValue
}
return formatter.string(from: self)
}
}
| true
|
074b0c32358dd46fcb5cb6c0d25ff2de41157ee9
|
Swift
|
Viniciuscarvalho/MarvelApp
|
/MarvelApp/MarvelApp/Shared/Models/Serie.swift
|
UTF-8
| 1,007
| 2.75
| 3
|
[] |
no_license
|
//
// Serie.swift
// MarvelApp
//
// Created by Vinicius Marques on 19/04/2018.
// Copyright © 2018 Vinicius Carvalho. All rights reserved.
//
import Foundation
class Serie: ResourceURI, BaseItem {
var resourceURI: String!
var name: String?
var id: Int?
var title: String?
var description: String?
var urls: [Url]?
var startYear: Int?
var endYear: Int?
var rating: String?
var modified: String?
var thumbnail: Thumbnail?
var next: Serie?
var previous: Serie?
func isLoaded() -> Bool {
return (title != nil)
}
func populate(item: Serie) {
self.id = item.id
self.title = item.title
self.description = item.description
self.urls = item.urls
self.startYear = item.startYear
self.endYear = item.endYear
self.rating = item.rating
self.modified = item.modified
self.thumbnail = item.thumbnail
self.next = item.next
self.previous = item.previous
}
}
| true
|
432b57becc1b15db75a99c56e2af770684632807
|
Swift
|
zhengry/ZZSwiftUI
|
/ZZSwiftUI/UpdateDetail.swift
|
UTF-8
| 871
| 3
| 3
|
[] |
no_license
|
//
// UpdateDetail.swift
// ZZSwiftUI
//
// Created by zry on 2019/11/29.
// Copyright © 2019 ZRY. All rights reserved.
//
import SwiftUI
struct UpdateDetail: View {
var title:String = ""
var image:String = ""
var content:String = ""
var color:Color = .white
var body: some View {
VStack(alignment: .center, spacing: 20){
Text(title)
.font(.largeTitle)
Image(systemName:image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width:300)
.foregroundColor(color)
Text(content)
.frame(alignment:.leading)
Spacer()
}
.padding(.horizontal,20)
}
}
struct UpdateDetail_Previews: PreviewProvider {
static var previews: some View {
UpdateDetail()
}
}
| true
|
5a8c5f6d61f0985ac48825554555d105d997e91f
|
Swift
|
leonardowf/CircularUpperTabs
|
/CircularUpperTabs/CircularUpperTabsView/CircularUpperTabsCellState.swift
|
UTF-8
| 968
| 2.625
| 3
|
[] |
no_license
|
//
// CircularUpperTabsCellState.swift
// CircularUpperTabs
//
// Created by Leonardo Wistuba de França on 3/12/17.
// Copyright © 2017 Leonardo. All rights reserved.
//
import UIKit
class CircularUpperTabsCellState: NSObject {
var selectedBackgroundColor: UIColor?
var unselectedBackgroundColor: UIColor?
var text: String
var unselectedFontColor: UIColor?
var selectedFontColor: UIColor?
var textFont: UIFont?
var isSelected = false
init(text: String) {
self.text = text
}
func width() -> CGFloat {
let nsstring = NSString(string: text)
let maxSize = CGSize(width: CGFloat(FLT_MAX), height: CGFloat(FLT_MAX))
let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: UIFont.systemFontSize)]
let boundingRect = nsstring.boundingRect(with: maxSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil)
return boundingRect.width + 20
}
}
| true
|
2f98835f3ae011b693ede9e1177dbde5d3e9e54f
|
Swift
|
avito-tech/Mixbox
|
/ci/swift/Sources/Cocoapods/Search/CocoapodsSearchOutputParser/CocoapodsSearchOutputParser.swift
|
UTF-8
| 111
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
public protocol CocoapodsSearchOutputParser {
func parse(output: String) throws -> CocoapodsSearchResult
}
| true
|
c0cac2dc78a6da5aee6b89ee5ff9aa634d34837f
|
Swift
|
modestman/tdlib-swift
|
/TdlibKit/Models/ClearRecentStickers.swift
|
UTF-8
| 459
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// ClearRecentStickers.swift
// tl2swift
//
// Created by Code Generator
//
import Foundation
/// Clears the list of recently used stickers
public struct ClearRecentStickers: Codable {
/// Pass true to clear the list of stickers recently attached to photo or video files; pass false to clear the list of recently sent stickers
public let isAttached: Bool?
public init(isAttached: Bool?) {
self.isAttached = isAttached
}
}
| true
|
dc88ab05cec0ae339be776d8c44ca718a1d4b147
|
Swift
|
Nang01T2/NNLogger
|
/NNLogger/NNLogger.swift
|
UTF-8
| 2,741
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// NNLogger.swift
//
// Created by Nang Nguyen on 3/31/19.
//
import Foundation
import SwiftyBeaver
public class NNLogger {
private let context: String
public init( _ context: String = "APP") {
self.context = context
var consoleDestinationAlreadyExists = false
for destination in SwiftyBeaver.destinations {
if let consoleDest = destination as? ConsoleDestination {
consoleDestinationAlreadyExists = true
configureDestination(consoleDest)
}
}
if !consoleDestinationAlreadyExists {
let consoleDest = ConsoleDestination()
configureDestination(consoleDest)
SwiftyBeaver.addDestination(consoleDest)
}
}
//MARK: Public logging methods
public func verbose(_ message: String?, _ file: String = #file, _ function: String = #function, _ line: Int = #line) {
SwiftyBeaver.verbose(formatMessage(message),file,function,line: line)
}
public func debug(_ message: String?, _ file: String = #file, _ function: String = #function, _ line: Int = #line) {
SwiftyBeaver.debug(formatMessage(message),file,function,line: line)
}
public func info(_ message: String?, _ file: String = #file, _ function: String = #function, _ line: Int = #line) {
SwiftyBeaver.info(formatMessage(message),file,function,line: line)
}
public func warning(_ message: String?, _ file: String = #file, _ function: String = #function, _ line: Int = #line) {
SwiftyBeaver.warning(formatMessage(message),file,function,line: line)
}
public func error(_ message: String?, _ file: String = #file, _ function: String = #function, _ line: Int = #line) {
SwiftyBeaver.error(formatMessage(message),file,function,line: line)
}
//MARK: Private
private func formatMessage( _ message: String?) -> String {
let c = self.context
if let m = message {
return "[\(c)] \(m)"
} else {
return ""
}
}
private func configureDestination( _ consoleDest: ConsoleDestination) {
consoleDest.format = "[$Dyyyy-MM-dd HH:mm:ss$d] |$T| $N.$F:$l $C [$L$c] - $M"
consoleDest.levelColor.verbose = "💭"
consoleDest.levelColor.debug = "✅"
consoleDest.levelColor.info = "ℹ️"
consoleDest.levelColor.warning = "⚠️"
consoleDest.levelColor.error = "🚫"
#if DEBUG
consoleDest.minLevel = .verbose
consoleDest.asynchronously = false
#else
consoleDest.minLevel = .info
consoleDest.asynchronously = true
#endif
}
}
| true
|
ca126029ab5177308e5e6fea59eb9199fedf58e7
|
Swift
|
sarangborude/SwiftUIViewSCNKit
|
/SwiftUIViewSCNKit/SwiftUIARCardView.swift
|
UTF-8
| 1,205
| 3.265625
| 3
|
[] |
no_license
|
//
// SwiftUIARView.swift
// SwiftUIARView
//
// Created by Sarang Borude on 4/10/20.
// Copyright © 2020 Sarang Borude. All rights reserved.
//
import SwiftUI
struct SwiftUIARCardView: View {
@State private var textToShow = "Hello AR"
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 20)
.fill(LinearGradient(gradient: Gradient(colors: [Color.red, Color.blue]), startPoint: .topLeading, endPoint: .bottomTrailing))
.edgesIgnoringSafeArea(.all)
VStack {
Text(textToShow)
.foregroundColor(.white)
.bold().font(.title)
Button(action: {
self.textToShow = "Button Tapped!"
}) {
ZStack {
RoundedRectangle(cornerRadius: 15)
.fill(Color.white)
.frame(width: 150, height: 50)
Text("Tap Me")
}
}
}
}
}
}
struct SwiftUIARCardView_Previews: PreviewProvider {
static var previews: some View {
SwiftUIARCardView()
}
}
| true
|
913e0c3219ea4fd101a78bb57afc92e74d974fdb
|
Swift
|
nileshdeshmukh/Swiftilities
|
/Example/Swiftilities/Views/Lifecycle/NavBarTitleTransitionDemoViewController.swift
|
UTF-8
| 2,002
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// NavBarTitleTransitionDemoViewController.swift
// Swiftilities
//
// Created by Jason Clark on 5/26/17.
// Copyright © 2017 Raizlabs. All rights reserved.
//
import Swiftilities
class NavBarTitleTransitionDemoViewController: UIViewController {
let scrollView = UIScrollView()
let titleLabel = UILabel()
let contentView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Title Transition"
titleLabel.text = "Title Transition"
view.backgroundColor = .lightGray
let behavior = NavTitleTransitionBehavior(scrollView: scrollView, titleView: titleLabel)
addBehaviors([behavior])
}
}
extension NavBarTitleTransitionDemoViewController {
override func loadView() {
view = UIView()
view.addSubview(scrollView)
scrollView.addSubview(contentView)
contentView.addSubview(titleLabel)
for view in [scrollView, titleLabel, contentView] {
view.translatesAutoresizingMaskIntoConstraints = false
}
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor),
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
contentView.leftAnchor.constraint(equalTo: scrollView.leftAnchor),
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
contentView.rightAnchor.constraint(equalTo: scrollView.rightAnchor),
contentView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 2),
titleLabel.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
titleLabel.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 200),
])
}
}
| true
|
e44ac32e001fff4a3071145a8dab627d46031d39
|
Swift
|
HackingGate/Swift-Public-IP
|
/SwiftPublicIP-CLI/main.swift
|
UTF-8
| 518
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
//
// main.swift
// SwiftPublicIP-CLI
//
// Created by ERU on 2019/05/13.
// Copyright © 2019 SwiftPublicIP. All rights reserved.
//
import Foundation
import SwiftPublicIP
print("Hello, World!")
var sema = DispatchSemaphore(value: 0)
SwiftPublicIP.getPublicIP(url: PublicIPAPIURLs.IPv4.icanhazip.rawValue) { string, error in
if let error = error {
print(error.localizedDescription)
} else if let string = string {
print(string) // Your IP address
}
sema.signal()
}
sema.wait()
| true
|
4e69122e4f778a9996e88c62500a492a9760df79
|
Swift
|
dumpling0522/190910
|
/190910/LeaderboardController.swift
|
UTF-8
| 1,154
| 2.78125
| 3
|
[] |
no_license
|
//
// LeaderboardController.swift
// 190910
//
// Created by 水餃 on 2019/10/17.
// Copyright © 2019年 水餃. All rights reserved.
//
import UIKit
class LeaderboardController: UIViewController {
@IBOutlet weak var leaderboard: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var move = UserDefaults.standard.array(forKey: "move") as? [Int]
move?.sort(by: { (grade1, grade2) -> Bool in
return grade1 < grade2
})
var number = 1
if move != nil {
for move in move! {
leaderboard.text.append("No" + number.description + " " + move.description + "\n")
number += 1
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
c5e1b65dcfed0e8c48011d89c14a550462b90ce8
|
Swift
|
ttyguy1/filterDropDownView
|
/filterTab/ViewController.swift
|
UTF-8
| 4,514
| 2.53125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// filterTab
//
// Created by Tyler Middleton on 7/25/18.
// Copyright © 2018 Tyler Middleton. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var filterView: UIView!
@IBOutlet weak var startField: UITextField!
@IBOutlet weak var endField: UITextField!
let datePicker = UIDatePicker()
let datePicker1 = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
addInputAccessoryForTextFields(textFields: [startField, endField], dismissable: true, previousNextable: true)
showFilterView()
}
@IBAction func doneButtonTapped(_ sender: UIButton) {
}
@IBAction func filterButtonTapped(_ sender: UIBarButtonItem) {
showFilterView()
}
func showDatePicker(){
//Formate Date
datePicker.datePickerMode = .date
//ToolBar
let toolbar = UIToolbar()
toolbar.sizeToFit()
startField.inputAccessoryView = toolbar
startField.inputView = datePicker
datePicker.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)
}
@objc func handleDatePicker(sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM dd, yyyy"
let dateStr = formatter.string(from: datePicker.date)
startField.text = dateStr
self.filterView.frame.origin.y = -128
}
func showDatePicker1(){
//Formate Date
datePicker1.datePickerMode = .date
//ToolBar
let toolbar = UIToolbar()
toolbar.sizeToFit()
endField.inputAccessoryView = toolbar
endField.inputView = datePicker1
datePicker1.addTarget(self, action: #selector(handleDatePicker2(sender:)), for: .valueChanged)
}
@objc func handleDatePicker2(sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM dd, yyyy"
let dateStr = formatter.string(from: datePicker1.date)
endField.text = dateStr
}
@objc func showFilterView() {
if filterView.frame.origin.y == 88 {
UIView.animate(withDuration: 1, delay: 0, options: UIViewAnimationOptions(), animations: {
self.filterView.frame.origin.y = -58
}, completion: nil)
} else {
UIView.animate(withDuration: 1, delay: 0, options: UIViewAnimationOptions(), animations: {
self.filterView.frame.origin.y = 88
}, completion: nil)
}
}
}
extension UIViewController {
func addInputAccessoryForTextFields(textFields: [UITextField], dismissable: Bool = true, previousNextable: Bool = false) {
for (index, textField) in textFields.enumerated() {
let toolbar: UIToolbar = UIToolbar()
toolbar.sizeToFit()
var items = [UIBarButtonItem]()
if previousNextable {
let previousButton = UIBarButtonItem(image: UIImage(named: "leftArrow1"), style: .plain, target: nil, action: nil)
previousButton.width = 30
if textField == textFields.first {
previousButton.isEnabled = false
} else {
previousButton.target = textFields[index - 1]
previousButton.action = #selector(UITextField.becomeFirstResponder)
}
let nextButton = UIBarButtonItem(image: UIImage(named: "rightArrow1"), style: .plain, target: nil, action: nil)
nextButton.width = 30
if textField == textFields.last {
nextButton.isEnabled = false
} else {
nextButton.target = textFields[index + 1]
nextButton.action = #selector(UITextField.becomeFirstResponder)
}
items.append(contentsOf: [previousButton, nextButton])
}
let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: view, action: #selector(UIView.endEditing))
items.append(contentsOf: [spacer, doneButton])
toolbar.setItems(items, animated: false)
textField.inputAccessoryView = toolbar
}
}
}
| true
|
cc2e2fcd5e351fa44ec775745950aa54b7dbeb0e
|
Swift
|
gibsonsmiley/Collections
|
/Collections/ImageController.swift
|
UTF-8
| 1,393
| 3.046875
| 3
|
[] |
no_license
|
//
// ImageController.swift
// Collections
//
// Created by Gibson Smiley on 5/3/16.
// Copyright © 2016 Gibson Smiley. All rights reserved.
//
import UIKit
class ImageController {
static func uploadImage(image: UIImage?, completion: (id: String?) -> Void) {
if let base64Image = image?.base64String {
let base = FirebaseController.base.childByAppendingPath("images").childByAutoId()
base.setValue(base64Image)
completion(id: base.key)
} else {
completion(id: nil)
}
}
static func imageForID(id: String, completion: (image: UIImage?) -> Void) {
FirebaseController.dataAtEndpoint("images/\(id)") { (data) in
if let data = data as? String {
let image = UIImage(base64: data)
completion(image: image)
} else {
completion(image: nil)
}
}
}
}
extension UIImage {
var base64String: String? {
guard let data = UIImageJPEGRepresentation(self, 0.8) else { return nil }
return data.base64EncodedStringWithOptions(.EncodingEndLineWithCarriageReturn)
}
convenience init?(base64: String) {
if let imageData = NSData(base64EncodedString: base64, options: .IgnoreUnknownCharacters) {
self.init(data: imageData)
} else {
return nil
}
}
}
| true
|
345752febc78efb976d8776c51fdf0b61221dec2
|
Swift
|
pranavlathigara/Swift_100days
|
/7Day/7Day/ViewController.swift
|
UTF-8
| 1,293
| 2.5625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// 7Day
//
// Created by 杜维欣 on 16/1/27.
// Copyright © 2016年 Nododo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var topTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
topTextView.becomeFirstResponder()
self.createLeftNavigationItem()
self.createSwipeGes()
// Do any additional setup after loading the view, typically from a nib.
}
func createLeftNavigationItem() {
let leftBtn = UIButton(frame: CGRectMake(0, 0, 25, 25))
leftBtn.setBackgroundImage(UIImage(named: "navigation_back_button"), forState: .Normal)
let leftItem = UIBarButtonItem.init(customView: leftBtn)
self.navigationItem.leftBarButtonItem = leftItem;
}
func createSwipeGes() {
let swipeGes = UISwipeGestureRecognizer.init(target: self, action: Selector ("swipeToResign"))
swipeGes.direction = .Down
view .addGestureRecognizer(swipeGes)
}
func swipeToResign() {
topTextView.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
f01fc864d84c68067a2a42b5048d2a4ec1fbaf6d
|
Swift
|
sk8Guerra/SwiftTutorials
|
/Enumerations/Enumerations.playground/Contents.swift
|
UTF-8
| 1,287
| 3.640625
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
enum NameOfEnum {
case caseOne
case caseTwo
case caseThree
}
let enumeration: NameOfEnum = .caseOne
enum NameOfEnum2 {
case caseOne,caseTwo, caseThree
}
let enumeration2: NameOfEnum2 = .caseOne
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
var prodBarcode = Barcode.upc(8, 85909, 51226, 3)
prodBarcode = .qrCode("kjaklsjdfasdf")
switch prodBarcode {
case let .upc(numberSystem, manufacturer, product, check):
print("UPC \(numberSystem), \(manufacturer), \(product), \(check)")
case let .qrCode(productCode):
print("QR CODE: \(productCode)")
default:
print("Malo")
}
enum JediMaster: String {
case yoda = "Yoda"
case maceWindu = "Mace Windu"
case quiGonJinn = "QuiGon Jinn"
case obiWanKenobi = "ObiWan Kenobi"
case lukeSkywalker = "Luke Skywalker"
}
print(JediMaster.yoda.rawValue)
enum SwitchStatus {
case on
case off
}
var switchStatus: SwitchStatus = .off
func flipSwitch(status: SwitchStatus) -> SwitchStatus {
if status == .off {
return .on
} else {
return .off
}
}
flipSwitch(status: <#T##SwitchStatus#>)
switchStatus = .on
flipSwitch(status: <#T##SwitchStatus#>)
| true
|
cbe042c3936896cb4489c3c9ddadb1786e2998b6
|
Swift
|
SydneyRaeBlackburn/iOS-assignment5
|
/Assignment5/ClassIDsList.swift
|
UTF-8
| 1,374
| 3.296875
| 3
|
[] |
no_license
|
//
// ClassIDsList.swift
// Assignment5
//
// Created by Sydney Blackburn on 11/14/18.
// Copyright © 2018 Sydney Blackburn. All rights reserved.
//
import Foundation
enum ClassIDsResult {
case success([ClassID])
case failure(Error)
}
class ClassIDsList {
/*
create a URLSession
*/
private let session: URLSession = {
let config = URLSessionConfiguration.default
return URLSession(configuration: config)
}()
/*
process request
*/
private func processClassIDsRequest(data: Data?, error: Error?) -> ClassIDsResult {
guard let jsonData = data else {
return .failure(error!)
}
return ClassIDsListAPI.courses(fromJSON: jsonData)
}
/*
GET method
returns a JSON array of ints of the ids of the classes that are in the given subject and meet the given criteria
*/
func fetchClassIDs(parameters: [String:String]?, completion: @escaping (ClassIDsResult) -> Void) {
let url = ClassIDsListAPI.classIDsListURL(parameters: parameters)
let request = URLRequest(url: url)
let task = session.dataTask(with: request) {
(data, response, error) -> Void in
let result = self.processClassIDsRequest(data: data, error: error)
completion(result)
}
task.resume()
}
}
| true
|
9c03dadc238a0f1cbb68749f407078552598f361
|
Swift
|
msseock/GURU_iOS_lecture
|
/Week1/assignment/Memo/Memo/ViewController.swift
|
UTF-8
| 4,267
| 2.84375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Memo
//
// Created by 석민솔 on 2021/07/05.
//
import UIKit
import FMDB
class ViewController: UIViewController {
var memos = Array<String>()
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var textField: UITextField!
// 데이터베이스 경로 저장
var databasePath = String()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// 데이터베이스 초기화, create table
// DB 초기화 함수 호출
self.initDB()
self.loadDB()
}
func initDB() {
// 데이터 파일 저장할 위치 잡기
let fileMgr = FileManager.default // 현재 켜져있는 앱 시스템에서 공유 파일에 접근할 수 있도록 해주는 메소드
let dirPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) // 현재 사용자에게 파일을 저장할 권한이 있는 폴더 목록들이 반환
let docDir = dirPaths[0] // 접근할 폴더 추출(위치 잡기)
databasePath = docDir + "/memo.db"
if !fileMgr.fileExists(atPath: databasePath) {
// DB 만들기
let db = FMDatabase(path: databasePath)
if db.open() { // 접근
// 테이블 만들기
// SQL: 질의문
let query = "create table if not exists memo(id integer primary key autoincrement, memoText text)"
if !db.executeStatements(query) {
NSLog("DB 생성 실패")
} else {
NSLog("DB 생성 성공")
}
}
} else {
NSLog("DB파일 있음")
}
}
func loadDB() {
NSLog("Load DB")
memos = Array<String>()
let db = FMDatabase(path: databasePath)
if db.open() {
let query = "select * from memo"
if let result = db.executeQuery(query, withArgumentsIn: []) {
while result.next() {
var columnArray = Array<String>()
columnArray.append(String(result.string(forColumn: "memoText")!))
memos.append(contentsOf: columnArray)
}
self.tableView.reloadData()
} else {
NSLog("결과 없음")
}
} else {
NSLog("DB Connection Error")
}
}
// tableview에 띄우기, DB에 저장하기
@IBAction func doSave(_ sender: Any) {
NSLog("Save")
// 키보드 없애기
view.endEditing(true)
// 입력한 텍스트값 받아오기
if let text = textField.text, !text.isEmpty {
// table view에 띄우기
memos.append(text)
self.tableView.reloadData()
// DB에 저장
saveDB()
}
}
func saveDB() {
NSLog("Save start")
let db = FMDatabase(path: databasePath)
if db.open() {
do {
let query = "insert into memo(memoText) values (?)"
try db.executeUpdate(query, values: [memos.last!])
} catch let error as NSError {
NSLog("Insert Error: \(error.localizedDescription)")
}
NSLog("Save finished")
} else {
NSLog("DB Connection Error")
}
}
@IBAction func textFieldEndEditing(_ sender: UITextField) {
sender.resignFirstResponder()
}
@IBAction func textEndEditing(_ sender: Any) {
view.endEditing(true)
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// 셀 몇개?
return memos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 셀에 내용 넣어서 반환
let cell = tableView.dequeueReusableCell(withIdentifier: "memoCell", for: indexPath)
cell.textLabel?.text = "\(self.memos[indexPath.row])"
return cell
}
}
| true
|
931b28a50b906579d22a4fa826245239943f1257
|
Swift
|
mohsinalimat/VRCodeView
|
/VRCodeView/Classes/Utils.swift
|
UTF-8
| 1,039
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
//
// Utils.swift
// VRCodeView
//
// Created by Vatsal Rustagi on 9/6/18.
//
import Foundation
extension UIView {
/// Sets shadow for a UIView
///
/// - Parameters:
/// - color: shadow color
/// - offset: shadow offset
/// - opacity: shadow opacity
/// - radius: shadow blur radius
/// - corderRadius: corner radius of the UIView
func setShadowWithValues(color: UIColor, offset: CGSize, opacity: Float, radius: CGFloat, corderRadius: CGFloat) {
self.layer.shadowColor = color.cgColor
self.layer.shadowOffset = offset
self.layer.shadowRadius = radius
self.layer.shadowOpacity = opacity
self.layer.cornerRadius = corderRadius
}
/// Sets border for a UIView
///
/// - Parameters:
/// - color: border color
/// - width: border width
/// - corderRadius: corner radius of the UIView
func setBorder(color: UIColor, width: CGFloat, corderRadius: CGFloat) {
self.layer.borderColor = color.cgColor
self.layer.borderWidth = width
self.layer.cornerRadius = corderRadius
self.clipsToBounds = true
}
}
| true
|
6a451faf1d6e7b833be2d782a8fc8d2e618be140
|
Swift
|
thangcao/VIPER_IOS
|
/viper/LoginViewController.swift
|
UTF-8
| 1,030
| 2.875
| 3
|
[] |
no_license
|
//
// LoginViewController.swift
// viper
//
// Created by Cao Thắng on 6/18/17.
// Copyright © 2017 Cao Thắng. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
// MARK: - Declare UI variables
@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
var presenter: LoginPresentation!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func actionLogin(_ sender: Any) {
if let username = username.text
, let password = password.text {
if !username.isEmpty , !password.isEmpty {
let account = Account(name: username, password: password)
presenter.login(account: account)
} else {
showError(message: "Username or password is empty")
}
}
}
}
// MARK: - LoginView
extension LoginViewController: LoginView {
func showError(message: String) {
// TODO: show dilalog
}
}
| true
|
3e734f61292a6783607c8886c228ff760e926725
|
Swift
|
ultra7677/GlowProject
|
/GlowProject/TopicTableViewController.swift
|
UTF-8
| 7,687
| 2.9375
| 3
|
[] |
no_license
|
//
// TopicTableViewController.swift
// GlowProject
//
// Created by ultra on 10/10/15.
// Copyright © 2015 ultra. All rights reserved.
//
import UIKit
import Foundation
// Add a new method to create hex form color
extension UIColor {
convenience init(red: Int, green: Int, blue: Int, alphar:CGFloat) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alphar)
}
convenience init(netHex:Int,alpha:CGFloat) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff,alphar:alpha)
}
}
class TopicTableViewController: UITableViewController {
// MARK Properties
var topics = [Topic]()
var comments = NSMutableArray()
var comments1 = NSMutableArray()
// load json form data from Glow_Data.json
func loadSampleTopics(){
guard let path = NSBundle.mainBundle().pathForResource("Glow_Data", ofType: "json") else{
print("error finding file")
return
}
do{ // File has been find
let data: NSData? = NSData(contentsOfFile: path)
if let jsonResult: NSDictionary =
try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary{
// get topics
let topicArray = jsonResult["topics"] as! NSMutableArray
for topic in topicArray{
// the author of ont topic
let author = topic["author"] as! NSDictionary
// the photo of author, saved in Assets.xcassets
let image1 = UIImageView()
image1.image = UIImage(named: author["profile_image"]! as! String)
// author1 is the author of this topic
let author1 = Author(id: 10001, firstName: author["first_name"]! as! String, lastName: author["last_name"]! as! String, profileImage: image1)
// get comments for this topic
let commentArray = topic["comments"] as! NSMutableArray
// comments is the set including every comment of this topic
let comments = NSMutableArray()
for comment in commentArray{
//get author of one comment
let author = comment["author"] as! NSDictionary
let image0 = UIImageView()
image0.image = UIImage(named: author["profile_image"]! as! String)
let author0 = Author(id: 10001, firstName: author["first_name"]! as! String, lastName: author["last_name"]! as! String, profileImage: image0)
let comment0 = MyComment(id: 10001 ,content: comment["content"]! as! String, author: author0)
//add one comment to the set
comments.addObject(comment0)
}
// topic0 is a topic
let topic0 = Topic(id: 10001, title: topic["title"]!! as! String, content: topic["content"]!! as! String, tag: topic["tag"]!! as! String, author: author1, comments: comments)
// add topic0 to the topics set
topics += [topic0]
}
}
} catch let error as NSError{
print("Error:\n \(error)")
return
}
}
// Transfer data between two ViewControllers
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "showComments"){
let commentTableViewController = segue.destinationViewController as! CommentTableViewController
// get which topic user selected and then show detail of this topic
if let selectedTopicCell = sender as?TopicTableViewCell{
let indexPath = tableView.indexPathForCell(selectedTopicCell)!
let selectedTopic = topics[indexPath.row]
commentTableViewController.topic = selectedTopic
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Load the sample data
loadSampleTopics()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return topics.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "TopicTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! TopicTableViewCell
// Fetches the appropriate topic for the data source layout.
let topic = topics[indexPath.row]
cell.tagLabel.text = topic.getTag() + " >"
cell.titleLabel.text = topic.getTitle()
cell.contentLabel.text = topic.getContent()
//get the latest commender of this topic
let latestComment = topic.getComments().objectAtIndex(topic.getComments().count-1) as! MyComment
cell.authorNameLabel.text = latestComment.getAuthor().getFirstName()
//different tag at diffrent row should have different background color and text color
if(indexPath.row % 3 == 0){
cell.tagLabel.backgroundColor = UIColor(netHex: 0x915C57,alpha: 0.3)
cell.tagLabel.textColor = UIColor(netHex:0x915C57,alpha: 0.7)
}else if(indexPath.row % 3 == 1){
cell.tagLabel.backgroundColor = UIColor(netHex: 0x536156,alpha: 0.3)
cell.tagLabel.textColor = UIColor(netHex:0x536156,alpha: 0.7)
cell.backgroundColor = UIColor(netHex:0xE8E8EB,alpha: 0.15)
}else{
cell.tagLabel.backgroundColor = UIColor(netHex: 0x9D9DB0,alpha: 0.5)
cell.tagLabel.textColor = UIColor(netHex:0x9D9DB0,alpha: 0.8)
}
// set color
cell.authorNameLabel.textColor = UIColor(netHex:0x9BA678,alpha: 1)
cell.titleLabel.textColor = UIColor(netHex:0x465449,alpha: 1)
cell.contentLabel.textColor = UIColor(netHex:0x9BA678,alpha: 1)
// When the number of response is one
if(topic.getComments().count == 1){
cell.commentsNumberLabel.text = "1 response"
}else{
cell.commentsNumberLabel.text = String(topic.getComments().count) + " responses"
}
// set profile image
let profileImageView = latestComment.getAuthor().getProfileImage()
cell.profileImage.image = profileImageView.image
return cell
}
}
| true
|
0715b6cfbdfa29716146b446808ca83e165a7833
|
Swift
|
codablestudio/unpause-ios
|
/Unpause/Unpause/Views/CustomUIElements/UITextFields/PaddedTextField.swift
|
UTF-8
| 1,169
| 2.734375
| 3
|
[] |
no_license
|
//
// PaddedTextField.swift
// Unpause
//
// Created by Krešimir Baković on 13/03/2020.
// Copyright © 2020 Krešimir Baković. All rights reserved.
//
import UIKit
class PaddedTextField: UITextField {
public var textInsets = UIEdgeInsets.zero {
didSet {
setNeedsDisplay()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init() {
self.init(frame: .zero)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: textInsets)
}
open override func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: textInsets)
}
open override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: textInsets)
}
open override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: textInsets))
}
open override func caretRect(for position: UITextPosition) -> CGRect {
return CGRect.zero
}
}
| true
|
c89629a88dc72adcfda15b30ff7ddebdd4e72d47
|
Swift
|
omidgolparvar/NoskheKit
|
/NoskheKit/Sources/NKVersionsData.swift
|
UTF-8
| 2,443
| 2.875
| 3
|
[] |
no_license
|
import Foundation
public final class NKVersionsData {
let versionsItems : [NKVersionData]
init(items: [NKVersionData]) {
let versionsItems = items.sorted { $0.number > $1.number }
self.versionsItems = versionsItems
#if DEBUG
if versionsItems.isEmpty {
debugPrint("⚠️ NoskheKit.NKVersionsData: There is no version item.")
} else {
let numberOfItemsForCurrentVersion = versionsItems
.filter { $0.status == .current }
.count
if numberOfItemsForCurrentVersion == 0 {
debugPrint("⚠️ NoskheKit.NKVersionsData: There is no item for current version.")
}
if numberOfItemsForCurrentVersion > 1 {
debugPrint("⚠️ NoskheKit.NKVersionsData: There is multiple item for current version.")
}
}
#endif
}
public convenience init?(plistFileConfiguration: PlistFileConfiguration) {
let bundle = plistFileConfiguration.bundle
let fileName = plistFileConfiguration.fileName
guard let path = bundle.path(forResource: fileName, ofType: "plist"),
let nsArray = NSArray(contentsOfFile: path) as? [NSDictionary]
else { return nil }
let codingKeysType = VersionData.CodingKeys.self
let items: [VersionData] = nsArray.compactMap { nsDictionary in
guard let versionString = nsDictionary.object(forKey: codingKeysType.number.rawValue) as? String,
let changesStrings = nsDictionary.object(forKey: codingKeysType.changes.rawValue) as? [String],
let versionNumber = VersionNumber(string: versionString)
else { return nil }
let versionChanges = VersionChanges(changes: changesStrings)
return VersionData(number: versionNumber, changes: versionChanges)
}
self.init(items: items)
}
}
// MARK: Decodable
extension NKVersionsData: Decodable {
public convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let items = try container.decode([NKVersionData].self, forKey: .versionDataItems)
self.init(items: items)
}
fileprivate enum CodingKeys: String, CodingKey {
case versionDataItems = "items"
}
}
// MARK: Models
extension NKVersionsData {
public struct PlistFileConfiguration {
public static let `default` = PlistFileConfiguration(bundle: .main, fileName: "Versions")
let bundle : Bundle
let fileName : String
public init(bundle: Bundle, fileName: String) {
self.bundle = bundle
self.fileName = fileName
}
}
}
| true
|
061bab4830129d25924c32f7b3b9c3a13ab987a6
|
Swift
|
kiran147/DropDownDemo
|
/DropMenu/DropDownMenu.swift
|
UTF-8
| 1,778
| 2.875
| 3
|
[] |
no_license
|
//
// DropDownMenu.swift
// Mailbox
//
// Created by Kian on 29/05/18.
// Copyright © 2018 Kiran. All rights reserved.
//
import Foundation
import DropDown
protocol DropDownDelegate {
func didSelect(option : String)
}
class DropDownMenu
{
let dropDown = DropDown()
var delegate : DropDownDelegate?
var width : CGFloat!
var anchorView : UIView?
func showMenuWith(options : [String],anchorView : UIButton)
{
self.anchorView = anchorView
self.dropDown.dataSource = options
self.dropDown.anchorView = anchorView
self.dropDown.show()
self.dropDown.dismissMode = .onTap
self.dropDown.selectionAction = { (index, item) in
self.delegate?.didSelect(option: item)
}
}
func spinnerWith(options : [String],anchorView : UIView)
{
self.anchorView = anchorView
self.dropDown.dataSource = options
self.dropDown.anchorView = anchorView
self.dropDown.bottomOffset = CGPoint.init(x: 0, y: anchorView.frame.height)
self.dropDown.width = (self.width != nil ? self.width : anchorView.frame.width)
self.dropDown.show()
self.dropDown.dismissMode = .onTap
self.dropDown.selectionAction = { (index, item) in
self.delegate?.didSelect(option: item)
}
}
func setUpSpinnerTo(anchorView : UIView)
{
self.dropDown.anchorView = anchorView
self.dropDown.bottomOffset = CGPoint.init(x: 0, y: anchorView.frame.height)
self.dropDown.width = (self.width != nil ? self.width : anchorView.frame.width)
self.dropDown.dismissMode = .automatic
self.anchorView = anchorView
}
func hideMenu()
{
self.dropDown.hide()
}
}
| true
|
d376ad19b56a0fd7a9278e4cc2feae657734f99a
|
Swift
|
artemch/CocoaHeads_Workshop_2019
|
/source/Shared/Functions/F+FormField.swift
|
UTF-8
| 354
| 2.53125
| 3
|
[] |
no_license
|
import Foundation
extension F {
static func formattedFormField<Value>(value: Value?, values: String...) -> String? {
return value.map { "\($0)" + values.joined() }
}
}
extension F {
static func formattedFormField<Value>(value: Value?, placeholder: Value) -> String {
return value.map { "\($0)" } ?? "\(placeholder)"
}
}
| true
|
58dc8263d96c3f11c8999be44bedddd281e20a51
|
Swift
|
incwo/erp-ios
|
/Classes/NewsItemCell.swift
|
UTF-8
| 1,570
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
//
// NewsItemCell.swift
// facile
//
// Created by Renaud Pradenc on 28/08/2019.
//
import UIKit
class NewsItemCell: UITableViewCell {
private static var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.timeStyle = .short
formatter.dateStyle = .medium
return formatter
}()
@objc var date: Date? = nil {
didSet {
if let date = date {
dateLabel.text = NewsItemCell.dateFormatter.string(from: date)
} else {
dateLabel.text = ""
}
}
}
@objc var title: String? = nil {
didSet {
titleLabel.text = title
}
}
// TODO: the title should be bold when not read
@objc var isRead: Bool = false {
didSet {
titleLabel.textColor = titleColor(isRead: isRead)
titleLabel.font = UIFont.systemFont(ofSize: 15.0, weight: isRead ? .regular : .semibold)
}
}
private func titleColor(isRead: Bool) -> UIColor {
if #available(iOS 11, *) {
if isRead {
return UIColor(named: "news.title.read")!
} else {
return UIColor(named: "news.title.unread")!
}
} else { // < iOS 11
if isRead {
return UIColor(white: 0.3, alpha: 1.0)
} else {
return .black
}
}
}
@IBOutlet private weak var dateLabel: UILabel!
@IBOutlet private weak var titleLabel: UILabel!
}
| true
|
62195794b61d31566ad3ace4597f552964157384
|
Swift
|
TodayHu/WatchAnimationHelper
|
/Example/LayerAnimations/ViewController.swift
|
UTF-8
| 1,329
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// LayerAnimations
//
// Created by Sergey Pronin on 1/16/15.
// Copyright (c) 2015 AITA LTD. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var point: RoundView!
var plane: PlaneView!
var imageView: UIImageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
point = RoundView(location: CGPointMake(self.view.center.x, self.view.center.y))
point.backgroundColor = UIColor.clearColor()
self.view.addSubview(point)
imageView.frame = CGRectMake(100, 100, 100, 100)
imageView.backgroundColor = UIColor.grayColor()
self.view.addSubview(imageView)
plane = PlaneView()
plane.center = self.view.center
self.view.addSubview(plane)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func clickButton(sender: AnyObject) {
var image = plane.animate()
// var image = point.animate()
imageView.animationImages = image.images!
imageView.animationDuration = 2
imageView.startAnimating()
}
}
| true
|
54d2203778a2b664eeaa67cf88ca38c798863b07
|
Swift
|
TravelMateSSU/IOS
|
/TravelMate/ViewController.swift
|
UTF-8
| 1,702
| 2.5625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// TravelMate
//
// Created by 이동규 on 2016. 9. 30..
// Copyright © 2016년 이동규. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let dbManager = DBManager()
let isBeginner = UserDefaults.standard.value(forKey: "isBeginner")
if isBeginner == nil { // 처음 앱을 시작한 사람
// 카테고리 SQLite -> Realm DB화
dbManager.copyCategories()
// 앱을 실행했음을 마킹
UserDefaults.standard.set(1, forKey: "isBeginner")
}
// let category = dbManager.categoriesDict()
// 사용법
/*
let routeView = RouteView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 150))
routeView.backgroundColor = UIColor.orange
let tourist = SpotModel()
tourist.title = "실험"
routeView.append(spot: tourist)
routeView.title = "연습타이틀"
self.view.addSubview(routeView)
routeView.setNeedsDisplay()
let apiManager = TourAPIManager()
let spot = SpotModel()
spot.contentTypeId = "12"
spot.contentId = "636266"
apiManager.querySearchByKeyword(keyword: "서울", completion: { spots in
apiManager.querySearchById(spot: spots[0], completion: {
spotModel in
guard let resSpot = spotModel else {
return
}
print(resSpot.title)
})
})*/
}
}
| true
|
da0b9a8c73a7db2ad26f8f969d6570d021a5959d
|
Swift
|
jagjeetgandhi/Hacktoberfest2020-1
|
/ByteCoin-iOS13/ByteCoin/View Model/ViewController.swift
|
UTF-8
| 3,359
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// ByteCoin
//
// Created by Angela Yu on 11/09/2019.
// Copyright © 2019 The App Brewery. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate,CoinManagerDelegate{
@IBOutlet weak var pricelabel:UILabel!
@IBOutlet weak var cursymbol:UILabel!
@IBOutlet weak var picker:UIPickerView!
@IBOutlet weak var cryptoCurrency:UICollectionView!
var CoinType:String = "BTC"
var Crypto:String = ""
@IBAction func click(_ sender:UIButton) {
}
func updateUI(_ coinObject: bitcoin) {
DispatchQueue.main.async {
self.pricelabel.text = coinObject.price
self.cursymbol.text = coinObject.asset_id_quote
}
}
var coin = CoinManager()
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
picker.dataSource = self
coin.delegate = self
let nib = UINib(nibName: "Crypto", bundle: nil)
self.cryptoCurrency.register(nib, forCellWithReuseIdentifier: "Cell")
self.cryptoCurrency.collectionViewLayout = UICollectionViewFlowLayout()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return coin.currencyArray.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return coin.currencyArray[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let Currency = coin.currencyArray[row]
self.Crypto = Currency
coin.getURL(Currency, CoinType)
}
}
extension ViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Crypto
cell.cryptoimage.image = UIImage(named: "\(coin.CoinArray[indexPath.row])")
cell.cryptoimage.contentMode = .scaleAspectFit
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = CGSize(width:(Int(cryptoCurrency.frame.size.width)-50)/3, height:(Int(cryptoCurrency.frame.height)))
return size
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let currency = coin.CoinArray[indexPath.row]
self.CoinType = currency
coin.getURL(Crypto, CoinType)
}
func alert() {
let alert = UIAlertController(title: " Error", message: "Try some other Value ", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert,animated:true)
}
}
| true
|
c2cd98aa8078838b1f29a6c45fa0712a3752cf2f
|
Swift
|
msaradeth/GenericDataSource
|
/Common/Extensions.swift
|
UTF-8
| 2,877
| 2.859375
| 3
|
[] |
no_license
|
//
// Extensions.swift
// GenDataSource
//
// Created by Mike Saradeth on 6/27/19.
// Copyright © 2019 Mike Saradeth. All rights reserved.
//
import Foundation
import UIKit
//MARK: UIView extension
extension UIView {
func fillsuperView(padding: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)) {
guard let superview = superview else { return }
topAnchor.constraint(equalTo: superview.topAnchor, constant: padding.top).isActive = true
leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: padding.left).isActive = true
trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: padding.right).isActive = true
bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: padding.bottom).isActive = true
}
}
//MARK: UICollectionView extension
extension UICollectionView {
// //MARK: Generic function to calc cell with and height base on number of columns
// //constraint Model datatype and Cell datatype must be the same
// func getCellSize<CellType: UICollectionViewCell, DataType>(cell: CellType, item: DataType, numberOfColumns: Int) -> CGSize
// where CellType: CellProtocol, DataType == CellType.DataType {
//
// //set up cell
// cell.configure(item: item)
//
// //calc cell Width
// let cellWidth = self.getCellWidth(numberOfColumns: numberOfColumns)
//
// //set contentView width constraint
// cell.contentViewWidthConstraint?.constant = cellWidth
//
// //calc cell height
// cell.setNeedsLayout()
// cell.layoutIfNeeded()
// let size = cell.contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
//
// return CGSize(width: cellWidth, height: size.height)
// }
//MARK: Get cell Width
func getCellWidth(numberOfColumns: Int) -> CGFloat {
let availableWidth = getAvailableWidth(numberOfColumns: numberOfColumns)
//available width divided by number of columns
let cellWidth = availableWidth / CGFloat(numberOfColumns)
return cellWidth > 0 ? cellWidth : 0
}
//Mark: Get available width
func getAvailableWidth(numberOfColumns: Int) -> CGFloat {
let numberOfColumns = CGFloat(numberOfColumns)
//calc available width minus safeAreaInsets
var availableWidth = self.bounds.width - (self.safeAreaInsets.left + self.safeAreaInsets.right)
//available width minus FlowLayout settings
if let flowLayout = self.collectionViewLayout as? UICollectionViewFlowLayout {
availableWidth = availableWidth - (flowLayout.minimumInteritemSpacing*numberOfColumns + flowLayout.sectionInset.left + flowLayout.sectionInset.right)
}
return availableWidth > 0 ? availableWidth : 0
}
}
| true
|
220538beb1664c6e3c8aefb499ad13b07d5bca00
|
Swift
|
misolubarda/Travel
|
/Travel/Model/Server/APIRequestProtocol.swift
|
UTF-8
| 3,291
| 3.421875
| 3
|
[] |
no_license
|
//
// APIProtocol.swift
// Travel
//
// Created by Miso Lubarda on 20/08/16.
// Copyright © 2016 test. All rights reserved.
//
import Foundation
/**
* Protocol defines API request data, parsing function and response data.
*/
protocol APIRequestProtocol: class {
/// This defines the type of response data.
associatedtype ResponseType
/// Base URL of the request.
var baseURL: NSURL {get}
/// Endpoint URL path, relative to baseURL
var endpointPath: String {get}
/// Queue on which to provide response.
var responseQueue: dispatch_queue_t {get}
/// This function parses response from NSData to specified response type.
var responseParsing: ((data: NSData) throws -> ResponseType) {get}
/// Reference to NSURLSessionDataTask created when configuring the request
var dataTask: NSURLSessionDataTask? {get set}
}
extension APIRequestProtocol {
/**
Configuring request with resulting NSURLSessionDataTask response on a provided queue with completion block which throws ErrorType if NSURLSession returns NSError.
Usage without error rethrow:
apiRequest.prepareWithCompletion() { (response: () throws -> NSData)
do {
let response = try response()
// Continue using response.
} catch let error {
// Handle error
}
}
Usege with error rethrow:
//Inside a funciton that throws error
apiRequest.prepareWithCompletion() { (response: () throws -> NSData)
let response = try response()
// Continue using response.
}
- parameter completion: Completion returns APIResponse or throws error if NSURLSession returns NSError.
*/
func prepareWithCompletion(completion: (response: () throws -> ResponseType) -> Void) {
let session = NSURLSession.sharedSession()
guard let url = NSURL(string: endpointPath, relativeToURL: baseURL) else {
completion(response: { throw APIRequestError.URL })
return
}
dataTask = session.dataTaskWithURL(url) { (data: NSData?, response: NSURLResponse?, error: NSError?) in
dispatch_async(self.responseQueue, {
if error == nil {
if let data = data {
do {
let response = try self.responseParsing(data: data)
completion(response: { return response})
} catch let error {
completion(response: { throw error })
}
} else {
completion(response: { throw APIRequestError.NoData })
}
} else {
completion(response: { throw APIRequestError.Response(message: error?.localizedDescription) })
}
})
}
}
/**
Execute the request and invoke completion block, specified in prepareWithCompletion function.
*/
func execute() {
dataTask?.resume()
}
}
enum APIRequestError: ErrorType {
case URL, Response(message: String?), NoData
}
| true
|
ef0ae2ec2fd29caeb366e5028a28ecff8feb27a8
|
Swift
|
Elhoej/Tasks
|
/Tasks/View Controllers/TaskDetailViewController.swift
|
UTF-8
| 3,127
| 2.90625
| 3
|
[] |
no_license
|
//
// TaskDetailViewController.swift
// Tasks
//
// Created by Simon Elhoej Steinmejer on 13/08/18.
// Copyright © 2018 Simon Elhoej Steinmejer. All rights reserved.
//
import UIKit
class TaskDetailViewController: UIViewController
{
var task: Task?
{
didSet
{
updateViews()
}
}
var taskController: TaskController?
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var notesTextView: UITextView!
@IBOutlet weak var prioritySegmentedControl: UISegmentedControl!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var priorityLabel: UILabel!
@IBOutlet weak var notesLabel: UILabel!
override func viewDidLoad()
{
super.viewDidLoad()
view.backgroundColor = Appearance.backgroundColor
updateViews()
setupAppearance()
}
private func setupAppearance()
{
titleTextField.font = Appearance.appFont(with: .caption1, size: 13)
notesTextView.font = Appearance.appFont(with: .caption1, size: 13)
notesTextView.layer.cornerRadius = 6
notesTextView.keyboardAppearance = .dark
titleLabel.font = Appearance.appFont(with: .title2, size: 20)
priorityLabel.font = Appearance.appFont(with: .title2, size: 20)
notesLabel.font = Appearance.appFont(with: .title2, size: 20)
}
private func updateViews()
{
guard isViewLoaded else { return }
title = task?.name
titleTextField.text = task?.name
notesTextView.text = task?.notes
// guard let priority = TaskPriority(rawValue: priorityString) else { return }
// prioritySegmentedControl.selectedSegmentIndex = TaskPriority.allPriorities.index(of: priority)
}
@IBAction func save(_ sender: Any)
{
guard let name = titleTextField.text, !name.isEmpty else { return }
let notes = notesTextView.text
if let task = task
{
task.name = name
task.notes = notes
task.priority = TaskPriority.allPriorities[prioritySegmentedControl.selectedSegmentIndex].rawValue
taskController?.put(task: task)
}
else
{
var priority: TaskPriority
switch(prioritySegmentedControl.selectedSegmentIndex) {
case 0:
priority = TaskPriority.low
case 1:
priority = TaskPriority.medium
case 2:
priority = TaskPriority.high
case 3:
priority = TaskPriority.critical
default:
priority = TaskPriority.medium
}
let task = Task(name: name, notes: notes, priority: priority)
taskController?.put(task: task)
}
do
{
let moc = CoreDataStack.shared.mainContext
try moc.save()
} catch
{
NSLog("Error saving: \(error)")
}
navigationController?.popViewController(animated: true)
}
}
| true
|
974b491e25d9d514199187745545d89be5629b08
|
Swift
|
khetiSubrat/SwiftPlayGround
|
/Operation.playground/Contents.swift
|
UTF-8
| 3,345
| 3.1875
| 3
|
[] |
no_license
|
import UIKit
var str = "Hello, playground"
var op1 = BlockOperation.init {
print("My Operation1")
}
var op2 = BlockOperation.init {
print("My Operation2")
}
let opq = OperationQueue()
op2.addDependency(op1)
opq.addOperations([op1, op2], waitUntilFinished: true)
print("Done")
struct GitData:Decodable {
let login: String
}
class BaseOperation: Operation {
private var _executing = false {
willSet {
willChangeValue(forKey: "isExecuting")
}
didSet{
didChangeValue(forKey: "isExecuting")
}
}
override var isExecuting: Bool {
return _executing
}
private var _finished = false {
willSet {
willChangeValue(forKey: "isFinished")
}
didSet{
didChangeValue(forKey: "isFinished")
}
}
override var isFinished:Bool {
return _finished
}
func executing(_ exe:Bool) {
_executing = exe
}
func finish(_ fin:Bool) {
_finished = fin
}
}
class MyOperation: BaseOperation {
override func start() {
URLSession.shared.dataTask(with: URL(string: "https://api.github.com/users/shashikant86")!) { (data, response, error) in
print(data ?? "")
self.executing(false)
self.finish(true)
}.resume()
}
}
let op = MyOperation()
op.start()
op.completionBlock = {()->() in
print("all task are done")
}
class MyClass {
init() {
self.name = "Kanchan"
}
var name: String {
willSet {
print("The old value is \(name)")
}
didSet {
print("The new value is \(name)")
}
}
var test: String {
get {
return name
}
set {
name = newValue
}
}
}
var myClass = MyClass()
myClass.name = "Subrat"
myClass.name = "Super"
myClass.test = "Happy"
print(myClass.name)
// New OperationTest
class FirstOperation: Operation {
private var _isExecuting = false {
willSet {
willChangeValue(forKey: "isExecuting")
}
didSet {
willChangeValue(forKey: "isExecuting")
}
}
private var _isFinished = false {
willSet {
willChangeValue(forKey: "isFinished")
}
didSet {
willChangeValue(forKey: "isFinished")
}
}
override func main() {
}
override func start() {
}
func finished(_ isFinished: Bool) {
_isFinished = isFinished
}
}
class SecondOperation: Operation {
private var _isExecuting = false {
willSet {
willChangeValue(forKey: "isExecuting")
}
didSet {
willChangeValue(forKey: "isExecuting")
}
}
private var _isFinished = false {
willSet {
willChangeValue(forKey: "isFinished")
}
didSet {
willChangeValue(forKey: "isFinished")
}
}
override func main() {
}
override func start() {
}
}
var firstOperation = FirstOperation()
var secondOperation = SecondOperation()
let queue = OperationQueue()
queue.addOperations([firstOperation, secondOperation], waitUntilFinished: true)
| true
|
07d6d26136689a7ee1c62f55bcdbe91013aa6ad4
|
Swift
|
rafaelcpalmeida/Countdowner
|
/Countdowner/Model/AppDelegate.swift
|
UTF-8
| 945
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// AppDelegate.swift
// Countdowner
//
// Created by Rafael Almeida on 06/09/17.
// Copyright © 2017 Rafael Almeida. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
setWindow(width: 200, height: 100, x: 25, y: 25)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func setWindow(width: Int, height: Int, x: Int, y: Int) {
guard
let window = NSApplication.shared.windows.first,
let screenWidth = NSScreen.main?.frame.width else { return }
let windowOrigin = CGPoint(x: screenWidth - CGFloat(width + x), y: CGFloat(y))
let windowSize = CGSize(width: width, height: height)
window.setFrame(NSRect(origin: windowOrigin, size: windowSize), display: true)
}
}
| true
|
72f90df3f7cebf716b461a2274ace220ce904969
|
Swift
|
aguserre/iWeather
|
/weather-app/weather-app/Flow/CardsViews/TempCard/TempCardViewModel.swift
|
UTF-8
| 881
| 3.015625
| 3
|
[] |
no_license
|
//
// TempCardViewModel.swift
// weather-app
//
// Created by Agustin Errecalde on 06/10/2021.
//
import SwiftUI
final class TempCardViewModel: ObservableObject {
@Published var cityName: String
@Published var currentTemp: String
@Published var spaces: CGFloat
@Published var weatherDescription: String
@Published var minTemp: String
@Published var maxTemp: String
@Published var icon: String
@Published var imageWeather: UIImage = UIImage()
init(cityName: String, currentTemp: String, spaces: CGFloat, weatherDescription: String, minTemp: String, maxTemp: String, icon: String) {
self.cityName = cityName
self.currentTemp = currentTemp
self.spaces = spaces
self.weatherDescription = weatherDescription
self.minTemp = "L: \(minTemp)º"
self.maxTemp = "H: \(maxTemp)º"
self.icon = icon
}
}
| true
|
89ae25e2df5a9c7f2a2cca71bd793a2ab47d0834
|
Swift
|
RBuewaert/OC-Project9-Reciplease
|
/RecipleaseTests/DishTypeTestCase.swift
|
UTF-8
| 6,805
| 2.8125
| 3
|
[] |
no_license
|
//
// DishTypeTestCase.swift
// RecipleaseTests
//
// Created by Romain Buewaert on 30/09/2021.
//
import XCTest
@testable import Reciplease
class DishTypeTestCase: XCTestCase {
let firstRecipeToSave = Recipe(title: "Recipe To Save",
imageUrl: "this is an image url", url: "this is the recipe url",
ingredientList: "detailed list of all ingredients",
ingredientName: "list of all ingredients name",
totalTime: 60.0, cuisineType: "american", dishType: ["main course"])
let secondRecipeToSave = Recipe(title: "Recipe To Save2",
imageUrl: "this is an image url", url: "this is the recipe url",
ingredientList: "detailed list of all ingredients",
ingredientName: "list of all ingredients name",
totalTime: 50.0, cuisineType: "french", dishType: ["main course"])
let firstExistingDishType = "dessert"
let secondExistingDishType = "main course"
func testSaveRecipeWithNewDishType_WhenCorrectValuesAreEntered_ThenShouldSaveRecipe() {
let context = TestCoreDataStack().persistentContainer.newBackgroundContext()
DishType.currentContext = context
expectation(forNotification: .NSManagedObjectContextDidSave, object: context) { _ in
return true
}
XCTAssertNoThrow(try DishType().saveRecipe(firstRecipeToSave))
waitForExpectations(timeout: 2.0) { error in
XCTAssertNil(error, "Save did not occur")
}
}
func testSaveRecipeWithExistingDishType_WhenCorrectValuesAreEntered_ThenShouldSaveRecipe() {
let context = TestCoreDataStack().persistentContainer.newBackgroundContext()
DishType.currentContext = context
expectation(forNotification: .NSManagedObjectContextDidSave, object: context) { _ in
return true
}
let firstDishTypeToSave = DishType(context: context)
firstDishTypeToSave.type = firstExistingDishType
let secondDishTypeToSave = DishType(context: context)
secondDishTypeToSave.type = secondExistingDishType
XCTAssertNoThrow(try DishType().saveRecipe(firstRecipeToSave))
waitForExpectations(timeout: 2.0) { error in
XCTAssertNil(error, "Save did not occur")
}
}
func testRemoveRecipeWithExistingDishType_WhenCorrectValuesAreEntered_ThenShouldRemoveRecipe() {
let context = TestCoreDataStack().persistentContainer.newBackgroundContext()
DishType.currentContext = context
expectation(forNotification: .NSManagedObjectContextDidSave, object: context) { _ in
return true
}
let firstDishTypeToSave = DishType(context: context)
firstDishTypeToSave.type = firstExistingDishType
let secondDishTypeToSave = DishType(context: context)
secondDishTypeToSave.type = secondExistingDishType
do {
try DishType().saveRecipe(firstRecipeToSave)
} catch {
print("Recipe not saved")
}
guard let recipeToRemove = DishType().returnExistingSavedRecipe(firstRecipeToSave) else { return }
XCTAssertNoThrow(try DishType().removeSavedRecipe(recipeToRemove))
waitForExpectations(timeout: 2.0) { error in
XCTAssertNil(error, "Save did not occur")
}
}
func testReturnExistingSavedRecipe_WhenIncorrectRecipeIsSearched_ThenShouldReturnNil() {
let context = TestCoreDataStack().persistentContainer.newBackgroundContext()
DishType.currentContext = context
expectation(forNotification: .NSManagedObjectContextDidSave, object: context) { _ in
return true
}
let firstDishTypeToSave = DishType(context: context)
firstDishTypeToSave.type = firstExistingDishType
let secondDishTypeToSave = DishType(context: context)
secondDishTypeToSave.type = secondExistingDishType
do {
try DishType().saveRecipe(firstRecipeToSave)
} catch {
print("Recipe not saved")
}
do {
try DishType().saveRecipe(secondRecipeToSave)
} catch {
print("Recipe not saved")
}
let recipeToSearch = Recipe(title: "Recipe Unknown",
imageUrl: "this is an image url",
url: "this is the recipe url",
ingredientList: "All ingredients",
ingredientName: "list of all ingredients names",
totalTime: 0.0,
cuisineType: "american",
dishType: ["main course"])
XCTAssertNil(DishType().returnExistingSavedRecipe(recipeToSearch))
waitForExpectations(timeout: 2.0) { error in
XCTAssertNil(error, "Save did not occur")
}
}
func testReturnExistingSavedRecipe_WhenCorrectRecipeIsSearched_ThenShouldRecipeSaved() {
let context = TestCoreDataStack().persistentContainer.newBackgroundContext()
DishType.currentContext = context
expectation(forNotification: .NSManagedObjectContextDidSave, object: context) { _ in
return true
}
let firstDishTypeToSave = DishType(context: context)
firstDishTypeToSave.type = firstExistingDishType
let secondDishTypeToSave = DishType(context: context)
secondDishTypeToSave.type = secondExistingDishType
do {
try DishType().saveRecipe(firstRecipeToSave)
} catch {
print("Recipe not saved")
}
do {
try DishType().saveRecipe(secondRecipeToSave)
} catch {
print("Recipe not saved")
}
let recipeFind = DishType().returnExistingSavedRecipe(firstRecipeToSave)
XCTAssertEqual(recipeFind?.recipeTitle, firstRecipeToSave.recipeTitle)
XCTAssertEqual(recipeFind?.recipeImageUrl, firstRecipeToSave.recipeImageUrl)
XCTAssertEqual(recipeFind?.recipeUrl, firstRecipeToSave.recipeUrl)
XCTAssertEqual(recipeFind?.recipeIngredientsName, firstRecipeToSave.recipeIngredientsName)
XCTAssertEqual(recipeFind?.recipeIngredientsList, firstRecipeToSave.recipeIngredientsList)
XCTAssertEqual(recipeFind?.recipeTime, firstRecipeToSave.recipeTime)
XCTAssertEqual(recipeFind?.recipeCuisineType, firstRecipeToSave.recipeCuisineType)
XCTAssertEqual(recipeFind?.recipeDishType, firstRecipeToSave.recipeDishType)
waitForExpectations(timeout: 2.0) { error in
XCTAssertNil(error, "Save did not occur")
}
}
}
| true
|
cbe3a913a2f2dd70a5beb1160b011e9d313036e6
|
Swift
|
DXu1998/tim.ly
|
/tim.ly/Model/MinutePicker.swift
|
UTF-8
| 826
| 2.6875
| 3
|
[] |
no_license
|
//
// MinutePicker.swift
// tim.ly
//
// Contains the view and delegate functionality for any UIPickerViews of 1-60 minutes
//
// Created by Daniel Xu on 6/13/18.
// Copyright © 2018 Daniel Xu. All rights reserved.
//
import Foundation
import UIKit
class MinutePicker: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 65
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
}
| true
|
a7f6786c74251144d73c13f3ad5c4b305fb701e2
|
Swift
|
mofodox/100DaysOfSwift
|
/Day2/arrays.playground/Contents.swift
|
UTF-8
| 620
| 3.953125
| 4
|
[] |
no_license
|
import UIKit
// Arrays are collections of values that are stored as a single value.
let john = "John Lennon"
let paul = "Paul McCartney"
let george = "George Harrison"
let ringo = "Ringo Starr"
let beatles = [john, paul, george, ringo]
// This is how we access a value in an array.
// Below code access the beatles array at position 2 because array starts at 0
// and this will return "Paul McCartney"
beatles[1]
// Be careful: Swift crashes if you read an item that doesn't exist.
// If you access like below code, this will crash:
// Uncomment to see the example:
// beatles[9]
// Type annotations in arrays
var arr: [Bool] = [true, false]
arr[1]
| true
|
d4bfbd70d91c3cb5fa71be85037827508a38d9a3
|
Swift
|
JeanVinge/tmdb-movies
|
/Utility/Protocols/Stateable.swift
|
UTF-8
| 1,253
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewControllerStateble.swift
// Utility
//
// Created by jean.vinge on 14/06/19.
// Copyright © 2019 Jean Vinge. All rights reserved.
//
import RxSwift
import RxCocoa
public protocol Stateable {
var onEnterForeground: Driver<Notification> { get set }
var onEnterBackground: Driver<Notification> { get set }
var viewDidLoad: Driver<Void> { get set }
var viewDidAppear: Driver<Void> { get set }
var viewWillAppear: Driver<Void> { get set }
var viewWillDisappear: Driver<Void> { get set }
}
struct StateableViewController: Stateable {
var onEnterForeground: Driver<Notification>
var onEnterBackground: Driver<Notification>
var viewDidLoad: Driver<Void>
var viewDidAppear: Driver<Void>
var viewWillAppear: Driver<Void>
var viewWillDisappear: Driver<Void>
init(_ viewController: UIViewController) {
self.onEnterForeground = viewController.rx.onEnterForeground
self.onEnterBackground = viewController.rx.onEnterBackground
self.viewDidLoad = viewController.rx.viewDidLoad
self.viewDidAppear = viewController.rx.viewDidAppear
self.viewWillAppear = viewController.rx.viewWillAppear
self.viewWillDisappear = viewController.rx.viewWillDisappear
}
}
| true
|
a994cfb7cff7b8fbadf1b1dc17a16dbd1020289f
|
Swift
|
antonhoang/The-Movie-DB
|
/The Movie DB/Modules/DetailsModule/DetailsCoordinator.swift
|
UTF-8
| 638
| 2.625
| 3
|
[] |
no_license
|
//
// DetailsCoordinator.swift
// The Movie DB
//
// Created by Anton Hoang on 21.02.2021.
//
import Foundation
import UIKit
protocol DetailsCoordinatorFlow { }
final class DetailsCoordinator: CoordinatorProtocol, DetailsCoordinatorFlow {
let navController: UINavigationController
let movieVO: MovieVO
init(navController: UINavigationController, movieVO: MovieVO) {
self.navController = navController
self.movieVO = movieVO
}
func start() {
let detailsVC = DetailsAssembler(movieVO: movieVO).assembly()
detailsVC.coordinator = self
navController.pushViewController(detailsVC, animated: true)
}
}
| true
|
f9ae501cce9dbc8443fea27a3150817417ef88b1
|
Swift
|
MakeSchool-17/trip-planner-ios-client-gordoneliel
|
/TripPlanner/TripPlanner/Views/PresentTripView.swift
|
UTF-8
| 1,174
| 2.671875
| 3
|
[] |
no_license
|
//
// PresentTripView.swift
// TripPlanner
//
// Created by Eliel Gordon on 11/3/15.
// Copyright © 2015 Saltar Group. All rights reserved.
//
import UIKit
class PresentTripView: UIView {
var trip: Trip?
var dataSource: ArrayDataSource?
@IBOutlet weak var tableView: UITableView!
func setupTableView() {
dataSource = ArrayDataSource(items:trip!.waypoints!.allObjects, cellIdentifier: "waypointsCell") {
(cell, item) in
if let placeCell = cell as? UITableViewCell {
if let itemForCell = item as? Waypoint {
placeCell.textLabel?.text = itemForCell.name
placeCell.detailTextLabel?.text = "\(itemForCell.longitude!.stringValue), \(itemForCell.latitude!.stringValue)"
}
}
}
tableView.dataSource = dataSource
}
}
extension PresentTripView: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 250
}
}
| true
|
74ce0484311de434736989ed36b674e7779ada09
|
Swift
|
s1Moinuddin/bongoCodeTest
|
/BongoCodeTest/ViewController.swift
|
UTF-8
| 885
| 2.515625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// BongoCodeTest
//
// Created by S.M.Moinuddin on 10/31/21.
//
import UIKit
import SVProgressHUD
class ViewController: UIViewController {
@IBOutlet weak private var textView: UITextView!
private let viewModel = ViewModel()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
textView.isEditable = false
textView.layer.borderWidth = 2.0
textView.layer.borderColor = UIColor.gray.cgColor
}
@IBAction private func fetchDataAction(_ sender: UIButton) {
SVProgressHUD.show()
viewModel.fetchData { [weak self] (result) in
DispatchQueue.main.async {
self?.textView.text = result
SVProgressHUD.dismiss()
}
}
}
}
| true
|
91e03e25e004d8e490b50f0710ff2e80ef3481df
|
Swift
|
UNILUU/XLTWeibo
|
/NewTableView/NewTableView/Classes/SessionManager.swift
|
UTF-8
| 1,775
| 2.921875
| 3
|
[] |
no_license
|
//
// SessionManager.swift
// NewTableView
//
// Created by on 12/11/18.
//
import Foundation
import UIKit
enum Result<T> {
case success(T?)
case failure
}
class SessionManager {
static let cache = NSCache<NSString, UIImage>()
static var dict = [String: URLSessionDataTask]()
static var operationQ = OperationQueue()
static func downloadImage(urlString: String, completion: @escaping (_ result: Result<UIImage>) -> ()){
guard let url = URL(string: urlString) else {
completion(Result.failure)
return
}
operationQ.maxConcurrentOperationCount = 4
guard let imagedata = try? Data(contentsOf: url) else {
print("There was an error!")
return
}
print("start --- \(urlString)")
let operation = BlockOperation {
if let image = UIImage(data: imagedata) {
cache.setObject(image, forKey: urlString as NSString)
OperationQueue.main.addOperation({
completion(Result.success(nil))
})
}
}
operationQ.addOperation(operation)
}
static func getImage(urlString: String, completion: @escaping (_ result: Result<UIImage> ) -> ()){
if let image = cache.object(forKey: urlString as NSString){
completion(Result.success(image))
return
}
downloadImage(urlString: urlString, completion: completion)
}
static func cancelTask(urlString: String){
if let task = dict[urlString]{
print("cancel ------------------------\(urlString)")
task.cancel()
dict[urlString] = nil
}
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.