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
b1eed9cf3b790d56b876c05bfd102b1dad71ba0a
Swift
devdebonair/snoogle-ios
/snoogle/ServiceRedditAuth.swift
UTF-8
1,760
2.78125
3
[]
no_license
// // ServiceAuth.swift // snoogle // // Created by Vincent Moore on 8/10/17. // Copyright © 2017 Vincent Moore. All rights reserved. // import Foundation import KeychainSwift class ServiceRedditAuth: Service { func fetchTokens(code: String, completion: ((String?)->Void)?) { requestTokens(code: code) { (json: [String:Any]?) in guard let json = json, let accessToken = json["access_token"] as? String, let refreshToken = json["refresh_token"] as? String, let name = json["name"] as? String else { guard let completion = completion else { return } return completion(nil) } let keychainKeyPrefix = name.lowercased().trimmingCharacters(in: .whitespacesAndNewlines) let keychain = KeychainSwift(keyPrefix: keychainKeyPrefix) var success: Bool = false success = keychain.set(refreshToken, forKey: "refresh_token") success = keychain.set(accessToken, forKey: "access_token") guard let completion = completion else { return } if success { return completion(name) } return completion(nil) } } func requestTokens(code: String, completion: @escaping ([String:Any]?)->Void) { let url = URL(string: "auth/token", relativeTo: base)! Network() .get() .header(add: "AuthCode", value: code) .url(url) .parse(type: .json) .success() { (data, response) in return completion(data as? [String:Any]) } .failure() { _ in return completion(nil) } .error() { _ in return completion(nil) } .sendHTTP() } }
true
abe5e905637d88f7479a0d9be2126d6fd2595fdc
Swift
fadielse/TP_Search_filter
/TP_Search_filter/View/FilterShopTableViewCell.swift
UTF-8
3,172
2.765625
3
[]
no_license
// // FilterShopTableViewCell.swift // TP_Search_filter // // Created by fadielse on 09/09/18. // Copyright © 2018 fadielse. All rights reserved. // import UIKit protocol FilterShopDelegate { func shopSelected(shopList: [ShopType]) func openShopList() } enum ShopType: String { case goldMerchant = "Gold Merchant" case officialStore = "Official Store" } class FilterShopTableViewCell: UITableViewCell { @IBOutlet weak var shopSelectButton: UIButton! @IBOutlet weak var collectionView: UICollectionView! var official: Bool = true var fshop: String = "2" var delegate: FilterShopDelegate? var shopList: [ShopType] = [] var rowCount: Int = 0 func configureCell(official: Bool, fshop: String) { self.selectionStyle = .none self.official = official self.fshop = fshop shopList.removeAll() if self.fshop == "2" { shopList.append(.goldMerchant) } if self.official { shopList.append(.officialStore) } setupSubviews() } } // MARK: - Setup extension FilterShopTableViewCell { func setupSubviews() { setupShopSelectButton() setupCollectionView() } func setupShopSelectButton() { shopSelectButton.addTarget(self, action: #selector(shopSelectButtonTapped), for: .touchUpInside) } func setupCollectionView() { collectionView.delegate = self collectionView.dataSource = self collectionView.register(UINib(nibName: "ShopTagCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "shopTagCell") collectionView.reloadData() } } // MARK: - Action extension FilterShopTableViewCell { @objc func shopSelectButtonTapped() { self.delegate?.openShopList() } } // MARK: - CollectionView Delegate extension FilterShopTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return shopList.count } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(0, 10, 0, 0) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "shopTagCell", for: indexPath) as? ShopTagCollectionViewCell { cell.configureCell(type: shopList[indexPath.row]) cell.delegate = self return cell } else { return ShopTagCollectionViewCell() } } } // MARK: - Shop Tag Delegate extension FilterShopTableViewCell: ShopTagDelegate { func deleteShop(type: ShopType) { shopList.remove(at: shopList.index(of: type)!) collectionView.reloadData() self.delegate?.shopSelected(shopList: shopList) } }
true
be2b99024a0e3773bb7a58fc959c6daaa443798d
Swift
victor-pavlychko/AccessibilityElement
/Sources/AccessibilityElement/FocusedUIElementChangedHandler.swift
UTF-8
3,473
2.578125
3
[ "Apache-2.0" ]
permissive
// // FocusedUIElementChangedHandler.swift // // Copyright © 2018 Doug Russell. All rights reserved. // import Cocoa // TODO: This is a direct extraction of logic from Application and needs more design work public enum FocusedUIElementChangedHandlerError : Error { case containerSearchFailed } public protocol FocusedUIElementChangedHandler { func findContainer<ElementType, HierarchyType>(element: ElementType, hierarchy: HierarchyType) throws -> ElementType where HierarchyType : Hierarchy, HierarchyType.ElementType == ElementType func focusChanged<ElementType, HierarchyType>(element: ElementType, hierarchy: HierarchyType, focus: ApplicationFocus<ElementType>, applicationController: _Controller<ElementType>) -> String? where HierarchyType : Hierarchy, HierarchyType.ElementType == ElementType } public extension FocusedUIElementChangedHandler { public func findContainer<ElementType, HierarchyType>(element: ElementType, hierarchy: HierarchyType) throws -> ElementType where HierarchyType : Hierarchy, HierarchyType.ElementType == ElementType { var current: ElementType? = element while current != nil { if hierarchy.classify(current!) == .container { return current! } do { current = try current!.parent() } catch let error { print(error) throw error } } throw FocusedUIElementChangedHandlerError.containerSearchFailed } public func focusChanged<ElementType, HierarchyType>(element: ElementType, hierarchy: HierarchyType, focus: ApplicationFocus<ElementType>, applicationController: _Controller<ElementType>) -> String? where HierarchyType : Hierarchy, HierarchyType.ElementType == ElementType { do { let container = try findContainer(element: element, hierarchy: hierarchy) var focusedNode: Node<ElementType>? = Node(element: element, role: .include) let node = hierarchy.buildHierarchy(from: container, targeting: &focusedNode) try focus.set(focusedContainerNode: node, focusedControllerNode: focusedNode, applicationController: applicationController) return focus.state.focused?.eventHandler.focusIn() } catch { do { let node = Node(element: element, role: .include) try focus.set(focusedContainerNode: nil, focusedControllerNode: node, applicationController: applicationController) return focus.state.focused?.eventHandler.focusIn() } catch { } } return nil } } public struct DefaultFocusedUIElementChangedHandler : FocusedUIElementChangedHandler { public init() { } }
true
79d2379ee097fa814385256c79e48e86c8eef542
Swift
Rylaris/LeetCode-Solution
/[744]寻找比目标字母大的最小字母NextGreatestLetter.swift
UTF-8
256
3.125
3
[]
no_license
class Solution { func nextGreatestLetter(_ letters: [Character], _ target: Character) -> Character { for char in letters { if char > target { return char } } return letters.first! } }
true
53e932afb356e596422130344c477995f6e13076
Swift
MustafaMahmoudMM/Movies-List
/Movies List/Data/AddingMovie/AddingMovieRepository.swift
UTF-8
1,515
3.015625
3
[]
no_license
// // AddingMovieRepository.swift // Movies List // // Created by Mustafa Mahmoud on 12/23/18. // Copyright © 2018 Mustafa Mahmoud. All rights reserved. // import Foundation class AddingMovieRepository: Repository { // MARK: - Shared Instance private static var addingMovieRepository : AddingMovieRepository? // MARK: - data source Instance private final var localDataSource: AddingMovieDataSource? // MARK: - get Shared Instance static func getAddingMovieRepository(localDataSource: AddingMovieDataSource ) -> AddingMovieRepository{ if addingMovieRepository == nil { addingMovieRepository = AddingMovieRepository(localDataSource: localDataSource) } return addingMovieRepository! } private init(localDataSource: AddingMovieDataSource ) { self.localDataSource = localDataSource } // MARK: - implement Repository Protocol func getData(requestValue: RequestValues, compilationHandler:@escaping (ResponseValues?,Error?) -> Void){ localDataSource?.addMovie(requestValue: requestValue, compilationHandler: { (responseData, error) in if let data = responseData as? Bool { let responseValue = AddingMovieResponseValues(isSucceeded: data) compilationHandler(responseValue,error) } else { compilationHandler(AddingMovieResponseValues(isSucceeded: false),error) } }) } }
true
ee3a09f61aa655d750e66cbf76c5de40ca8f94d5
Swift
getcityhub/iOS
/CityHub/SettingsViewController.swift
UTF-8
3,430
2.703125
3
[]
no_license
// // SettingsViewController.swift // CityHub // // Created by Jack Cook on 3/4/17. // Copyright © 2017 CityHub. All rights reserved. // import UIKit class SettingsViewController: UITableViewController { // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() tableView.backgroundColor = UIColor(white: 233/255, alpha: 1) tableView.contentInset = UIEdgeInsets(top: -48, left: 0, bottom: 0, right: 0) tableView.separatorStyle = .none let dummyView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 60)) tableView.tableHeaderView = dummyView } override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return 2 default: return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch (indexPath.section, indexPath.row) { case (0, 0): let cell = SettingsTextCell() cell.configure("Log In".localized, "") return cell case (1, 0): let cell = SettingsTextCell() cell.configure("Send Feedback".localized, "") return cell case (1, 1): let cell = SettingsTextCell() if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String, let build = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String { cell.configure("Version".localized, "\(version) (\(build))") } else { cell.configure("Version".localized, "?") } return cell default: break } return SettingsCell() } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 40 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = SettingsHeaderView() switch section { case 0: view.configure("Your Account".localized) case 1: view.configure("About".localized) default: break } return view } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 32 } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let view = UIView() view.backgroundColor = UIColor(white: 233/255, alpha: 1) return view } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 12 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch (indexPath.section, indexPath.row) { case (0, 0): let lvc = LoginViewController() present(lvc, animated: true, completion: nil) case (1, 0): print("send feedback") default: break } } }
true
d08b6595c958756b41f1348a296559815ddda250
Swift
orta/ACRAutoComplete
/Example/Tests/TrieTest.swift
UTF-8
2,611
3.125
3
[ "MIT" ]
permissive
// // TrieTest.swift // ACRAutoComplete // // Created by Andrew C on 9/19/16. // Copyright © 2016 CocoaPods. All rights reserved. // import XCTest import ACRAutoComplete class AutoCompleteTest: XCTestCase { var trie : AutoComplete<SearchExample>! override func setUp() { super.setUp() print("running setup") trie = AutoComplete<SearchExample>() } override func tearDown() { super.tearDown() print("running teardown") } func testSearchShouldFindBall() { let football = SearchExample(id: "Football", words: ["ball"]) trie.insert(football) XCTAssert(trie.search("Ball").contains(football), "Contains Football") } func testSearchShouldHaveMultipleResults() { let soccer = SearchExample(id: "Soccer", words: ["ball"]) let football = SearchExample(id: "Football", words: ["ball"]) trie.insert(set: [soccer, football]) let results = trie.search("ball") XCTAssert(results.contains(soccer), "Contains soccer") XCTAssert(results.contains(football), "Contains Football") } func testSearchSearchShouldFindLongerWords() { // This tests to make sure "Foot" matches against "Football" let ball = SearchExample(id: "Ball", words: ["football"]) trie.insert(ball) XCTAssert(trie.search("Foot").count == 1, "Contains Foot as part of football") } func testSearchSearchShouldFindInSeveralWords() { // This tests to make sure "Foot" matches against "Football" let smile = SearchExample(id: "Smile", words: ["happy", "silly"]) trie.insert(smile) XCTAssert(trie.search("ha").count == 1, "Contains happy as partial search ha for happy") XCTAssert(trie.search("si").count == 1, "Contains happy as partial search si for silly") } func testSearchShouldNotFindShorterWords() { // This tests to make sure "Football" does not match against "foot" let ball = SearchExample(id: "Ball", words: ["foot"]) trie.insert(ball) XCTAssert(trie.search("Football").isEmpty, "Does not contain Football") } func testSearchShouldOnlyFindMatchesWhichIncludeAllWords() { let soccer = SearchExample(id: "Soccer", words: ["soccer", "ball"]) let football = SearchExample(id: "Football", words: ["foot", "ball"]) trie.insert(set: [soccer, football]) let results = trie.search("foot ball") XCTAssert(results.count == 1, "Only contains one result") XCTAssert(results.first == football, "Contains Football") } }
true
06fa8f2b218d20ce9acd5bbccdd09f2428ddf60e
Swift
felipedelara/MarvelSuperheroes
/MarvelSuperHeroes/MarvelSuperHeroes/Modules/Detail/HeroDetailsViewModel.swift
UTF-8
1,635
2.984375
3
[]
no_license
// // HeroDetailViewModel.swift // MarvelSuperHeroes // // Created by Felipe Ramon de Lara on 07/10/19. // Copyright © 2019 Felipe de Lara. All rights reserved. // import Foundation struct HeroDetailViewModel{ let name: String let details: String let isFavourite: Bool init(hero: Hero, isFavourite:Bool) { self.name = hero.name ?? "no name" var _details = "" if let description = hero.resultDescription, description != ""{ _details.append("\(description)\n\n") } if let comics = hero.comics{ _details.append("Comics: \(HeroDetailViewModel.listFirst3(appearances: comics))\n") } if let events = hero.events{ _details.append("\nEvents: \(HeroDetailViewModel.listFirst3(appearances: events))\n") } if let stories = hero.stories{ _details.append("\nStories: \(HeroDetailViewModel.listFirst3(appearances: stories))\n") } if let series = hero.series{ _details.append("\nSeries: \(HeroDetailViewModel.listFirst3(appearances: series))\n") } self.details = _details self.isFavourite = isFavourite } static func listFirst3(appearances : Appearances) -> String{ guard let items = appearances.items, items.count >= 1 else{ return "No appearances for this category." } let maxIndex = items.count - 1 let index = maxIndex < 2 ? maxIndex : 2 let resultString = items[0...index].map{"\($0.name ?? "no name")"}.reduce(""){$0+"\n"+$1} return resultString } }
true
f121a6d30a5eb063913b2b850aec479f27c667ea
Swift
matikos/Repositories-53
/Repositories53/ViewController.swift
UTF-8
1,947
2.921875
3
[]
no_license
// // ViewController.swift // Repositories53 // // Created by Your Host on 10/23/19. // Copyright © 2019 Mati Kos. All rights reserved. // import UIKit class ViewController: UITableViewController { @IBOutlet weak var searchBar: UISearchBar! var listOfRepositories = [RepositoryDetail]() { didSet { DispatchQueue.main.async { self.tableView.reloadData() self.navigationItem.title = "\(self.listOfRepositories.count) Repositories found!" } } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listOfRepositories.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let repository = listOfRepositories[indexPath.row] cell.textLabel?.text = repository.name cell.detailTextLabel?.text = repository.language return cell } override func viewDidLoad() { super.viewDidLoad() searchBar.delegate = self } } extension ViewController:UISearchBarDelegate{ func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { // print("Hello, World.") guard let searchBarText = searchBar.text else {return} let repositoryRequest = RepositoryRequest(repositoryName: searchBarText) repositoryRequest.getRepositories { [weak self] result in switch result{ case .failure(let error): print(error) print("Hello, Line 57.") case .success(let repositories): self?.listOfRepositories = repositories print("Hello, Line 60.") } } } }
true
d5d7d2a1c787049f87bb17b2a454ce3e80e4587e
Swift
adamgoth/ios-tiny-tabs
/tiny-tabs/SpecialCell.swift
UTF-8
2,406
2.71875
3
[]
no_license
// // SpecialCell.swift // tiny-tabs // // Created by Adam Goth on 10/12/16. // Copyright © 2016 Adam Goth. All rights reserved. // import UIKit class SpecialCell: UITableViewCell { @IBOutlet weak var timeImg: UIImageView! @IBOutlet weak var drinkImg: UIImageView! @IBOutlet weak var foodImg: UIImageView! @IBOutlet weak var websiteBtn: UIButton! @IBOutlet weak var restaurantLbl: UILabel! @IBOutlet weak var neighborhoodLbl: UILabel! @IBOutlet weak var addressLbl: UILabel! @IBOutlet weak var timeLbl: UILabel! @IBOutlet weak var drinkLbl: UILabel! @IBOutlet weak var foodLbl: UILabel! var special: Special! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func configureCell(special: Special, restaurant: Restaurant, neighborhood: Neighborhood) { self.special = special restaurantLbl.text = restaurant.name neighborhoodLbl.text = neighborhood.name addressLbl.text = restaurant.address1 if special.time == "" { timeImg.isHidden = true timeLbl.isHidden = true } else { timeImg.isHidden = false timeLbl.isHidden = false timeLbl.text = special.time } if special.drink == "" { drinkImg.isHidden = true drinkLbl.isHidden = true } else { drinkImg.isHidden = false drinkLbl.isHidden = false drinkLbl.text = special.drink } if special.food == "" { foodImg.isHidden = true foodLbl.isHidden = true } else { foodImg.isHidden = false foodLbl.isHidden = false foodLbl.text = special.food } if special.website == "" { websiteBtn.isHidden = true } else { websiteBtn.isHidden = false } } @IBAction func websiteTapped(_ sender: AnyObject) { let url = URL(string: "\(special.website)")! if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(url) } } }
true
e151171e50bd069ad5078b257b99f9009ffb8628
Swift
mjeragh/ParallismGPU
/ParallismGPU/main.swift
UTF-8
1,873
2.640625
3
[]
no_license
// // main.swift // ParallismGPU // // Created by Mohammad Jeragh on 10/5/19. // Copyright © 2019 Mohammad Jeragh. All rights reserved. // import Foundation import MetalKit let row : uint = 30000 var column : uint = 4000 var array = Array(repeating: Array<Float>(repeating: 0, count: Int(column)), count: Int(row)) let start = DispatchTime.now() // <<<<<<<<<< Start time var device = MTLCreateSystemDefaultDevice()! var commandQueue = device.makeCommandQueue()! var library = device.makeDefaultLibrary() let commandBuffer = commandQueue.makeCommandBuffer() let computeEncoder = commandBuffer?.makeComputeCommandEncoder() var computeFunction = library?.makeFunction(name: "kernel_main")! var computePipelineState = try! device.makeComputePipelineState(function: computeFunction!) var matrixBuffer = device.makeBuffer(bytes: &array, length: Int(row*column) * MemoryLayout<Float>.stride, options: []) computeEncoder?.pushDebugGroup("settingup") computeEncoder?.setComputePipelineState(computePipelineState) computeEncoder?.setBuffer(matrixBuffer, offset: 0, index: 0) computeEncoder?.setBytes(&column, length: MemoryLayout<uint>.stride, index: 1) let threadsPerThreadGrid = MTLSizeMake(Int(row * column), 1, 1) computeEncoder?.dispatchThreadgroups(threadsPerThreadGrid, threadsPerThreadgroup: MTLSizeMake(1, 1, 1)) computeEncoder?.endEncoding() computeEncoder?.popDebugGroup() commandBuffer?.commit() commandBuffer?.waitUntilCompleted() let end = DispatchTime.now() // <<<<<<<<<< end time let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds // <<<<< Difference in nano seconds (UInt64) let timeInterval = Double(nanoTime) / 1_000_000_000 // Technically could overflow for long running tests print("Time to execute: \(timeInterval) seconds") let contents = matrixBuffer?.contents() let pointer = contents?.bindMemory(to: Float.self, capacity: Int(row*column))
true
2c31573c45a35310e2fe8f47b7d1d3a42309961f
Swift
trumanliu/swift-programming-languague
/the swift programing language.playground/Contents.swift
UTF-8
5,225
4.3125
4
[ "Apache-2.0" ]
permissive
//: Playground - noun: a place where people can play import UIKit //变量 var str = "Hello, playground" var myVariable = 42 myVariable = 50 //常量 let myConstant = 42 let price:Float = 2.01 let label = "my MacBook Air" let width = 94 //类型转换 let widthLabel = label + String(width) let apples = 3 let oranges = 5 //在string中进行拼接 let appleSummary = "I have \(apples) apples" let fruitSummary = "I hava \(apples + oranges) pices of fruit" //数组 var shoppingList = ["catfish","water","tulips" ,"blue paint"] shoppingList[1] = "bottle of water" //字典 var occupations = ["Malcolm" : "captain" ,"Kaylee" : "Mechanic"] occupations["foo"] = "bar" occupations //空数组与字典 let emptyArray = [String] () let emptyDictionary = [String:Float]() //for循环 let individualScores = [75,43,103,87,12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 }else{ teamScore += 1 } } teamScore var optionalString : String? = "Hello" optionalString == nil var OptionalName : String? = "truman Liu" var greeting = "Hello" if let name = OptionalName { greeting = "Hello,\(name)" } //switch case语句 不需要在子句中写break let vegetable = "red pepper" switch vegetable { case "celery": let vegetableComment = "Add some raisins and make ants on a log." case "cucumber","watercress": let vegetableComment = "That would make a good tea sandwich" case let x where x.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(x)?" default: let VegetableComment = "Everything tastes good in soup" } //for in 可以遍历字典 let interstingNumbers = [ "Prime" : [2,3,5,7,11,13], "Fibonacci" : [1,1,2,3,5,8], "Square":[1,4,9,16,25,36] ] var largest = 0 var largestKind = "" for(kind,numbers) in interstingNumbers{ for number in numbers { if number > largest { largest = number largestKind = kind } } } print(largest) print(largestKind) //练习题要求输出最大的kind //while 语句 while在前或后 var n = 2 while n < 100{ n = n * 2 } print(n) var m = 2 repeat{ m = m*2 }while m < 100 print(m) //for循环中使用..<表示范围 var total = 0 for i in 0..<10{ total += 1 } total // 0..<10 ➡️ [0-10) // 0...10 ➡️ [0-10] var total2 = 0 for i in 0...10{ total2 += 1 } total2 //函数与闭包 func greet(person: String,day:String) -> String{ return "Hello \(person), today is \(day)." } greet(person:"truman",day:"Tuesday") //greet(day:"DiDi",person:"Monday") error: argument 'person' must precede argument 'day' //函数的参数名称作为参数的标签,参数名称钱可以自定义参数标签,“_”表示不使用参数标签 func greet2(_ person: String,_ day:String) -> String{ return "Hello \(person), today is \(day)." } greet2("Didi","Sunday") func greet3(who person: String,_ day:String) -> String{ return "Hello \(person), today is \(day)." } greet3(who:"Didi","Sunday") // 使用元组返回多个值 func calculateStatistics(scores:[Int]) -> ( min:Int,max:Int,sum:Int){ var min = scores[0] var max = scores[0] var sum = 0 for score in scores{ if score > max { max = score }else if score < min{ min = score } sum += score } return(min,max,sum) } let statics = calculateStatistics(scores: [5,3,100,3,9]) statics.0 statics.max //可变个数参数 func sumOf(numbers:Int...) -> Int { var sum = 0 for number in numbers{ sum += number } return sum } sumOf() sumOf(numbers: 1,2,3) func sumOfPara(numbers:Int...,kind:String) -> Int { var sum = 0 for number in numbers{ sum += number } print(kind) return sum } sumOfPara(numbers: 1,2,3,4 , kind: "wow") //由于在调用方法时会显式指明参数名称,所以可变个参数的位置可以不是最后一个 //练习题:均值 func meanOf(numbers:Int...) -> Int { var sum = 0 for number in numbers{ sum += number } return sum/numbers.count } meanOf(numbers: 1,2,3,4,5,6,7) //函数可以嵌套 func returnFifteen() -> Int { var y = 10 func minus(){ y = 25 - y } minus() return y } returnFifteen() //函数时一级类型,可以作为返回值 func makeIncrementer() -> ( (Int) -> Int){ func addOne(number:Int) -> Int{ return 1 + number } return addOne } var increment = makeIncrementer() increment(1) //函数可以当作参数传入另一个函数 func hasAnyMatches(list:[Int],condition:(Int) -> Bool) -> Bool{ for item in list{ if condition(item){ return true } } return false } func lessThanTen(number:Int) -> Bool{ return number < 10 } var numbers = [72,39,27,11] hasAnyMatches(list: numbers, condition: lessThanTen) //使用{} 来创建一个匿名闭包。使用in将参数根返回值类型与声明与闭包函数体进行分离 numbers.map({ (number : Int) -> Int in let result = 3 * number return result }) let mappedNumbers = numbers.map({number in 3 * number}) print(mappedNumbers)
true
f0a76d1b6fec83602bbd9ac37e5997bd93e1f9a2
Swift
a2/shortcuts-swift
/ShortcutsSwift.playgroundbook/Contents/Sources/Actions/Dictionary.swift
UTF-8
3,635
3.359375
3
[ "MIT" ]
permissive
import Foundation enum ItemType: Int { case string = 0 case dictionary = 1 case array = 2 case number = 3 case boolean = 4 } public enum DictionaryValue { case string(String) case number(Number) case boolean(Bool) case dictionary([String: DictionaryValue]) case array([DictionaryValue]) var propertyList: PropertyList { switch self { case .string(let string): return [ "WFItemType": ItemType.string.rawValue, "WFValue": [ "Value": ["string": string, "attachmentsByRange": [:]], "WFSerializationType": "WFTextTokenString" ] ] case .number(let number): return [ "WFItemType": ItemType.number.rawValue, "WFValue": [ "Value": ["string": "\(number)", "attachmentsByRange": [:]], "WFSerializationType": "WFTextTokenString" ] ] case .boolean(let bool): return [ "WFItemType": ItemType.boolean.rawValue, "WFValue": [ "Value": bool, "WFSerializationType": "WFNumberSubstitutableState" ] ] case .array(let values): return [ "WFItemType": ItemType.array.rawValue, "WFValue": [ "Value": values.map { $0.propertyList }, "WFSerializationType": "WFArrayParameterState" ] ] case .dictionary(let values): return [ "WFItemType": ItemType.dictionary.rawValue, "WFValue": [ "Value": serialize(values), "WFSerializationType": "WFDictionaryFieldValue", ] ] } } } extension DictionaryValue: ExpressibleByArrayLiteral { public init(arrayLiteral elements: DictionaryValue...) { self = .array(elements) } } extension DictionaryValue: ExpressibleByBooleanLiteral { public init(booleanLiteral value: Bool) { self = .boolean(value) } } extension DictionaryValue: ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, DictionaryValue)...) { self = .dictionary(Dictionary(uniqueKeysWithValues: elements)) } } extension DictionaryValue: ExpressibleByIntegerLiteral { public init(integerLiteral value: Int) { self = .number(value) } } extension DictionaryValue: ExpressibleByFloatLiteral { public init(floatLiteral value: Double) { self = .number(value) } } extension DictionaryValue: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self = .string(value) } } func serialize(_ dictionary: [String: DictionaryValue]) -> PropertyList { var valueItems = [PropertyList]() valueItems.reserveCapacity(dictionary.count) for (key, value) in dictionary { var propertyList = value.propertyList propertyList["WFKey"] = [ "Value": ["string": key, "attachmentsByRange": [:]], "WFSerializationType": "WFTextTokenString", ] valueItems.append(propertyList) } return [ "Value": ["WFDictionaryFieldValueItems": valueItems], "WFSerializationType": "WFDictionaryFieldValue" ] } public func dictionary(_ value: [String: DictionaryValue]) -> ActionWithOutput { return Action(identifier: "is.workflow.actions.dictionary", parameters: ["WFItems": serialize(value)]) }
true
307e894d2a4eef6d79ac72f3a7110c5afa8a43ec
Swift
tofiqueahmedkhan/Concentration
/Concentration/ViewController.swift
UTF-8
1,412
3.09375
3
[]
no_license
// // ViewController.swift // Concentration // // Created by Macbook Pro on 23/04/18. // Copyright © 2018 tofiqueahmedkhan. All rights reserved. // import UIKit class ViewController: UIViewController { //MARK: - Variable & Constant & Array var flipCount = 0{ didSet{ flipCountLabel.text = "Flip Count : \(flipCount)" } } var emojiArray = ["👻","🎃","👻","🎃"] //MARK: - IBOutlets @IBOutlet weak var flipCountLabel: UILabel! @IBOutlet var cardButton: [UIButton]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } //MARK: - IBActions @IBAction func touchButton(_ sender: UIButton) { if let buttonNumber = cardButton.index(of: sender){ flipCard(withEmoji: emojiArray[buttonNumber], on: sender) flipCount += 1 } } //MARK: - Custom Funtion func flipCard(withEmoji emoji : String, on button : UIButton){ if button.currentTitle == emoji{ button.backgroundColor = #colorLiteral(red: 1, green: 0.5843137255, blue: 0, alpha: 1) button.setTitle("", for: UIControlState.normal) }else{ button.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) button.setTitle(emoji, for: UIControlState.normal) } } }
true
3372130d80f40d62abd0d9e148dda1c290463d41
Swift
menttofly/LeetCode-Swift
/String/jewels_and_stones.swift
UTF-8
1,010
3.765625
4
[]
no_license
// // jewels_and_stones.swift // LeetCode-Swift // // Created by menttofly on 2019/3/15. // Copyright © 2019 menttofly. All rights reserved. // import Foundation /** * Question Link: https://leetcode.com/problems/jewels-and-stones/ (771) * Primary idea: 使用 Set 保存 jewels,遍历 stones 中的字符,如果在 jewels 中则 res 加一 * * Time Complexity: O(n), Space Complexity: O(n) */ class JewelsAndStones { func numJewelsInStones(_ J: String, _ S: String) -> Int { let jewels = J.reduce(into: [:]) { res, next in res[next] = true } var res = 0 for s in S { if jewels[s] == true { res += 1 } } return res } func numJewelsInStones1(_ J: String, _ S: String) -> Int { let jewels = Set(J); var res = 0 for s in S { if jewels.contains(s) { res += 1 } } return res } }
true
a687d80d028f512e32b1b4467001c0c0b31170bd
Swift
manshiro/RChat
/RChat-iOS/RChat/Views/Components/InputField.swift
UTF-8
1,480
3.28125
3
[ "Apache-2.0" ]
permissive
// // InputField.swift // RChat // // Created by Andrew Morgan on 23/11/2020. // import SwiftUI struct InputField: View { let title: String @Binding private(set) var text: String var showingSecureField = false private enum Dimensions { static let noSpacing: CGFloat = 0 static let bottomPadding: CGFloat = 16 static let iconSize: CGFloat = 20 } var body: some View { VStack(spacing: Dimensions.noSpacing) { CaptionLabel(title: title) HStack(spacing: Dimensions.noSpacing) { if showingSecureField { SecureField("", text: $text) .padding(.bottom, Dimensions.bottomPadding) .foregroundColor(.primary) .font(.body) } else { TextField("", text: $text) .padding(.bottom, Dimensions.bottomPadding) .foregroundColor(.primary) .font(.body) } } } } } struct InputField_Previews: PreviewProvider { static var previews: some View { AppearancePreviews( Group { InputField(title: "Input", text: .constant("Data")) InputField(title: "Input secure", text: .constant("Data"), showingSecureField: true) } .previewLayout(.sizeThatFits) .padding() ) } }
true
05a3f3eda8bdd9701f1084c01d433fe723a5f9b9
Swift
saikishoreagrapalem/testtrailproject
/UINavigationBar.swift
UTF-8
2,904
2.609375
3
[]
no_license
// // UINavigationBar.swift // TestProject // // Created by SAI on 10/04/20. // Copyright © 2020 Sai Kishore. All rights reserved. // import UIKit extension UINavigationBar { override open func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if ( self.point(inside: point, with: event)) { self.isUserInteractionEnabled = true } else { self.isUserInteractionEnabled = false } return super.hitTest(point, with: event) } func makeClear() { self.isTranslucent = true self.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.backgroundColor = UIColor.clear self.shadowImage = nil self.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] self.barTintColor = UIColor.clear self.tintColor = UIColor.clear if #available(iOS 13.0, *) { } else{ let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView if statusBar.responds(to: #selector(setter: UIView.backgroundColor)) { statusBar.backgroundColor = UIColor.clear } } hideBottomHairline() } func makeDefault(_ title: String) { self.isTranslucent = false self.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.backgroundColor = UIColor.fromRGB(rgb: 0x329EEA) self.shadowImage = nil self.topItem?.title = title self.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] self.barTintColor = UIColor.fromRGB(rgb: 0x329EEA) if #available(iOS 13.0, *) { } else{ let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView if statusBar.responds(to: #selector(setter: UIView.backgroundColor)) { statusBar.backgroundColor = UIColor.fromRGB(rgb: 0x329EEA) } } showBottomHairline() } func hideBottomHairline() { let navBarHairlineImageView = findHairlineImageViewUnder(view: self) navBarHairlineImageView?.isHidden = true; } func showBottomHairline() { let navBarHairlineImageView = findHairlineImageViewUnder(view: self) navBarHairlineImageView?.isHidden = false; } func findHairlineImageViewUnder(view:UIView) -> UIImageView! { if view.isKind(of: UIImageView.self) && view.bounds.size.height <= 1.0 { return view as? UIImageView; } for subview in view.subviews { let imageView = findHairlineImageViewUnder(view: subview) if let imgView = imageView { return imgView } } return nil } }
true
ef51bc776d61d7eb9f3beda3a8043c4acfe7d6ec
Swift
microservices-course-itmo/ios-client
/WineUp/WineUp/Views/Login/LoginVerificationCodeView.swift
UTF-8
5,745
2.875
3
[]
no_license
// // LoginVerificationCodeView.swift // WineUp // // Created by Александр Пахомов on 19.10.2020. // import SwiftUI import Combine import Firebase // MARK: - View struct LoginVerificationCodeView: View { @ObservedObject private(set) var viewModel: ViewModel init(viewModel: ViewModel, onSubmit: @escaping () -> Void) { self.viewModel = viewModel viewModel.onSubmit = onSubmit } var body: some View { LoginContainer(title: "Введите код", viewLabel: { TextField("XXXXXX", text: $viewModel.code.value) .lineLimit(1) .multilineTextAlignment(.center) .keyboardType(.decimalPad) .onChange(of: viewModel.code.value, perform: viewModel.codeDidChange(code:)) }, actionLabel: { () -> AnyView in if viewModel.canResendCode { return Button(action: viewModel.resendButtonDidTap) { Text("Переотправить") } .anyView } else { return Text("Отправить повторно можно через \(viewModel.secondsToResendCode)с").anyView } }) .activity(hasActivity: viewModel.isResendInProgress || viewModel.isSubmitInProgress) } } // MARK: - LoginVerificationCodeView+ViewModel extension LoginVerificationCodeView { final class ViewModel: ObservableObject { // MARK: Variables @Published var isCodeWrong = false @Published var canResendCode = false @Published var secondsToResendCode = 60 @Published var isResendInProgress = false @Published var isSubmitInProgress = false @Published var code: FormattableContainer<String>! private let container: DIContainer private let cancelBag = CancelBag() private var timer: Timer! var onSubmit: (() -> Void)? // MARK: Public Methods init(container: DIContainer) { self.container = container self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in self?.tick() } self.code = .init("", formatter: ViewModel.format) cancelBag.collect { container.appState.bindDisplayValue(\.userData.loginForm.verificationCode, to: self, by: \.code.value) $code.map { $0!.value }.toInputtable(of: container.appState, at: \.value.userData.loginForm.verificationCode) } } func resendButtonDidTap() { guard let phoneNumber = container.appState.value.userData.loginForm.phoneNumber.value else { return } assert(secondsToResendCode == 0 && canResendCode && !isResendInProgress && !isSubmitInProgress) isResendInProgress = true container.services.firebaseService .sendVerificationCode(to: phoneNumber) .sinkToResult { [weak self] result in switch result { case .success(let verificationID): self?.container.appState.value.userData.loginForm.verificationId = verificationID self?.isResendInProgress = false self?.secondsToResendCode = 60 self?.updateUI() case .failure(let error): print("verifyError: ", error.description) } } .store(in: cancelBag) } func codeDidChange(code: String) { guard code.count == 6 else { return } isSubmitInProgress = true submitVerificationCode(code) .sinkToResult { [weak self] result in self?.isSubmitInProgress = false switch result { case let .success(token): self?.container.appState.value.userData.loginForm.token = token self?.onSubmit?() print("Successful phone verification, token: \(token)") case let .failure(error): self?.isCodeWrong = true print("Phone verification error: \(error.description)") } }.store(in: cancelBag) } // MARK: Private Methods private func tick() { if secondsToResendCode > 0 { secondsToResendCode -= 1 updateUI() } } private func updateUI() { canResendCode = secondsToResendCode == 0 && !isResendInProgress && !isSubmitInProgress } private func submitVerificationCode(_ code: String) -> AnyPublisher<String, Error> { guard let verificationId = container.appState.value.userData.loginForm.verificationId else { let error = WineUpError.invalidAppState("Unable to extract verificationId from AppState") return Fail<String, Error>(error: error) .eraseToAnyPublisher() } return container.services.firebaseService .submitVerificationCode(code, verificationId: verificationId) } private static func format(_ rawValue: String) -> String { return rawValue.onlyDigits } } } // MARK: - Preview #if DEBUG extension LoginVerificationCodeView.ViewModel { static let preview = LoginVerificationCodeView.ViewModel(container: .preview) } struct LoginVerificationCodeView_Previews: PreviewProvider { static var previews: some View { LoginVerificationCodeView(viewModel: .preview, onSubmit: {}) } } #endif
true
51a18836154b4d151d2d468cb3a1bea1b1c2da88
Swift
shayla1996/TapCounterProject1
/Tap Counter Project 1/ViewController.swift
UTF-8
666
2.6875
3
[]
no_license
// // ViewController.swift // Tap Counter Project 1 // // Created by Shaikat on 22/12/20. // Copyright © 2020 Shayla.18. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var levelOutlet: UILabel! var count: Int = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func tapButtonPressed(_ sender: Any) { count += 1 levelOutlet.text = String(count) } @IBAction func resetButtonPressed(_ sender: Any) { count = 0 levelOutlet.text = String(count) } }
true
f9bf553931c4e53758bde56434d2784143e53a0b
Swift
Flipkart/Swifty
/Sources/Core/NetworkResponse.swift
UTF-8
2,588
3.125
3
[ "Apache-2.0" ]
permissive
// // // Swifty (https://github.com/Flipkart/Swifty) // // Copyright 2017 Flipkart Internet Pvt. Ltd. // Apache License // Version 2.0, January 2004 // // See https://github.com/Flipkart/Swifty/blob/master/LICENSE for the full license // import Foundation /// The protocol for creating a Response Parser public protocol ResponseParser { /** Custom Response parser need to implement this method. When done deserializing the NetworkResponse's data, they have to set it to the NetworkResponse's result variable. Any error thrown here while parsing will fail the NetworkResponse, and call the failure block with the thrown error. */ func parse(response: NetworkResponse) throws } /// The NetworkResponse class contains the Data, URLResponse, Error (if any) and possibly the serialized response for a given resource. @objc public class NetworkResponse: NSObject { // MARK: - Properties /// The HTTPURLResponse receieved from the network @objc public var response : HTTPURLResponse? /// The raw Data receieved from the network @objc public var data: Data? /// Error that response encountered (if any) @objc public var error: NSError? /// The result of the response serialization @objc public var result: Any? /// The ResponseParser that Swifty should use to serialize this repsonse public var parser: ResponseParser? // MARK: - Initializers /// Initializes the network response /// /// - Parameters: /// - response: HTTPURLResponse? /// - data: Data? /// - error: NSError? /// - parser: ResponseParser? public init(response: HTTPURLResponse? = nil, data: Data? = nil, error: NSError? = nil, parser: ResponseParser? = nil){ self.response = response self.data = data self.error = error self.parser = parser } // MARK: - Modifiers /// Forcefully succeeds the response, with the given response and data. This internally sets the error to nil. This is especially useful in response interceptors. /// /// - Parameters: /// - response: HTTPURLResponse? /// - data: Data? @objc public func succeed(response: HTTPURLResponse?, data: Data?){ self.response = response self.data = data self.error = nil } /// Forcefully fails the response, with the given error. This is especially useful in response interceptors. /// /// - Parameter error: NSError. @objc public func fail(error: NSError){ self.error = error } }
true
d4aa16a95ae6e6f57f00d18f3c224f4e111cf961
Swift
Ninarciso/StatefulTableView
/Sources/StatefulTableView+LoadMore.swift
UTF-8
2,264
2.625
3
[ "MIT" ]
permissive
// // StatefulTableView+LoadMore.swift // Pods // // Created by Tim on 23/06/2016. // // import UIKit extension StatefulTableView { // MARK: - Load more /** Tiggers loading more of data. Also called when the scroll content offset reaches the `loadMoreTriggerThreshold`. */ public func triggerLoadMore() { guard !state.isLoading else { return } loadMoreViewIsErrorView = false lastLoadMoreError = nil updateLoadMoreView() setState(.loadingMore) guard let delegate = statefulDelegate else { return } delegate.statefulTable(self, loadMoreCompletion: { [weak self] canLoadMore, errorOrNil, showErrorView in DispatchQueue.main.async(execute: { self?.setHasFinishedLoadingMore(canLoadMore, error: errorOrNil, showErrorView: showErrorView) }) }) } internal func updateLoadMoreView() { if watchForLoadMore || lastLoadMoreError != nil { tableView.tableFooterView = viewForLoadingMore(withError: (loadMoreViewIsErrorView ? lastLoadMoreError : nil)) } else { tableView.tableFooterView = UIView() } } internal func setHasFinishedLoadingMore(_ canLoadMore: Bool, error: NSError?, showErrorView: Bool) { guard state == .loadingMore else { return } self.canLoadMore = canLoadMore loadMoreViewIsErrorView = (error != nil) && showErrorView lastLoadMoreError = error setState(.idle) } internal func watchForLoadMoreIfApplicable(_ watch: Bool) { var watch = watch if (watch && !canLoadMore) { watch = false } watchForLoadMore = watch updateLoadMoreView() triggerLoadMoreIfApplicable(tableView) } /** Should be called when scrolling the tableView. This determines when to call `triggerLoadMore` - parameter scrollView: The scrolling view. */ public func scrollViewDidScroll(_ scrollView: UIScrollView) { triggerLoadMoreIfApplicable(scrollView) } internal func triggerLoadMoreIfApplicable(_ scrollView: UIScrollView) { guard watchForLoadMore && !loadMoreViewIsErrorView else { return } let scrollPosition = scrollView.contentSize.height - scrollView.frame.size.height - scrollView.contentOffset.y if scrollPosition < loadMoreTriggerThreshold { triggerLoadMore() } } }
true
e6bf259e4312b9cfdc64887ae551af31eb224540
Swift
sorin360/Handyman
/Handyman/Jobs/Job.swift
UTF-8
828
2.90625
3
[]
no_license
// // Job.swift // Handyman // // Created by Lica Sorin on 31/12/2020. // import SwiftUI class Job: ObservableObject { var id: String var user: String var imageURL: String var title: String? var description: String @Published var image: UIImage? init(id: String, user: String, image: String, title: String?, description: String) { self.id = id self.user = user self.imageURL = image self.title = title self.description = description } init(dictionary: [String: Any]) { self.id = dictionary["id"] as! String self.user = dictionary["user"] as! String self.imageURL = dictionary["imageURL"] as! String self.title = dictionary["title"] as? String self.description = dictionary["description"] as! String } }
true
684af256b0a595547bf1a12e89a9e083cd6123f3
Swift
leandrohdez/itunes-artist-demo
/itunes-artist-demo/Front/Artist/Search/ArtistSearchViewController.swift
UTF-8
3,983
2.5625
3
[]
no_license
// // ArtistSearchViewController.swift // itunes-artist-demo // // Created by Leandro Hernandez on 19/1/18. // Copyright © 2018 antrax. All rights reserved. // import UIKit import Spring class ArtistSearchViewController: BaseViewController { // MARK: IBOutlets @IBOutlet var nameTextField: UITextField! { didSet { nameTextField.styleSearchField() nameTextField.delegate = self } } @IBOutlet var boxView: SpringView! { didSet { boxView.styleSearchView() } } @IBOutlet var topBoxLayoutConstraint: NSLayoutConstraint! @IBOutlet var searchButton: SpringButton! { didSet { searchButton.stylePrimaryButton() } } // MARK: Presenter var artistPresenter: ArtistSearchPresenter! override var presenter: Presenter! { return artistPresenter } // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() // Keyboard Observers NotificationCenter.default.addObserver(self, selector: #selector(ArtistSearchViewController.keyboardWillShow), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ArtistSearchViewController.keyboardWillHide), name: .UIKeyboardWillHide, object: nil) let tap: UITapGestureRecognizer = UITapGestureRecognizer( target: self, action: #selector(ArtistSearchViewController.dismissKeyboard) ) view.addGestureRecognizer(tap) customizeUI() } private func customizeUI() { self.title = "" self.navigationController?.performTransparentBackground() // cerrar self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(ArtistSearchViewController.closeButtonTapped)) } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil) } } // MARK: - Actions extension ArtistSearchViewController { @objc func closeButtonTapped() { self.dismissKeyboard() self.artistPresenter.closeView() } @IBAction func searchButtonTapped() { self.dismissKeyboard() let name = self.nameTextField.text! self.artistPresenter.searchArtist(byName: name) } @objc func dismissKeyboard() { view.endEditing(true) } } // MARK: - Presenter Methods extension ArtistSearchViewController: ArtistSearchPresenterView { } // MARK: - Observers extension ArtistSearchViewController { @objc func keyboardWillShow(notification:NSNotification) { print("abre teclado") self.adjustingConstraint(show: true, notification: notification) } @objc func keyboardWillHide(notification:NSNotification) { print("cierra teclado") self.adjustingConstraint(show: false, notification: notification) } func adjustingConstraint(show:Bool, notification:NSNotification) { var userInfo = notification.userInfo! let animationDurarion = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval let navBarHeight = CGFloat(64.0) let scala = CGFloat(0.05) let newAdjustConstraintValue = navBarHeight + self.view.frame.height * scala self.topBoxLayoutConstraint.constant = (show) ? newAdjustConstraintValue : 150 UIView.animate(withDuration: animationDurarion, animations: { () -> Void in self.view.layoutIfNeeded() }) } } // MARK: - UITextFieldDelegate extension ArtistSearchViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
true
06b6d9173103beb21a53e1ebb33dff85df51632f
Swift
eduasinco/ComeAquiOS
/ComeAquiOS/Login/RegisterViewController.swift
UTF-8
4,598
2.734375
3
[]
no_license
// // RegisterViewController.swift // ComeAquiOS // // Created by eduardo rodríguez on 15/04/2020. // Copyright © 2020 Eduardo Rodríguez Pérez. All rights reserved. // import UIKit class RegisterViewController: KUIViewController { @IBOutlet weak var viewHolder: UIView! @IBOutlet weak var username: ValidatedTextField! @IBOutlet weak var firstName: ValidatedTextField! @IBOutlet weak var lastName: ValidatedTextField! @IBOutlet weak var email: ValidatedTextField! @IBOutlet weak var password: ValidatedTextField! @IBOutlet weak var registerButton: LoadingButton! @IBOutlet weak var bottomHolderConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() self.bottomConstraintForKeyboard = bottomHolderConstraint } func isValid() -> Bool{ var valid = true if username.text!.isEmpty || !username.text!.isValidUsername() { username.validationText = "Please insert a valid username" valid = false } if firstName.text!.isEmpty { firstName.validationText = "Please insert a valid name" valid = false } if lastName.text!.isEmpty { lastName.validationText = "Please insert a valid surname" valid = false } if email.text!.isEmpty || !email.text!.isValidEmail() { email.validationText = "Please insert a valid email" valid = false } if password.text!.isEmpty || !password.text!.isValidPassword() { password.validationText = "It must have at least 8 characters \n" + "A digit must occur at least once \n" + "A lower case letter must occur at least once \n" + "An upper case letter must occur at least once \n" + "A special character (!?@#$%^&+=) must occur at least once \n" + "No whitespace allowed in the entire string \n" valid = false } return valid } @IBAction func registerPress(_ sender: Any) { if isValid() { register() } } } extension RegisterViewController { private struct ErrorResponseObject: Decodable { var username: [String]? var email: [String]? } func register(){ let endpointUrl = URL(string: SERVER + "/register/")! // whatever is your url var request = URLRequest(url: endpointUrl) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") registerButton.showLoading() do { let data = try JSONSerialization.data(withJSONObject: ["username": username.text, "first_name": firstName.text, "last_name": lastName.text, "email": email.text, "password": password.text], options: []) request.httpMethod = "POST" request.httpBody = data let task = URLSession.shared.dataTask(with: request, completionHandler: {data, response, error -> Void in DispatchQueue.main.async { self.registerButton.hideLoading() } if let _ = error { DispatchQueue.main.async { self.viewHolder.showToast(message: "No internet connection") } } guard let data = data else {return} do { USER = try JSONDecoder().decode(User.self, from: data) DispatchQueue.main.async { self.performSegue(withIdentifier: "PresentationSegue", sender: nil) } } catch _ { do { let errorObject = try JSONDecoder().decode(ErrorResponseObject.self, from: data) DispatchQueue.main.async { if let usernameError = errorObject.username, usernameError.count > 0 { self.username.validationText = usernameError[0] } if let emailError = errorObject.email, emailError.count > 0 { self.email.validationText = emailError[0] } } } catch _ {} } }) task.resume() }catch{ // } } }
true
914d8e90bf5d3e40d2a2ed1e91d4edb1ea068c41
Swift
raoarafat/AKPinsOnTheMap-Swift-
/AKPinsOnTheMap/Modal/GeoLocation.swift
UTF-8
539
2.78125
3
[ "MIT" ]
permissive
// // GeoLocation.swift // AKPinsOnTheMap // // Created by Arafat on 6/24/15. // Copyright (c) 2015 Arafat Khan. All rights reserved. // import Foundation import MapKit struct GeoLocation { var latitude: Double var longitude: Double } // MARK: Class extensions and computed properties extension GeoLocation { var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2DMake( self.latitude, self.longitude) } var mapPoint: MKMapPoint { return MKMapPointForCoordinate(self.coordinate) } }
true
eb8599f53d71856b7838df079051c17993830e25
Swift
mschmulen/donorschoose-app13
/donorsChoose/App/AppViews/ProposalViews/ProposalDetailView.swift
UTF-8
9,239
2.609375
3
[]
no_license
// // ProposalDetailView.swift // donorsChoose // // Copyright © 2020 jumptack. All rights reserved. // import SwiftUI struct ProposalDetailView: View { @EnvironmentObject var appState: AppState var model: ProposalModel @State var isFavorite: Bool = false @State var showActionSheet: Bool = false @State var percentCompleteProgressValue:Float = 0 var imagePlaceHolder: some View { ZStack { Color(.lightGray).edgesIgnoringSafeArea(.all) Text("") .font(.system(size: 15, weight: .medium, design: .rounded)) .foregroundColor(.white) } } var header: some View { ZStack{ AsyncSimpleImage( imageURLString: model.imageURL, placeholder: imagePlaceHolder ) .aspectRatio(contentMode: .fill) .frame(height:150) // .edgesIgnoringSafeArea(.all) .clipped() VStack { HStack { NavigationLink(destination: TeacherDetailView( store: DCTeacherStore(teacherID: model.teacherId) )){ Text(model.teacherName) .font(.system(size: 20, weight: .bold, design: .rounded)) .foregroundColor(.white) .padding() }.buttonStyle(PlainButtonStyle()) Spacer() Text( "\(model.city),\(model.state)") .font(.system(size: 15, weight: .bold, design: .rounded)) .foregroundColor(.white) .padding() } if model.extractedSchoolID == nil { Text(model.schoolName) .font(.system(size: 20, weight: .bold, design: .rounded)) .foregroundColor(.white) .padding() } else { NavigationLink(destination: SchoolDetailView( //store: DCSchoolStore(schoolID: model.extractedSchoolID!) store: DCSchoolStore(schoolID: "44656") )){ Text(model.schoolName) .font(.system(size: 20, weight: .bold, design: .rounded)) .foregroundColor(.white) .padding() }.buttonStyle(PlainButtonStyle()) } } } } // TODO: Extract this to a custom view var statusBar: some View { VStack { HStack(alignment: .center, spacing: 60) { VStack { Text("$\(model.costToComplete)") .font(.system(size: 22, weight: .bold, design: .rounded)) Text("Still Needed") .font(.system(size: 13, weight: .light, design: .rounded)) } VStack { Text("\(model.percentFunded)%") .font(.system(size: 22, weight: .bold, design: .rounded)) Text("Funded") .font(.system(size: 13, weight: .light, design: .rounded)) } VStack { Text("\(model.numDonors)") .font(.system(size: 22, weight: .bold, design: .rounded)) Text("Donors") .font(.system(size: 13, weight: .light, design: .rounded)) } } // Text("\(model.percentFunded)") VStack(alignment: .leading) { ProgressBar(value: $percentCompleteProgressValue) .frame(height: 10) } .padding(.leading, 10) .padding(.trailing, 10) } } var body: some View { VStack { header statusBar ScrollView(.vertical, showsIndicators: false) { Text("\(model.title)") .font(.system(size: 20, weight: .medium, design: .rounded)) .frame(maxWidth: .infinity, alignment: .leading) .padding() Text("\(model.fulfillmentTrailer)") .font(.system(size: 20, weight: .medium, design: .rounded)) .frame(maxWidth: .infinity, alignment: .leading) .padding() Text("My Students:") .font(.system(size: 22, weight: .bold, design: .rounded)) .frame(maxWidth: .infinity, alignment: .leading) .padding() Text("\(model.shortDescription)") .font(.system(size: 20, weight: .medium, design: .rounded)) .padding() Text("My Project:") .font(.system(size: 22, weight: .bold, design: .rounded)) .frame(maxWidth: .infinity, alignment: .leading) .padding() Text("\(model.shortDescription)") .font(.system(size: 20, weight: .medium, design: .rounded)) .padding() VStack { Text("latitude \(model.totalPrice)") Text("fundingStatus \(model.fundingStatus)") Text("expirationDate \(model.expirationDate)") Text("gradeLevel \(model.gradeLevel.name)") Text("latitude \(model.latitude)") Text("latitude \(model.povertyLevel)") } } Button(action: { if let fundURL = self.model.fundURL, let url = URL(string: fundURL) { UIApplication.shared.open(url) } }) { Text("Give") .foregroundColor(.white) .padding(8) .padding(.leading, 40) .padding(.trailing, 40) .background(Color.accentColor) .cornerRadius(8) } }.onAppear(perform: { self.startProgressBar(percentFunded: self.model.percentFunded) }) .navigationBarTitle(Text("Proposal"), displayMode: .inline) .navigationBarItems(leading: leadingButton, trailing: trailingButton) .sheet(isPresented: $showActionSheet) { ProjectActionSheet(model: self.model) .environmentObject(self.appState) } } func startProgressBar(percentFunded: Int ) { self.percentCompleteProgressValue = 0.0 for _ in 0...percentFunded { self.percentCompleteProgressValue += 0.01 } } private var trailingButton: some View { Group { if isFavorite { Button(action:onFavoriteTouch) { Image(systemName: "heart.circle.fill") } } else { Button(action:onFavoriteTouch) { Image(systemName: "heart") } } } } func onFavoriteTouch() { isFavorite.toggle() appState.addFavoriteProject( id:model.id, title:model.title, expirationDate: model.expirationDate ) } private var leadingButton: some View { HStack { Button(action:onMore) { Image(systemName: "square.and.arrow.up") } } } func onMore() { showActionSheet.toggle() } } struct ProjectDetailView_Previews: PreviewProvider { static var previews: some View { ProposalDetailView(model: ProposalModel.mock) } } // TODO: Clean up // iOS 14 // https://www.hackingwithswift.com/quick-start/swiftui/how-to-open-web-links-in-safari // Link("Learn SwiftUI", destination: URL(string: "https://www.hackingwithswift.com/quick-start/swiftui")!) struct ProjectActionSheet: View { @EnvironmentObject var appState: AppState var model: ProposalModel var body: some View { VStack(alignment: .center, spacing: 20) { Button(action: { print( "TODO email") }) { Text("Email to a friend") .foregroundColor(.red) } Button(action: { print( "TODO email") }) { Text("Open in Safari") .foregroundColor(.red) } Button(action: { print( "TODO copy URL") }) { Text("Copy URL") .foregroundColor(.red) } Button(action: { self.appState.addFavoriteProject( id: self.model.id, title: self.model.title, expirationDate: self.model.expirationDate ) }) { Text("Add to my favorites") } } } }
true
2f51104ba1226ea76d1de15bc9c3f9abd2287392
Swift
Xecca/LeetCodeProblems
/118.Pascals_Triangle.swift
UTF-8
1,441
3.75
4
[]
no_license
// Solved by Xecca //118. Pascal's Triangle //Сomplexity: Easy //https://leetcode.com/problems/pascals-triangle/ //---------------------------------------------------- //Runtime: 0 ms, faster than 100.00% of Swift online submissions for Pascal's Triangle. //Memory Usage: 14 MB, less than 98.14% of Swift online submissions for Pascal's Triangle. //---------------------------------------------------- //Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. // //In Pascal's triangle, each number is the sum of the two numbers directly above it. //---------------------------------------------------- func generate(_ numRows: Int) -> [[Int]] { var rowLength = 0 var currentRow = 0 var i = 0 var triangle = [[Int]]() var tempArr = [1] while i < numRows { triangle.append(tempArr) tempArr.append(1) i += 1 } if numRows > 2 { currentRow = 2 while currentRow < numRows { i = 1 rowLength = triangle[currentRow].count while i < rowLength - 1 && i > 0 { triangle[currentRow][i] = triangle[currentRow - 1][i - 1] + triangle[currentRow - 1][i] i += 1 } currentRow += 1 } } return triangle } //Input: let num = 5 //Output: //[ // [1], // [1,1], // [1,2,1], // [1,3,3,1], // [1,4,6,4,1] //] generate(num)
true
b1c7f3f97b9fc5c8fb78cfceb79bc954f54e6dd4
Swift
samgold89/griffy
/Griffy/Beta Screens/Intro/BetaSetupVC.swift
UTF-8
2,982
2.671875
3
[]
no_license
// // BetaSetupVC.swift // Griffy // // Created by Sam Goldstein on 2/11/20. // Copyright © 2020 Sam Goldstein. All rights reserved. // import Foundation import UIKit import SSSpinnerButton // https://github.com/simformsolutions/SSSpinnerButton class BetaSetupVC: BaseViewController { @IBOutlet weak var spinnerButton: SSSpinnerButton! @IBOutlet weak var firstNameField: PaddedTextField! @IBOutlet weak var betaCodeField: PaddedTextField! override func viewDidLoad() { super.viewDidLoad() let tap = UITapGestureRecognizer(target: self, action: #selector(tapperTapped)) view.addGestureRecognizer(tap) } @objc fileprivate func tapperTapped() { firstNameField.resignFirstResponder() betaCodeField.resignFirstResponder() } @IBAction func nextButtonPressed() { if validateTextFields() { spinnerButton.startAnimate(spinnerType: .ballRotateChase, spinnercolor: .white, spinnerSize: 30, complete: nil) guard let name = firstNameField.text, let code = betaCodeField.text else { return } createUser(name: name, code: code) } } fileprivate func validateTextFields() -> Bool { guard let text = firstNameField.text, text.count > 1 else { showAlertWithTitle(title: "Bad Name", body: "🛑 Please enter your full name and try again!", buttonTitles: ["OK"]) return false } guard let betaCode = betaCodeField.text, betaCode.contains("89") else { showAlertWithTitle(title: "Invalide Code", body: "🛑 That code is not valid. Please double check and try again!", buttonTitles: ["OK"]) return false } return true } fileprivate func createUser(name: String, code: String) { let _ = BetaUser.create(withName: name, betaCode: code) firstNameField.isEnabled = false betaCodeField.isEnabled = false delay(1.8) { self.spinnerButton.stopAnimatingWithCompletionType(completionType: .success) { self.present(UIStoryboard.betaVC(betaType: .instructions), animated: true, completion: nil) } } } override func keyboardWillShow(_ info: BaseViewController.KeyboardInfo) { if info.keyboardSize.height <= betaCodeField.frame.maxY { UIView.animate(withDuration: info.duration) { let overlap = self.betaCodeField.frame.maxY - info.keyboardSize.height let buffer = CGFloat(20) self.view.transform = CGAffineTransform(translationX: 0, y: -(overlap+buffer)) } } } override func keyboardWillHide(_ info: BaseViewController.KeyboardInfo) { UIView.animate(withDuration: info.duration) { self.view.transform = .identity } } @IBAction func seePolicyPressed(_ sender: Any) { } } extension BetaSetupVC: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == firstNameField { betaCodeField.becomeFirstResponder() } else { nextButtonPressed() betaCodeField.resignFirstResponder() } return true } }
true
04ddb388c79c0fcddd29eb741088cb40952c10a0
Swift
dgtic-dam/Swift-Basic
/Downloader/Downloader/ViewController.swift
UTF-8
3,571
2.703125
3
[ "MIT" ]
permissive
// // ViewController.swift // Downloader // // Created by Jan Zelaznog on 23/11/17. // Copyright © 2017 Jan Zelaznog. All rights reserved. // // Selasor Azodnem Leinad ed Susej import UIKit class ViewController: UIViewController, URLSessionDelegate, URLSessionDownloadDelegate { var urlString:String = "" @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var conn:URLSession? var data:Data? func guardarImagen() { if let image = UIImage(data:self.data!) { UIImageWriteToSavedPhotosAlbum(image, self, #selector(savedImage), nil) } } @objc func savedImage(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafeRawPointer) { //Compatible con Objective C if error != nil { print ("ocurrió un error al guardar la imagen") } else { print ("la imagen ya se guardó") } } func guardarArchivo() { //obtener la ubicacion de Documents let docsPath = FileManager.default.urls(for:.documentDirectory, in:.userDomainMask)[0] // obtener el nombre del archivo a partir de la URL de descarga let urlTMP = URL(string:urlString) let fileName = urlTMP?.lastPathComponent let imagePath = docsPath.appendingPathComponent(fileName!) print (imagePath) // guardar el arreglo de bytes como el tipo de archivo correspondiente do { try self.data?.write(to:imagePath) } catch { print ("Error al guardar el archivo " + error.localizedDescription) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let config = URLSessionConfiguration.background(withIdentifier: "\(Bundle.main.bundleIdentifier!).background") //configuración conn = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue()) urlString = "http://chandra.harvard.edu/photo/2014/15year/crab.jpg" if let url = URL(string:urlString) { let task = conn!.downloadTask(with: url) task.resume() } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if totalBytesExpectedToWrite > 0 { let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite) debugPrint("Progress \(downloadTask) \(progress)") } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { debugPrint("Download finished: \(location)") do { data = try Data(contentsOf: location) guardarImagen() DispatchQueue.main.async { self.imageView.image = UIImage(data: self.data!) self.activityIndicator.stopAnimating() } } catch { } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if error != nil { debugPrint("error: "+error!.localizedDescription) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
f11df1468dde276bf748bd1ccf54c6222599e873
Swift
dbarrett0815/ItunesMedia
/ItunesMedia/Extentions.swift
UTF-8
1,836
2.71875
3
[]
no_license
// // Extentions.swift // ItunesMedia // // Created by Davone Barrett on 2/22/19. // Copyright © 2019 Davone Barrett. All rights reserved. // import Foundation import UIKit extension UITableView { func showCenterText(_ centerText: String) { let textLabel = UILabel() textLabel.textColor = .white textLabel.font = UIFont.systemFont(ofSize: 20) textLabel.textAlignment = .center textLabel.center = self.center textLabel.text = centerText backgroundView = textLabel separatorStyle = .none } func showCenterTextWithLoadingIndicator(_ text: String) { separatorStyle = .none let loadingLabel = UILabel() loadingLabel.text = text loadingLabel.textColor = .white addSubview(loadingLabel) let activityIndicator = UIActivityIndicatorView(style: .white) activityIndicator.startAnimating() activityIndicator.hidesWhenStopped = true addSubview(activityIndicator) let stackView = UIStackView(arrangedSubviews: [loadingLabel, activityIndicator]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.alignment = .center stackView.axis = .vertical stackView.distribution = .equalSpacing stackView.spacing = 5 stackView.center = center backgroundView = UIView(frame: frame) backgroundView?.addSubview(stackView) stackView.centerXAnchor.constraint(equalTo: backgroundView!.safeAreaLayoutGuide.centerXAnchor).isActive = true stackView.centerYAnchor.constraint(equalTo: backgroundView!.safeAreaLayoutGuide.centerYAnchor).isActive = true } func hideCenterText() { backgroundView = nil separatorStyle = .singleLine } }
true
a8eb79068d1d9a03fea66f6f4007987d177087c7
Swift
SukhjeetSandhu/Assignment-3
/GraphingCalculator/GraphingCalculator/CalculatorViewController.swift
UTF-8
12,715
2.6875
3
[]
no_license
// // CalculatorViewController.swift // GraphingCalculator // // Created by sukhjeet singh sandhu on 21/06/16. // Copyright © 2016 sukhjeet singh sandhu. All rights reserved. // import UIKit class CalculatorViewController: UIViewController { //MARK: views fileprivate let buttonsView = UIView() fileprivate let display: UILabel = { $0.translatesAutoresizingMaskIntoConstraints = false $0.text = "0" $0.textAlignment = .right $0.font = $0.font.withSize(55) $0.setContentHuggingPriority(251, for: .vertical) $0.setContentCompressionResistancePriority(751, for: .vertical) $0.adjustsFontSizeToFitWidth = true $0.backgroundColor = UIColor(red: 148/255, green: 148/255, blue: 148/255, alpha: 1) return $0 }(UILabel()) fileprivate let descriptionDisplay: UILabel = { $0.translatesAutoresizingMaskIntoConstraints = false $0.text = " " $0.textAlignment = .right $0.font = $0.font.withSize(40) $0.setContentHuggingPriority(251, for: .vertical) $0.setContentCompressionResistancePriority(751, for: .vertical) $0.adjustsFontSizeToFitWidth = true $0.backgroundColor = UIColor(red: 148/255, green: 148/255, blue: 148/255, alpha: 1) return $0 }(UILabel()) //MARK: Calc properties fileprivate var userIsInTheMiddleOfTyping = false fileprivate var brain = CalculatorBrain() fileprivate var doesDotExists = false fileprivate var buttons: [[UIButton]] = [] fileprivate var savedOperation: AnyObject? fileprivate let buttonTitles = [["AC", "⌫", "sin", "cos"], ["x²", "x³", "π", "e"], ["+", "±", "M", "→M"], ["-", "7", "8", "9"],["×", "4", "5", "6"], ["÷", "1", "2", "3"], ["√", ".", "0", "="]] fileprivate var displayValue: Double? { get { if let text = display.text, let value = Double(text) { return value } else { return nil } } set { if let value = newValue { display.text = String(value) descriptionDisplay.text = brain.description + (brain.isPartialResult ? "..." : "=") } else { display.text = "0" descriptionDisplay.text = " " userIsInTheMiddleOfTyping = false } } } //MARK: Lifecycle method override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "graph", style: .plain, target: self, action: #selector(CalculatorViewController.loadGraphViewController)) createDisplay() createDescriptionDisplay() addbuttonsView() createButtons() } //MARK: Adding subviews fileprivate func createDisplay() { view.addSubview(display) view.addConstraint(NSLayoutConstraint(item: display, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: UIApplication.shared.statusBarFrame.size.height + (navigationController?.navigationBar.frame.height)! + 4)) view.addConstraint(NSLayoutConstraint(item: display, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 8.0)) view.addConstraint(NSLayoutConstraint(item: display, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: -8.0)) } fileprivate func createDescriptionDisplay() { view.addSubview(descriptionDisplay) view.addConstraint(NSLayoutConstraint(item: descriptionDisplay, attribute: .top, relatedBy: .equal, toItem: display, attribute: .bottom, multiplier: 1.0, constant: 1.0)) view.addConstraint(NSLayoutConstraint(item: descriptionDisplay, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 8.0)) view.addConstraint(NSLayoutConstraint(item: descriptionDisplay, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: -8.0)) } fileprivate func addbuttonsView() { buttonsView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(buttonsView) view.addConstraint(NSLayoutConstraint(item: buttonsView, attribute: .top, relatedBy: .equal, toItem: descriptionDisplay, attribute: .bottom, multiplier: 1.0, constant: 1.0)) view.addConstraint(NSLayoutConstraint(item: buttonsView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 8.0)) view.addConstraint(NSLayoutConstraint(item: buttonsView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: -8.0)) view.addConstraint(NSLayoutConstraint(item: buttonsView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: -8.0)) } fileprivate func createButtons() { let buttonRows = 7 let buttonColumns = 4 let gapInButtonWidth: CGFloat = 1 let gapInButtonHeight: CGFloat = 1 for row in 0..<buttonRows { for column in 0..<buttonColumns { let button: UIButton = { $0.translatesAutoresizingMaskIntoConstraints = false $0.setTitle(buttonTitles[row][column], for: UIControlState()) if Double($0.titleLabel!.text!) != nil || $0.titleLabel!.text! == "." || $0.titleLabel!.text! == "=" { $0.backgroundColor = UIColor(red: 224/255, green: 224/255, blue: 224/255, alpha: 1) } else { $0.backgroundColor = UIColor(red: 214/255, green: 214/255, blue: 214/255, alpha: 1) } $0.setTitleColor(.black, for: UIControlState()) $0.titleLabel?.font = $0.titleLabel?.font.withSize(30) $0.addTarget(self, action: #selector(performAction), for: .touchUpInside) return $0 }(UIButton()) buttonsView.addSubview(button) if row - 1 >= 0 { // If it is not the first row, we are setting the top constraint of the button to the bottom constraint of the button above it. buttonsView.addConstraint(NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: buttons[row - 1][column], attribute: .bottom, multiplier: 1.0, constant: gapInButtonHeight)) // we are making height of the button to equal to the height of the button above it. buttonsView.addConstraint(NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: buttons[row - 1][column], attribute: .height, multiplier: 1.0, constant: 0.0)) } else { // If it is the first row, we are setting the top constraint of the button to the buttonsView's top constraint. buttonsView.addConstraint(NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: buttonsView, attribute: .top, multiplier: 1.0, constant: 0.0)) } if column - 1 >= 0 { // If it is not the first column, we are setting the leading constraint of the button to the trailing constraint of the button behind it. buttonsView.addConstraint(NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: buttons[row][column - 1], attribute: .trailing, multiplier: 1.0, constant: gapInButtonWidth)) // we are making width of the button to equal to the width of the button behind it. buttonsView.addConstraint(NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: buttons[row][column - 1], attribute: .width, multiplier: 1.0, constant: 0.0)) } else { // If it is the first column, we are setting the leading constraint of the button to the buttonsView's leading constraint. buttonsView.addConstraint(NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: buttonsView, attribute: .leading, multiplier: 1.0, constant: 0.0)) } if column == buttonColumns - 1 { // If it is the last column, we are setting trailing constraint of this button to the trailing constraint of buttonsView. buttonsView.addConstraint(NSLayoutConstraint(item: button, attribute: .trailing, relatedBy: .equal, toItem: buttonsView, attribute: .trailing, multiplier: 1.0, constant: 0.0)) } if row == buttonRows - 1 { // If it is the last row, we are setting bottom constraint of this button to the bottom constraint of buttonsView. buttonsView.addConstraint(NSLayoutConstraint(item: button, attribute: .bottom, relatedBy: .equal, toItem: buttonsView, attribute: .bottom, multiplier: 1.0, constant: 0.0)) } if buttons.count == row { buttons.append([button]) } else { buttons[row].append(button) } } } } //MARK: Append and backspace methods fileprivate func appendDigitOrDot(_ isInMiddle:Bool, title: String) { if isInMiddle { display.text = display.text! + title if title == "." { doesDotExists = true } } else { display.text = title if title == "." { doesDotExists = true } } } fileprivate func backSpace() { if display.text?.characters.count != 1 { if let index = display.text?.characters.index(before: (display.text?.endIndex)!) { let removedDigit = display.text?.remove(at: index) if removedDigit == "." { doesDotExists = false } } } else { if brain.undo() { savedOperation = brain.program brain.program = savedOperation! displayValue = brain.result } else { displayValue = nil } doesDotExists = false } } //MARK: Target method for buttons func performAction(_ sender:UIButton) { let title = sender.currentTitle! if Double(title) != nil { appendDigitOrDot(userIsInTheMiddleOfTyping, title: title) userIsInTheMiddleOfTyping = true } else if title == "." { if !doesDotExists { appendDigitOrDot(userIsInTheMiddleOfTyping, title: title) userIsInTheMiddleOfTyping = true } } else if title == "⌫" { backSpace() } else if title == "M" { brain.setOpreand(title) } else if title == "→M" { brain.variableValues["M"] = displayValue if let savedOperation = savedOperation { brain.program = savedOperation displayValue = brain.result } } else { doesDotExists = false if userIsInTheMiddleOfTyping { brain.setOperand(displayValue!) userIsInTheMiddleOfTyping = false } brain.performOperation(title) if title == "AC" { brain.clear() displayValue = nil savedOperation = nil brain.variableValues.removeAll() } else { displayValue = brain.result } savedOperation = brain.program } } //MARK: Segueing to next MVC func loadGraphViewController() { //It will only segue to the gvc if there is a variable present in equation or no equation is there. var isAnyVariable = false if let arrayOfOps = savedOperation as? [AnyObject] { for op in arrayOfOps { if let op = op as? String { if op == "M" { isAnyVariable = true } } } } else { isAnyVariable = true } if isAnyVariable { let gvc = GraphViewController() gvc.operation = savedOperation self.navigationController?.pushViewController(gvc, animated: true) } } }
true
6536f61bab27f51b823b5b913b54dd9d678e98fc
Swift
realityworks/broadcast-app
/Broadcast/Presentation/Styling/UILabel+Styling.swift
UTF-8
2,626
2.8125
3
[]
no_license
// // UILabel+Styling.swift // Broadcast // // Created by Piotr Suwara on 26/11/20. // import UIKit extension UILabel { private static func text(_ text: String? = nil, font: UIFont = .body, textColor: UIColor = .secondaryBlack) -> UILabel { let label = UILabel() label.text = text label.font = font label.textColor = textColor return label } static func text(_ text: LocalizedString? = nil, font: UIFont = .body, textColor: UIColor = .secondaryBlack) -> UILabel { return Self.text(text?.localized, font: font, textColor: textColor) } static func body(_ text: LocalizedString = .none, textColor: UIColor = .text) -> UILabel { return Self.text(text.localized, textColor: textColor) } static func extraLargeTitle(_ text: LocalizedString = .none, textColor: UIColor = .text) -> UILabel { return Self.text(text.localized, font: .extraLargeTitle, textColor: textColor) } static func largeTitle(_ text: LocalizedString = .none, textColor: UIColor = .text) -> UILabel { return Self.text(text.localized, font: .largeTitle, textColor: textColor) } static func subTitle(_ text: LocalizedString = .none, textColor: UIColor = .text) -> UILabel { return Self.text(text.localized, font: .largeTitle, textColor: textColor) } static func bodyMedium(_ text: LocalizedString = .none, textColor: UIColor = .text) -> UILabel { return Self.text(text.localized, font: .bodyMedium, textColor: textColor) } static func bodyBold(_ text: LocalizedString = .none, textColor: UIColor = .text) -> UILabel { return Self.text(text.localized, font: .bodyBold, textColor: textColor) } static func lightGreySmallBody(_ text: LocalizedString = .none) -> UILabel { return Self.text(text.localized, font: .smallBody, textColor: .primaryLightGrey) } static func tinyBody(_ text: LocalizedString = .none, textColor: UIColor = .text) -> UILabel { return Self.text(text.localized, font: .tinyBody, textColor: textColor) } static func largeBodyBold(_ text: LocalizedString = .none, textColor: UIColor = .text) -> UILabel { return Self.text(text.localized, font: .largeBodyBold, textColor: textColor) } static func smallBody(_ text: LocalizedString = .none, textColor: UIColor = .text) -> UILabel { return Self.text(text.localized, font: .smallBody, textColor: textColor) } }
true
6cc7c6669dd3bf38ac172753fa78fe502627f4e8
Swift
hujewelz/emojiArt-app
/Shared/PaletteStore.swift
UTF-8
2,954
3.078125
3
[]
no_license
// // PaletteStore.swift // EmojiArt // // Created by huluobo on 2021/7/2. // import SwiftUI struct Palette: Identifiable, Codable, Hashable { let id: Int var name: String var emojis: String } class PaletteStore: ObservableObject { let name: String @Published var palettes: [Palette] = [] { didSet { storeInUserDefaults() } } init(named name: String) { self.name = name restoreFromUserDefaults() if palettes.isEmpty { insertPallete(named: "Favorites", emojis: "👹🤡😸💀☠️👽🤖👇🏻🖕🏼😾😿🫀🧠🧖🏼‍♂️🤯😶‍🌫️🥶🌝🌕🌞☄️") insertPallete(named: "Animals", emojis: "🐶🐱🐭🐹🐰🦊🐻🐼🐻‍❄️🐨🐯🦁🐮🐷🐽🐸🐵🙈🙉🙊🐒🐔🐧🐦🦆🐝🦉🐴🦄") insertPallete(named: "Faces", emojis: "😀😃😄😂😅😆🥲🤣😇😌🥰😍😘😗😛😙😝😜🤪🤨🥸😎🤓🧐🤩🥳😏😒") insertPallete(named: "Nature", emojis: "🌞🌝🌛🌚🌕🌖🌗🌘🌔🌓🪐⭐️☄️💥🔥🌟🌈🌪") insertPallete(named: "Weather", emojis: "☀️🌤⛅️🌥☁️🌦🌧⛈🌩🌨❄️☃️⛄️🌬💨💧💦☔️☂️🌊🌫") insertPallete(named: "Foods", emojis: "🍏🍎🍐🍊🍋🍌🍉🍇🍓🫐🍈🍒🍑🥭🍍🥥🥝🍅🥑🧅") insertPallete(named: "Activities", emojis: "⚽️🏀🏈⚾️🥎🎾🏐🏉🎱🪀🏓🏒🏑🪃🏹🥊🥋🤿⛸🏂🥌🏄🏻🏄🏻‍♂️") } } // MARK: - Intent func pallete(at index: Int) -> Palette { let safeIndex = min(max(index, 0), palettes.count - 1) return palettes[safeIndex] } @discardableResult func removePallete(at index: Int) -> Int { if palettes.count > 1, palettes.indices.contains(index) { palettes.remove(at: index) } return index % palettes.count } func insertPallete(named name: String, emojis: String? = nil, at index: Int = 0) { let unique = (palettes.max { $0.id < $1.id }?.id ?? 0) + 1 let pallete = Palette(id: unique, name: name, emojis: emojis?.removingDuplicateCharacters ?? "") let safeIndex = min(max(index, 0), palettes.count) palettes.insert(pallete, at: safeIndex) } // MARK: - Private private var userDefaultsKey: String { "PalletStore." + name } private func storeInUserDefaults() { if let data = try? palettes.json() { UserDefaults.standard.set(data, forKey: userDefaultsKey) } } private func restoreFromUserDefaults() { if let data = UserDefaults.standard.data(forKey: userDefaultsKey) , let storedPallettes = try? Array<Palette>(json: data) { palettes = storedPallettes } } }
true
4a939205f76fc886b7613dcd51eadd598b64d025
Swift
green1823/Game-Show-App
/Game Show App/PlayerName.swift
UTF-8
574
2.96875
3
[]
no_license
// // PlayerName.swift // Game Show App // // Created by Green, Jackie on 9/24/19. // Copyright © 2019 Green, Jackie. All rights reserved. // import Foundation import CloudKit struct PlayerName: Codable { var name: String var itemIdentifier: UUID init(name: String, itemIdentifier: UUID) { self.name = name self.itemIdentifier = itemIdentifier } func saveItem() { DataManager.save(self, with: "\(itemIdentifier.uuidString)") } func deleteItem() { DataManager.delete(itemIdentifier.uuidString) } }
true
8a160f0161c5e8421202b04e45a5ac62c3fa261f
Swift
KKFantasy/ARDemo
/ARDemo/WordTrackingViewController.swift
UTF-8
4,719
2.625
3
[]
no_license
// // ViewController.swift // ARDemo // // Created by KKFantasy on 2019/4/19. // Copyright © 2019 kk. All rights reserved. // import ARKit import SceneKit import UIKit // 基本的AR效果,快照 class WordTrackingViewController: UIViewController, ARSCNViewDelegate { var sceneView: ARSCNView! var snapshots = [SCNNode]() override func viewDidLoad() { super.viewDidLoad() sceneView = ARSCNView(frame: view.bounds) view.addSubview(sceneView) // Set the view's delegate sceneView.delegate = self // Show statistics such as fps and timing information sceneView.showsStatistics = true // Create a new scene let scene = SCNScene(named: "art.scnassets/ship.scn")! // Set the scene to the view sceneView.scene = scene // 添加点击事件 let clearItem = UIBarButtonItem(title: "Clear", style: .plain, target: self, action: #selector(clear(_:))) let captureItem = UIBarButtonItem(title: "Capture", style: .plain, target: self, action: #selector(capture)) navigationItem.rightBarButtonItems = [clearItem, captureItem] } // 点击屏幕 @objc func capture() { // 截图并创建平面 let imagePlane = SCNPlane(width: sceneView.bounds.width / 6000, height: sceneView.bounds.height / 6000) imagePlane.firstMaterial?.diffuse.contents = sceneView.snapshot() imagePlane.firstMaterial?.lightingModel = .constant // 创建plane node并添加到场景 let planeNode = SCNNode(geometry: imagePlane) sceneView.scene.rootNode.addChildNode(planeNode) snapshots.append(planeNode) // 改变其在空间的位置为摄像头的位置 let currentFrame = sceneView.session.currentFrame if let transform = currentFrame?.camera.transform { var translation = matrix_identity_float4x4 updateTranslationMatrix(&translation) planeNode.simdTransform = matrix_multiply(transform, translation) } } func updateTranslationMatrix(_ translation: inout simd_float4x4) { switch UIDevice.current.orientation{ case .portrait, .portraitUpsideDown, .unknown, .faceDown, .faceUp: print("portrait ") translation.columns.0.x = -cos(.pi/2) translation.columns.0.y = sin(.pi/2) translation.columns.1.x = -sin(.pi/2) translation.columns.1.y = -cos(.pi/2) case .landscapeLeft : print("landscape left") translation.columns.0.x = 1 translation.columns.0.y = 0 translation.columns.1.x = 0 translation.columns.1.y = 1 case .landscapeRight : print("landscape right") translation.columns.0.x = cos(.pi) translation.columns.0.y = -sin(.pi) translation.columns.1.x = sin(.pi) translation.columns.1.y = cos(.pi) default: break } translation.columns.3.z = -0.15 //60cm in front of the camera } @objc func clear(_ sender: UIBarButtonItem) { // sceneView.scene.rootNode.enumerateChildNodes({ node, _ in // node.removeFromParentNode() // }) snapshots.forEach({$0.removeFromParentNode()}) snapshots.removeAll() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Create a session configuration let configuration = ARWorldTrackingConfiguration() // Run the view's session sceneView.session.run(configuration) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Pause the view's session sceneView.session.pause() } // MARK: - ARSCNViewDelegate /* // Override to create and configure nodes for anchors added to the view's session. func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { let node = SCNNode() return node } */ func session(_ session: ARSession, didFailWithError error: Error) { // Present an error message to the user } func sessionWasInterrupted(_ session: ARSession) { // Inform the user that the session has been interrupted, for example, by presenting an overlay } func sessionInterruptionEnded(_ session: ARSession) { // Reset tracking and/or remove existing anchors if consistent tracking is required } }
true
a0384b3da852cacdfeded18d3aaffe081df3bf29
Swift
karlvr/MathQuiz
/puppies and kittens math quiz/MathQuizViewController.swift
UTF-8
7,843
2.96875
3
[]
no_license
// // BaseMathViewController.swift // puppies and kittens math quiz // // Created by Karl von Randow on 28/05/16. // Copyright © 2016 XK72. All rights reserved. // import UIKit struct MathQuizQuestion { var correctAnswer: Int var question: String } protocol QuestionHandler { func nextQuestion() -> MathQuizQuestion } class MathQuizViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var question: UILabel! @IBOutlet weak var answer: UITextField! @IBOutlet weak var right: UILabel! @IBOutlet weak var wrong: UILabel! @IBOutlet weak var huh: UILabel! @IBOutlet weak var close: UILabel! @IBOutlet weak var score: UILabel! private var correctAnswer: Int { return currentQuestion!.correctAnswer } private var currentScore: Int = 0 private var waitingForNextQuestion: Bool = false private var speechRecognizer: SpeechRecognizerProtocol? private var currentQuestion: MathQuizQuestion? var questionHandler: QuestionHandler? override func viewDidLoad() { super.viewDidLoad() if #available(iOS 10.0, *) { speechRecognizer = SpeechRecognizer(handler: { (result) in self.checkSpeechResult(result: result) }) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) answer.text = "" nextQuestion() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) answer.becomeFirstResponder() } func nextQuestion() { currentQuestion = questionHandler!.nextQuestion() question.text = currentQuestion?.question answer.text = "" didNextQuestion() } func didNextQuestion() { answer.becomeFirstResponder() do { try speechRecognizer?.start(contextualStrings: ["\(correctAnswer)"]) } catch { print("Failed to start speech recognition: \(error)") } } private func extractNumbers(string: String) -> [Int] { let spellOutFormatter = NumberFormatter() spellOutFormatter.numberStyle = .spellOut let numberFormatter = NumberFormatter() var result = [Int]() string.enumerateLinguisticTags(in: string.startIndex..<string.endIndex, scheme: NSLinguisticTagScheme.lexicalClass.rawValue, options: [], orthography: nil) { (tag, tokenRange, _, _) in let token = String(string[tokenRange]).lowercased() if let number = spellOutFormatter.number(from: token) { print("FOUND SPELLED NUMBER \(number)") result.append(number.intValue) } else if let number = numberFormatter.number(from: token) { print("FOUND NUMBER \(number)") result.append(number.intValue) } else if token == "to" || token == "too" { result.append(2) } else if token == "sex" || token == "sucks" { result.append(6) } else if token == "teen" || token == "team" || token == "tin" { result.append(10) } else if token == "through" { result.append(3) } else if token == "won" { result.append(1) } else if token == "ate" { result.append(8) } else if token == "sarah" { result.append(0) } else { print("NOT NUMBER \"\(token)\"") } } return result } private func checkSpeechResult(result: String) { guard !waitingForNextQuestion else { return } let numbers = extractNumbers(string: result) print("Checking \(result) => \(numbers)") guard !numbers.isEmpty else { answer.text = "" gotUnintelligibleAnswer() return } let lastNumber = numbers[numbers.endIndex.advanced(by: -1)] answer.text = "\(lastNumber)" checkAnswerNumber(lastNumber) } private func cancelPreviousDelays() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(hideRight), object: nil) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(hideClose), object: nil) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(hideWrong), object: nil) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(hideUnintelligble), object: nil) } private func gotAnswerRight() { guard !waitingForNextQuestion else { return } right.isHidden = false close.isHidden = true wrong.isHidden = true huh.isHidden = true cancelPreviousDelays() perform(#selector(hideRight), with: nil, afterDelay: 2) currentScore = currentScore + 1 updateScore() waitingForNextQuestion = true answer.resignFirstResponder() } private func gotAnswerClose() { guard !waitingForNextQuestion else { return } close.isHidden = false right.isHidden = true wrong.isHidden = true huh.isHidden = true cancelPreviousDelays() perform(#selector(hideClose), with: nil, afterDelay: 2) } private func gotAnswerWrong() { guard !waitingForNextQuestion else { return } wrong.isHidden = false close.isHidden = true right.isHidden = true huh.isHidden = true cancelPreviousDelays() perform(#selector(hideWrong), with: nil, afterDelay: 15) } private func gotUnintelligibleAnswer() { guard !waitingForNextQuestion else { return } huh.isHidden = false wrong.isHidden = true close.isHidden = true right.isHidden = true cancelPreviousDelays() perform(#selector(hideUnintelligble), with: nil, afterDelay: 2) } private func checkAnswerNumber(_ answerNumber: Int) { if answerNumber == correctAnswer { gotAnswerRight() } else if answerIsClose(answerNumber) { gotAnswerClose() } else { gotAnswerWrong() } } @IBAction func checkAnswer(_ sender: AnyObject) { if let answerText = answer.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines), let answerNumber = Int(answerText), !waitingForNextQuestion { checkAnswerNumber(answerNumber) } else { answer.text = "" } } @objc func hideRight() { right.isHidden = true waitingForNextQuestion = false nextQuestion() } @objc func hideWrong() { wrong.isHidden = true } @objc func hideClose() { close.isHidden = true } @objc func hideUnintelligble() { huh.isHidden = true } func answerIsClose(_ answerNumber: Int) -> Bool { return abs(correctAnswer - answerNumber) <= 2 } func updateScore() { score.text = "Score: \(currentScore)" } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if string.endIndex == string.startIndex { return true } guard let _ = Int(string) else { return false } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { checkAnswer(textField) return true } @IBAction func dismiss(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } }
true
c61718b88d401f52846b87d2478cbb265c223f66
Swift
ElijahMalashko/hw
/Dz7/Dz7(3,3)/Dz7(3,3)/SecondViewController.swift
UTF-8
3,218
2.875
3
[]
no_license
// // SecondViewController.swift // Dz7(3,3) // // Created by Elijah Malashko on 21.03.21. // import UIKit class SecondViewController: UIViewController { var buttonUP: UIButton! var buttonDown: UIButton! var buttonLeft: UIButton! var buttonRight: UIButton! var object: UILabel! var xCoordinates: Int = 186 var yCoordinates: Int = 351 override func viewDidLoad() { super.viewDidLoad() let customView = UIView(frame: UIScreen.main.bounds) customView.backgroundColor = .black buttonUP = UIButton(frame: CGRect(x: 184, y: 642, width: 50, height: 50)) buttonUP.addTarget(self, action: #selector(UpButton), for: .touchUpInside) customView.addSubview(buttonUP) view = customView buttonDown = UIButton(frame: CGRect(x: 184, y: 729, width: 50, height: 50)) buttonDown.addTarget(self, action: #selector(DownButton), for: .touchUpInside) customView.addSubview(buttonDown) view = customView buttonLeft = UIButton(frame: CGRect(x: 101, y: 686, width: 50, height: 50)) buttonLeft.addTarget(self, action: #selector(LeftButton), for: .touchUpInside) customView.addSubview(buttonLeft) view = customView buttonRight = UIButton(frame: CGRect(x: 264, y: 686, width: 50, height: 50)) buttonRight.addTarget(self, action: #selector(RightButton), for: .touchUpInside) customView.addSubview(buttonRight) view = customView object = UILabel(frame: CGRect(x: xCoordinates, y: yCoordinates, width: 70, height: 70)) object.backgroundColor = .white customView.addSubview(object) if let image = UIImage(named: "down") { self.buttonDown.setImage(image, for: .normal) } if let image = UIImage(named: "up") { self.buttonUP.setImage(image, for: .normal) } if let image = UIImage(named: "left") { self.buttonLeft.setImage(image, for: .normal) } if let image = UIImage(named: "right") { self.buttonRight.setImage(image, for: .normal) } } @objc func UpButton(){ yCoordinates = yCoordinates - 15 object.frame = CGRect(x: xCoordinates, y: yCoordinates, width: 70, height: 70) } @objc func DownButton(){ yCoordinates = yCoordinates + 15 object.frame = CGRect(x: xCoordinates, y: yCoordinates, width: 70, height: 70) } @objc func LeftButton(){ if xCoordinates < 0 { xCoordinates = xCoordinates + 186 } xCoordinates = xCoordinates - 15 object.frame = CGRect(x: xCoordinates, y: yCoordinates, width: 70, height: 70) } @objc func RightButton(){ if xCoordinates > 355 { xCoordinates = xCoordinates - 186 } xCoordinates = xCoordinates + 15 object.frame = CGRect(x: xCoordinates, y: yCoordinates, width: 70, height: 70) } }
true
08087cf739cfbc596118f1488e1197ae8175b7a4
Swift
Sirius1996/TodoList
/TodoList/TodoList/RegisterView.swift
UTF-8
4,480
3.046875
3
[]
no_license
// // RegisterView.swift // ToDoList // // Created by Xizhen Huang on 06.01.21. // import SwiftUI struct RegisterView: View { @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> @ObservedObject private var manager = RequestHandle() @State private var email: String = "" @State private var username: String = "" @State private var password: String = "" @State private var uFlag = false @State private var pFlag = false @State private var isEmailValid = true @State private var isLegal = false @State private var showAlert = false var isCanRegister: Bool { username.count >= 4 && password.count >= 6 } init(){ UITableView.appearance().backgroundColor = .clear } var body: some View { VStack { // app name HStack{ Text("Create Account") .font(.largeTitle) .fontWeight(.bold) .foregroundColor(Color.white) .multilineTextAlignment(.center) } Spacer() .frame(height: 50.0) // information form Form { // email Hstack TextField("email", text: $email, onEditingChanged: { (isChanged) in if !isChanged { if isValidEmail(email) { self.isEmailValid = true } else { self.isEmailValid = false self.email = "" } } }) .autocapitalization(/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/) .prefixedWithIcon(named: "envelope.fill") if !isEmailValid { Text("Email is Not Valid") .font(.callout) .foregroundColor(Color.red) } // username Hstack Section(footer: Text(" username should be no less than 4 letters")){ TextField("username", text: $username) .autocapitalization(/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/) .prefixedWithIcon(named: "person.fill") } // password HStack Section(footer: Text(" password should no less than 6 digits")){ SecureField("password", text: $password, onCommit: {}) .prefixedWithIcon(named: "lock.fill") } } .background(Color.orange) if (isCanRegister) && (self.isEmailValid) { Button(action: { self.manager.postRegisterRequest(username: self.username, email: self.email, passwd: self.password) if manager.lostConnection { self.showAlert = true self.presentationMode.wrappedValue.dismiss() } if self.manager.legalregister == true{ isLegal = true self.presentationMode.wrappedValue.dismiss() } }) { Text("Sign Up") .fontWeight(.bold) .foregroundColor(.white) } .frame(width: 300, height: 45, alignment: .center) .background(Color.green) .cornerRadius(20) .alert(isPresented: $showAlert) { () -> Alert in Alert(title: Text("Network is not available :(")) } } Spacer() } .navigationBarTitle("Register") .navigationBarHidden(true) .padding(.top, 80.0) .padding(.bottom, 20.0) .padding(.horizontal) .background(Color(UIColor.systemOrange).edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)) } } struct RegisterView_Previews: PreviewProvider { static var previews: some View { RegisterView() } } extension View { func prefixedWithIcon(named name: String) -> some View { HStack { Image(systemName: name) .foregroundColor(Color.orange) self } } }
true
a4d90395bb543887c4df7d60e006458215c8ef2b
Swift
igorgcustodio/swift-clean-architecture
/Presentation/Presenters/Login/LoginRequest.swift
UTF-8
507
2.765625
3
[]
no_license
// // SignUpViewModel.swift // Presentation // // Created by Igor Custodio on 26/01/21. // import Foundation import Domain public struct LoginRequest: Model { public var email: String? public var password: String? public init(email: String? = nil, password: String? = nil) { self.email = email self.password = password } public func toAuthenticationModel() -> AuthenticationModel { return AuthenticationModel(email: email!, password: password!) } }
true
374cb08bd7a8b99bddd52e491348721b671106a1
Swift
ataias/OnTheMap
/OnTheMap/StudentLocationDetailView.swift
UTF-8
1,539
3.046875
3
[]
no_license
// // StudentLocationDetailView.swift // OnTheMap // // Created by Ataias Pereira Reis on 30/01/21. // import SwiftUI extension HorizontalAlignment { private enum CustomAlignment: AlignmentID { static func defaultValue(in context: ViewDimensions) -> CGFloat { return context[HorizontalAlignment.leading] } } static let customAlignment = HorizontalAlignment(CustomAlignment.self) } struct StudentLocationDetailView: View { let studentLocation: StudentInformation var columns: [GridItem] = [ .init(.fixed(150)), .init(.flexible()) ] var body: some View { LazyVGrid(columns: columns, spacing: 2) { HorizontalItemView(title: "Name", value: studentLocation.fullName) HorizontalItemView(title: "URL", value: studentLocation.mediaURL, isUrl: true) HorizontalItemView(title: "Latitude", value: studentLocation.latitude) HorizontalItemView(title: "Longitude", value: studentLocation.longitude) HorizontalItemView(title: "Location", value: studentLocation.mapString) HorizontalItemView(title: "Created At", value: studentLocation.formattedCreatedAt) HorizontalItemView(title: "Updated At", value: studentLocation.formattedUpdatedAt) } .font(.body) .padding() } } struct StudentLocationDetailView_Previews: PreviewProvider { static var previews: some View { StudentLocationDetailView(studentLocation: StudentInformation.sample) } }
true
37af7b2116f8c232ae6bb17c9376f27630f259f6
Swift
chenkefeng/SDRequest
/Example/SDRequest/DownloadApi.swift
UTF-8
753
2.515625
3
[ "MIT" ]
permissive
// // DownloadApi.swift // SDRequest // // Created by 陈克锋 on 2017/8/1. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit import SDRequest let downloadProvider = SDRequestProvider<DownloadApi>() enum DownloadApi { case download(DownloadDestination) } extension DownloadApi: SDRequestable { var baseURL: URL { return URL(string: "http://files.playplus.me")! } var path: String { return "/wk_vid_2c08d191d1e4457e94229ae5bd51a708" } var method: HttpMethod { return .get } var task: Task { switch self { case .download(let destination): return .download(DownloadType.request(destination)) } } }
true
0314274c72ea325656378df20f7038b6990f0e8e
Swift
CaryZheng/iOS-Examples
/Example-Audio/Example-Audio/ContentView.swift
UTF-8
3,612
2.984375
3
[]
no_license
// // ContentView.swift // Example-Audio // // Created by Cary on 2019/11/29. // Copyright © 2019 Cary. All rights reserved. // import SwiftUI struct ContentView: View { @State private var currentState = AudioState.none @State private var recordItems: [RecordItem] = [ // RecordItem(id: 1, title: "View 1"), // RecordItem(id: 2, title: "View 2"), // RecordItem(id: 3, title: "View 3") // RecordItem(id: 4, title: "View 4"), // RecordItem(id: 5, title: "View 5"), // RecordItem(id: 6, title: "View 6"), // RecordItem(id: 7, title: "View 7"), // RecordItem(id: 8, title: "View 8"), // RecordItem(id: 9, title: "View 9"), // RecordItem(id: 10, title: "View 10"), // RecordItem(id: 11, title: "View 11"), // RecordItem(id: 12, title: "View 12"), // RecordItem(id: 13, title: "View 13"), // RecordItem(id: 14, title: "View 14"), // RecordItem(id: 15, title: "View 15"), // RecordItem(id: 16, title: "View 16"), // RecordItem(id: 17, title: "View 17"), // RecordItem(id: 18, title: "View 18"), // RecordItem(id: 19, title: "View 19") ] var body: some View { VStack { Text("当前状态:\(currentState.getStateInfo())") .foregroundColor(Color.gray) List(recordItems, id: \.id) { item in HStack { Text("\(item.id) : " + item.title) .background(Color.red) Spacer() Button(action: { self.onItemPlayButtonClicked(item: item) }) { Text("播放") .foregroundColor(.blue) .font(.system(size: 14)) .padding(8) .overlay( RoundedRectangle(cornerRadius: 10) .stroke(Color.blue, lineWidth: 1) ) } } } HStack { MyButton(title: "开始录音", onButtonClicked: { self.currentState = .recording RecordManager.getInstance().setupRecorder() RecordManager.getInstance().startRecord() }) MyButton(title: "停止录音", onButtonClicked: { self.currentState = .stop RecordManager.getInstance().stopRecord() self.addItem() }) // MyButton(title: "播放录音", onButtonClicked: { // self.currentState = .playing // // RecordManager.getInstance().playRecord() // }) } } .frame(minWidth: 0, idealWidth: 0, maxWidth: .infinity, minHeight: 0, idealHeight: 0, maxHeight: .infinity, alignment: .top) } private func onItemPlayButtonClicked(item: RecordItem) { RecordManager.getInstance().playRecord(index: item.id-1) } private func addItem() { let path = RecordManager.getInstance().getRecordFilename() recordItems.append(RecordItem(id: recordItems.count+1, title: path)) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
true
410a40c6f130e6ee41dd57055f711f037a63f4e2
Swift
aoverholtzer/PlutoSwitcher
/Source/Extension/String+Spelling+Language.swift
UTF-8
1,928
3.0625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // String+Spelling+Language.swift // PlutoSwitcher // // Created by Mike Price on 22.04.2021. // import AppKit extension String { private static let cyrillicSymbols = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя" private static let englishSymbols = "abcdefghijklmnopqrstuvwxyz" private static let cyrillicQwertySymbols = Array("йцукенгшщзхъфывапролджэёячсмитьбю") private static let englishQwertySymbols = Array("qwertyuiop[]asdfghjkl;'\\zxcvbnm,.") var isCyrillic: Bool { removeCharacters(from: CharacterSet.letters.inverted) .allSatisfy({ String.cyrillicSymbols.contains($0.lowercased()) }) } var isEnglish: Bool { removeCharacters(from: CharacterSet.letters.inverted) .allSatisfy({ String.englishSymbols.contains($0.lowercased()) }) } var languageCode: String? { if isEnglish, !isCyrillic { return Locale.enRaw } else if isCyrillic, !isEnglish { return Locale.ruRaw } else { return nil } } var isReal: Bool { guard let language = languageCode else { return false } let checker = NSSpellChecker.shared checker.automaticallyIdentifiesLanguages = false guard checker.setLanguage(language) else { return false } return checker.checkSpelling(of: self, startingAt: 0).location == NSNotFound } func removeCharacters(from forbiddenChars: CharacterSet) -> String { String(self.unicodeScalars.filter({ !forbiddenChars.contains($0) })) } func translated(toRu: Bool) -> String { let fromArr = toRu ? String.englishQwertySymbols : String.cyrillicQwertySymbols let toArr = toRu ? String.cyrillicQwertySymbols : String.englishQwertySymbols return String(self.map { char in return fromArr.firstIndex(of: Character(char.lowercased())) .flatMap { ind in let newChar = toArr[ind] return Character(char.isUppercase ? newChar.uppercased() : newChar.lowercased()) } ?? char }) } }
true
83bcde059f012a810724a4e32e410d945e8ff1f0
Swift
Swoop12/OnyxTilt
/OnyxTilt/ModelControllers/CoreMotionController.swift
UTF-8
2,134
2.84375
3
[]
no_license
// // CoreMotionManager.swift // OnyxTilt // // Created by DevMountain on 4/11/19. // Copyright © 2019 trevorAdcock. All rights reserved. // import Foundation import UIKit.UIImpactFeedbackGenerator import CoreMotion protocol CoreMotionControllerDelegate: class { func deviceDidEnterSweetSpot() func deviceDidExitSweetSpot() func deviceDidUpdatePitch() } class CoreMotionController { //MARK: - Properties let motionManager = CMMotionManager() weak var delegate: CoreMotionControllerDelegate? var onSweetSpot: Bool = false let hapticGenerator = UIImpactFeedbackGenerator() var pitchInRadians: Double = 0{ didSet{ if phoneIsProperlyTilted{ if !onSweetSpot{ hapticGenerator.impactOccurred() onSweetSpot = true } delegate?.deviceDidEnterSweetSpot() }else { if onSweetSpot { hapticGenerator.impactOccurred() delegate?.deviceDidExitSweetSpot() onSweetSpot = false } } } } var pitchInDegrees: Double { get { return pitchInRadians.convertingRadiansToDegrees() } set { pitchInRadians = newValue.convertingDegreesToRadians() } } var phoneIsProperlyTilted: Bool { return pitchInDegrees > 65 && pitchInDegrees < 70 } func startDeviceMotion() { if motionManager.isDeviceMotionAvailable { let interval = 1.0 / 60 motionManager.deviceMotionUpdateInterval = interval motionManager.showsDeviceMovementDisplay = true motionManager.startDeviceMotionUpdates(using: .xMagneticNorthZVertical) Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { (_) in if let data = self.motionManager.deviceMotion { self.pitchInRadians = data.attitude.pitch self.delegate?.deviceDidUpdatePitch() } } } } }
true
50f9156101d8434213ff013d30766aeb61625b6e
Swift
VitorRodrigues/PokemonList-SwiftUI
/PokeList/PokelistViewModel.swift
UTF-8
2,310
3.03125
3
[]
no_license
// // PokelistViewModel.swift // PokeList // // Created by Vitor do Nascimento Rodrigues on 06/11/19. // Copyright © 2019 Vitor do Nascimento Rodrigues. All rights reserved. // import Foundation import Combine class PokeListViewModel: ObservableObject { @Published var pokemons: [Pokemon] = [] var disposables = Set<AnyCancellable>() func fetchList() { PokeService() .fetchPokemons() .map { response in response.pokemon } .receive(on: DispatchQueue.main) .sink(receiveCompletion: { [weak self] (value) in guard let self = self else { return } switch value { case .failure: self.pokemons = [] case .finished: break } }, receiveValue: { [weak self] list in guard let self = self else { return } self.pokemons = list }) .store(in: &disposables) } } struct PokedexResponse: Codable { var pokemon: [Pokemon] } enum PokemonError : Error{ case network(String) case parse(String) case api(Error) } protocol PokemonFetchable { func fetchPokemons() -> AnyPublisher<PokedexResponse, PokemonError> } class PokeService: PokemonFetchable { let contentUrl = "https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json" func fetchPokemons() -> AnyPublisher<PokedexResponse, PokemonError> { guard let url = URL(string: contentUrl) else { return Fail(error: PokemonError.network("Can't create URL")).eraseToAnyPublisher() } return URLSession.shared .dataTaskPublisher(for: url) .mapError { error in return PokemonError.api(error) } .flatMap(maxPublishers: .max(1)) { pair in return self.decode(pair.data) } .eraseToAnyPublisher() } func decode<T: Decodable>(_ data: Data) -> AnyPublisher<T, PokemonError> { let decoder = JSONDecoder() return Just(data) .decode(type: T.self, decoder: decoder) .mapError { error in return .parse(error.localizedDescription) } .eraseToAnyPublisher() } }
true
06fd37aab731bb0d5dbe81f533b1d4940b3fcd05
Swift
takasurazeem/MVP-C
/CoordinatorPattern/Coodrinator/ApplicationCoordinator.swift
UTF-8
780
2.59375
3
[]
no_license
// // ApplicationCoordinator.swift // CoordinatorPattern // // Created by Takasur Azeem on 7/26/21. // import UIKit class ApplicationCoordinator: Coordinator { private let window: UIWindow! private let rootNavigationController: UINavigationController! private let loginCoordinator: LoginCoordinator! init(window: UIWindow) { self.window = window self.rootNavigationController = UINavigationController() loginCoordinator = LoginCoordinator(navigationController: rootNavigationController) loginCoordinator.navigationController = rootNavigationController } func start() { window.rootViewController = rootNavigationController loginCoordinator.start() window.makeKeyAndVisible() } }
true
92cfaf0337e7c93e6a33cd3164e151ee007fbbaf
Swift
mrainka/just-currency
/JustCurrency/ExchangeRates/Item/Views/ExchangeRateView.swift
UTF-8
3,675
2.8125
3
[]
no_license
// // ExchangeRateView.swift // JustCurrency // // Created by Marcin Rainka on 19/04/2020. // Copyright © 2020 Marcin Rainka. All rights reserved. // import SnapKit import UIKit final class ExchangeRateView: CustomView { private(set) var model: ExchangeRateViewModel? // MARK: - Subviews private weak var stackView: UIStackView? private weak var substackView: UIStackView? private weak var separator: UIView? // MARK: Labels private weak var averageRateLabel: Label? private weak var purchaseRateLabel: Label? private weak var sellingRateLabel: Label? private weak var codeLabel: Label? private weak var effectiveDateLabel: Label? private weak var tradingDateLabel: Label? private weak var nameLabel: Label? // MARK: - override func configureLayout() { stackView?.snp.makeConstraints { $0.edges.equalToSuperview().inset(8) } separator?.snp.makeConstraints { $0.width.equalTo(CGFloat.pixel) } codeLabel?.snp.makeConstraints { $0.width.equalTo(50) } } // MARK: - Adding the Subviews override func addSubviews() { addStackView() addCodeLabel() addSeparator() addSubstackView() addNameLabel() averageRateLabel = addRateLabel() purchaseRateLabel = addRateLabel() sellingRateLabel = addRateLabel() effectiveDateLabel = addDateLabel() tradingDateLabel = addDateLabel() } private func addStackView() { let stackView = UIStackView(frame: .zero) stackView.spacing = 8 addSubview(stackView) self.stackView = stackView } private func addSubstackView() { let stackView = UIStackView(frame: .zero) stackView.axis = .vertical self.stackView?.addArrangedSubview(stackView) substackView = stackView } private func addSeparator() { let separator = UIView(frame: .zero) separator.backgroundColor = .opaqueSeparator stackView?.addArrangedSubview(separator) self.separator = separator } // MARK: Labels private func addCodeLabel() { let label = Label(frame: .zero) label.font = .boldSystemFont(ofSize: 21) label.textAlignment = .center stackView?.addArrangedSubview(label) codeLabel = label } private func addDateLabel() -> Label { let label = Label(frame: .zero) label.font = .systemFont(ofSize: 15) label.textColor = .tertiaryLabel substackView?.addArrangedSubview(label) return label } private func addNameLabel() { let label = Label(frame: .zero) label.font = .boldSystemFont(ofSize: 17) label.numberOfLines = 0 substackView?.addArrangedSubview(label) nameLabel = label } private func addRateLabel() -> Label { let label = Label(frame: .zero) label.font = .systemFont(ofSize: 15) label.textColor = .secondaryLabel substackView?.addArrangedSubview(label) return label } } extension ExchangeRateView: ConfigurableWithModel { func configure(with model: ExchangeRateViewModel) { self.model = model averageRateLabel?.configure(with: model.averageRate) purchaseRateLabel?.configure(with: model.purchaseRate) sellingRateLabel?.configure(with: model.sellingRate) codeLabel?.configure(with: model.code) effectiveDateLabel?.configure(with: model.effectiveDate) tradingDateLabel?.configure(with: model.tradingDate) nameLabel?.configure(with: model.name) separator?.isHidden = model.code.isHidden } }
true
9f53e5b7db47b98bbf8637fdd7aadf08a571b53a
Swift
subsub/Simple-Todo-MacOS
/Simple Todo/Views/Components/MyMenuButton.swift
UTF-8
1,705
3.515625
4
[]
no_license
// // MyMenuButton.swift // Simple Todo // // Created by Subkhan Sarif on 01/07/23. // import SwiftUI struct MyMenuButton: View { @State var isHovered: Bool = false @ViewBuilder var label: (_ isHovered: Bool) -> AnyView var callback: () -> Void var expanded: Bool = true var padding: EdgeInsets? init(expanded: Bool = true, padding: EdgeInsets? = EdgeInsets(top: 0, leading: 4, bottom: 0, trailing: 4), label: @escaping (_ isHovered: Bool) -> AnyView, callback: @escaping () -> Void) { self.label = label self.callback = callback self.expanded = expanded self.padding = padding } var body: some View { Button{ callback() } label: { HStack{ HStack { label(isHovered) .foregroundColor(isHovered ? ColorTheme.instance.staticWhite: ColorTheme.instance.textDefault) if expanded { Spacer() } }.padding(defaultPadding) .contentShape(Rectangle()) } } .background( isHovered ? .blue : .clear ) .cornerRadius(4) .padding(padding ?? EdgeInsets(top: 0, leading: 4, bottom: 0, trailing: 4)) .buttonStyle(.plain) .onHover { hovered in isHovered = hovered } } } struct MyMenuButton_Previews: PreviewProvider { static var previews: some View { MyMenuButton { _ in AnyView( Text("This is button") ) } callback: { } } }
true
461223a89922ccc590c45b4f143e30c543802caf
Swift
baquiax/ImageProcessor
/ImageProcessor.playground/Sources/Filters/Filter.swift
UTF-8
74
2.859375
3
[ "MIT" ]
permissive
public protocol Filter { func apply(image: RGBAImage) -> RGBAImage ; }
true
15c7d9af1f2611faf5f80947be34d902f10d08cf
Swift
weihengpan/Motif
/Motif/View/Sample List View/SampleListView.swift
UTF-8
5,099
2.796875
3
[ "MIT" ]
permissive
// // SampleListView.swift // Motif // // Created by Pan Weiheng on 2020/3/29. // import SwiftUI struct SampleListView: View { @EnvironmentObject var recorder: Recorder @State var editMode: EditMode = .inactive @State var isShowingShareActionSheet = false @State var isShowingShareActivitySheet = false @State var shareActivitySheetFileFormat: ShareSampleActivityView.FileFormat = .csv @State var selectedID = Set<UUID>() private var selectedSamples: [MotionDataSample] { var samples = [MotionDataSample]() for id in selectedID { if let index = recorder.samples.firstIndex(where: { $0.id == id }) { samples.append(recorder.samples[index]) } } return samples } // MARK: - Body var body: some View { NavigationView { List(selection: $selectedID) { ForEach(recorder.samples) { sample in NavigationLink(destination: SampleDetailView(sample: sample)) { SampleRow(sample: sample) .padding(.vertical) .contextMenu { Button(action: { self.selectedID = [sample.id] self.isShowingShareActivitySheet.toggle() self.shareActivitySheetFileFormat = .csv }) { Text("Share as CSV") } Button(action: { self.selectedID = [sample.id] self.isShowingShareActivitySheet.toggle() self.shareActivitySheetFileFormat = .json }) { Text("Share as JSON") } } } } .onDelete(perform: delete) .onMove(perform: move) } .listStyle(GroupedListStyle()) .navigationBarTitle("Samples") .navigationBarItems( leading: leadingItems.opacity(editMode == .active ? 1.0 : 0.0), trailing: EditButton() ) .sheet(isPresented: $isShowingShareActivitySheet, content: { ShareSampleActivityView(fileFormat: self.shareActivitySheetFileFormat, samples: self.selectedSamples) }) .environment(\.editMode, self.$editMode) } } // MARK: - Custom Views private var leadingItems: AnyView { AnyView(HStack { shareButton.padding(.trailing, 22) deleteButton }) } private var deleteButton: AnyView { if editMode == .inactive { return AnyView(Text("")) } else { return AnyView(Button(action: deleteRows) { Image(systemName: "trash") //.font(.system(size: 22)) .accentColor(.red) }) } } private var shareButton: AnyView { if editMode == .inactive { return AnyView(Text("")) } else { return AnyView(Button(action: { self.isShowingShareActionSheet.toggle() }) { Image(systemName: "square.and.arrow.up") //.font(.system(size: 22)) }.actionSheet(isPresented: $isShowingShareActionSheet, content: { self.shareActionSheet }) ) } } private var shareActionSheet: ActionSheet { ActionSheet(title: Text("Share sample as..."), message: nil, buttons: [ .default(Text("CSV")) { self.isShowingShareActivitySheet.toggle() self.shareActivitySheetFileFormat = .csv }, .default(Text("JSON")) { self.isShowingShareActivitySheet.toggle() self.shareActivitySheetFileFormat = .json }, .cancel() ]) } // MARK: - Methods private func delete(at offsets: IndexSet) { recorder.samples.remove(atOffsets: offsets) } private func deleteRows() { for id in selectedID { if let index = recorder.samples.firstIndex(where: { $0.id == id }) { recorder.samples.remove(at: index) } } selectedID = Set<UUID>() } private func move(from source: IndexSet, to destination: Int) { recorder.samples.move(fromOffsets: source, toOffset: destination) } } struct SamplesList_Previews: PreviewProvider { static var previews: some View { let recorder = Recorder() recorder.samples = MotionDataSample.previewSamples return SampleListView().environmentObject(recorder) } }
true
5b05ff1379a2c1d808190f7f6c825bf386202aa8
Swift
sturdysturge/SwiftUIColourPickerMaker
/Sources/ColourPickerMaker/19. BidirectionalDragModifier/BidirectionalDragModifier.swift
UTF-8
2,073
3.46875
3
[ "MIT" ]
permissive
// BidirectionalDragModifier.swift // ColourPickerMaker // // Created by Rob Sturgeon on 09/06/2020. // Copyright © 2020 Rob Sturgeon. All rights reserved. // // Released under the MIT license // https://sturdysturge.com/mit/ import SwiftUI extension View { /** A way to use BidirectionalDragModifier without using .modifier(BidirectionalDragModifier()) syntax - Parameters: - offset: The amount that the circular thumb is offset - xValue: The value based on horizontal position between 0 and 1 - yValue: The value based on vertical position between 0 and 1 - size: The size of the canvas - Returns: A View that has bidirectional dragging functionality */ func bidirectionalDrag(offset: Binding<CGPoint>, xValue: Binding<Double>, yValue: Binding<Double>, size: CGSize) -> some View { return modifier(BidirectionalDragModifier(offset: offset, xValue: xValue, yValue: yValue, size: size)) } } /// A modifier for dragging in two dimensions on CanvasView public struct BidirectionalDragModifier: ViewModifier { public init(offset: Binding<CGPoint>, xValue: Binding<Double>, yValue: Binding<Double>, size: CGSize) { maxX = size.width - 25 maxY = size.height - 25 _xValue = xValue _yValue = yValue _offset = offset } @Binding var offset: CGPoint @Binding var xValue: Double @Binding var yValue: Double let maxX: CGFloat let maxY: CGFloat public func body(content: Content) -> some View { content .gesture(DragGesture(minimumDistance: 0) .onChanged { value in self.offset.x = value.location.x .clampFromZero(to: self.maxX) self.offset.y = value.location.y .clampFromZero(to: self.maxY) self.xValue = Double(self.offset.x / self.maxX) .clampFromZero(to: 1) self.yValue = Double(self.offset.y / self.maxY) .clampFromZero(to: 1) }) } }
true
d94cbfa0967293b23b27255be2d1bf19f01ff70f
Swift
FultonG/List-App
/TechKnights/SecondViewController.swift
UTF-8
1,245
2.703125
3
[]
no_license
// // SecondViewController.swift // TechKnights // // Created by Fulton Garcia on 4/11/17. // Copyright © 2017 Fulton Garcia. All rights reserved. // import UIKit class SecondViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var nameTxt: UITextField! @IBOutlet weak var quantityTxt: UITextField! //the function that will be fired off by the save button @IBAction func saveBtn(_ sender: AnyObject) { //if the name textfield is not empty add the name and quantity to the array if(nameTxt.text != ""){ var num = Int(quantityTxt.text!) if(num == nil){ num = 1 } itemList.addItem(name: nameTxt.text!, quantity: num!) self.view.endEditing(true) //empty the textfields after adding the new item nameTxt.text = "" quantityTxt.text = "" } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
b57dde8efbadb6a5bef8b7e2cc085c6cf21a1b75
Swift
sauvikatinnofied/CoreDataPractice
/AlertTest/Model/Error/AppErrors.swift
UTF-8
4,080
3.078125
3
[]
no_license
// // AppErrors.swift // CoreDataPractice // // Created by Sauvik Dolui on 07/04/16. // Copyright © 2016 VSP Vision Care. All rights reserved. // import Foundation protocol AppError: ErrorType, CustomStringConvertible { var description: String {get} } enum CoreDataError: Int, AppError { // General Errors case PersistanceStoreLoadError case ManagedObjectContextSaveError // Department services Errors case DepartmentCreationError case DepartmentAlreadyExistError case DepartmentNotFoundError // User Services Errors case UserCreationError case UserAlreadyExistError case UserNotFoundError case UnKnownError func errorCode() -> Int { var errorCode = 5000 switch self { // -------------------------------- // GENERAL ERRORS // -------------------------------- case .PersistanceStoreLoadError: errorCode += CoreDataError.PersistanceStoreLoadError.rawValue case .ManagedObjectContextSaveError: errorCode += CoreDataError.ManagedObjectContextSaveError.rawValue // -------------------------------- // DEPARTMENT SERVICES ERROR // -------------------------------- case .DepartmentCreationError: errorCode += CoreDataError.DepartmentCreationError.rawValue case .DepartmentAlreadyExistError: errorCode += CoreDataError.DepartmentAlreadyExistError.rawValue case .DepartmentNotFoundError: errorCode += CoreDataError.DepartmentNotFoundError.rawValue // -------------------------------- // USER SERVICES ERROR // -------------------------------- case .UserCreationError: errorCode += CoreDataError.UserCreationError.rawValue case .UserAlreadyExistError: errorCode += CoreDataError.UserAlreadyExistError.rawValue case .UserNotFoundError: errorCode += CoreDataError.UserNotFoundError.rawValue // -------------------------------- // UNKNOWN ERROR // -------------------------------- case .UnKnownError: errorCode += CoreDataError.UnKnownError.rawValue } return errorCode } func errorString() -> String { var errorString = "CORE DATA ERROR: \(errorCode()) " switch self { // -------------------------------- // GENERAL ERRORS // -------------------------------- case .PersistanceStoreLoadError: errorString += "Persistance coordinator load error" case .ManagedObjectContextSaveError: errorString += "Managed object context save error" // -------------------------------- // DEPARTMENT SERVICES ERROR // -------------------------------- case .DepartmentCreationError: errorString += "Deptmenent creation error" case .DepartmentAlreadyExistError: errorString += "Deptmenent already exists" case .DepartmentNotFoundError: errorString += "Could not found department" // -------------------------------- // USER SERVICES ERROR // -------------------------------- case .UserCreationError: errorString += "User addition error" case .UserAlreadyExistError: errorString += "User already exists" case .UserNotFoundError: errorString += "Could not found user" // -------------------------------- // UNKNOWN ERROR // -------------------------------- case .UnKnownError: errorString += "Unknown error" } return errorString } var description: String {return "\(errorString())" } }
true
ff3b1632648d8ff69480c432f1b89f5d3de7efcb
Swift
Zaxeluz/CoolApp2.1
/Tabs/ViewControllers/Site.swift
UTF-8
507
2.9375
3
[]
no_license
// // Site.swift // Tabs // // Created by Alumno on 27/09/18. // Copyright © 2018 Alumno. All rights reserved. // import Foundation import UIKit class Site { var name : String var description : String var image : UIImage init() { name = "" description = "" image = UIImage() } init(name : String, description : String, image : UIImage) { self.name = name self.description = description self.image = image } }
true
7f2697aa16080d1c341b9763a8def32df9c2cdda
Swift
ikbalyasar/Corona
/corona/CoronaList/CoronaContract.swift
UTF-8
583
2.546875
3
[ "MIT" ]
permissive
// // CoronaContract.swift // corona // // Created by İkbal Yaşar on 30.03.2020. // Copyright © 2020 ikbSoft. All rights reserved. // import Foundation protocol CoronaViewModelProtocol { var delegate : CoronaViewModelDelegate? {get set} func load() func selectCity(indexpath:Int) } enum CoronaViewModelOutput { case setLoading(Bool) case showCoronaList([List]) } enum CoronaRoute { case detail } protocol CoronaViewModelDelegate : class { func handleViewModelOutput(_ output: CoronaViewModelOutput) func navigate(to route : CoronaRoute) }
true
4cd90f03da578c3b6efba37afeb8e69126351fdb
Swift
onlyAPK/algorithm014-algorithm014
/Week_02/Leetcode1.swift
UTF-8
533
2.828125
3
[]
no_license
// // Leetcode1.swift // week2 // // Created by DA WENG on 2020/8/18. // Copyright © 2020 DA WENG. All rights reserved. // import UIKit class Leetcode1: NSObject { func twoSum(_ nums: [Int], _ target: Int) -> [Int] { var dict:[Int:Int] = [:] for i in 0..<nums.count { let num = nums[i] let delt = target - num if dict.keys.contains(delt) && dict[delt] != i{ return [dict[delt]!,i] } dict[num] = i } return [] } }
true
b941c057170bc84c871b284ff49f42e613d68053
Swift
Omnicronical/swift-apps
/Tamagotchi App/Tamagotchi App/Tamagotchi.swift
UTF-8
1,896
3.265625
3
[]
no_license
// // statistics.swift // Tamagotchi App // // Created by Hassall, Oscar (HWTA) on 14/01/2020. // Copyright © 2020 Hassall, Oscar (HWTA). All rights reserved. // import Foundation class Tamagotchi { var name: String var age: Int var health: Int var hunger: Int var discipline: Int var weight: Int var death: Bool var numberOfPoos: Int var satiated: Bool { get { return hunger <= 0 } } init() { name = "Horatio" age = 0 health = 5 hunger = 5 discipline = 5 weight = 10 death = false numberOfPoos = 0 } func displayStats() -> String { return """ Name: \(name) Age: \(age) Health: \(health) Hunger: \(hunger) Discipline: \(discipline) Weight: \(weight) """ } @objc func ageUp() { age = age+1 } func healthDown() { health = health-1 if health <= 0 { deathByHealth() } } func eatSnack() { hunger = hunger-2 weight = weight+5 if weight > 100 { deathByOverweight() } } func eatMeal() { hunger = hunger-4 weight = weight+10 if weight > 100 { deathByOverweight() } } func disciplineUp() { discipline = discipline+10 } func disciplineDown() { discipline = discipline - 10 } func flush() { numberOfPoos = 0 } func poo() { numberOfPoos = numberOfPoos+1 } func deathByOverweight() { death = true } func deathByAge() { death = true } func deathByHealth() { death = true } }
true
ecc3f262103d0c95859d3a5ddc1d24f71cccfefd
Swift
uber/RIBs
/ios/RIBs/Classes/MultiStageComponentizedBuilder.swift
UTF-8
6,353
2.796875
3
[ "Apache-2.0" ]
permissive
// // Copyright (c) 2017. Uber Technologies // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// The base class of a builder that involves multiple stages of building /// a RIB. Witin the same pass, accesses to the component property shares /// the same instance. Once `finalStageBuild` is invoked, a new instance /// is returned from the component property, representing a new pass of /// the multi-stage building process. /// /// - SeeAlso: SimpleMultiStageComponentizedBuilder open class MultiStageComponentizedBuilder<Component, Router, DynamicBuildDependency>: Buildable { // Builder should not directly retain an instance of the component. // That would make the component's lifecycle longer than the built // RIB. Instead, whenever a new instance of the RIB is built, a new // instance of the DI component should also be instantiated. /// The DI component used for the current iteration of the multi- /// stage build process. Once `finalStageBuild` method is invoked, /// this property returns a separate new instance representing a /// new pass of the multi-stage building process. public var componentForCurrentBuildPass: Component { if let currentPassComponent = currentPassComponent { return currentPassComponent } else { let currentPassComponent = componentBuilder() // Ensure each invocation of componentBuilder produces a new // component instance. let newComponent = currentPassComponent as AnyObject if lastComponent === newComponent { assertionFailure("\(self) componentBuilder should produce new instances of component when build is invoked.") } lastComponent = newComponent self.currentPassComponent = currentPassComponent return currentPassComponent } } /// Initializer. /// /// - parameter componentBuilder: The closure to instantiate a new /// instance of the DI component that should be paired with this RIB. public init(componentBuilder: @escaping () -> Component) { self.componentBuilder = componentBuilder } /// Build a new instance of the RIB with the given dynamic dependency /// as the last stage of this mult-stage building process. /// /// - note: Subsequent access to the `component` property after this /// method is returned will result in a separate new instance of the /// component, representing a new pass of the multi-stage building /// process. /// - parameter dynamicDependency: The dynamic dependency to use. /// - returns: The router of the RIB. public final func finalStageBuild(withDynamicDependency dynamicDependency: DynamicBuildDependency) -> Router { let router = finalStageBuild(with: componentForCurrentBuildPass, dynamicDependency) defer { currentPassComponent = nil } return router } /// Abstract method that must be overriden to implement the RIB building /// logic using the given component and dynamic dependency, as the last /// building stage. /// /// - note: This method should never be invoked directly. Instead /// consumers of this builder should invoke `finalStageBuild(with dynamicDependency:)`. /// - parameter component: The corresponding DI component to use. /// - parameter dynamicDependency: The given dynamic dependency. /// - returns: The router of the RIB. open func finalStageBuild(with component: Component, _ dynamicDependency: DynamicBuildDependency) -> Router { fatalError("This method should be overridden by the subclass.") } // MARK: - Private private let componentBuilder: () -> Component private var currentPassComponent: Component? private weak var lastComponent: AnyObject? } /// A convenient base multi-stage builder class that does not require any /// build dynamic dependencies. /// /// - note: If the build method requires dynamic dependency, please /// refer to `MultiStageComponentizedBuilder`. /// /// - SeeAlso: MultiStageComponentizedBuilder open class SimpleMultiStageComponentizedBuilder<Component, Router>: MultiStageComponentizedBuilder<Component, Router, ()> { /// Initializer. /// /// - parameter componentBuilder: The closure to instantiate a new /// instance of the DI component that should be paired with this RIB. public override init(componentBuilder: @escaping () -> Component) { super.init(componentBuilder: componentBuilder) } /// This method should not be directly invoked. public final override func finalStageBuild(with component: Component, _ dynamicDependency: ()) -> Router { return finalStageBuild(with: component) } /// Abstract method that must be overriden to implement the RIB building /// logic using the given component. /// /// - note: This method should never be invoked directly. Instead /// consumers of this builder should invoke `finalStageBuild()`. /// - parameter component: The corresponding DI component to use. /// - returns: The router of the RIB. open func finalStageBuild(with component: Component) -> Router { fatalError("This method should be overridden by the subclass.") } /// Build a new instance of the RIB as the last stage of this mult- /// stage building process. /// /// - note: Subsequent access to the `component` property after this /// method is returned will result in a separate new instance of the /// component, representing a new pass of the multi-stage building /// process. /// - returns: The router of the RIB. public final func finalStageBuild() -> Router { return finalStageBuild(withDynamicDependency: ()) } }
true
d5a5e0151e5d3351fba68a9d45a172c3951418e2
Swift
manindertuli126/Group2_OnlineShopping
/ShoppingCart/ShoppingCart.swift
UTF-8
3,338
3.15625
3
[]
no_license
// // ShoppingCart.swift // Group2_OnlineShopping // // Created by Maninder Singh on 2019-02-17. // Copyright © 2019 MacStudent. All rights reserved. // import Foundation class ShoppingCart : UserDetails { var shoppingCartId : Int! var itemID : String? var exitMenu : Bool! var itemList = Array<String>() var osAndFeature = (OS:("iOS","Android"), SF:("Facial Recogination","Fingerprint Scanner")) // var apple = ["Iphone x","Apple",osAndFeature.OS.0,"5.8",osAndFeature.SF.0,"256"] func showListOfItems(){ itemList.append("1- Iphone X") itemList.append("2- Samsung S9") itemList.append("3- Mi MIX 3") itemList.append("4- Google Pixel 3") itemList.append("5- OnePlus 6T") itemList.append("6- Huawei Mate 10") itemList.append("7- Exit") repeat{ for v in itemList{ print(v) } let userSelectedItem = Int(readLine()!)! switch userSelectedItem{ case 1: print("\nProduct details \(itemList[0])- \nBrand: Apple \nOperating system: \(osAndFeature.OS.0) \nScreen size: 5.8 inches screen \nSecurity features: \(osAndFeature.SF.0) \nStorage capacity: 256 GB") self.itemID = "IPX" break case 2: print("\nProduct details \(itemList[1])- \nBrand: Samsung \nOperating system: \(osAndFeature.OS.1) \nScreen size: 5.8 inches screen \nSecurity features: \(osAndFeature.SF.0), \(osAndFeature.SF.1) \nStorage capacity: 128 GB") self.itemID = "S9" break case 3: print("\nProduct details \(itemList[2])- \nBrand: Xiaomi \nOperating system: \(osAndFeature.OS.1) \nScreen size: 6.3 inches screen \nSecurity features: \(osAndFeature.SF.1) \nStorage capacity: 64 GB") self.itemID = "MX3" break case 4: print("\nProduct details \(itemList[3])- \nBrand: Google \nOperating system: \(osAndFeature.OS.1) \nScreen size: 5.0 inches screen \nSecurity features: \(osAndFeature.SF.0), \(osAndFeature.SF.1) \nStorage capacity: 64 GB") self.itemID = "PI3" break case 5: print("\nProduct details \(itemList[4])- \nBrand: OnePlus \nOperating system: \(osAndFeature.OS.1) \nScreen size: 6.4 inches screen \nSecurity features: \(osAndFeature.SF.0), \(osAndFeature.SF.1) \nStorage capacity: 128 GB") self.itemID = "OP6" break case 6: print("\nProduct details \(itemList[5])- \nBrand: Huawei \nOperating system: \(osAndFeature.OS.1) \nScreen size: 6.0 inches screen \nSecurity features: \(osAndFeature.SF.0) \nStorage capacity: 256 GB") self.itemID = "HM10" break case 7: exitMenu = false break default: print("Invalid option selected.\n") } if userSelectedItem <= 6{ exitMenu = addToCart() } }while(exitMenu) } func addToCart() -> Bool{ print("\nAdd to Cart? (Y/N)") let addToCart = readLine()!.lowercased() if addToCart == "y"{ print("Product successfully added to cart. Please select the quantity of product.") return false //quantity }else{ return true } } }
true
ef342fc3998d5405acad0ce22846e8c915a5e472
Swift
sachinpatra/XebiaWeather
/Weather/Weather/WeatherView.swift
UTF-8
5,723
3.125
3
[]
no_license
// // WeatherView.swift // Weather // // Created by Sachin Kumar Patra on 6/14/20. // Copyright © 2020 Sachin Kumar Patra. All rights reserved. // import SwiftUI import Alamofire struct Weather: Identifiable, Hashable { let id: String = UUID().uuidString var name: String var tempMax: String var tempMin: String var des: String var windSpeed: String var date: Date = Date() var dateTime: Date = Date() } struct WeatherView: View { // @State private var citiNames: String = "Bengaluru,Kolkata,Mumbai" @State private var citiNames: String = "" @State var searchResults: [Weather] = [] var body: some View { VStack(spacing: 50.0) { VStack(spacing: 20.0) { TextField("Enter City Names", text: $citiNames) .textFieldStyle(RoundedBorderTextFieldStyle()) .multilineTextAlignment(.center) Button(action: { let queryList = self.citiNames.replacingOccurrences(of: " ", with: "").components(separatedBy: ",") guard (queryList.count >= 3) && (queryList.count <= 7) else { Weatherutility.showAlert(withMessage: "You have to enter atlest 3 and atmost 7 citi names") return } self.searchResults = [] queryList.forEach { (cityName) in AF.request("https://api.openweathermap.org/data/2.5/weather?q=\(cityName)&appid=2a1bf90981e862dd82a3943a6df7f2d8", method: .get, parameters: nil).responseJSON { (response) in switch response.result { case .success(let value): var data: [String: String] = [:] if let result = value as? [String: Any] { if let message = result["message"] as? String, message == "city not found" { Weatherutility.showAlert(withMessage: message) return } else if let message = result["message"] as? String, message == "Nothing to geocode" { Weatherutility.showAlert(withMessage: message) return } if let name = result["name"] as? String { data["name"] = name } if let main = result["main"] as? [String: Any] { if let tempMax = main["temp_max"] as? Double { data["temp_max"] = "\(tempMax)" } if let tempMin = main["temp_min"] as? Double { data["temp_min"] = "\(tempMin)" } } if let wet = result["weather"] as? [[String: Any]], let weather = wet.first, let des = weather["description"] as? String { data["weth_des"] = des } if let wind = result["wind"] as? [String: Any], let speed = wind["speed"] as? Double { data["wind_speed"] = String(speed) } self.searchResults.append(Weather(name: data["name"]!, tempMax: data["temp_max"]!, tempMin: data["temp_min"]!, des: data["weth_des"]!, windSpeed: data["wind_speed"]!)) } case .failure(let error): print(error.localizedDescription) } } } }) { Text("Submit") .padding() } .background( RoundedRectangle(cornerRadius: 10) .stroke(Color(.systemBlue), lineWidth: 1) ) } List { ForEach(searchResults) { (weather) in Section(header: Text(weather.name)) { HStack { Text("Temperature") Spacer() Text("Max: \(weather.tempMax)").foregroundColor(.secondary) Text("Max: \(weather.tempMin)").foregroundColor(.secondary) } HStack { Text("Weather") Spacer() Text(weather.des).foregroundColor(.secondary) } HStack { Text("Wind Speed") Spacer() Text(weather.windSpeed).foregroundColor(.secondary) } } } } } .padding() } } struct WeatherView_Previews: PreviewProvider { static var previews: some View { WeatherView() } }
true
1fb9b691d6ff80ca9191c0077e82d261f316352c
Swift
bwork35/tipCalculator
/tipCalculator/TipCalculator/Views/Custom UI/Custom TextField/CalcTextField.swift
UTF-8
1,089
2.625
3
[]
no_license
// // CalcTextField.swift // TipCalculator // // Created by Bryan Workman on 7/6/20. // Copyright © 2020 Bryan Workman. All rights reserved. // import UIKit class CalcTextField: UITextField { override func awakeFromNib() { super.awakeFromNib() setupViews() } func setupViews() { setupPlaceholderText() updateFontTo(font: FontNames.latoRegular) self.addCornerRadius(radius: 10) self.addAccentBorder() self.textColor = .mainText self.backgroundColor = .lighterBlue self.layer.masksToBounds = true } func setupPlaceholderText() { let currentPlaceholder = self.placeholder self.attributedPlaceholder = NSAttributedString(string: currentPlaceholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: UIColor.subtleText, NSAttributedString.Key.font: UIFont(name: FontNames.latoLight, size: 16)!]) } func updateFontTo(font: String) { guard let size = self.font?.pointSize else {return} self.font = UIFont(name: font, size: size) } }
true
1f63ab2ff0b97f30b4e89a8dd4d6f6db9b3074a7
Swift
RodrigoLGuimaraes/unit-testing-ios
/quickNimbleTests/Calculator/ResultViewController.swift
UTF-8
2,012
2.734375
3
[]
no_license
// // ResultViewController.swift // quickNimbleTests // // Created by Rodrigo Longhi Guimarães on 30/08/18. // Copyright © 2018 Rodrigo Longhi Guimarães. All rights reserved. // import UIKit class ResultViewController: UIViewController { @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var resultValueLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var iconView: UIImageView! var totalSingleValue: Double var totalInstallmentsValue: Double init(totalSingleValue: Double, totalInstallmentsValue: Double) { self.totalSingleValue = totalSingleValue self.totalInstallmentsValue = totalInstallmentsValue super.init(nibName: String(describing: "ResultViewController"), bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { self.configureViews() } func configureViews() { let difference = (self.totalSingleValue - totalInstallmentsValue) let moneyEarned = difference.magnitude self.resultValueLabel.text = "Você vai economizar R$\(moneyEarned.format(f: ".2"))" if difference < 0 { self.resultLabel.text = "Pague a vista!" self.descriptionLabel.text = "Se você pagar parcelado e aplicar o valor a vista, vão faltar \(moneyEarned.format(f: ".2")) reais na hora de pagar as parcelas." iconView.image = UIImage(named: "money") } else { self.resultLabel.text = "Pague parcelado!" self.descriptionLabel.text = "Se você pagar parcelado e aplicar o valor a vista, vão sobrar \(moneyEarned.format(f: ".2")) reais após pagar as parcelas." iconView.image = UIImage(named: "card") } } @IBAction func dismiss(_ sender: Any) { self.dismiss(animated: true, completion: nil) } }
true
5c361f0a75a5a28778d0f543ca14fe842bcf1d37
Swift
qaze/FlickrEye
/FlickrEye/Networking/ApiClient/URLSessionClient.swift
UTF-8
1,962
2.765625
3
[]
no_license
// // URLSessionClient.swift // FlickrEye // // Created by Nik Rodionov on 24.07.2021. // import Foundation import Combine class URLSessionClient<NetworkDecoder: TopLevelDecoder>: ApiClient where NetworkDecoder.Input == Data { private let session: URLSession private let apiKey: String private let decoder: NetworkDecoder private let baseURL: URL init( session: URLSession, apiKey: String, decoder: NetworkDecoder, baseURL: URL ) { self.session = session self.apiKey = apiKey self.decoder = decoder self.baseURL = baseURL } private func map(request: Request) -> URLRequest? { var components = URLComponents( url: baseURL.appendingPathComponent(request.path), resolvingAgainstBaseURL: true ) components?.queryItems = request.queryItems + [.init(name: "api_key", value: apiKey)] guard let url = components?.url else { return nil } var result = URLRequest(url: url) result.httpBody = request.body result.httpMethod = request.type.rawValue return result } func perform<ResultModel: Decodable>(request: Request) -> AnyPublisher<ResultModel, Error> { guard let urlRequest = map(request: request) else { return Fail(error: ApiClientError.wrongRequest(request)) .eraseToAnyPublisher() } return session .dataTaskPublisher(for: urlRequest) .tryMap { element in guard let httpResponse = element.response as? HTTPURLResponse, httpResponse.statusCode == 200 else { throw URLError(.badServerResponse) } return element.data } .decode(type: ResultModel.self, decoder: decoder) .eraseToAnyPublisher() } func download(url: URL) -> AnyPublisher<Data?, Error> { session .dataTaskPublisher(for: url) .tryMap { element in guard let httpResponse = element.response as? HTTPURLResponse, httpResponse.statusCode == 200 else { throw URLError(.badServerResponse) } return element.data } .eraseToAnyPublisher() } }
true
17ff2a77c8d41035dc93d00fe6bd30f55a766fda
Swift
HellocsWorld/Spyapp
/SpyApp/CeaserCipher.swift
UTF-8
4,457
3.703125
4
[]
no_license
//Author: Raul A Serrano Hernandez //CSC 690 //Spyapp to encrypt and decrept messages import Foundation protocol Cipher { func encode(_ plaintext: String, secret: String) -> String? func decode(_ txt: String, msg: String) -> String? } //alphanumeric cipher struct alphanumericCesarCipher: Cipher { let char = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] //function to encrypt the message func encode(_ plaintext: String, secret: String) -> String? { let charact = plaintext.uppercased() guard let shiftby = Int(secret) else { return nil } if shiftby == 0 { return charact } var encoded = "" var count: Int = 0 for character in charact { count = 0 for index in char { if index == String(character) { //go back to 0 if greater than 0 if count + shiftby > 35 { count = (count + shiftby) - 36 break } //go back to Z if less than 0 else if count + shiftby < 0 { count = (count + shiftby) + 36 break } else{ count = count + shiftby break } }else if index != String(character) && count == 36 { break } else { count = count + 1 } } if count != 36 { //append new character to string encoded = encoded + String(char[count]) } } return encoded } //function to decrypt ther message func decode(_ txt: String, msg: String) -> String? { //convert the string to uppercase letters only let charact = txt.uppercased() guard let shiftby = Int(msg) else { return nil } if shiftby == 0 { return charact } var decoded = "" var count: Int = 0 for character in charact { count = 0 for index in char { if index == String(character) { //if value is greater than 35 go back to 0 if count - shiftby > 35 { count = (count - shiftby) - 36 break } //if value is less than 0 go back to 35 or Z else if count - shiftby < 0 { count = (count - shiftby) + 36 break } else{ count = count - shiftby break } }else if index != String(character) && count == 36{ break }else{ count = count + 1 } } if count != 36 { decoded = decoded + String(char[count]) } } return decoded } } struct CeaserCipher: Cipher { //function to encrypt the message func encode(_ plaintext: String, secret: String) -> String? { var encoded = "" guard let shiftBy = UInt32(secret) else { return nil } for character in plaintext { let unicode = character.unicodeScalars.first!.value let shiftedUnicode = unicode + shiftBy let shiftedCharacter = String(UnicodeScalar(UInt8(shiftedUnicode))) encoded = encoded + shiftedCharacter } return encoded } //function to decrypt the message func decode(_ txt: String, msg: String) -> String? { var decoded = "" guard let shiftBack = UInt32(msg) else { return nil } for char in txt { let unicode = char.unicodeScalars.first!.value let backShiftUnicode = unicode - shiftBack let shiftChar = String(UnicodeScalar(UInt8(backShiftUnicode))) decoded = decoded + shiftChar } return decoded } }
true
6ff459c9e5c5d556b6dad8e5a20aa69d8b9789ac
Swift
TiagoSantosSilva/Listenr
/NetworkingKit/NetworkingKit/Models/DiskWrappedData.swift
UTF-8
322
2.6875
3
[]
no_license
// // DiskWrappedData.swift // NetworkingKit // // Created by Tiago Silva on 26/10/2020. // import Foundation final class DiskWrappedData: Codable { let data: Data let creationTime: Int init(data: Data) { self.data = data self.creationTime = Int(Date().timeIntervalSince1970) } }
true
ff2b25d469ae7d506e8a394586c208008e8e1d29
Swift
DanielSwift1992/Steam
/Frameworks/Services/Services/Managers/BackgroundWorkInteractor/BackgroundWorkInteractor.swift
UTF-8
5,338
2.578125
3
[]
no_license
import UIKit public final class BackgroundWorkManager: NSObject { // MARK: - Constants private enum Constants { static let timerInterval: TimeInterval = 10 } // MARK: - Properties public static let shared = BackgroundWorkManager() // MARK: - Pivate Properties private let storage = AchivementsHistoryStorage() private let recentrlyPlayedService = RecentlyPlayedGamesService() private let friendListService = FriendListService() private let achivementForGameService = PlayerAchivementForGameService() private let semaphore = DispatchSemaphore(value: 1) private var historyItemIDs = [String]() private var isRequestInProcess = false private var onComplited: ((UIBackgroundFetchResult) -> Void)? } // MARK: - Actions private extension BackgroundWorkManager { @objc func fetchData() { setHistoryItemsIfEmpty() guard !isRequestInProcess, let steamId = historyItemIDs.first else { onComplited?(.noData) return } isRequestInProcess = true recentrlyPlayedService.getGames(steamId: steamId) { self.handleGameFetching(steamId: steamId, result: $0) } } } // MARK: - Methods public extension BackgroundWorkManager { func start(completion: @escaping (UIBackgroundFetchResult) -> Void) { self.onComplited = completion fetchData() } func start() { DispatchQueue.global(qos: .background).async { self.setTimer() } } } // MARK: - Private Methods private extension BackgroundWorkManager { func setTimer() { let timer = Timer.scheduledTimer(timeInterval: Constants.timerInterval, target: self, selector: #selector(fetchData), userInfo: nil, repeats: true) let runLoop = RunLoop.current runLoop.add(timer, forMode: .default) runLoop.run() } func setHistoryItemsIfEmpty() { guard historyItemIDs.count <= 1, let currentUser = storage.getCurrentUser() else { return } semaphore.wait() historyItemIDs = ([currentUser.steamId] + currentUser.friends.map(\.steamId)) .compactMap { storage.getOrCreatePlayerHistory(steamId: $0) } .sorted(by: \.lastUpdated) .map(\.steamId) semaphore.signal() uploadFriendsIfNeeded() } func uploadFriendsIfNeeded() { guard historyItemIDs.count <= 1 else { return } friendListService.uploadCurrentUserFriends() { _ in self.fetchData() } } func handleGameFetching(steamId: String, result: Result<[Game], Error>) { guard steamId == historyItemIDs.first, let historyEntry = storage.getOrCreatePlayerHistory(steamId: steamId), let games = try? result.get() else { updateIsFinished(steamId: steamId, result: .noData) return } let gamesToUpdate = games.filter { gameItem in let playedTime = historyEntry.totalPlayed.first { $0.appId == gameItem.appId }?.time return playedTime != 0 && playedTime != gameItem.playTime } update(games: gamesToUpdate, for: steamId) } func update(games: [Game], for steamId: String) { guard !games.isEmpty else { updateIsFinished(steamId: steamId, result: .noData) return } let group = DispatchGroup() games.forEach { gameItem in update(steamId: steamId, appId: gameItem.appId, group: group) { result in guard let achivements = try? result.get() else { return } self.storage.save(steamId: steamId, appId: gameItem.appId, achivements: achivements.map(\.name)) } } group.notify(queue: .global(qos: .background)) { self.update(steamId: steamId, with: games) } } func update(steamId: String, appId: Int, group: DispatchGroup, completion: @escaping BaseCompletion<[PlayerAchivementEntry]>) { achivementForGameService.getAchivements(steamId: steamId, appId: appId, completion: group.wrap(completion)) } func update(steamId: String, with games: [Game]) { storage.updateHistoryEntry(steamId: steamId, with: games) updateIsFinished(steamId: steamId, result: .newData) } func updateIsFinished(steamId: String, result: UIBackgroundFetchResult) { putDownHistoryItem() onComplited?(result) onComplited = nil isRequestInProcess = false guard .newData != result else { return } storage.setUpdatedPlayerHistory(steamId: steamId) } func putDownHistoryItem() { semaphore.wait() let item = historyItemIDs.removeFirst() historyItemIDs.append(item) semaphore.signal() } }
true
ecaa80252c6452cb3e4440747aba97d0a0ef6d08
Swift
npage-ho/npagelibraryios
/NpageLibrary/Classes/Libraries/LoadingIndicator/NPLoadingIndicator.swift
UTF-8
2,395
2.578125
3
[ "MIT" ]
permissive
// // NPLoadingIndicator.swift // FBSnapshotTestCase // // Created by Cheolho on 2018. 8. 9.. // import UIKit public class NPLoadingIndicator: UIView { @IBOutlet weak var viewBg: UIView! @IBOutlet weak var lcLeading: NSLayoutConstraint! @IBOutlet weak var lcTop: NSLayoutConstraint! var arrayKey = Array<String>() public static let shared: NPLoadingIndicator = .fromNib() init() { super.init(frame: UIScreen.main.bounds) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func awakeFromNib() { super.awakeFromNib() viewBg.layer.cornerRadius = 10 viewBg.clipsToBounds = true let screenFrame = UIScreen.main.bounds lcLeading.constant = (screenFrame.size.width - viewBg.frame.size.width) / 2 lcTop.constant = (screenFrame.size.height - viewBg.frame.size.height) / 2 UIView.animate(withDuration: 0) { self.layoutIfNeeded() } } public func show(target: UIViewController, key: String?) { let topViewController = NPUtil.topViewControllerWithRootViewController(rootViewController: target) var isHasIndicator = false for view in (topViewController?.view.subviews)! { if view is NPLoadingIndicator { isHasIndicator = true topViewController?.view.bringSubview(toFront: NPLoadingIndicator.shared) break } } if isHasIndicator == false { topViewController?.view.addSubview(NPLoadingIndicator.shared) } if key != nil { arrayKey.append(key!) } DispatchQueue.main.async { self.isHidden = false } } public func hide(key: String?) { if key != nil { if arrayKey.contains(key!) { if let index = arrayKey.index(of: key!) { arrayKey.remove(at: index) } if arrayKey.count == 0 { DispatchQueue.main.async { self.isHidden = true } } } } else { DispatchQueue.main.async { self.isHidden = true } } } }
true
d1e589450413595aee8156db94ea8a9832b4f188
Swift
gudkesh19/FloodfillDemo
/FloodfillDemo/CameraViewController.swift
UTF-8
2,945
2.5625
3
[]
no_license
// // CameraViewController.swift // FloodfillDemo // // Created by Gudkesh Kumar on 22/11/18. // Copyright © 2018 Gudkesh Kumar. All rights reserved. // import UIKit import AVFoundation protocol CameraViewControllerDelegate: class { func didCapture(_ image: UIImage) } class CameraViewController: ViewController { let cameraManager = CameraManager() weak var delegate: CameraViewControllerDelegate? @IBOutlet fileprivate var captureButton: UIButton! @IBOutlet fileprivate var capturePreviewView: UIView! @IBOutlet fileprivate var toggleCameraButton: UIButton! override func viewDidLoad() { super.viewDidLoad() styleCaptureButton() requestCameraAccess() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func requestCameraAccess() { let status = AVCaptureDevice.authorizationStatus(for: .video) switch status { case .notDetermined: AVCaptureDevice.requestAccess(for: .video) {[weak self] (granted) in if granted { self?.configureCameraManager() } else { print("Permission denied") } } case .restricted, .denied: print("Enable camera access in settings to capture photos") case .authorized: configureCameraManager() } } deinit { print("Camera viewController deallocated") } } extension CameraViewController { private func styleCaptureButton() { captureButton.layer.borderColor = UIColor.black.cgColor captureButton.layer.borderWidth = 2 captureButton.layer.cornerRadius = min(captureButton.frame.width, captureButton.frame.height) / 2 } private func configureCameraManager() { cameraManager.prepareCamera {[weak self](error) in if let error = error { print(error) } try? self?.cameraManager.addCameraPreview(on: (self?.capturePreviewView)!) } } } extension CameraViewController { @IBAction func closeCamera() { self.dismiss(animated: true, completion: nil) } @IBAction func switchCameras(_ sender: UIButton) { do { try cameraManager.switchCamera() } catch { print(error) } } @IBAction func captureImage(_ sender: UIButton) { cameraManager.capturePhoto {(image, error) in guard let image = image else { print(error ?? "Image capture error") return } if let delegate = self.delegate { delegate.didCapture(image) self.dismiss(animated: true, completion: nil) } } } }
true
d70e4e75005238c0a05c1e776ced942633b13335
Swift
firots/Hotshot-IOS
/Hotshot/ViewModels/CollectionViewCells/CollectionViewCellModel.swift
UTF-8
437
2.515625
3
[]
no_license
// // CollectionViewCellModelBase.swift // Hotshot // // Created by Firot on 18.10.2019. // Copyright © 2019 Firot. All rights reserved. // import Foundation protocol CollectionViewCellModel { var style: CollectionViewCellModelTypes { get } var nameTag: String { get set } var selectAction: (() -> Void)? { get set } var selectable: Bool { get set } } enum CollectionViewCellModelTypes { case selectedPhoto }
true
ec047add4fdf6e12d516ee6a35a94d7312f18988
Swift
AamirAnwar/watchdog-iOS
/animalhelp/animalhelp/Account Page/ContributeViewController.swift
UTF-8
2,691
2.890625
3
[ "MIT" ]
permissive
// // ContributeViewController.swift // animalhelp // // Created by Aamir on 20/01/18. // Copyright © 2018 AamirAnwar. All rights reserved. // import Foundation class ContributeViewController:BaseViewController { let tableView = UITableView(frame: CGRect.zero, style: .plain) let kCellReuseID = "ContributeCellReuseIdentifier" var tableData:[(title:String, detailText:String)] { get { var data = [(title:String, detailText:String)]() data += [("Spreading the word", "Letting people know that they can use this platform in a time of need can help speed up the process of finding missing pets. The more people aware, the more chances of the pet being found.")] data += [("Helping catalog and verifying help centers", "Writing to us about how good a clinic is can really help in not just finding the nearest clinic to you but also helps us factor in the quality of service.")] data += [("Sending stories and feedback","The more feedback we get the more we can do better, if you see something amiss or any improvements it would mean the world to us if you could let us know.")] return data } } override func viewDidLoad() { super.viewDidLoad() self.customNavBar.setTitle("How to help") self.view.addSubview(self.tableView) self.tableView.snp.makeConstraints { (make) in make.top.equalTo(self.customNavBar.snp.bottom) make.leading.equalToSuperview() make.trailing.equalToSuperview() make.bottom.equalToSuperview() } self.tableView.delegate = self self.tableView.dataSource = self self.tableView.separatorStyle = .none self.tableView.tableFooterView = UIView(frame:CGRect.zero) self.tableView.register(ListItemDetailTableViewCell.self, forCellReuseIdentifier: self.kCellReuseID) } } extension ContributeViewController:UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: self.kCellReuseID) as! ListItemDetailTableViewCell cell.setTitleFont(CustomFontBodyMedium) let (title,subtitle) = tableData[indexPath.row] cell.setTitle(title, subtitle: subtitle) if indexPath.row < self.tableData.count - 1 { cell.showBottomPaddedSeparator() } return cell } }
true
ef667d2a3a9d3e7ffbd0a96afc318d880c217baf
Swift
azimin/Alexander-Zimin
/Alexander Zimin/Alexander Zimin/Source/Model/Parsers/EducationParser.swift
UTF-8
1,129
2.796875
3
[]
no_license
// // EducationParser.swift // Alexander Zimin // // Created by Alex Zimin on 26/04/15. // Copyright (c) 2015 Alex Zimin. All rights reserved. // import Foundation class EducationParser { fileprivate struct Keys { static var infoNameKey = "name" static var infoDescriptionKey = "description" } static var education: [[InfoItem]] = EducationParser.loadEducationInfo() fileprivate class func loadEducationInfo() -> [[InfoItem]] { var result: [[InfoItem]] = [] let arr = NSArray(contentsOfFile: Bundle.main.path(forResource: "Education", ofType: "plist")!)! for educationCategoryArray in arr as! [NSArray] { var localResult: [InfoItem] = [] for additionalInfoItem in educationCategoryArray as! [NSDictionary] { let projectInfo = InfoItem(name: additionalInfoItem.parse(Keys.infoNameKey), description: additionalInfoItem.parse(Keys.infoDescriptionKey)) localResult.append(projectInfo) } result.append(localResult) } return result } }
true
ab8c306577b765f40aee1080c1a23c41149ef22a
Swift
tymate/tymate-swift-extensions
/TymateSwiftExtensions/UIImageViewExtensions.swift
UTF-8
1,070
2.859375
3
[ "MIT" ]
permissive
// // UIImageViewExtensions.swift // TymateSwiftExtensions // // Created by Simon on 11/07/2019. // Copyright © 2019 Tymate. All rights reserved. // import Foundation import Kingfisher public extension UIImageView { func loadImage(withUrl url: String?, andPlaceHolder placeHolder: UIImage? = nil, preloadWithPlaceHolder: Bool = true) { if preloadWithPlaceHolder { self.image = placeHolder ?? UIImage(named: "placeholder") } guard let urlString = url, let url = URL(string: urlString) else { self.image = placeHolder ?? UIImage(named: "placeholder") return } let resource = ImageResource(downloadURL: url, cacheKey: url.path) self.kf.setImage(with: resource, placeholder: placeHolder) } func designRounded(radius: Int) { self.layer.cornerRadius = CGFloat(radius) self.layer.masksToBounds = true } func designCircle() { self.layer.cornerRadius = self.frame.height / 2 self.layer.masksToBounds = true } }
true
3f3672575ca61cfe0cff48a2b6e12ee51a50fe56
Swift
cameronac/ToDo
/ToDo/Models/Section.swift
UTF-8
6,071
3.03125
3
[]
no_license
// // Section.swift // ToDo // // Created by Cameron Collins on 5/21/20. // Copyright © 2020 iOS BW. All rights reserved. // import UIKit class Section { //MARK: - Properties public var name: String //Section Name public var isCollapsed: Bool //Section Collapsed? public var tasks: [Task?] //Tasks for this Section public var isViewSet: Bool = false //Did we setup the views public var delegate: TaskTableViewController //Delegate used for adding targets for the buttons public var viewColor: UIColor = UIColor.systemGray { //Assigns the new Color when set willSet { guard let view = view else { print("Bad View when trying to assign color! \(#file) \(#function) \(#line)") return } view.backgroundColor = newValue } } public var colorIndex = 2 //Used to find colors by their index in ColorController public var sectionIndex: Int { //When section index is assigned set their tags willSet { //Adding Button Tags button.tag = newValue colorButton.tag = newValue deleteButton.tag = newValue } } //View Objects public var view: UIView? = nil //Public since we need to return it as a tableView header private let label = UILabel() private let button = UIButton() private let colorButton = UIButton() private let deleteButton = UIButton() private let stackView = UIStackView() //MARK: - Initializer init(name: String, tasks: [Task], isCollapsed: Bool = false, taskTableView: TaskTableViewController, sectionIndex: Int) { self.name = name self.tasks = tasks self.isCollapsed = isCollapsed self.delegate = taskTableView self.sectionIndex = sectionIndex self.setupView() } //MARK: - Methods ///Sets up the header view with the appropriate colors and buttons in a stackView private func setupView() { //Adding Button Tags button.tag = sectionIndex colorButton.tag = sectionIndex deleteButton.tag = sectionIndex //Create View view = UIView(frame: CGRect(x: 0, y: 0, width: delegate.tableView.frame.width, height: TaskTableViewController.headerHeight)) //Unwrapping guard let view = view else { print("Bad View in Section!") return } //Setting Up Properties view.backgroundColor = viewColor //Set StackView Properties stackView.spacing = 5 stackView.alignment = .center stackView.distribution = .fillProportionally stackView.axis = .horizontal stackView.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(button) stackView.addArrangedSubview(colorButton) stackView.addArrangedSubview(deleteButton) //Set Button Properties button.tintColor = .white button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("\(name)", for: .normal) button.contentHorizontalAlignment = .leading button.isUserInteractionEnabled = true //Set ColorButton colorButton.setTitle("", for: .normal) colorButton.setImage(UIImage(systemName: "paintbrush.fill"), for: .normal) colorButton.translatesAutoresizingMaskIntoConstraints = false colorButton.tintColor = UIColor.white colorButton.isUserInteractionEnabled = true //Set DeleteButton deleteButton.setTitle("", for: .normal) deleteButton.setImage(UIImage(systemName: "trash.fill"), for: .normal) deleteButton.translatesAutoresizingMaskIntoConstraints = false deleteButton.tintColor = UIColor.white deleteButton.isUserInteractionEnabled = true view.addSubview(stackView) //Setting up Button Constraints let stackViewXC = NSLayoutConstraint(item: stackView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0) let stackViewYC = NSLayoutConstraint(item: stackView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0) let stackViewWC = NSLayoutConstraint(item: stackView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1.0, constant: 0) let stackViewWH = NSLayoutConstraint(item: stackView, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1.0, constant: 0) NSLayoutConstraint.activate([stackViewXC, stackViewYC, stackViewWC, stackViewWH]) //Setting up Button Constraints let buttonXC = NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: stackView, attribute: .leading, multiplier: 1.0, constant: 15) NSLayoutConstraint.activate([buttonXC]) //Setting up colorButton Constraints let colorButtonWH = NSLayoutConstraint(item: colorButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: 50) NSLayoutConstraint.activate([colorButtonWH]) //Setting up deleteButton Constraints let deleteButtonWH = NSLayoutConstraint(item: deleteButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: 50) NSLayoutConstraint.activate([deleteButtonWH]) //Adding Target button.addTarget(delegate, action: #selector(delegate.sectionButtonPressed(sender:)), for: .touchUpInside) colorButton.addTarget(delegate, action: #selector(delegate.sectionColorButtonPressed(sender:)), for: .touchUpInside) deleteButton.addTarget(delegate, action: #selector(delegate.sectionDeleteButtonPressed(sender:)), for: .touchUpInside) isViewSet = true } }
true
eb23e33a151d22196bd3582789d9588ee14d433b
Swift
Jthornburg1/MovieSearchDisplay
/MovieBrowser/Source/Network/Network.swift
UTF-8
2,054
2.84375
3
[]
no_license
// // Network.swift // SampleApp // // Created by Struzinski, Mark - Mark on 9/17/20. // Copyright © 2020 Lowe's Home Improvement. All rights reserved. // import UIKit class Network { let apiKey = "5885c445eab51c7004916b9c0313e2d3" static func fetch(from queryString: String, completion: @escaping ([Movie], Error?) -> Void) { guard let encodedQuery = queryString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return } let urlString = String(format: NetworkingConstants.baseUrlString, encodedQuery) guard let url = URL(string: urlString) else { return } var request = URLRequest(url: url) request.httpMethod = NetworkingConstants.getMethod URLSession.shared.dataTask(with: request) { data, _, networkError in guard let data = data, networkError == nil else { completion([], networkError) return } do { let decoder = JSONDecoder() let batch = try decoder.decode(MovieBatch.self, from: data) completion(batch.results, nil) } catch { completion([], error) } }.resume() } static func fetchPosterImage(path: String, completion: @escaping (UIImage?, Error?) -> Void) { let fullPath = (NetworkingConstants.basePosterUrlString + path) guard let url = URL(string: fullPath) else { return } var request = URLRequest(url: url) request.httpMethod = NetworkingConstants.getMethod URLSession.shared.dataTask(with: request) { data, _, error in guard let data = data, let image = UIImage(data: data), error == nil else { completion(nil, error) return } DispatchQueue.main.async { completion(image, nil) } }.resume() } }
true
5ccd17ea906ca1c7682740b7e62b5e9e9f0d4272
Swift
ywangnon/Algorithm
/Programmers/Level2/JadenCase 문자열 만들기/JadenCase문자열만들기.playground/Contents.swift
UTF-8
1,211
4.59375
5
[]
no_license
/*: # JadenCase 문자열 만들기 ## 문제 설명 JadenCase란 모든 단어의 첫 문자가 대문자이고, 그 외의 알파벳은 소문자인 문자열입니다. 문자열 s가 주어졌을 때, s를 JadenCase로 바꾼 문자열을 리턴하는 함수, solution을 완성해주세요. ## 제한 조건 - s는 길이 1 이상인 문자열입니다. - s는 알파벳과 공백문자(" ")로 이루어져 있습니다. - 첫 문자가 영문이 아닐때에는 이어지는 영문은 소문자로 씁니다. ( 첫번째 입출력 예 참고 ) ## 입출력 예 s | return ---|--- "3people unFollowed me" | "3people Unfollowed Me" "for the last week" | "For The Last Week" */ import Foundation import UIKit func solution(_ s:String) -> String { var ans = "" var index = 0 for char in s { if char != " " { if index == 0 { ans += String(char).uppercased() } else { ans += String(char).lowercased() } index += 1 } else { ans += " " index = 0 } } return ans } solution("3people unFollowed me") solution("for the last week")
true
5c3c5bce80a4f66c1ba85234083d70805d70a03c
Swift
StevenWatremez/swift4Encoder
/Swift4CodableXcode9.playground/Contents.swift
UTF-8
848
3.875
4
[ "Apache-2.0" ]
permissive
import UIKit enum PetType: String, Codable { case cat case dog } struct Pet: Codable { let name: String let type: PetType } struct Human: Codable { let lastName: String let firstName: String let pets: [Pet] } extension Human { func toData() -> Data? { return try? JSONEncoder().encode(self) } init(data: Data) throws { self = try JSONDecoder().decode(Human.self, from: data) } } // Usage Example let tsuki = Pet(name: "Tsuki", type: .cat) let steven = Human(lastName: "Watremez", firstName: "Steven", pets: [tsuki]) let dataHuman = steven.toData() do { let human = try Human.init(data: dataHuman!) print(""" \(human.firstName) \(human.lastName) has a pet named \(steven.pets.first!.name). \(steven.pets.first!.name) is a \(steven.pets.first!.type.rawValue) ! """) } catch { // catch error }
true
cedcbc24e2ae8ecbdb2bd51318c64ac992ef51b4
Swift
OrWest/iOS-lessons
/Project15/Project15/model/Card.swift
UTF-8
321
2.921875
3
[]
no_license
import Foundation import Alamofire struct Card: Decodable { let title: String let text: String let imageURL: URL let imageGoldURL: URL enum CodingKeys: String, CodingKey { case title = "name" case text case imageURL = "img" case imageGoldURL = "imgGold" } }
true
46afdedc96c3cd8a73b82830888036db2d744969
Swift
HeQiang-IOS/swiftStudy
/新特性/响应式编程/响应式编程/ViewController.swift
UTF-8
2,006
3.828125
4
[]
no_license
// // ViewController.swift // 响应式编程 // // Created by 何强 on 2019/12/11. // Copyright © 2019 何强. All rights reserved. // /* 响应式编程(Reactive Programming)是一种编程思想,相对应的也有面向过程编程、面向对象编程、函数式编程等等。不同的是,响应式编程的核心是面向异步数据流和变化的。 在现在的前端世界中,我们需要处理大量的事件,既有用户的交互,也有不断的网络请求,还有来自系统或者框架的各种通知,因此也无可避免产生纷繁复杂的状态。使用响应式编程后,所有事件将成为异步的数据流,更加方便的是可以对这些数据流可以进行组合变换,最终我们只需要监听所关心的数据流的变化并做出响应即可。 举个有趣的例子来解释一下: 当你早上起床之后,你需要一边洗漱一边烤个面包,最后吃早饭。 */ import UIKit // 传统的编程方法: /* func goodMorning() { wake{ let group = DispatchGroup() group.enter() wash { group.leave() } group.enter() cook { group.leave() } group.notify(queue: .main) { eat { print("Finished") } } } }*/ // 响应式编程 /* func reactiveGoodMorning() { let routine = wake.rx.flapLatest { return Observable.zip(wash, cook) }.flapLatest { return eat.rx } routine.subsrible(onCompleted: { print("Finished") }) 不同于传统可以看到 wake/wash/cook/eat 这几个事件通过一些组合转换被串联成一个流,我们也只需要订阅这个流就可以在应该响应的时候得到通知。 }*/ class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
true
6133dfd9064c3330367133043d64183bd738c05a
Swift
coreyrshaw/gotem
/MOYO/MOYO/ContactUsViewController.swift
UTF-8
929
2.515625
3
[]
no_license
// // ContactUsViewController.swift // MOYO // // Created by Corey S on 9/19/18. // Copyright © 2018 Clifford Lab. All rights reserved. // import UIKit class ContactUsViewController: UIViewController { let contactUsURL = "https://moyohealth.net/contact.html" @IBOutlet weak var contactUsWebView: UIWebView! override func viewWillAppear(_ animated: Bool) { let requestURL = URL(string:contactUsURL) let request = URLRequest(url: requestURL!) contactUsWebView.loadRequest(request) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
adebc3d75d6cdc43998084eeb41328dc4185012f
Swift
lolgear/SwiftLipstickViewer
/Core/Domains/Main/MainCoordinator.swift
UTF-8
4,120
2.515625
3
[ "MIT" ]
permissive
// // MainCoordinator.swift // SwiftLipstickViewer // // Created by Dmitry Lobanov on 28.07.2019. // Copyright © 2019 Dmitry Lobanov. All rights reserved. // import Foundation import UIKit class MainCoordinator: BaseCoordinator { var viewController: Domain_Main.MainViewController? var dataProvider: DataProviderService? var media: MediaDeliveryService? override func start() { // so, it is ready and we can configure it properly. // configure other controllers. // let listModel = Domain_Main.Lipstick.ListViewController.Model() listModel.controller = { [weak self] (index) in return self?.wantsLipstickDetails(at: index) } let samplersModel = Domain_Main.Lipstick.SamplersListViewController.Model() samplersModel.didSelect = { [weak listModel] (index) in let (previous, next) = index listModel?.didSelect?(.init((previous ?? 0, next)), next) } // let list = [.red, .orange, .yellow, .green, .blue, .purple, .black].map(LipstickSamplersListViewController.Model.Row.init) // samplersModel.list = list // samplersModel.list = self.dataProvider?.dataProvider?.list.compactMap{LipstickSamplersListViewController.Model.Row(color: $0.color)} ?? [] let listController = Domain_Main.Lipstick.ListViewController().configured(model: listModel) let samplersController = Domain_Main.Lipstick.SamplersListViewController().configured(model: samplersModel) let model = Domain_Main.MainViewController.Model() model.topController = listController model.bottomController = samplersController self.viewController?.configured(model: model) // and... // go! self.start(model: samplersModel) } func updateSamplers(model: Domain_Main.Lipstick.SamplersListViewController.Model) { let list = self.dataProvider?.dataProvider?.list.compactMap{Domain_Main.Lipstick.SamplersListViewController.Model.Row(color: $0.color)} ?? [] model.reset(list: list) } func start(model: Domain_Main.Lipstick.SamplersListViewController.Model) { self.updateSamplers(model: model) } func wantsMoreData(waitingForImages: Bool, onResult: @escaping (Result<Bool>) -> ()) { self.dataProvider?.dataProvider?.getProducts(options: waitingForImages ? [.shouldWaitForImages] : [], { (result) in // just append data, I suppose? onResult(result.map { !$0.isEmpty }) }) } func reactOnIndexNearEnd(index: Int) { } override init() {} init(viewController: Domain_Main.MainViewController?) { self.viewController = viewController } } // MARK: Configurations extension MainCoordinator { func configured(dataProvider: DataProviderService?) -> Self { self.dataProvider = dataProvider return self } func configured(media: MediaDeliveryService?) -> Self { self.media = media return self } } // MARK: Controllers extension MainCoordinator { func stubDetails() -> UIViewController? { let model = Domain_Main.Lipstick.DetailViewController.Model() model.title = "First" model.details = "Second" model.price = "Third" return Domain_Main.Lipstick.DetailViewController().configured(model: model) } func wantsLipstickDetails(at index: Int) -> UIViewController? { // return stubDetails() guard let dataProvider = self.dataProvider?.dataProvider else { return nil } guard dataProvider.list.count > index else { return nil } let model = dataProvider.list[index] // and also set media downloader for image. guard let details = Domain_Main.Lipstick.DetailViewController.DetailsProvider.details(model) else { return nil } details.media = self.media let controller = Domain_Main.Lipstick.DetailViewController().configured(model: details) return controller } }
true
39bc08be4e1d864c4aad7632e01556e6e11f389f
Swift
korczis/MinervaEye
/Minerva Eye/Component/Eye/EyeView.swift
UTF-8
2,060
2.921875
3
[]
no_license
// // EyeView.swift // Minerva Eye // // Created by Tomas Korcak on 5/14/20. // Copyright © 2020 Tomas Korcak. All rights reserved. // import SwiftUI struct EyeView: View { // @State private var completionHandler: ([String]?) -> Void @State private var isShowingScannerSheet = false @State private var text: String = "" private let buttonInsets = EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16) private let completionHandler: ([String]?) -> Void @Environment(\.presentationMode) var presentation init(completion: @escaping ([String]?) -> Void) { self.completionHandler = completion } var body: some View { VStack { EyeScannerView(completion: { textPerPage in if let text = textPerPage?.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) { self.text = text print("Recognized text: \(text)") self.completionHandler([text]) } self.isShowingScannerSheet = false self.presentation.wrappedValue.dismiss() }) .edgesIgnoringSafeArea(.all) } .sheet(isPresented: self.$isShowingScannerSheet) { self.makeScannerView() } } private func openCamera() { isShowingScannerSheet = true } private func makeScannerView() -> EyeScannerView { EyeScannerView(completion: { textPerPage in if let text = textPerPage?.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) { self.text = text print("EyeScannerView completion, text - \(text)") } self.isShowingScannerSheet = false self.presentation.wrappedValue.dismiss() }) } } #if DEBUG struct EyeView_Previews: PreviewProvider { static var previews: some View { EyeView(completion: { msg in print(msg!) }) } } #endif
true
0f8a60133d0752e00eaed4e994b762eef947230e
Swift
ednofedulo/pokemon-app
/source/pokemon-app/Components/CustomTextField.swift
UTF-8
1,085
2.796875
3
[]
no_license
// // CustomTextField.swift // pokemon-app // // Created by Edno Fedulo on 27/12/20. // import Foundation import UIKit class CustomTextField: UITextField { @IBInspectable var uiEdgeInsetsTop:CGFloat = 15 @IBInspectable var uiEdgeInsetsLeft:CGFloat = 30 @IBInspectable var uiEdgeInsetBottom:CGFloat = 15 @IBInspectable var uiEdgeInsetsRight:CGFloat = 30 override open func textRect(forBounds bounds: CGRect) -> CGRect { let padding = self.getUIEdgeInsets() return bounds.inset(by: padding) } override open func placeholderRect(forBounds bounds: CGRect) -> CGRect { let padding = self.getUIEdgeInsets() return bounds.inset(by: padding) } override open func editingRect(forBounds bounds: CGRect) -> CGRect { let padding = self.getUIEdgeInsets() return bounds.inset(by: padding) } private func getUIEdgeInsets() -> UIEdgeInsets { return UIEdgeInsets(top: self.uiEdgeInsetsTop, left: self.uiEdgeInsetsLeft, bottom: self.uiEdgeInsetBottom, right: self.uiEdgeInsetsRight) } }
true
5767612eeaf17f9a866b442eb594abbb15cdb413
Swift
smyshlaevalex/WeatherLookup
/WeatherLookup/Models/WeatherData.swift
UTF-8
680
3.21875
3
[ "MIT" ]
permissive
// // WeatherData.swift // WeatherLookup // // Created by Alexander Smyshlaev on 15/07/2019. // Copyright © 2019 Alexander Smyshlaev. All rights reserved. // import Foundation struct WeatherData { let temperature: Double } extension WeatherData: Decodable { enum CodingKeys: CodingKey { case main } enum MainCodingKeys: CodingKey { case temp } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let mainContainer = try container.nestedContainer(keyedBy: MainCodingKeys.self, forKey: .main) temperature = try mainContainer.decode(Double.self, forKey: .temp) } }
true
71024fbfbb126a7ab61f757fa1f3b9012c03c223
Swift
bengottlieb/nearby
/Sources/Nearby/AvatarCache.swift
UTF-8
2,334
2.9375
3
[]
no_license
// // AvatarCache.swift // EyeFull // // Created by Ben Gottlieb on 8/2/23. // import Foundation import CrossPlatformKit class AvatarCache { static let instance = AvatarCache() var cachedAvatars: [String: CachedAvatar] = [:] let directory = URL.cache(named: "cached_nearby_avatars") init() { try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) } func avatarInfo(forHash hash: String?) -> CachedAvatar? { guard let hash else { return nil } if let cached = cachedAvatars[hash] { return cached } let url = directory.appendingPathComponent(hash) do { if let data = try? Data(contentsOf: url) { let cache = try JSONDecoder().decode(CachedAvatar.self, from: data) cachedAvatars[hash] = cache return cache } } catch { print("Failed to retreive avatar info: \(error)") } return nil } func store(_ message: NearbySystemMessage.Avatar) { print("Storing avatar for \(message.hash)") let cache = CachedAvatar(image: message.image, name: message.name, hash: message.hash) cachedAvatars[message.hash] = cache do { let data = try JSONEncoder().encode(cache) let url = directory.appendingPathComponent(message.hash) try data.write(to: url) } catch { print("Failed to store avatar info: \(error)") } } } extension AvatarCache { struct CachedAvatar: Codable { enum CodingKeys: String, CodingKey { case name, image, hash } let image: UXImage? let name: String? let hash: String init(image: UXImage?, name: String?, hash: String) { self.image = image self.name = name self.hash = hash } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if let data = try container.decodeIfPresent(Data.self, forKey: .image) { image = UXImage(data: data) } else { image = nil } name = try container.decodeIfPresent(String.self, forKey: .name) hash = try container.decode(String.self, forKey: .hash) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if let data = image?.pngData() { try container.encode(data, forKey: .image) } if let name { try container.encode(name, forKey: .name) } try container.encode(hash, forKey: .hash) } } }
true
1d51662b3069a0cead7038ddd35a26a00ce8d2be
Swift
gary17/dron3r
/Dron3r/Client/ClientDrone.swift
UTF-8
1,174
2.71875
3
[]
no_license
// // ClientDrone.swift // Dron3r // // Copyright © 2019 R&F Consulting, Inc. All rights reserved. // // https://github.com/swiftsocket/SwiftSocket // provides as easy to use interface for socket based connections import SwiftSocket // represents a network-enabled piece of hardware (as opposed to a server-side drone dashboard) internal protocol ClientDrone { var client: UDPClient { get } } extension ClientDrone where Self: Drone { internal func reportIn() { // TODO: consider what to do when location and/or speed are unknown for a period of time, perhaps report-in as broken? // a Memento makes >>A COPY<< of the current state of a Drone, since it might change soon let memento = Memento(of: self, at: Timestamp.now()) // UDP, connectionless, ping/pong-less // serialize and stream-up if let data = memento.data() { switch client.send(data: data) { case .success: break case .failure(let error): do { // TODO: request a specification on how to report client-side errors let message = "drone: UDP send failure [\(error)]" Logger.log(message, severity: .error) } } } } }
true
1e8e6665e0da5a8589b6f1f808e62a4c8b024585
Swift
lelouch20/CodeDemo
/CodeDemo/Easy/14-LongestCommonPrefix.swift
UTF-8
808
3.09375
3
[]
no_license
// // 14-LongestCommonPrefix.swift // CodeDemo // // Created by Firo on 2019/10/24. // Copyright © 2019 firo. All rights reserved. // import Foundation class Solution14 { func longestCommonPrefix(_ strs: [String]) -> String { //判空 if strs.count == 0 { return "" } var result = strs.first! for i in 1..<strs.count { let str = strs[i] //判空 if str == "" { return "" } while !str.hasPrefix(result) { //每次移除最后一个字母 result.removeLast() //判空 if result == "" { return "" } } } return result } }
true
e3f428893a90061260e8c35515a67f2f722d06af
Swift
sadjason/SBDB
/SBDBTests/Cases/SelectTests.swift
UTF-8
2,388
3.453125
3
[]
no_license
// // SelectTests.swift // SBDBTests // // Created by SadJason on 2019/10/28. // Copyright © 2019 SadJason. All rights reserved. // import XCTest @testable import SBDB /// Select 相关 cases class SelectTests: XCTestCase { var database: Database! override func setUp() { database = try! Util.openDatabase() try? database.delete(from: Student.self) } /// 插入一条数据,然后取出,前后二者是相等的 func testInsertOne() throws { let s1 = Util.generateStudent() try database.insert(s1) let s2 = try database.selectOne(from: Student.self) print(s1) print(s2!) XCTAssert(s1 == s2) } /// 测试 where:插入多条数据,然后能根据条件将其选出来 func testWhere() throws { let students = (1...100).map { (index) -> Student in var s = Util.generateStudent() s.age = UInt8(index) s.isBoy = (index % 2 == 1) return s } try students.forEach { try database.insert($0) } let result1 = try database.select(from: Student.self, where: \Student.age > 50) XCTAssert(result1.count == 50) result1.forEach { XCTAssert($0.age > 50) } let result2 = try database.select(from: Student.self, where: \Student.age > 50 && \Student.isBoy == 1) XCTAssert(result2.count == 25) result2.forEach { XCTAssert($0.age > 50 && $0.isBoy!) } } /// 测试 order:确保返回值的顺序是正确的 func testOrder() throws { let students = (1...100).map { (index) -> Student in var s = Util.generateStudent() s.age = UInt8(index) s.isBoy = (index % 2 == 1) return s } try students.forEach { try database.insert($0) } // 正序 let result1 = try database.select(from: Student.self, orderBy: \Student.age) XCTAssert(result1.count == students.count) students.enumerated().forEach { (index, r) in XCTAssert(result1[index] == r) } // 逆序 let result2 = try database.select(from: Student.self, orderBy: (\Student.age).desc()) XCTAssert(result2.count == students.count) students.enumerated().forEach { (index, r) in XCTAssert(result2[students.count - 1 - index] == r) } } }
true
9e8d2d5dae594965bb93bd0c207dfbf142a21cad
Swift
vctrsmelo/suita-challenge
/SuitabilityChat/SuitabilityChat/View Controllers/Chat View Controller/Views/User Input Views/UserInputView.swift
UTF-8
564
3.015625
3
[]
no_license
// // UserInputViewDelegate.swift // SuitabilityChat // // Created by Victor S Melo on 08/03/18. // Copyright © 2018 Victor Melo. All rights reserved. // import UIKit protocol UserInputViewDelegate: class { /** Called when user touches send button. - Parameters: - value: it is the saved value to be sent to API - answer: the message that will be shown into chat. */ func userDidAnswer(value: String, answer: String) } protocol UserInputView: class { weak var delegate: UserInputViewDelegate? { get set } }
true
8c27fda03bf6b5261b40c557d3539c212286bb8e
Swift
gladiusKatana/RedNiteLite
/RedNiteLite/AppDelegate.swift
UTF-8
2,501
2.6875
3
[]
no_license
import UIKit // RedNiteLite created by Garth Snyder @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var nightLightViewController = UIViewController() lazy var orientationLock = UIInterfaceOrientationMask.all // set orientations you want allowed by default func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = .red // will likely add a nicer, custom (researched) optimal red color window?.makeKeyAndVisible() let backgroundVC = UIViewController() backgroundVC.view.backgroundColor = window?.backgroundColor /// must match window's background color, for rotating landscape->portrait UINavigationBar.appearance().barTintColor = .red UINavigationBar.appearance().shadowImage = UIImage() return true } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let navController = UINavigationController(rootViewController: nightLightViewController) window?.rootViewController = navController AppUtility.lockOrientation(.portrait, andRotateTo: .portrait) // locked to landscape to hide status bar for cleaner look return true } } extension AppDelegate { func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return orientationLock } } struct AppUtility { static func lockOrientation(_ orientation: UIInterfaceOrientationMask) { if let appDelegate = UIApplication.shared.delegate as? AppDelegate { appDelegate.orientationLock = orientation } else { print("[AppUtility] error casting app delegate instance") } } static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation: UIInterfaceOrientation) { self.lockOrientation(orientation) UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation") } } // This is definitely the shortest useful iOS app I've ever written created by Garth Snyder
true
cf6ca20b4aed79f4207431129456240ecdfa8051
Swift
manvelov/IChat
/IChat/Extensions/UIKit/UIViewController+Extention.swift
UTF-8
1,065
2.75
3
[]
no_license
// // UIViewController+Extention.swift // IChat // // Created by Kirill Manvelov on 17.09.2020. // Copyright © 2020 Kirill Manvelov. All rights reserved. // import UIKit extension UIViewController { func configureCell<T: SelfConfigureCell, U: Hashable>(celltype: T.Type, with value: U, indexPath: IndexPath, collectionView: UICollectionView) -> T { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: celltype.reuseId, for: indexPath) as? T else { fatalError("No such type \(celltype)") } cell.configure(with: value) return cell } } extension UIViewController { func showAlert(with title: String, and message: String, complition: @escaping () -> Void = {}) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let alertAction = UIAlertAction(title: "OK", style: .default) { (_) in complition() } alertController.addAction(alertAction) present(alertController, animated: true, completion: nil) } }
true
99181b1edda2523fe7f3060ff348a0ef6b855e31
Swift
E-B-Smith/Buildasaur
/Buildasaur/ViewControllers/Editables/EmptyProjectViewController.swift
UTF-8
4,921
2.71875
3
[ "MIT" ]
permissive
// // EmptyProjectViewController.swift // Buildasaur // // Created by Honza Dvorsky on 30/09/2015. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Cocoa import BuildaKit import BuildaUtils protocol EmptyProjectViewControllerDelegate: class { func didSelectProjectConfig(_ config: ProjectConfig) } extension ProjectConfig { var name: String { let fileWithExtension = (self.url as NSString).lastPathComponent let file = (fileWithExtension as NSString).deletingPathExtension return file } } class EmptyProjectViewController: EditableViewController { //for cases when we're editing an existing syncer - show the //right preference. var existingConfigId: RefType? weak var emptyProjectDelegate: EmptyProjectViewControllerDelegate? @IBOutlet weak var existingProjectsPopup: NSPopUpButton! private var projectConfigs: [ProjectConfig] = [] private var selectedConfig: ProjectConfig? = nil { didSet { self.nextAllowed = self.selectedConfig != nil } } override func viewDidLoad() { super.viewDidLoad() self.setupDataSource() self.setupPopupAction() } override func viewDidAppear() { super.viewDidAppear() //select if existing config is being edited let index: Int if let id = self.selectedConfig?.id { let ids = self.projectConfigs.map { $0.id } index = ids.index(of: id) ?? 0 } else if let configId = self.existingConfigId { let ids = self.projectConfigs.map { $0.id } index = ids.index(of: configId) ?? 0 } else { index = 0 } self.selectItemAtIndex(index) self.existingProjectsPopup.selectItem(at: index) self.nextAllowed = self.selectedConfig != nil } private var addNewString: String { return "Add new Xcode Project..." } private func newConfig() -> ProjectConfig { return ProjectConfig() } override func shouldGoNext() -> Bool { var current = self.selectedConfig! if current.url.isEmpty { //just new config, needs to be picked guard let picked = self.pickNewProject() else { return false } current = picked } self.didSelectProjectConfig(current) return super.shouldGoNext() } private func selectItemAtIndex(_ index: Int) { let configs = self.projectConfigs // last item is "add new" let config = (index == configs.count) ? self.newConfig() : configs[index] self.selectedConfig = config } private func setupPopupAction() { self.existingProjectsPopup.onClick = { [weak self] _ in guard let sself = self else { return } let index = sself.existingProjectsPopup.indexOfSelectedItem sself.selectItemAtIndex(index) } } private func setupDataSource() { let update = { [weak self] in guard let sself = self else { return } sself.projectConfigs = sself.storageManager.projectConfigs.values.filter { (try? Project(config: $0)) != nil }.sorted { $0.name < $1.name } let popup = sself.existingProjectsPopup popup?.removeAllItems() var configDisplayNames = sself.projectConfigs.map { $0.name } configDisplayNames.append(sself.addNewString) popup?.addItems(withTitles: configDisplayNames) } self.storageManager.onUpdateProjectConfigs = update update() } private func didSelectProjectConfig(_ config: ProjectConfig) { Log.verbose("Selected \(config.url)") self.emptyProjectDelegate?.didSelectProjectConfig(config) } private func pickNewProject() -> ProjectConfig? { if let url = StorageUtils.openWorkspaceOrProject() { do { try self.storageManager.checkForProjectOrWorkspace(url: url) var config = ProjectConfig() config.url = url.path return config } catch { //local source is malformed, something terrible must have happened, inform the user this can't be used (log should tell why exactly) let buttons = ["See workaround", "OK"] UIUtils.showAlertWithButtons("Couldn't add Xcode project at path \(url.absoluteString), error: \((error as NSError).userInfo["info"] ?? "Unknown").", buttons: buttons, style: .critical, completion: { (tappedButton) -> Void in if tappedButton == "See workaround" { openLink("https://github.com/czechboy0/Buildasaur/issues/165#issuecomment-148220340") } }) } } else { //user cancelled } return nil } }
true
c8639af543c85315ea07d7a663f0b79bebf9f951
Swift
jamirdurham/LeetCode
/Array/Plus One/plus-one.playground/Contents.swift
UTF-8
901
3.1875
3
[ "MIT" ]
permissive
import Foundation // https://leetcode.com/problems/plus-one class Solution { func plusOne(_ digits: [Int]) -> [Int] { var offset = 1, result = digits for i in stride(from: digits.count - 1, through: 0, by: -1) { result[i] += offset offset = result[i] / 10 result[i] %= 10 } if offset > 0 { result.insert(offset, at: 0) } return result } } import XCTest // Executed 3 tests, with 0 failures (0 unexpected) in 0.008 (0.009) seconds class Tests: XCTestCase { private let s = Solution() func test1() { let res = s.plusOne([1,2,3]) XCTAssertEqual(res, [1,2,4]) } func test2() { let res = s.plusOne([4,3,2,1]) XCTAssertEqual(res, [4,3,2,2]) } func test3() { let res = s.plusOne([0]) XCTAssertEqual(res, [1]) } } Tests.defaultTestSuite.run()
true
58306fbe8c44d47b73b099d94bfb456f71b7502d
Swift
DW8Reaper/cal-sync
/cal-sync/CalendarSync.swift
UTF-8
9,043
2.625
3
[ "MIT" ]
permissive
// // Created by De Wildt van Reenen on 11/7/16. // Copyright (c) 2016 Broken-D. All rights reserved. // import Foundation import EventKit public class CalendarSync { private var syncConfig: SyncArguments private(set) var srcCalendar: EKCalendar private(set) var dstCalendar: EKCalendar private(set) var syncStart: Date private(set) var syncEnd: Date private var eventStore = EKEventStore() init(syncConfig: SyncArguments) throws { //Store configuration self.syncConfig = syncConfig eventStore = try createEventStore(maxAuthWaitSeconds: MAX_AUTH_WAIT) guard let src = eventStore.calendar(withIdentifier: syncConfig.srcCalID) else { throw SyncError.invalidSourceCalendar } guard let dst = eventStore.calendar(withIdentifier: syncConfig.dstCalID) else { throw SyncError.invalidDestinationCalendar } guard src.calendarIdentifier != dst.calendarIdentifier else { throw SyncError.sameSrcDst } srcCalendar = src dstCalendar = dst syncStart = Date().addingTimeInterval(TimeInterval(-syncConfig.historyDays*24*60*60)) syncEnd = Date().addingTimeInterval(TimeInterval(syncConfig.futureDays*24*60*60)) } private func getName(calendar: EKCalendar) -> String { return "\(calendar.source.title): \"\(calendar.title)\" (\(calendar.title))" } public func getSourceName() -> String { return getName(calendar: srcCalendar) } public func getDestinationName() -> String { return getName(calendar: dstCalendar) } public func makeHash(event: EKEvent, config: SyncArguments) -> String { let sep = ";;##--##;;" var data: String = "\(event.startDate) to \(event.endDate) length \(event.isAllDay)" if config.syncTitle { data = "\(data)\(sep)\(event.title)" } if config.syncLocation { data = "\(data)\(sep)\(event.location)" } if config.syncAvailability { data = "\(data)\(sep)\(event.availability.rawValue)" } else { data = "\(data)\(sep)FREE" } if config.syncNotes { data = "\(data)\(sep)\(event.notes)" } return makeHashSHA1(data: data) } public func determineEventActions() throws -> [SyncEvent] { return try determineEventActions(from: syncStart, to: syncEnd) } public func determineEventActions(from: Date, to: Date) throws -> [SyncEvent] { var dstEvents: [String: EKEvent] = [:] var actions: [SyncEvent] = [] var processed: [String] = [] //Get destination events and remove them let dstStartDate = Date(timeIntervalSinceNow: TimeInterval((-200 * 1) * 24 * 60 * 60)) let dstEndDate = Date(timeIntervalSinceNow: TimeInterval((200 * 1) * 24 * 60 * 60)) let dstEventMatcher = eventStore.predicateForEvents(withStart: dstStartDate, end: dstEndDate, calendars: [dstCalendar]) let dstEvList = eventStore.events(matching: dstEventMatcher) for var dstEvent in dstEvList { if dstEvent.hasRecurrenceRules { // For exchange calendars it can happen that when you sync a recurring event it creates a duplicate for each recursion each // time you sync. To prevent this we find the first occurrence of any event with a recursion rule and sync it instead try dstEvent = eventStore.calendarItem(withIdentifier: dstEvent.eventIdentifier) as! EKEvent } if let url = dstEvent.url { if url.absoluteString.hasPrefix(syncConfig.prefix) { var parts: [String] = url.absoluteString.components(separatedBy: ":") if parts.count == 3 { dstEvents.updateValue(dstEvent, forKey: parts[2]) } else { // doesn't have a valid ID but the prefix matched so add with own ID so it will be unique dstEvents.updateValue(dstEvent, forKey: dstEvent.eventIdentifier) } } } } //Get source events let srcEventMatcher = eventStore.predicateForEvents(withStart: from, end: to, calendars: [srcCalendar]) let srcEvents = eventStore.events(matching: srcEventMatcher) for srcEvent in srcEvents { // only process recurring events the first time we find them if processed.contains(srcEvent.eventIdentifier) { continue } else { processed.append(srcEvent.eventIdentifier) } let srcHash = makeHash(event: srcEvent, config: syncConfig) if let dstEvent = dstEvents[srcEvent.eventIdentifier] { var parts: [String] = dstEvent.url!.absoluteString.components(separatedBy: ":") if ( parts.count < 2 ) || ( parts[1] != srcHash ) { // exists but the data has changed actions.append(SyncEvent(action: SyncEventAction.update, src: srcEvent, dst: dstEvent, srcHash: srcHash)) } dstEvents.removeValue(forKey: srcEvent.eventIdentifier) } else { // New Event actions.append(SyncEvent(action: SyncEventAction.create, src: srcEvent, dst: nil, srcHash: srcHash)) } } // remove any remaining events for (_, value) in dstEvents { actions.append(SyncEvent(action: SyncEventAction.delete, src: value, dst: value, srcHash: "")) } return actions } private func copyEvent(src: EKEvent, hash: String, dst: EKEvent) { dst.startDate = src.startDate dst.endDate = src.endDate dst.isAllDay = src.isAllDay dst.alarms = src.alarms dst.url = URL(string: syncConfig.prefix + ":" + makeHash(event: src, config: syncConfig) + ":" + src.eventIdentifier) if syncConfig.syncTitle { dst.title = src.title } else { dst.title = "" } if syncConfig.syncNotes { dst.notes = src.notes } else { dst.notes = nil } if syncConfig.syncLocation { dst.location = src.location } else { dst.location = nil } if syncConfig.syncAvailability { dst.availability = src.availability } else { dst.availability = EKEventAvailability.free } if let rules = src.recurrenceRules { for rule : EKRecurrenceRule in rules { dst.addRecurrenceRule(rule) } } } public func resetEventStore() { eventStore.reset() } public func syncEvents(actions: [SyncEvent]) throws { let pref = (syncConfig.testMode) ? "TEST MODE -> " : "" for action in actions { switch action.action { case SyncEventAction.delete: if (syncConfig.verbose) { print(" \(pref)Delete event \"\(action.srcEvent.title)\" (\(action.srcEvent.eventIdentifier)) starts \"\(action.srcEvent.startDate)\"") } if (syncConfig.testMode == false) { try eventStore.remove(action.dstEvent!, span: EKSpan.futureEvents, commit: false) } case SyncEventAction.create: if (syncConfig.verbose) { print(" \(pref)Create event \"\(action.srcEvent.title)\" (\(action.srcEvent.eventIdentifier)) starts \"\(action.srcEvent.startDate)\"") } if (syncConfig.testMode == false) { let newEvent = EKEvent(eventStore: eventStore) newEvent.calendar = dstCalendar copyEvent(src: action.srcEvent, hash: action.srcHash, dst: newEvent) try eventStore.save(newEvent, span: EKSpan.futureEvents, commit: false) } case SyncEventAction.update: if (syncConfig.verbose) { print(" \(pref)Update event \"\(action.srcEvent.title)\" (\(action.srcEvent.eventIdentifier)) starts \"\(action.srcEvent.startDate)\"") } if (syncConfig.testMode == false) { // for recurring events we always use the first occurrence of the recursion as our source, for this reason we also update the current // event and all future events every time copyEvent(src: action.srcEvent, hash: action.srcHash, dst: action.dstEvent!) try eventStore.save(action.dstEvent!, span: EKSpan.futureEvents, commit: false) } } } if (syncConfig.testMode == false) { try eventStore.commit() } } }
true
0e47e2fa83327cce73573e46ecc0389d3eeb147d
Swift
zhaoleiVin/NailSalonSwift
/NailSalonSwift/NailSalonSwift/Search/ZL_SSLabelVC.swift
UTF-8
2,685
2.75
3
[]
no_license
// // ZL_SSLabelVC.swift // NailSalonSwift // // Created by 赵磊 on 15/4/10. // Copyright (c) 2015年 宇周. All rights reserved. // import UIKit class ZL_SSLabelVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() var searchBar = UISearchBar(frame: CGRectMake(0, 0, 200, 30)) searchBar.placeholder = "请输入标签" //self.navigationItem.titleView = searchBar searchBar.delegate = self var testString = NSMutableAttributedString(string: "Hello word") var range = NSMakeRange(1, 3) testString.setAttributes([NSForegroundColorAttributeName : UIColor.blueColor()], range: range) var label = UILabel(frame: CGRectMake(0, 0, 200, 40)) label.attributedText = testString self.navigationItem.titleView = label // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension ZL_SSLabelVC :UISearchBarDelegate , UITableViewDelegate , UITableViewDataSource { func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { print(searchText) } /* 搜索代理UISearchBarDelegate方法,点击虚拟键盘上的Search按钮时触发*/ func searchBarSearchButtonClicked(searchBar: UISearchBar!) { print(searchBar.text) searchBar.resignFirstResponder() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var labelCell = tableView.dequeueReusableCellWithIdentifier(ZL_SSLabelCell.cellID()) as ZL_SSLabelCell labelCell.imgName.image = UIImage(named: "headerHolder") labelCell.titleLabel.text = "爱国者就做爱过美甲" labelCell.nameLabel.text = "小米爆米花" return labelCell } func nameLabelChange(oldText : String) ->String{ var newText = "哈哈" return "" } }
true
1ec4187ef5d6f1896490c4f757cbd59692ae5edf
Swift
acqiang/Calculator
/Calculator/CalculatorBrain.swift
UTF-8
3,523
3.453125
3
[]
no_license
// // CalculatorBrain.swift // Calculator // // Created by qiang on 16/1/11. // Copyright © 2016年 qiang. All rights reserved. // import Foundation class CalculatorBrain { private enum Op{ case Operand(Double) case UnaryOperation(String,Double->Double) case BinaryOperation(String,(Double,Double)->Double) var description : String{ get{ switch self{ case .Operand(let operand): return "\(operand)" case .UnaryOperation(let symbol, _): return symbol case .BinaryOperation(let symbol, _): return symbol } } } } private var opStack = [Op]() // var knownOps = Dictionary<String,Op>() private var knonwnOps = [String:Op]() init(){ knonwnOps["×"] = Op.BinaryOperation("×",*) knonwnOps["÷"] = Op.BinaryOperation("÷") { $1 / $0 } knonwnOps["+"] = Op.BinaryOperation("+",+) knonwnOps["−"] = Op.BinaryOperation("−") { $1 - $0 } knonwnOps["√"] = Op.UnaryOperation ("√",sqrt) } typealias PropertyList = AnyObject var program:PropertyList{ // guaranteed to be a PropertyList get{ return opStack.map { $0.description } /* var returnValue = Array<String>() for op in opStack{ returnValue.append(op.description) } return returnValue */ } set{ if let opSymbols = newValue as?Array<String>{ var newOpStack = [Op]() for opSymbol in opSymbols{ if let op = knonwnOps[opSymbol]{ newOpStack.append(op) }else if let operand = NSNumberFormatter().numberFromString(opSymbol)?.doubleValue{ newOpStack.append(.Operand(operand)) } } opStack = newOpStack } } } private func evaluate(ops: [Op]) -> (result:Double?,remainingOps:[Op]){ if !ops.isEmpty{ var remainingOps = ops let op = remainingOps.removeLast() switch op{ case .Operand(let operand): return (operand,remainingOps) case .UnaryOperation(_, let operation): let operandEvalution = evaluate(remainingOps) if let operand = operandEvalution.result{ return (operation(operand),operandEvalution.remainingOps) } case .BinaryOperation(_, let operation): let op1Evalution = evaluate(remainingOps) if let operand1 = op1Evalution.result{ let op2Evaluation = evaluate(op1Evalution.remainingOps) if let operand2 = op2Evaluation.result{ return (operation(operand1,operand2),op2Evaluation.remainingOps) } } } } return (nil,ops) } func evaluate() -> Double? { let (result,remainder) = evaluate(opStack) print("\(opStack) = \(result) with \(remainder) left over") return result } func pushOperandA(operand:Double)->Double?{ opStack.append(Op.Operand(operand)) return evaluate() } func performOperation(symbol:String)->Double?{ if let operation = knonwnOps[symbol]{ opStack.append(operation) } return evaluate() } }
true
148ec003d3b79cfd857e36f93f0679f9209e7e20
Swift
GuiyeC/WWDC-2019
/Neural Networks.playgroundbook/Contents/Chapters/Chapter1.playgroundchapter/Pages/4_TicTacChec.playgroundpage/Sources/Game/Board.swift
UTF-8
4,522
3.484375
3
[ "MIT" ]
permissive
// // Board.swift // Neural Networks // // Created by Guillermo Cique on 23/03/2019. // import Foundation public typealias Coordinate = Int extension Coordinate { public var x: Int { return self - 4*y } public var y: Int { return self/4 } public init(x: Int, y: Int) { self = y*4 + x } public func inverse() -> Coordinate { return (self - 15) * -1 } } public enum SquareState: Equatable { case empty case occupied(player: Player, piece: Piece) } public struct Board { private(set) var data: [SquareState] public private(set) var whitePieces: [Piece: Int] = [:] public private(set) var blackPieces: [Piece: Int] = [:] init(data: [SquareState]) { self.data = data for (index, state) in data.enumerated() { if case .occupied(let player, let piece) = state { if player == .white { whitePieces.updateValue(index, forKey: piece) } else { blackPieces.updateValue(index, forKey: piece) } } } } init() { self.data = [SquareState](repeating: .empty, count: 16) } public subscript(cell: Int) -> SquareState { get { return data[cell] } set(newValue) { if case .occupied(let player, let piece) = data[cell] { if player == .white { whitePieces.removeValue(forKey: piece) } else { blackPieces.removeValue(forKey: piece) } } if case .occupied(let player, let piece) = newValue { if player == .white { whitePieces.updateValue(cell, forKey: piece) } else { blackPieces.updateValue(cell, forKey: piece) } } data[cell] = newValue } } func coordinateFor(piece: Piece, player: Player) -> Coordinate? { switch player { case .white: if let cell = whitePieces[piece] { return cell } case .black: if let cell = blackPieces[piece] { return cell } } return nil } func pieceCount(for player: Player) -> Int { switch player { case .white: return whitePieces.count case .black: return blackPieces.count } } func checkWinner(player: Player) -> Bool { switch player { case .white: return checkWinner(pieces: whitePieces) case .black: return checkWinner(pieces: blackPieces) } } private func checkWinner(pieces: [Piece:Int]) -> Bool { guard pieces.count == 4 else { return false } let coordinates = pieces.values.sorted() // Horizontal if coordinates[0]%4 == 0, coordinates[3] == coordinates[0] + 3 { return true } // Vertical if coordinates[0]%4 == coordinates[1]%4, coordinates[0]%4 == coordinates[2]%4, coordinates[0]%4 == coordinates[3]%4 { return true } // Diagonal top left to bottom right if !coordinates.contains(where: { $0%5 != 0} ) { return true } // Diagonal top right to bottom left if !coordinates.contains(where: { ($0 == 0 || $0 == 15 || $0%3 != 0) }) { return true } return false } func alignedPieceCount(for player: Player) -> Int { switch player { case .white: return alignedPieceCount(pieces: whitePieces) case .black: return alignedPieceCount(pieces: blackPieces) } } private func alignedPieceCount(pieces: [Piece:Int]) -> Int { let coordinates = pieces.values.sorted() var piecesPerRow = [ coordinates.filter({ $0%5 == 0 }).count, coordinates.filter({ ($0 != 0 && $0 != 15 && $0%3 == 0) }).count ] for i in stride(from: 0, to: 16, by: 4) { piecesPerRow.append( coordinates.filter({ ($0 >= i && $0 < i+4) }).count ) } for i in 0..<4 { piecesPerRow.append( coordinates.filter({ $0%4 == i }).count ) } return piecesPerRow.max()! } }
true
44cb2cbc2ccf40b69322f010c4666cde7883bd78
Swift
rphlfc/TravelServicesMobileApp
/TravelServicesMobileApp/Views/Home/HomeView.swift
UTF-8
1,258
2.609375
3
[]
no_license
// // HomeView.swift // TravelServicesMobileApp // // Created by Raphael Cerqueira on 19/09/20. // Copyright © 2020 Raphael Cerqueira. All rights reserved. // import SwiftUI struct HomeView: View { @Binding var selectedItem: Place! @Binding var showDetails: Bool var animation: Namespace.ID var body: some View { NavigationView { VStack { VStack(alignment: .leading) { TopView() Text("Let's enjoy\nyour trip!") .font(.system(size: 40, weight: .semibold)) .padding(.top) SearchView() PopularTravelersView() } .padding(.horizontal, 20) AllView(selectedItem: $selectedItem, showDetails: $showDetails, animation: animation) } .navigationBarBackButtonHidden(true) .navigationBarTitle("") .navigationBarHidden(true) } } } //struct HomeView_Previews: PreviewProvider { // static var previews: some View { // HomeView(selectedItem: .constant(places[0]), showDetails: .constant(false)) // } //}
true
f66f183a537a9685fed849c3892ee114af295343
Swift
gb4iosdev/TTH_TechDegree_Unit-06
/theAPIAwakens/Model/Planet.swift
UTF-8
334
2.953125
3
[]
no_license
// // Planet.swift // theAPIAwakens // // Created by Gavin Butler on 16-09-2019. // Copyright © 2019 Gavin Butler. All rights reserved. // import Foundation //Structure to capture the character’s homeworld's name. struct Planet: Codable { let name: String enum CodingKeys: String, CodingKey { case name } }
true
c0177dc3bc8ef78f590e5ac4935e23dec9db2292
Swift
BarbrDo/iOS
/barbrdo/BarbrDo/BRDModels/BRDAPIResponses/ShopFinanceSale.swift
UTF-8
1,843
2.875
3
[]
no_license
// // ShopFinanceSale.swift // BarbrDo // // Created by Shami Kumar on 20/07/17. // Copyright © 2017 Sumit Sharma. All rights reserved. // import UIKit class ShopFinanceSale: NSObject { var _id : String? var appointments : Int? = 0 var shop_sale : Int? = 0 var appointment_Date: String? var total_sale : Int? = 0 public class func modelsFromDictionaryArray(array:NSArray) -> [ShopFinanceSale] { var models:[ShopFinanceSale] = [] for item in array { models.append(ShopFinanceSale(dictionary: item as! NSDictionary)!) } return models } override init() { self._id = "" self.appointments = 0 self.shop_sale = 0 self.appointment_Date = "" self.total_sale = 0 } required public init?(dictionary: NSDictionary) { _id = dictionary["_id"] as? String appointments = dictionary["appointments"] as? Int appointment_Date = dictionary["appointment_Date"] as? String shop_sale = dictionary["shop_sale"] as? Int total_sale = dictionary["total_sale"] as? Int } /** Returns the dictionary representation for the current instance. - returns: NSDictionary. */ public func dictionaryRepresentation() -> NSDictionary { let dictionary = NSMutableDictionary() dictionary.setValue(self._id, forKey: "_id") dictionary.setValue(self.appointments, forKey: "appointments") dictionary.setValue(self.appointment_Date, forKey: "appointment_Date") dictionary.setValue(self.total_sale, forKey: "total_sale") dictionary.setValue(self.shop_sale, forKey: "shop_sale") return dictionary } }
true
3586bc6d0e304a87f84472925bf6dd7bb9e110d1
Swift
Artemshchurev/yandex_mapkit
/ios/Classes/Utils.swift
UTF-8
2,255
2.546875
3
[ "MIT" ]
permissive
import YandexMapsMobile class Utils { static func uiColor(fromInt value: Int64) -> UIColor { return UIColor( red: CGFloat((value & 0xFF0000) >> 16) / 0xFF, green: CGFloat((value & 0x00FF00) >> 8) / 0xFF, blue: CGFloat(value & 0x0000FF) / 0xFF, alpha: CGFloat((value & 0xFF000000) >> 24) / 0xFF ) } static func pointFromJson(_ json: [String: NSNumber]) -> YMKPoint { return YMKPoint( latitude: json["latitude"]!.doubleValue, longitude: json["longitude"]!.doubleValue ) } static func screenPointFromJson(_ json: [String: NSNumber]) -> YMKScreenPoint { return YMKScreenPoint( x: json["x"]!.floatValue, y: json["y"]!.floatValue ) } static func pointToJson(_ point: YMKPoint) -> [String: Any] { return [ "latitude": point.latitude, "longitude": point.longitude ] } static func screenPointToJson(_ screenPoint: YMKScreenPoint) -> [String: Any] { return [ "x": screenPoint.x, "y": screenPoint.y ] } static func circleToJson(_ circle: YMKCircle) -> [String: Any] { return [ "center": pointToJson(circle.center), "radius": circle.radius ] } static func cameraPositionToJson(_ cameraPosition: YMKCameraPosition) -> [String: Any] { return [ "target": pointToJson(cameraPosition.target), "zoom": cameraPosition.zoom, "tilt": cameraPosition.tilt, "azimuth": cameraPosition.azimuth, ] } static func circleFromJson(_ json: [String: Any]) -> YMKCircle { return YMKCircle( center: pointFromJson(json["center"] as! [String: NSNumber]), radius: (json["radius"] as! NSNumber).floatValue ) } static func polylineFromJson(_ json: [String: Any]) -> YMKPolyline { return YMKPolyline(points: (json["coordinates"] as! [[String: NSNumber]]).map { pointFromJson($0) }) } static func polygonFromJson(_ json: [String: Any]) -> YMKPolygon { return YMKPolygon( outerRing: YMKLinearRing(points: (json["outerRingCoordinates"] as! [[String: NSNumber]]).map { pointFromJson($0) }), innerRings: (json["innerRingsCoordinates"] as! [[[String: NSNumber]]]).map { YMKLinearRing(points: $0.map { pointFromJson($0) }) } ) } }
true