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
ac389708b039eeb8f3976d04d4285a7015e6497d
Swift
gameontext/sample-room-swift
/Sources/SwiftRoom/RoomEndpoint.swift
UTF-8
2,564
2.53125
3
[ "Apache-2.0" ]
permissive
/** * Copyright IBM Corporation 2017 * * 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 import LoggerAPI import KituraWebSocket /** * This is the WebSocket endpoint for a room. An instance of this class * will be created for every connected client. * https://book.gameontext.org/microservices/WebSocketProtocol.html */ public class RoomEndpoint: WebSocketService { private var roomImplementation: RoomImplementation = RoomImplementation() private var connections = [String: WebSocketConnection]() public init() { roomImplementation.roomDescription.addInventoryItem(item: "counter") } public func connected(connection: WebSocketConnection) { Log.info("A new connection has been made to the room.") connections[connection.id] = connection connection.send(message: Message.createAckMessage()) } public func disconnected(connection: WebSocketConnection, reason: WebSocketCloseReasonCode) { connections.removeValue(forKey: connection.id) Log.info("A connection to the room has been closed with reason \(reason.code())") } public func received(message: String, from: WebSocketConnection) { print("server received message: \(message)") for (_, connection) in connections { do { try roomImplementation.handleMessage(messageStr: message, endpoint: self, connection: connection) } catch { Log.error("Error handling message in the room.") } } } public func received(message: Data, from: WebSocketConnection) { from.close(reason: .invalidDataType, description: "GameOn Swift room only accepts text messages") connections.removeValue(forKey: from.id) } public func sendMessage(connection: WebSocketConnection, message: Message) { print("server sending processed message to client: \(message.toString())") connection.send(message: message.toString()) } }
true
232a29228bbe1dac7126555de8fce307cc158ebf
Swift
RickyYu/Mineral
/Mineral/Classes/Model/Base/BaseModel.swift
UTF-8
690
2.546875
3
[]
no_license
// // BaseModel.swift // ZhiAnTongGov // // Created by Ricky on 2016/11/23. // Copyright © 2016年 safetysafetys. All rights reserved. // import Foundation class BaseModel: NSObject { func getClassAllPropertys() -> [String] { var result = [String]() let count = UnsafeMutablePointer<UInt32>.alloc(0) let buff = class_copyPropertyList(object_getClass(self), count) let countInt = Int(count[0]) for i in 0..<countInt { let temp = buff[i] let tempPro = property_getName(temp) let proper = String(UTF8String: tempPro) result.append(proper!) } return result } }
true
9fdb93547a0f5331de52100081e833fd71f5b094
Swift
jamessnee1/iPhoneAssignment1
/SwiftAssignment1/CinemaTableViewController.swift
UTF-8
9,854
2.8125
3
[]
no_license
// // CinemaTableViewController.swift // SwiftAssignment1 // // Created by James Snee on 13/03/2015. // Copyright (c) 2015 James Snee and Heather Ingram. All rights reserved. // import UIKit import AVFoundation //this table view was created by following: http://www.raywenderlich.com/16873/how-to-add-search-into-a-table-view class CinemaTableViewController: UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate { var click = AVAudioPlayer() //create an array of cinema structs var cinemas = [Cinema]() var movies = [Movie]() let frozen = UIImage(named: "frozen.jpg") let startrek = UIImage(named: "startrek.jpg") let starwars = UIImage(named: "starwars.jpg") let terminator = UIImage(named: "terminator.jpg") let toystory = UIImage(named: "toystory.jpg") //If user decides to use the search bar, we can filter the cinemas to this var filteredMovies = [Movie]() var filteredCinemas = [Cinema]() override func viewDidLoad() { super.viewDidLoad() //sound URL var clickSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("click", ofType: "aif")!) click = AVAudioPlayer(contentsOfURL:clickSound, error: nil) //create sample data for cinemas self.cinemas = [ Cinema(cinemaName: "Chadstone", cinemaAddress: "10 Chadstone Shopping Centre, Chadstone VIC", cinemaDesc: "Chadstone Cinemas have the distinction\n of being the largest cinema in\n the Southern Hemisphere.", moviesPlaying: [ "Star Trek: Into Darkness", "The Terminator", "Frozen"]), Cinema(cinemaName: "Melbourne Central", cinemaAddress: "Melbourne Central Shopping Centre, Melbourne VIC", cinemaDesc: "Melbourne Central Cinemas are deluxe\n cinemas, situated on Level 3 of Melbourne\n Central Shopping Centre.", moviesPlaying: ["Star Wars Episode V: The Empire Strikes Back", "Toy Story", "The Terminator"]), Cinema(cinemaName: "Knox", cinemaAddress: "10 Knox ave, Knox VIC", cinemaDesc: "Knox Cinemas are a little away from\n the city, but are sure to delight the most\n discerning movie-goer.", moviesPlaying: ["Frozen", "Toy Story", "The Terminator"]), Cinema(cinemaName: "Doncaster", cinemaAddress: "25 Doncaster Way, Doncaster VIC", cinemaDesc: "Doncaster Cinemas boast 3\n IMAX Screens, as well as\n luxury Gold Class.", moviesPlaying: ["Star Trek: Into Darkness", "Toy Story", "Star Wars Episode V: The Empire Strikes Back"]), Cinema(cinemaName: "Werribee", cinemaAddress: "19 Werribee lane, Werribee VIC", cinemaDesc: "Werribee Cinema-goers enjoy\n a complimentary ticket every\n 6 months. Sign up to the \nrewards program today!", moviesPlaying: ["Toy Story", "Frozen", "Star Trek: Into Darkness"]), Cinema(cinemaName: "Dandenong", cinemaAddress: "93 Dandenong Rd, Dandenong VIC", cinemaDesc: "Dandenong Cinemas have classic movie\n nights, so if you missed it the\n first time around, we\n will play it again!", moviesPlaying: ["Frozen", "Star Wars Episode V: The Empire Strikes Back"]), Cinema(cinemaName: "Box Hill", cinemaAddress: "82 Box Hill Rd, Box Hill VIC", cinemaDesc: "The classic Box Hill Cinemas\n are a Melbourne icon,\n being one of the first\n cinemas in Australia, since 1902.", moviesPlaying: ["The Terminator", "Star Trek: Into Darkness"]), Cinema(cinemaName: "Selby", cinemaAddress: "39 Selby Rd, Selby VIC", cinemaDesc: "Selby Cinemas are the most\n advanced cinemas in the world,\n featuring not only Real-D 3D\n technology, but prototype holographic\n technology for a more immersive experience!", moviesPlaying: ["Star Wars Episode V: The Empire Strikes Back", "The Terminator", "Toy Story"]), Cinema(cinemaName: "Frankston", cinemaAddress: "78 Frankston Rd, Frankston VIC", cinemaDesc: "Frankston Cinemas feature 9 Cinemas,\n the most out of any\n in Melbourne. Additionally,\n sell $8 tickets on Tueday\n afternoons for matinee sessions.", moviesPlaying: ["The Terminator", "Frozen", "Star Trek: Into Darkness"]) ] //reload table view self.tableView.reloadData() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //returns the number of elements in the tableview if filtered or unfiltered if tableView == self.searchDisplayController!.searchResultsTableView { return self.filteredCinemas.count } else { return self.cinemas.count } } //when user selects an item in tableview, perform segue override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("cinemaDetail", sender: tableView) } //segue to the next view controller, pushing all the information to it override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "cinemaDetail" { let cinemaDetails = segue.destinationViewController as! CinemaDetailViewController //if using the search bar if sender as! UITableView == self.searchDisplayController!.searchResultsTableView { let indexPath = self.searchDisplayController!.searchResultsTableView.indexPathForSelectedRow()! let destinationTitle = self.filteredCinemas[indexPath.row].cinemaName let destinationDesc = self.filteredCinemas[indexPath.row].cinemaDesc let destinationAddress = self.filteredCinemas[indexPath.row].cinemaAddress let destinationCinemaInfo = self.filteredCinemas[indexPath.row].moviesPlaying cinemaDetails.title = destinationTitle cinemaDetails.cinemaDescText = destinationDesc cinemaDetails.cinemaAddressText = destinationAddress cinemaDetails.moviesPlaying = destinationCinemaInfo //play sound click.prepareToPlay() click.play() } //if not using the search bar else { let indexPath = self.tableView.indexPathForSelectedRow()! let destinationTitle = self.cinemas[indexPath.row].cinemaName let destinationDesc = self.cinemas[indexPath.row].cinemaDesc let destinationAddress = self.cinemas[indexPath.row].cinemaAddress let destinationCinemaInfo = self.cinemas[indexPath.row].moviesPlaying cinemaDetails.title = destinationTitle cinemaDetails.cinemaDescText = destinationDesc cinemaDetails.cinemaAddressText = destinationAddress cinemaDetails.moviesPlaying = destinationCinemaInfo //play sound click.prepareToPlay() click.play() } } } //back button @IBAction func backButton(sender: UIBarButtonItem) { click.prepareToPlay() click.play() self.dismissViewControllerAnimated(true, completion: nil) } //function to populate cells of the TableView override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("cinemaCell") as! UITableViewCell var cinema : Cinema //check to see if normal table or search results table is used, and set the object from the appropriate array. if tableView == self.searchDisplayController!.searchResultsTableView { cinema = filteredCinemas[indexPath.row] } else { // get the data from movies cinema = cinemas[indexPath.row] } //configure cell with name, and picture cell.textLabel!.text = cinema.cinemaName cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell } //helper method for filtering func filterContentForSearchText(searchText : String, scope: String = "All"){ self.filteredCinemas = self.cinemas.filter({ (cinema: Cinema) -> Bool in let stringMatch = cinema.cinemaName.rangeOfString(searchText) return (stringMatch != nil) }) } //search display controller method for search string func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool { self.filterContentForSearchText(searchString) return true } //search display controller method for scope func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchScope searchOption: Int) -> Bool { self.filterContentForSearchText(self.searchDisplayController!.searchBar.text) return true } }
true
a1c73f47ca29db5dd7685e0c148b5528e16a0078
Swift
danho322/breathoffire
/ARX Template/Helpers/UIViewExtensions.swift
UTF-8
1,278
2.71875
3
[]
no_license
// // UIViewExtensions.swift // ARX Template // // Created by Daniel Ho on 6/23/17. // Copyright © 2017 Daniel Ho. All rights reserved. // import UIKit extension UIView { class func fromNib<T : UIView>(_ nibNameOrNil: String? = nil) -> T? { var view: T? let name: String if let nibName = nibNameOrNil { name = nibName } else { // Most nibs are demangled by practice, if not, just declare string explicitly name = "\(T.self)".components(separatedBy: ".").last! } if let nibViews = Bundle.main.loadNibNamed(name, owner: nil, options: nil) { for v in nibViews { if let tog = v as? T { view = tog } } } return view } } extension UIViewController { func captureScreen() -> UIImage? { UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale) view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } extension Array { subscript (safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } }
true
fcd522c29501f0a85388b209ecd256fbc729db2b
Swift
Oelias84/Hero-Search
/HeroSearch/Helpers/Alerts.swift
UTF-8
975
2.953125
3
[]
no_license
// // Alerts.swift // HeroSearch // // Created by Ofir Elias on 13/05/2021. // import UIKit class Alerts { static func invalidSearchAlert(completion: @escaping () -> ()) -> UIAlertController { let alert = UIAlertController(title: "Oops!", message: "In order to search for your favorite super heroes please specify at least 3 characters", preferredStyle: .alert) alert.addAction(.init(title: "Got it", style: .cancel, handler: { _ in completion() })) return alert } static func networkErrorAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(.init(title: "Ok", style: .cancel)) if var topController = UIApplication.shared.windows.first?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } topController.present(alert, animated: true, completion: nil) } } }
true
16db12584b7c81b3d16d03041b323e1afdec28d8
Swift
ashraf789/Swift-Practice
/Hackerrank/Plus Minus.swift
UTF-8
851
4.03125
4
[ "MIT" ]
permissive
import Foundation /* Problem type: easy Function Description Complete the plusMinus function in the editor below. It should print out the ratio of positive, negative and zero items in the array, each on a separate line rounded to six decimals. plusMinus has the following parameter(s): arr: an array of integers */ /* Test case: -4 3 -9 0 4 1 Output: 0.500000 0.333333 0.166667 */ func plusMinus(arr: [Int]) -> Void { /* Plus = counter[0] Minus = counter[1] Zero = counter[2] */ var counter:[Int] = [0,0,0] let size:Int = arr.count for i in 0..<size{ if arr[i] > 0 { counter[0] += 1 }else if arr[i] < 0 { counter[1] += 1 }else{ counter[2] += 1 } } for i in 0...2{ print(String(format: "%.6f",Double(counter[i])/Double(size))) } } var arr:[Int] = [-4, 3, -9, 0, 4, 1] plusMinus(arr: arr)
true
2ddcf06e35f1905027757bd91309ce9927003ce6
Swift
saxes20/SeeFood
/SeeFood/SeeFood/ViewController.swift
UTF-8
3,813
2.765625
3
[]
no_license
// // ViewController.swift // SeeFood // // Created by James on 4/6/18. // Copyright © 2018 james. All rights reserved. // import UIKit class ViewController: UIViewController { let customCameraView = UIImageView() let bookmarksButton = UIButton() var detailsViewHeight = NSLayoutConstraint() let detailsView = UIView() var startLocation: CGPoint? var startHeight: CGFloat? override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() setupCustomCameraView() setupBookmarksButton() setupDetailsView() } override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) { if motion == .motionShake { detailsViewHeight.constant = Constants.DetailView.startingHeight UIView.animate(withDuration: 0.25) { self.view.layoutIfNeeded() } } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let location = touches.first?.location(in: view) { if location.isIn(detailsView.frame) { startLocation = location startHeight = detailsViewHeight.constant } } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if let location = touches.first?.location(in: view) { // checking if the start location is nil // if it is not nil, the user's touch started in the details view if let startLocation = startLocation, let startHeight = startHeight { detailsViewHeight.constant = startHeight + startLocation.y - location.y moveDetailView(in: location.y - startLocation.y < 0 ? .up : .down) } } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if let location = touches.first?.location(in: view) { if let startLocation = startLocation { self.startLocation = nil if location.distance(from: startLocation) < 10 && detailsViewHeight.constant == Constants.DetailView.startingHeight { detailsViewHeight.constant = view.frame.height * 3/4 UIView.animate(withDuration: 0.25) { self.view.layoutIfNeeded() } } else { moveDetailView(in: location.y - startLocation.y < 0 ? .up : .down) } } else { detailsViewHeight.constant = 100 UIView.animate(withDuration: 0.25) { self.view.layoutIfNeeded() } } } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) } func moveDetailView(in direction: Direction) { switch direction { case .up: if detailsViewHeight.constant > view.frame.height / 2 { detailsViewHeight.constant = view.frame.height * 3/4 } case .down: if detailsViewHeight.constant < view.frame.height / 2 { detailsViewHeight.constant = Constants.DetailView.startingHeight } } if startLocation == nil { if detailsViewHeight.constant > view.frame.height / 2 { detailsViewHeight.constant = view.frame.height * 3/4 } else { detailsViewHeight.constant = Constants.DetailView.startingHeight } } UIView.animate(withDuration: 0.25) { self.view.layoutIfNeeded() } } }
true
1186174aeef01faf874e67e1f4b951eb79792253
Swift
Longaray/ListagemDeFilmes
/ListagemDeFilmes/ListagemDeFilmes/ViewModel/FilmeViewModel.swift
UTF-8
1,278
2.96875
3
[]
no_license
// // FilmeViewModel.swift // ListagemDeFilmes // // Created by Rodrigo on 05/11/19. // Copyright © 2019 Rodrigo. All rights reserved. // import Foundation import UIKit struct FilmeViewModel { let titulo:String let rating:String let ano:String let overview:String let imagePosterURL:String let imageBackDropURL:String let filmeID:String init(filme: Filme) { self.filmeID = String(filme.id) self.titulo = filme.title ?? "" self.rating = String(format: "%.1f", filme.vote_average) if let stringAno = filme.release_date { self.ano = String((stringAno.split(separator: "-"))[0]) } else { self.ano = "" } self.overview = filme.overview ?? "" let urlPath = "https://image.tmdb.org/t/p/w500" self.imagePosterURL = (urlPath + filme.poster_path!) self.imageBackDropURL = (urlPath + filme.backdrop_path!) } func getDuracaoHora(duracao: String) -> String { var duracaoHoras = "" if let duracaoInt = Int(duracao) { duracaoHoras = String(format: "Duracao %ih %imin", (duracaoInt / 60), (duracaoInt % 60)) } return duracaoHoras } }
true
0b3d394174440a2aec4c24c12ebd6efe364d48a9
Swift
bluewhiteio/Presentations
/GameplayKit/Sample Code/Minmax/Sol/SuggestionEngine.swift
UTF-8
4,128
2.65625
3
[]
no_license
// // Suggestions.swift // Sol // // Created by Sash Zats on 10/3/15. // Copyright © 2015 Comyar Zaheri. All rights reserved. // import GameplayKit protocol SuggestionPredicate { func score(states states: [GKState]) -> Int? } private class BlockSuggestionPredicate: SuggestionPredicate { let block: [GKState] -> Int? init(block: [GKState] -> Int?) { self.block = block } private func score(states states: [GKState]) -> Int? { return block(states) } } class SuggestionEngine: NSObject { static let sharedInstance = SuggestionEngine() private static let AllStates: [GKState] = [Idle(), SwitchCity(), AddCity(), DeleteCity(), SwitchUnits(), FinishDemo(), Preferences()] private(set) var players: [GKGameModelPlayer]? private(set) var activePlayer: GKGameModelPlayer? private let player: Player = Player() private let stateMachine: StateMachine = StateMachine(states: SuggestionEngine.AllStates) private var predicates: [SuggestionPredicate] = [] var allStates: [GKState] = [] private let minmax: GKMinmaxStrategist = GKMinmaxStrategist() required override init() { players = [player] activePlayer = player super.init() minmax.gameModel = self minmax.maxLookAheadDepth = 1 minmax.randomSource = GKARC4RandomSource() } func enterState(type: AnyClass) -> Bool { if stateMachine.enterState(type) { allStates.append(stateMachine.currentState!) return true } return false } func suggest() -> Suggestion? { if let x = (minmax.bestMoveForPlayer(player) as? Update)?.state as? Suggestion { return x } assertionFailure() return nil } func register(type: AnyClass, predicate: [GKState] -> Int?) { register(BlockSuggestionPredicate{ states in if states.last?.dynamicType != type { return nil } return predicate(states) }) } func register(predicate: SuggestionPredicate) { predicates.append(predicate) } private func scoreForStates(states: [GKState]) -> Int { var maxScore: Int? for predicate in predicates { if let result = predicate.score(states: states) { if maxScore < result { maxScore = result } } } return maxScore ?? .min } } // MARK: GKGameModel extension SuggestionEngine: GKGameModel { func setGameModel(gameModel: GKGameModel) { guard let gameModel = gameModel as? SuggestionEngine else { assertionFailure() return } allStates = gameModel.allStates activePlayer = gameModel.activePlayer players = gameModel.players predicates = gameModel.predicates } func gameModelUpdatesForPlayer(player: GKGameModelPlayer) -> [GKGameModelUpdate]? { let result = SuggestionEngine.AllStates.filter{ stateMachine.canEnterState($0.dynamicType) } return result.map{ Update(state: $0) } } func applyGameModelUpdate(gameModelUpdate: GKGameModelUpdate) { if let update = gameModelUpdate as? Update { stateMachine.enterState(update.state.dynamicType) allStates.append(update.state) } else { assertionFailure() } } func scoreForPlayer(player: GKGameModelPlayer) -> Int { return scoreForStates(allStates) } } // MARK: NSCopying extension SuggestionEngine { @objc func copyWithZone(zone: NSZone) -> AnyObject { let copy = self.dynamicType.init() copy.setGameModel(self) return copy } } class StateMachine: GKStateMachine { } class Update: NSObject, GKGameModelUpdate { var value: Int = 0 let state: GKState init(state: GKState) { self.state = state } } private class Player: NSObject, GKGameModelPlayer { @objc var playerId: Int { return 42 } }
true
1d75dd6a2e6676ef8c1cb8c222e07972940177b3
Swift
Patryk1410/WeatherAppSwift
/WeatherApp/ForecastTableViewController.swift
UTF-8
1,618
2.515625
3
[]
no_license
// // ForecastTableViewController.swift // WeatherApp // // Created by patryk on 06.09.2017. // Copyright © 2017 patryk. All rights reserved. // import UIKit class ForecastTableViewController: UIViewController { @IBOutlet weak var forecastTableView: UITableView! var forecastData: ForecastData? var tableViewManager: TableViewManager? var dataProvider: ForecastProvider? override func viewDidLoad() { super.viewDidLoad() self.dataProvider = ForecastProvider() self.dataProvider?.delegate = self self.dataProvider?.forecastData = forecastData self.tableViewManager = TableViewManager(tableView: self.forecastTableView) self.tableViewManager?.delegate = self self.dataProvider?.requestData() } func initializeData(data: ForecastData) { self.forecastData = data } @IBAction func handleShowChart(_ sender: Any) { ViewControllerDispatcherImpl.instance.pushForecastChartViewController(navigationController: self.navigationController, weatherRecords: self.forecastData?.weatherRecords ?? []) } } extension ForecastTableViewController: TableViewManagerDelegate { func didSelect(_ item: DataObjectProtocol) { } func pinDelegate(_ item: DataObjectProtocol) { } } extension ForecastTableViewController: DataProviderDelegate { func didFinishFetching(_ data: [DataObjectProtocol]?) { self.tableViewManager?.addData(data) } func didStartFetching(_ data: [DataObjectProtocol]?) { } func didFinishFetchingWithError(_ error: NSError?) { } }
true
e8ca2191cc6399e54124d8678971dd1a7d02c1ec
Swift
Sob7y/Mvvm-demo
/MVVMDemo/Networking/NetworkDefaults.swift
UTF-8
411
2.5625
3
[]
no_license
// // NetworkDefaults.swift // // Created by Mohammed Khaled on 02/22/20. // Copyright © 2020 Mohammed Khaled. All rights reserved. // import Foundation struct NetworkDefaults { var baseUrl: String = "https://api.themoviedb.org/3" var apiKey: String = "81214f14b3b4fc4623c6b48bb307ab11" var language: String = "en-US" static var `defaults`: NetworkDefaults { let instance = NetworkDefaults() return instance } }
true
71bcc91db0aebdac6200bd3bcb534d2c64e93324
Swift
thangcao/VIPER_IOS
/viper/ExUiStoryBoard.swift
UTF-8
1,910
2.671875
3
[]
no_license
// // ExUiStoryBoard.swift // viper // // Created by Cao Thắng on 6/18/17. // Copyright © 2017 Cao Thắng. All rights reserved. // import UIKit class StoryboardController { static func initialViewControllerForStoryboardWithName(name: String) -> UIViewController? { let storyboard = UIStoryboard(name: name, bundle: nil) return storyboard.instantiateInitialViewController() } } // MARK: - UIStoryboard extension UIStoryboard { static var loginStoryboard: UIStoryboard { return UIStoryboard(name: "LoginStoryboard", bundle: nil) } static var customerFlowStoryboard: UIStoryboard { return UIStoryboard(name: "CustomerFlowStoryboard", bundle: nil) } static var customerSearchStoryboard: UIStoryboard { return UIStoryboard(name: "CustomerSearchStoryboard", bundle: nil) } } // MARK: - ViewController inside storyboard extension UIStoryboard { var loginController: LoginViewController { guard let vc = StoryboardController.initialViewControllerForStoryboardWithName(name: "LoginStoryboard") else { fatalError("LoginViewController couldn't be found in Storyboard file") } return vc as! LoginViewController } var customerFlow: CustomerViewController { guard let vc = StoryboardController.initialViewControllerForStoryboardWithName(name: "CustomerFlowStoryboard") else { fatalError("CutomerFlowViewController couldn't be found in Storyboard file") } return vc as! CustomerViewController } var customerSearch: CustomerSearchViewController { guard let vc = StoryboardController.initialViewControllerForStoryboardWithName(name: "CustomerSearchStoryboard") else { fatalError("CutomerFlowViewController couldn't be found in Storyboard file") } return vc as! CustomerSearchViewController } }
true
89cc5acd994bbcf7a6408962bc5c378be5c1dd13
Swift
shooooting/TIL
/MakeNavi/MakeNavi/ViewController.swift
UTF-8
6,556
2.546875
3
[ "MIT" ]
permissive
// // ViewController.swift // MakeNavi // // Created by ㅇ오ㅇ on 2020/08/02. // Copyright © 2020 shooooting. All rights reserved. // import UIKit class ViewController: UIViewController { private let upV: UIView = { let view = UIView() view.backgroundColor = .systemBackground return view }() private let upViewTitle = UILabel() private let inCollectionView = UIView() private let collectionV: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal return UICollectionView(frame: .zero, collectionViewLayout: layout) }() var isOneStepPaging = true var currentIndex: CGFloat = 0 override func viewDidLoad() { super.viewDidLoad() setUI() setConstraint() } private struct Standard { static let space: CGFloat = 8 static let inset: UIEdgeInsets = .init(top: 16, left: 16, bottom: 16, right: 16) } private func setUI() { [upV, upViewTitle, inCollectionView].forEach { view.addSubview($0) } upViewTitle.text = "PlayL:)st" upViewTitle.font = UIFont.boldSystemFont(ofSize: 35) inCollectionView.backgroundColor = .purple inCollectionView.addSubview(collectionV) collectionV.backgroundColor = .white // collectionV.isPagingEnabled = true collectionV.dataSource = self collectionV.delegate = self collectionV.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell") collectionV.decelerationRate = UIScrollView.DecelerationRate.fast } private func setConstraint() { upV.frame = CGRect(origin: .zero, size: CGSize(width: view.frame.width, height: view.frame.height / 6)) let space: CGFloat = 16 let guide = view.safeAreaLayoutGuide [upViewTitle, inCollectionView, collectionV].forEach { $0.translatesAutoresizingMaskIntoConstraints = false } NSLayoutConstraint.activate([ upViewTitle.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: space), upViewTitle.bottomAnchor.constraint(equalTo: upV.bottomAnchor, constant: -(space)), inCollectionView.topAnchor.constraint(equalTo: upV.bottomAnchor), inCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), inCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), inCollectionView.bottomAnchor.constraint(equalTo: guide.bottomAnchor), collectionV.topAnchor.constraint(equalTo: inCollectionView.topAnchor), collectionV.leadingAnchor.constraint(equalTo: view.leadingAnchor), collectionV.trailingAnchor.constraint(equalTo: view.trailingAnchor), collectionV.bottomAnchor.constraint(equalTo: inCollectionView.bottomAnchor) ]) } } extension ViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 5 } // func numberOfSections(in collectionView: UICollectionView) -> Int { // return 4 // } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) cell.backgroundColor = .purple return cell } } extension ViewController: UICollectionViewDelegate { func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { // item의 사이즈와 item 간의 간격 사이즈를 구해서 하나의 item 크기로 설정. // let layout = self.collectionV.collectionViewLayout as! UICollectionViewFlowLayout let cellWidthIncludingSpacing = view.frame.width - Standard.inset.left - Standard.inset.right + Standard.space // targetContentOff을 이용하여 x좌표가 얼마나 이동했는지 확인 // 이동한 x좌표 값과 item의 크기를 비교하여 몇 페이징이 될 것인지 값 설정 var offset = targetContentOffset.pointee let index = offset.x / cellWidthIncludingSpacing var roundedIndex = round(index) // scrollView, targetContentOffset의 좌표 값으로 스크롤 방향을 알 수 있다. // index를 반올림하여 사용하면 item의 절반 사이즈만큼 스크롤을 해야 페이징이 된다. // 스크로로 방향을 체크하여 올림,내림을 사용하면 좀 더 자연스러운 페이징 효과를 낼 수 있다. if scrollView.contentOffset.x > targetContentOffset.pointee.x { roundedIndex = floor(index) } else if scrollView.contentOffset.x < targetContentOffset.pointee.x { roundedIndex = ceil(index) } else { roundedIndex = round(index) } if isOneStepPaging { if currentIndex > roundedIndex { currentIndex -= 1 roundedIndex = currentIndex } else if currentIndex < roundedIndex { currentIndex += 1 roundedIndex = currentIndex } } // 위 코드를 통해 페이징 될 좌표값을 targetContentOffset에 대입하면 된다. offset = CGPoint(x: roundedIndex * cellWidthIncludingSpacing, y: -scrollView.contentInset.top) print(offset) targetContentOffset.pointee = offset } } extension ViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { Standard.inset } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { Standard.space } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = collectionView.frame.width - Standard.inset.left - Standard.inset.right let height = collectionView.frame.height - Standard.inset.top - Standard.inset.bottom // let size = collectionView.frame.size // let inset = Standard.inset // let width = size.width - inset.left - inset.right - Standard.space // let height = size.height - inset.top - inset.bottom return CGSize(width: width, height: height) } }
true
d61a9030730590774b85186e0111b35dec6522d5
Swift
omurayuki/VideoChatApp-iOS
/VideoChatApp/Presentation/Utility/Extension/AVCaptureDevice+Extension.swift
UTF-8
682
2.6875
3
[]
no_license
import Foundation import AVFoundation extension AVCaptureDevice { static func checkPermissionAudio(denied: () -> Void, restricted: () -> Void) { switch AVCaptureDevice.authorizationStatus(for: .audio) { case .authorized: break case .denied: denied() case .notDetermined: AVCaptureDevice.requestAccess(for: .audio) { result in Logger.debug("getAudioPermission: \(result)") } case .restricted: restricted() @unknown default: break } } }
true
7a6b3fe12923a626b3392f27c63a931058d44f52
Swift
sawijaya/wikimovie
/wikimovie/library/MovieService.swift
UTF-8
1,132
3.03125
3
[]
no_license
// // MovieService.swift // wikimovie // // Created by Salim Wijaya on 25/07/21. // import Foundation protocol IMovieService { var databaseService: IMovieDatabaseService { get set } var networkService: IMovieNetworkService { get set } func requestMovieAt(page: Int, completion: @escaping (_ movies:[Movie], _ currentPage: Int, _ totalPage: Int) -> Void) } class MovieService: IMovieService { var databaseService: IMovieDatabaseService var networkService: IMovieNetworkService init(databaseService: IMovieDatabaseService, networkService: IMovieNetworkService) { self.databaseService = databaseService self.networkService = networkService } func requestMovieAt(page: Int, completion: @escaping ([Movie], Int, Int) -> Void) { let movies:[Movie] = self.databaseService.fetchMovieAtPage(page) if movies.count == 0 { self.networkService.requestMovieAt(page: page) { (movies, page, totalPage) in completion(movies, page, totalPage) } } else { completion(movies, page, -1) } } }
true
7c55a0195cc74f2755284be58da97ebc665dfb50
Swift
qoncept/TensorSwift
/Tests/TensorSwiftTests/DimensionTests.swift
UTF-8
965
2.875
3
[ "MIT" ]
permissive
import XCTest @testable import TensorSwift class DimensionTests: XCTestCase { func testAdd() { do { let a = Dimension(2) let b = Dimension(3) XCTAssertEqual(a + b, 5) } } func testSub() { do { let a = Dimension(3) let b = Dimension(2) XCTAssertEqual(a - b, 1) } } func testMul() { do { let a = Dimension(2) let b = Dimension(3) XCTAssertEqual(a * b, 6) } } func testDiv() { do { let a = Dimension(6) let b = Dimension(2) XCTAssertEqual(a / b, 3) } } static var allTests : [(String, (DimensionTests) -> () throws -> Void)] { return [ ("testAdd", testAdd), ("testSub", testSub), ("testMul", testMul), ("testDiv", testDiv), ] } }
true
0dcd84ff5283c8b2eb36f6285656e492f4ee45d3
Swift
RomainPct/CSVGeneratorSwift
/Tests/CSVGeneratorSwiftTests/TestModels.swift
UTF-8
1,451
3.234375
3
[ "MIT" ]
permissive
// // File.swift // // // Created by Romain Penchenat on 08/09/2019. // import Foundation import CSVGeneratorSwift struct Truck : CSVExportable { var CSVFields: [Any] { return [name,engine,optionalFields] } let name:String let engine:Engine let optionalFields:[String:String] } struct Car : CSVExportable { var CSVFields: [Any] { return [name,dimensions,engine] } let name:String let dimensions:[Int] let engine:Engine } struct Engine : CSVExportable { var CSVFields: [Any] { return [type,autonomy] } enum EngineType : String { case electric case hybrid case combustion } let type:EngineType let autonomy:Int // Kilometers } class User: CSVExportable { init(id:Int, firstName:String, lastName:String, cars:[Car]) { self.id = id self.firstName = firstName self.lastName = lastName self.cars = cars } var CSVFields: [Any] { return [id,fullName,cars] } let id:Int let firstName:String let lastName:String let cars:[Car] var fullName: String { return "\(firstName) \(lastName)" } } struct Quote : CSVExportable { var CSVFields: [Any] { return [text,writtingDate] } let writtingDate = Date(timeIntervalSinceReferenceDate: 26000) let text:String }
true
e075028e868d8ab36cbcddeeb03932e57c1992b4
Swift
phuhuynh2411/TruyenTranh24h
/TruyenTranh24h/Extension/StringExtension.swift
UTF-8
1,039
3.28125
3
[]
no_license
// // StringExtension.swift // TruyenTranh24h // // Created by Huynh Tan Phu on 18/06/2021. // import Foundation extension String { var wordCounts: Int { let components = self.components(separatedBy: .whitespacesAndNewlines) let words = components.filter { !$0.isEmpty } return words.count } func words(_ numberOfWord: Int) -> String { let components = self.components(separatedBy: .whitespacesAndNewlines) let words = components.filter { !$0.isEmpty }.prefix(numberOfWord) return words.joined(separator: " ") } func fromBase64() -> String? { guard let data = Data(base64Encoded: self) else { return nil } return String(data: data, encoding: .utf8) } func toBase64() -> String { return Data(self.utf8).base64EncodedString() } func removeHTMLTags() -> Self { self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil) } }
true
c55b1c2b9eed8ae3e132fc24980a095da352feaa
Swift
JohnnyApps/Shreks
/Shreks/GameViewController.swift
UTF-8
8,649
2.8125
3
[ "MIT" ]
permissive
// // GameViewController.swift // Shreks // // Created by Jan Smolinski on 02/05/2018. // Copyright © 2018 Jan Smolinski. All rights reserved. // import UIKit import AVFoundation import MediaPlayer class GameViewController: UIViewController { @IBOutlet weak var fairyLabel: UILabel! @IBOutlet weak var tapButton: UIButton! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var godmother: UIImageView! @IBOutlet weak var image1: UIImageView! @IBOutlet weak var image2: UIImageView! @IBOutlet weak var image3: UIImageView! @IBOutlet weak var image4: UIImageView! var fairy1 = "welcome to beautiful fairy godmother world" var fairy2 = "here everyone is nice and you can find h a p p i n e s s and p e a c e" var fairy3 = "oh no is this s h r e k?!" var fairy4 = "fiona, fight him!!!!" var timer = Timer() var seconds = 11 var audioPlayer: AVAudioPlayer! var activePlayer = 1 //cross var gameState = [0, 0, 0, 0, 0, 0, 0, 0, 0] let winningCombinations = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] var gameIsActive = true @IBOutlet weak var label: UILabel! @IBAction func action(_ sender: Any) { if gameState[(sender as AnyObject).tag-1] == 0 && gameIsActive == true { gameState[(sender as AnyObject).tag-1] = activePlayer if activePlayer == 1 { (sender as AnyObject).setImage(UIImage(named: "shrekk.jpg")!, for: .normal) activePlayer = 2 } else { (sender as AnyObject).setImage(UIImage(named: "fiona.jpg")!, for: .normal) activePlayer = 1 } } for combination in winningCombinations { if gameState[combination[0]] != 0 && gameState[combination[0]] == gameState[combination[1]] && gameState[combination[1]] == gameState[combination[2]] { gameIsActive = false if gameState[combination[0]] == 1 { // shrek has won print("SHREK") label.text = "SHREK HAS WON!" } else { // fiona has won print("FIONA") label.text = "FIONA HAS WON!" } playAgainButton.isHidden = false label.isHidden = false image1.isHidden = true image2.isHidden = true image3.isHidden = true image4.isHidden = true audioPlayer.pause() } } gameIsActive = false for i in gameState { if i == 0 { gameIsActive = true break } } if gameIsActive == false { label.text = "DONKEY WON HEHEHEH" label.isHidden = false playAgainButton.isHidden = false audioPlayer.pause() image1.isHidden = true image2.isHidden = true image3.isHidden = true image4.isHidden = true } } @IBOutlet weak var playAgainButton: UIButton! @IBAction func playAgain(_ sender: Any) { gameState = [0, 0, 0, 0, 0, 0, 0, 0, 0] gameIsActive = true activePlayer = 1 playAgainButton.isHidden = true label.isHidden = true image1.isHidden = false image2.isHidden = false image3.isHidden = false image4.isHidden = false audioPlayer.play() for i in 1...9 { let button = view.viewWithTag(i) as! UIButton button.setImage(nil, for: UIControlState()) } } override func viewDidLoad() { super.viewDidLoad() fairyLabel.text = fairy1 let path = Bundle.main.path(forResource: "holding22", ofType: ".mp3")! let url = URL(fileURLWithPath: path) do { audioPlayer = try AVAudioPlayer(contentsOf: url) audioPlayer.prepareToPlay() } catch let error as NSError { print(error.debugDescription) } audioPlayer.play() playAgainButton.layer.cornerRadius = 6 playAgainButton.layer.shadowColor = UIColor.darkGray.cgColor playAgainButton.layer.borderWidth = 3 playAgainButton.layer.borderColor = UIColor.black.cgColor playAgainButton.backgroundColor = .green playAgainButton.layer.shadowOffset = CGSize(width: 0.0, height: 0.0) playAgainButton.layer.masksToBounds = false playAgainButton.layer.shadowRadius = 4 playAgainButton.layer.shadowOpacity = 0.5 playAgainButton.titleLabel?.adjustsFontSizeToFitWidth = true playButton.layer.cornerRadius = 6 playButton.layer.shadowColor = UIColor.darkGray.cgColor playButton.layer.borderWidth = 3 playButton.layer.borderColor = UIColor.green.cgColor playButton.backgroundColor = .black playButton.layer.shadowOffset = CGSize(width: 0.0, height: 0.0) playButton.layer.masksToBounds = false playButton.layer.shadowRadius = 4 playButton.layer.shadowOpacity = 0.5 playButton.titleLabel?.adjustsFontSizeToFitWidth = true image1.layer.masksToBounds = true image2.layer.masksToBounds = true image3.layer.masksToBounds = true image4.layer.masksToBounds = true image1.layer.cornerRadius = 3 image2.layer.cornerRadius = 3 image3.layer.cornerRadius = 3 image4.layer.cornerRadius = 3 godmother.layer.masksToBounds = true godmother.clipsToBounds = true godmother.layer.cornerRadius = 4 godmother.layer.shadowColor = UIColor.darkGray.cgColor godmother.layer.shadowOffset = CGSize(width: 0.0, height: 0.0) godmother.layer.masksToBounds = false godmother.layer.shadowRadius = 4 godmother.layer.shadowOpacity = 0.5 // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func Random() -> String { let numberOfImages: UInt32 = 7 let random = arc4random_uniform(numberOfImages) let imageName = "random\(random)" return imageName } @IBAction func goBack(_ sender: Any) { audioPlayer.stop() timer.invalidate() let storyBoardd : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let mainView = storyBoardd.instantiateViewController(withIdentifier: "MainVC") as! ViewController mainView.modalTransitionStyle = .flipHorizontal self.present(mainView, animated:true, completion:nil) } @IBAction func Tap(_ sender: Any) { if fairyLabel.text == fairy1 { fairyLabel.text = fairy2 } else if fairyLabel.text == fairy2 { fairyLabel.text = fairy3 godmother.image = #imageLiteral(resourceName: "mother1") } else if fairyLabel.text == fairy3 { fairyLabel.text = fairy4 godmother.image = #imageLiteral(resourceName: "mother2") playButton.isHidden = false tapButton.isHidden = true } } @IBAction func Play(_ sender: Any) { playButton.isHidden = true godmother.isHidden = true fairyLabel.isHidden = true timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(BlackViewController.Clock), userInfo: nil, repeats: true) } @objc func Clock() { image1.image = UIImage(named: Random()) image2.image = UIImage(named: Random()) image3.image = UIImage(named: Random()) image4.image = UIImage(named: Random()) } /* // 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
590ffaf8ec7629f42e3f6f6d3d2c9920275b42bb
Swift
hole19/media-viewer
/H19MediaViewer/MediaViewerTransitionAnimator.swift
UTF-8
6,604
2.578125
3
[ "MIT" ]
permissive
import UIKit public class MediaViewerTransitionAnimator: NSObject { // MARK: properties public var animationTime: TimeInterval = 0.2 public var sourceImageView: UIImageView? public var contentsView: MediaViewerContentsView! public var transitionDelegate: MediaViewerDelegate? // MARK: init public init(sourceImageView: UIImageView?, contentsView: MediaViewerContentsView, transitionDelegate: MediaViewerDelegate? = nil) { super.init() self.sourceImageView = sourceImageView self.contentsView = contentsView self.transitionDelegate = transitionDelegate } // MARK: public public func setupTransitionToDestinationImageView() { self.contentsView.interfaceAlpha = 0.0 guard let currentImageView = contentsView.scrollView.currentImageView(), let destinationSuperview = currentImageView.imageView.superview else { return } var sourceImageViewFrame: CGRect if let sourceImageView = sourceImageView, let sourceSuperview = sourceImageView.superview { sourceImageViewFrame = destinationSuperview.convert(sourceImageView.frame, from: sourceSuperview) } else { sourceImageViewFrame = currentImageView.frame sourceImageViewFrame.origin.y += currentImageView.frame.size.height } currentImageView.imageView.frame = sourceImageViewFrame currentImageView.imageView.alpha = 1.0 sourceImageView?.isHidden = true currentImageView.imageView.contentMode = .scaleAspectFill } public func transitionToDestinationImageView(_ animated: Bool, withCompletition completition: @escaping () -> (Void) = {}) { guard let currentImageView = contentsView.scrollView.currentImageView() else { return } let duration: TimeInterval = animated ? animationTime : 0.00 let center = currentImageView.imageView.center setupTransitionToDestinationImageView() let endImageFrame = frameToScaleAspectFitBoundToFrame(currentImageView.bounds, img: currentImageView.imageView) self.contentsView.scrollView.alpha = 1.0 UIView.animate(withDuration: duration, delay: 0.0, options: UIView.AnimationOptions.curveEaseIn, animations: { () -> Void in self.contentsView.interfaceAlpha = 1.0 currentImageView.imageView.frame = endImageFrame currentImageView.imageView.center = center }) { (finished) -> Void in currentImageView.imageView.contentMode = .scaleAspectFit currentImageView.imageView.frame = CGRect(x: 0.0, y: 0.0, width: self.contentsView.bounds.size.width, height: self.contentsView.bounds.size.height) completition() } } public func setupTransitionBackToSourceImageView(withImageView imageView: UIImageView?) { imageView?.isHidden = true } public func transitionBackToSourceImageView(_ animated: Bool, withCompletition completition: @escaping () -> (Void) = {}) { guard let currentImageView = contentsView.scrollView.currentImageView(), let currentSuperview = currentImageView.imageView.superview else { return } var endImageFrame = CGRect.zero var sourceImage = sourceImageView if let transitionDelegate = transitionDelegate, let image = currentImageView.imageModel, let imageView = transitionDelegate.imageViewForImage(image), let newSourceSuperview = imageView.superview { endImageFrame = currentSuperview.convert(imageView.frame, from: newSourceSuperview) sourceImage = imageView sourceImageView?.isHidden = false } else if let image = currentImageView.imageModel, let sourceImageView = sourceImageView, let sourceSuperview = sourceImageView.superview, image.sourceImageView === sourceImageView { endImageFrame = currentSuperview.convert(sourceImageView.frame, from: sourceSuperview) } else { sourceImage = nil endImageFrame = currentImageView.frame endImageFrame.origin.x = 0 endImageFrame.origin.y = currentImageView.frame.size.height } let duration: TimeInterval = animated ? animationTime : 0.00 setupTransitionBackToSourceImageView(withImageView: sourceImage) let center = currentImageView.imageView.center currentImageView.imageView.frame = frameToScaleAspectFit(currentImageView.imageView) currentImageView.imageView.center = center currentImageView.imageView.contentMode = .scaleAspectFill UIView.animate(withDuration: duration, delay: 0.0, options: UIView.AnimationOptions.curveEaseIn, animations: { () -> Void in self.contentsView.interfaceAlpha = 0.0 currentImageView.imageView.frame = endImageFrame }) { (finished) -> Void in sourceImage?.isHidden = false DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(20) / Double(NSEC_PER_SEC), execute: { completition() }) } } // MARK: private private func frameToScaleAspectFit(_ img: UIImageView) -> CGRect { guard let image = img.image, image.size.width > 0 && image.size.height > 0 else { return CGRect.zero } let ratioImg = (image.size.width) / (image.size.height) let ratioSelf = (img.frame.size.width) / (img.frame.size.height) if ratioSelf < 1 { return CGRect(x: 0, y: 0, width: img.frame.size.width, height: img.frame.size.width * 1.0/ratioImg) } else { return CGRect(x: 0, y: 0, width: img.frame.size.height * ratioImg, height: img.frame.size.height) } } private func frameToScaleAspectFitBoundToFrame(_ newFrame: CGRect, img: UIImageView) -> CGRect { guard let image = img.image, image.size.width > 0 && image.size.height > 0 else { return CGRect.zero } let ratioImg = (image.size.width) / (image.size.height) let ratioSelf = (newFrame.size.width) / (newFrame.size.height) if ratioSelf < 1 { return CGRect(x: 0, y: 0, width: newFrame.size.width, height: newFrame.size.width * 1.0/ratioImg) } else { return CGRect(x: 0, y: 0, width: newFrame.size.height * ratioImg, height: newFrame.size.height) } } }
true
62313b0f023c3f477f6b06127f9f52b1f2c28eec
Swift
radityakurnianto/RWNotificationView
/Classes/RWNotificationView.swift
UTF-8
6,007
2.6875
3
[ "MIT" ]
permissive
// // RWNotificationView.swift // RWNotificationView // // Created by Raditya Kurnianto on 1/9/19. // Copyright © 2019 Raditya Kurnianto. All rights reserved. // import UIKit open class RWNotificationView: UIViewController { var notifTopConstraint, notifLeftConstraint, notifRightConstraint, notifHeightConstraint, notifBottomConstraint: NSLayoutConstraint! var titleTopConstraint, titleLeftConstraint, titleRightConstraint, titleHeightConstraint: NSLayoutConstraint! var notificationTitle, notificationSubtitle: String? open var onClickNotification:(()->Void)? lazy var notificationView: UIView = { [unowned self] in let containerView = UIView() containerView.backgroundColor = .lightGray containerView.layer.cornerRadius = 8.0 return containerView }() lazy var buttonAction: UIButton = { [unowned self] in let button = UIButton() button.addTarget(self, action: #selector(doSomething), for: .touchUpInside) return button }() lazy var titleLabel: UILabel = { [unowned self] in let label = UILabel() label.textColor = .black label.font = UIFont.boldSystemFont(ofSize: 16) label.numberOfLines = 0 return label }() lazy var subtitleLabel: UILabel = { [unowned self] in let label = UILabel() label.textColor = .black label.numberOfLines = 2 label.font = UIFont.systemFont(ofSize: 14) return label }() public convenience init() { self.init(title: "", subtitle: nil) } public init(title: String, subtitle: String?) { self.notificationTitle = title self.notificationSubtitle = subtitle super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .clear setContent() createView() } @objc func doSomething() -> Void { onClickNotification?() self.dismiss(animated: false, completion: nil) } // MARK: - Setup View fileprivate func addNotificationConstraints() -> Void { notificationView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(notificationView) notifTopConstraint = notificationView.topAnchor.constraint(equalTo: view.topAnchor, constant: -100) notifLeftConstraint = notificationView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10) notifRightConstraint = notificationView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -10) NSLayoutConstraint.activate([notifTopConstraint, notifLeftConstraint, notifRightConstraint]) } fileprivate func addTitleConstraints() -> Void { titleLabel.translatesAutoresizingMaskIntoConstraints = false notificationView.addSubview(titleLabel) titleTopConstraint = titleLabel.topAnchor.constraint(equalTo: notificationView.topAnchor, constant: 15) titleLeftConstraint = titleLabel.leftAnchor.constraint(equalTo: notificationView.leftAnchor, constant: 15) titleRightConstraint = titleLabel.rightAnchor.constraint(equalTo: notificationView.rightAnchor, constant: -15) titleHeightConstraint = titleLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 21) NSLayoutConstraint.activate([titleTopConstraint, titleLeftConstraint, titleRightConstraint, titleHeightConstraint]) } fileprivate func addSubtitleConstraint() -> Void { subtitleLabel.translatesAutoresizingMaskIntoConstraints = false buttonAction.translatesAutoresizingMaskIntoConstraints = false notificationView.addSubview(subtitleLabel) notificationView.addSubview(buttonAction) let top = subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 15) let left = subtitleLabel.leftAnchor.constraint(equalTo: notificationView.leftAnchor, constant: 15) let right = subtitleLabel.rightAnchor.constraint(equalTo: notificationView.rightAnchor, constant: -15) notifBottomConstraint = subtitleLabel.bottomAnchor.constraint(equalTo: notificationView.bottomAnchor, constant: -15) NSLayoutConstraint.activate([top, left, right, notifBottomConstraint]) NSLayoutConstraint.activate([ buttonAction.topAnchor.constraint(equalTo: notificationView.topAnchor), buttonAction.leftAnchor.constraint(equalTo: notificationView.leftAnchor), buttonAction.rightAnchor.constraint(equalTo: notificationView.rightAnchor), buttonAction.bottomAnchor.constraint(equalTo: notificationView.bottomAnchor) ]) } func setContent() -> Void { titleLabel.text = notificationTitle if let subtitle = notificationSubtitle { subtitleLabel.text = subtitle } } fileprivate func createView() { addNotificationConstraints() addTitleConstraints() addSubtitleConstraint() animated(show: true) } fileprivate func animated(show param: Bool) -> Void { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in UIView.animate(withDuration: 0.6, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.9, options: .curveEaseInOut, animations: { self?.notificationView.transform = param ? CGAffineTransform(translationX: 0, y: 22 + (self?.notificationView.frame.height)!) : .identity }, completion: { (completed) in self?.animated(show: false) if !param { self?.dismiss(animated: false, completion: nil) } }) } } }
true
255f4a3f38ce37115b3a3532b5fe081c6ac99ea5
Swift
ReactiveCocoa/Loop
/Example/Misc/SwiftUI/CardView.swift
UTF-8
2,041
3.03125
3
[ "MIT" ]
permissive
import SwiftUI struct CardNavigationLink<Destination: View>: View { let label: String let color: Color let destination: Destination @State var canAnimate: Bool = false @State var isTouchedDown: Bool = false init(label: String, color: Color, @ViewBuilder destination: () -> Destination) { self.label = label self.color = color self.destination = destination() } var body: some View { NavigationLink( destination: destination, label: { Text(label) .font(.title) .fontWeight(.bold) .foregroundColor(.white) } ) .buttonStyle(CardButtonStyle(color: color)) } } struct CardView_Previews: PreviewProvider { static var previews: some View { NavigationView { ScrollView { CardNavigationLink(label: "Single Store + UIKit", color: .blue) { EmptyView() } } } } } struct CardButtonStyle: ButtonStyle { let color: Color func makeBody(configuration: Configuration) -> some View { VStack { Spacer() HStack { Spacer() configuration.label } } .frame(maxWidth: .infinity, minHeight: 100) .padding(16) .background( GeometryReader { proxy in RadialGradient( gradient: Gradient(colors: [self.color, self.color.opacity(0.5)]), center: UnitPoint(x: 0.9, y: 0.9), startRadius: proxy.size.height * 1.75, endRadius: proxy.size.height * 0.4 ) } ) .cornerRadius(20) .shadow(color: Color.gray, radius: 16) .padding(16) .scaleEffect(configuration.isPressed ? 0.95 : 1.0) .frame(maxWidth: .infinity) .animation(.spring(), value: configuration.isPressed) } }
true
bb77f6017df4b8dbcff3c4f72975038eeca34728
Swift
swarnsingh/CafeManagement
/Merchant Cafe App/Merchant Cafe App/ViewController.swift
UTF-8
1,375
2.5625
3
[]
no_license
/** * @author Swarn Singh. */ import UIKit class ViewController: UIViewController { override func viewDidAppear(_ animated: Bool) { let storyBoard : UIStoryboard = UIStoryboard(name: AppStoryBoard.Main.rawValue, bundle:nil) var nextViewController: UIViewController if PreferenceManager.isUserLogin() { nextViewController = storyBoard.instantiateViewController(withIdentifier: Constants.HOME_SEGUE) as! HomeViewController self.navigationController?.pushViewController(nextViewController, animated: true) } else { nextViewController = storyBoard.instantiateViewController(withIdentifier: Constants.LOGIN_SEGUE) as! LoginViewController self.present(nextViewController, animated:true, completion:nil) } } private func showAlert(message:String?) { let alert = UIAlertController(title: "Alert?", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alert, animated: true) } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
true
fc65f9e3745b08da8d076ad8a111d7419df40f29
Swift
nadaalmatouq/FirebaseTemplate
/FirebaseTemplate/Sample Views/SignUp.swift
UTF-8
2,092
3.109375
3
[]
no_license
// // Authentication.swift // FirebaseTemplate // // Created by Omar Alibrahim on 5/9/20. // Copyright © 2020 OMAR. All rights reserved. // import SwiftUI struct SignUp: View { @State var user: OmarUser = OmarUser() @State var password: String = "" @State var uid: String = "" @State var signedUp = false @State var signedUpFailed = false var body: some View { NavigationView { VStack{ TextField("first name", text: $user.firstname) .padding() TextField("last name", text: $user.lastname) .padding() TextField("email", text: $user.email) .padding() TextField("phone number", text: $user.phoneNumber) .padding() SecureField("password", text: $password) .padding() Button("Sign up", action: signUp) Spacer() } .alert(isPresented: $signedUp, content: signUpAlert) .padding() .navigationBarTitle("Sign up") }.alert(isPresented: $signedUpFailed, content: signUpFailedAlert) } func signUp(){ Networking.signUp(user: user, password: password, success: { uid in self.uid = uid self.signedUp = true }) { self.signedUpFailed = true } } func signUpAlert() -> Alert{ Alert(title: Text("Signed up!"), message: Text("You have signed up successfully with user id \(uid)"), dismissButton: .default(Text("Done"), action: { // })) } func signUpFailedAlert() -> Alert{ Alert(title: Text("Error!"), message: Text("Couldn't sign up with email \(self.user.email)."), dismissButton: .default(Text("Done"), action: { // })) } } struct SignUp_Previews: PreviewProvider { static var previews: some View { SignUp() } }
true
d5dda35f9ecc43d2772c7273f6d612643bff8f20
Swift
sayler8182/Theme
/Theme/ViewController.swift
UTF-8
2,204
2.984375
3
[]
no_license
// // ViewController.swift // Theme // // Created by Konrad on 10/09/2018. // Copyright © 2018 Konrad. All rights reserved. // import UIKit class ViewController: UIViewController { fileprivate var firstView: CustomView = CustomView() fileprivate var secondView: UIView = UIView() fileprivate lazy var toggleButton: UIButton = { let button: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 150, height: 44)) button.layer.cornerRadius = 8 button.backgroundColor = UIColor.black button.contentEdgeInsets = UIEdgeInsetsMake(8, 16, 8, 16) button.setTitle("Toggle", for: UIControlState.normal) button.addTarget(self, action: #selector(toggleClick(_:)), for: UIControlEvents.touchUpInside) return button }() override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(self.firstView) self.view.addSubview(self.secondView) self.view.addSubview(self.toggleButton) // register theme ThemeManager.shared.add(self, forceUpdate: true) } @objc func toggleClick(_ sender: UIButton) { if ThemeManager.shared.currentTheme is LightTheme { ThemeManager.shared.updateTheme(DarkTheme()) } else { ThemeManager.shared.updateTheme(LightTheme()) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let width: CGFloat = self.view.frame.width let height: CGFloat = self.view.frame.height / 2 self.firstView.frame = CGRect(x: 0, y: 0, width: width, height: height) self.secondView.frame = CGRect(x: 0, y: height, width: width, height: height) self.toggleButton.center = self.view.center } } // MARK: Themeable extension ViewController: Themeable { func updateTheme(_ theme: Theme) { self.secondView.backgroundColor = theme.secondaryColor if theme is LightTheme { self.toggleButton.setTitle("Toggle to dark", for: UIControlState.normal) } else { self.toggleButton.setTitle("Toggle to light", for: UIControlState.normal) } } }
true
46a34d47034d6b1ed5467b30b2bc5811ed45c03e
Swift
A-stro/City2CityAssess
/City2City729/Service/WeatherAPI.swift
UTF-8
676
3.03125
3
[]
no_license
// // WeatherAPI.swift // City2City729 // // Created by mac on 8/9/19. // Copyright © 2019 mac. All rights reserved. // import Foundation struct WeatherAPI { //api.openweathermap.org/data/2.5/weather?lat=33.7490&lon=84.3880&APPID=7cdcd7f9a8620c069b7159b27a5f7a34&units=imperial var city: City init(with city: City) { self.city = city } let base = "https://api.openweathermap.org/data/2.5/weather?" let key = "APPID=7cdcd7f9a8620c069b7159b27a5f7a34&units=imperial" var getUrl: URL? { let endpoint = base + key + "&lat=\(city.coordinates.latitude)&lon=\(city.coordinates.longitude)" return URL(string: endpoint) } }
true
76ddce835fabf7307a4867c32b44d345b88fbe6d
Swift
surayashivji/mello
/MelloApp/Controllers/Home CV Data Sources/DailyScheduleDataSource.swift
UTF-8
1,130
2.59375
3
[]
no_license
// // DailyScheduleDataSource.swift // MelloApp // // Created by Harrison Weinerman on 4/1/19. // Copyright © 2019 Suraya Shivji. All rights reserved. // import UIKit class DailyScheduleDataSource: NSObject, UITableViewDataSource, UITableViewDelegate { var schedule = UserScentManager.schedule(for: nil) var tableView: UITableView? func setDate(_ date: Date?) { schedule = UserScentManager.schedule(for: date) tableView?.reloadData() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return schedule.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView .dequeueReusableCell(withIdentifier: "scheduleCell", for: indexPath) as? ScheduleItemTableViewCell else { return UITableViewCell() } cell.setup(schedule[indexPath.row]) cell.layer.cornerRadius = 10 cell.layer.masksToBounds = true return cell } }
true
e8e762bccc25187cac3a724e004e7c09b27b3c2e
Swift
kean/Nuke
/Sources/Nuke/Processing/ImageProcessors+Circle.swift
UTF-8
1,046
2.9375
3
[ "MIT" ]
permissive
// The MIT License (MIT) // // Copyright (c) 2015-2023 Alexander Grebenyuk (github.com/kean). import Foundation #if !os(macOS) import UIKit #else import AppKit #endif extension ImageProcessors { /// Rounds the corners of an image into a circle. If the image is not a square, /// crops it to a square first. public struct Circle: ImageProcessing, Hashable, CustomStringConvertible { private let border: ImageProcessingOptions.Border? /// - parameter border: `nil` by default. public init(border: ImageProcessingOptions.Border? = nil) { self.border = border } public func process(_ image: PlatformImage) -> PlatformImage? { image.processed.byDrawingInCircle(border: border) } public var identifier: String { let suffix = border.map { "?border=\($0)" } return "com.github.kean/nuke/circle" + (suffix ?? "") } public var description: String { "Circle(border: \(border?.description ?? "nil"))" } } }
true
af46b568143375d952ff6b4bb9c95cfded5e5491
Swift
wanderwaltz/iMMPI
/iMMPI/Modules/Sources/MMPIRecordsListUI/RecordsListViewModel+Storage.swift
UTF-8
1,005
2.671875
3
[]
no_license
import Foundation import DataModel import Utils extension RecordStorage { public func makeViewModel( includeRecord: @escaping (RecordProtocol) -> Bool = Constant.value(true) ) -> RecordsListViewModel<RecordProtocol> { return RecordsListViewModel( provider: AsyncProvider({ completion in let startTimestamp = Date() DispatchQueue.global().async { if self.isEmpty { try? self.load() } let records = self.all.filter(includeRecord) DispatchQueue.main.async { let endTimestamp = Date() NSLog("Loaded \(records.count) records in \(endTimestamp.timeIntervalSince(startTimestamp)/1000.0) seconds") completion(records) } } }), delete: { item in try? self.remove(item) }) } }
true
8d92db93305c34405b0205802018ca949cc86499
Swift
wblt/Aolanya
/Meimeila/Classes/Home/ProductList/ViewModel/DDProductListViewModel.swift
UTF-8
1,600
2.5625
3
[]
no_license
// // DDProductListViewModel.swift // Mythsbears // // Created by HJQ on 2017/10/10. // Copyright © 2017年 HJQ. All rights reserved. // import UIKit import SwiftyJSON class DDProductListViewModel { var productListDatas: [DDProductListShopping] = [DDProductListShopping]() var numberPages: Int = 0 var tableView: UITableView! func getProductList(keyword: String, type: Int, successBlock: @escaping () -> ()) { DDHTTPRequest.request(r: ProductListAPI.productList(keyword: keyword, numberPages: numberPages, type: type), requestSuccess: { (result) in let model = DDProductListModel.init(fromJson: JSON.init(result)) if self.numberPages == 0 { self.productListDatas = model.shopping }else { model.shopping.forEach({ (data) in self.productListDatas.append(data) }) } let isNomore = model.shopping.count > 0 ? false : true self.endRefresh(isNomore: isNomore) successBlock() }, requestError: { (result, error) in self.endRefresh(isNomore: true) }) { (error) in self.endRefresh(isNomore: true) } } // tableView停止刷新 private func endRefresh(isNomore: Bool = false) { if numberPages == 0 { tableView.mj_header.endRefreshing() }else { tableView.mj_footer.endRefreshing() if isNomore { tableView.mj_footer.endRefreshingWithNoMoreData() } } } }
true
4dd4fcb981b8142f402e1d4ee65d830cd06c4a08
Swift
Ognjenm90/FitApp
/Plate.swift
UTF-8
1,868
3.1875
3
[]
no_license
// // Plate.swift // FitApp // // Created by Ognjen Milovanovic on 11.05.19. // Copyright © 2019 Ognjen Milivanovic. All rights reserved. // import UIKit enum ComponentName: String { case grams = "Gramm" case milliliters = "Mililiter" } typealias OutletComponent = (name: ComponentName, value: Int) struct Plate { enum Category: String { case meat = "mit Fleisch" case candy = "Suessigkeiten" case vegetables = "Gemuse" case fruit = "Obst"; case drink = "Trinken" case other } var id: Int var name: String var outlet: String var protein: String var calories:String var category: Category var categoryImage: UIImage? { switch category { case .vegetables: return UIImage(named: "CategoryVeget") case .fruit: return UIImage(named: "CategoryFruit") case .drink: return UIImage(named: "CategoryDrink") case .candy: return UIImage(named: "CategoryCandy") case .meat: return UIImage(named: "CategoryMeat") case .other: return UIImage(named: "CategoryOther") } } var outletComponents: [OutletComponent] { var components: [OutletComponent] = [] let rawComponents = outlet.components(separatedBy: "/") for rawComponent in rawComponents { guard let value = Int(rawComponent.trimmingCharacters(in: CharacterSet(charactersIn: "01234567890.").inverted)) else { continue } var component = ComponentName.grams if rawComponents.contains("ml") { component = .milliliters } components.append((component, value)) } return components } }
true
9a20d8c5c436c344216ea8b89a0f44fb96eeaf14
Swift
chuthin/CycleSwift
/CycleSwiftExample/CycleSwiftExample/Cells/GithubTextCell.swift
UTF-8
2,417
2.65625
3
[ "MIT" ]
permissive
// // GithubTextCell.swift // CycleSwift // // Created by chuthin on 3/4/19. // Copyright © 2019 chuthin. All rights reserved. // import Foundation import UIKit import CycleSwift public class GithubTextCell : UITableViewCell ,CellDataSource { public weak var actionDelegate: CellActionDelegate? public var data: Identifiable? fileprivate let name = UILabel() fileprivate let likebutton = UIButton() required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.name.translatesAutoresizingMaskIntoConstraints = false self.likebutton.translatesAutoresizingMaskIntoConstraints = false self.likebutton.tintColor = .blue self.likebutton.backgroundColor = .gray self.likebutton.addTarget(self, action: #selector(GithubTextCell.likeAction), for: .touchUpInside) selectionStyle = .none separatorInset = .zero name.numberOfLines = 0 self.likebutton.setTitle("Like", for: .normal) self.addSubview(name) self.addSubview(likebutton) let views = ["name":name,"like":likebutton] var allConstraints = [NSLayoutConstraint]() allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-24-[name]-8-|", options: [], metrics: nil, views: views) allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-12-[name]-12-|", options: [], metrics: nil, views: views) allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[like(50)]-12-|", options: [], metrics: nil, views: views) allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[like(48)]", options: [], metrics: nil, views: views) self.addConstraints(allConstraints) } @objc func likeAction() { if let indexPath = self.indexPath { self.actionDelegate?.action(action: "like", index: indexPath) } print("like") } var indexPath:IndexPath? = nil public func setDataContext(indexPath: IndexPath, data: Identifiable) { self.indexPath = indexPath if let data = data as? User { self.name.text = data.name } } }
true
1280014ae57f344f5d95666a0c01ad2455c0a5fd
Swift
0hoo/tddios
/Stock/Stock.swift
UTF-8
958
3.40625
3
[]
no_license
import Foundation final class Stock { let code: String let name: String let currentPrice: Double let priceDiff: Double let rateDiff: Double let isPriceUp: Bool let isPriceKeep: Bool var quantity = 0 var value: Double { return currentPrice * Double(quantity) } var priceDiffText: String { if isPriceKeep { return "0 +0.00%" } else if isPriceUp { return "▲ \(priceDiff) +\(rateDiff)%" } else { return "▼ \(priceDiff) -\(rateDiff)%" } } init(code: String, name: String, currentPrice: Double, priceDiff: Double, rateDiff: Double, isPriceUp: Bool, isPriceKeep: Bool) { self.code = code self.name = name self.currentPrice = currentPrice self.priceDiff = priceDiff self.rateDiff = rateDiff self.isPriceUp = isPriceUp self.isPriceKeep = isPriceKeep } }
true
06f137f358fcd3c46a4e611842dea7d1b6dd960c
Swift
andy1li/udacity-bios
/alien-adventure/Alien Adventure/MostCommonCharacter.swift
UTF-8
801
3.1875
3
[ "MIT" ]
permissive
// // MostCommonCharacter.swift // Alien Adventure // // Created by Jarrod Parkes on 10/4/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func charactersCount(_ inventory: [UDItem]) -> [Character: Int] { var count = [Character: Int]() inventory.flatMap({ item in item.name.lowercased().characters }).forEach({ character in if count[character] == nil { count[character] = 1 } else { count[character]! += 1 } }) return count } func mostCommonCharacter(inventory: [UDItem]) -> Character? { return (charactersCount(inventory) .max(by: {$0.1 < $1.1})? .0) ?? nil } }
true
bffdb8764cf03599e22004f3bcc4a2cc37edb885
Swift
MannarElkady/MovieTMDB-IOS-Application-Using-Swift
/MovieTMDB/Features/HomePage/Views/CardViewCellTableViewCell.swift
UTF-8
1,318
2.5625
3
[]
no_license
// // CardViewCellTableViewCell.swift // MovieTMDB // // Created by Manar on 6/6/20. // Copyright © 2020 Manar. All rights reserved. // import UIKit import Kingfisher class Cell { var movie : Movie? { didSet{ // let processor = DownsamplingImageProcessor(size: imageView.bounds.size)>> RoundCornerImageProcessor(cornerRadius: 20) let url = URL(string: Constants.BASE_IMAGE_URL + ((movie?.posterPath) ?? "" )) posterView.kf.setImage(with: url) titleLabel.text = movie?.title rateLabel.text = String(format:"%f", movie?.voteAverage ?? 0) + " / 10" releaseLabel.text = movie?.releaseDate } } @IBOutlet private weak var posterView: UIImageView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var rateLabel: UILabel! @IBOutlet private weak var releaseLabel: UILabel! private let xibName = "CardViewCellTableViewCell" override func awakeFromNib() { super.awakeFromNib() // Initialization code Bundle.main.loadNibNamed(xibName, owner: self, options: nil) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
true
01e99d17cf9ecaa567869299f6811af914ae6249
Swift
vikas-speedstar19/NewsApp
/News App/Networking/Models/NewsModel.swift
UTF-8
708
3
3
[]
no_license
// // NewsModel.swift // News App // // Created by monty on 27/02/21. // import Foundation struct NewsModel: Codable { // MARK: - Properties var source: NewsSourceModel? var author: String? var title: String? var description: String? var url: String? var urlToImage: String? var publishedAt: String? var content: String? // MARK: - Coding enum CodingKeys: String, CodingKey { case source = "source" case author = "author" case title = "title" case description = "description" case url = "url" case urlToImage = "urlToImage" case publishedAt = "publishedAt" case content = "content" } }
true
a931f307cf6aa60d574522dcf9bbb06425b68301
Swift
tomterror666/MyLotto
/MyLotto/MyLotto/Manager/HTTPManager.swift
UTF-8
2,055
2.6875
3
[ "MIT" ]
permissive
// // HTTPManager.swift // MyLotto // // Created by Andre Heß on 18/04/16. // Copyright © 2016 Andre Heß. All rights reserved. // import UIKit typealias RequestCompletion = (NSError?, AnyObject?) -> (Void) typealias RequestProgress = (NSProgress) -> (Void) class HTTPManager: NSObject { var sessionManager:AFHTTPSessionManager let lottoBasePath:NSString = "https://www.lotto.de/bin/" static func sharedManager() -> HTTPManager { let me = HTTPManager() return me } override init() { self.sessionManager = AFHTTPSessionManager(baseURL: NSURL(string: self.lottoBasePath as String)) super.init() self.configureSessionManager() } func configureSessionManager() { self.configureRequestSerializer() self.configureResponseSerializer() } func configureRequestSerializer() { let requestSerializer = AFHTTPRequestSerializer() self.sessionManager.requestSerializer = requestSerializer } func configureResponseSerializer() { let responseSerializer = AFHTTPResponseSerializer() self.sessionManager.responseSerializer = responseSerializer } func GET(urlString:NSString, parameters:NSDictionary?, progress:RequestProgress?, completion:RequestCompletion?) { let requestUrlString = (self.lottoBasePath as String) + (urlString as String) self.sessionManager.GET(requestUrlString, parameters: parameters, progress: { (downloadProgress:NSProgress) in if (progress != nil) { progress!(downloadProgress) } }, success: { (task:NSURLSessionDataTask, responseObject:AnyObject?) in if (completion != nil) { let jsonData = responseObject as! NSData let jsonDict = try? NSJSONSerialization.JSONObjectWithData(jsonData, options:NSJSONReadingOptions.AllowFragments) completion!(nil, jsonDict) } }, failure: { (task:NSURLSessionDataTask?, error:NSError) in if (completion != nil) { completion!(error, nil) } }) } }
true
7abebfd0bfbe4c746f351829c4a3ea84d472e45d
Swift
jogax/JLines
/JLines/MyPlayground.playground/Contents.swift
UTF-8
829
3.21875
3
[]
no_license
//: Playground - noun: a place where people can play import UIKit var str = "010255530" var str1 = "200150030" var any: AnyObject = str var arr1 = [AnyObject]() arr1.append(str) arr1.append(str1) var gesamt: NSString = String(arr1[0] as! NSString) + String(arr1[1] as! NSString) var st1 = gesamt.substringWithRange(NSRange(location: 0, length: 9)) as NSString var st2 = gesamt.substringWithRange(NSRange(location: 9, length: 9)) as NSString var farbe1 = st2.substringWithRange(NSRange(location: 0, length: 3)) var farbe2 = st2.substringWithRange(NSRange(location: 3, length: 3)) var farbe3 = st2.substringWithRange(NSRange(location: 6, length: 3)) let red = 25 let green = 3 let blue = 143 let redStr = String(format: "%03d", red) let greenStr = String(format: "%03d", green) let blueStr = String(format: "%03d", blue)
true
6a6a35a792ed4aec36f331f2c25b6d3e2cdc6ef9
Swift
shyh5/Swift
/Protocol.playground/Contents.swift
UTF-8
1,643
4.375
4
[]
no_license
//: Playground - noun: a place where people can play import UIKit var str = "Hello, Protocol" //Mutating 方法要求 主要用于值类型(结构体和枚举)的实例方法中,需要改变协议中方法的值时使用。 protocol Togglable { mutating func toggle() } enum OnOffSwitch : Togglable { case off, on mutating func toggle() { switch self { case .off: self = .on case .on: self = .off } } } var switch1 = OnOffSwitch.off switch1.toggle() //构造器类型 protocol anyProtocol { init(someParameter: Int) } //构造器要求在类中的实现 需要required修饰符 class SomeClass: anyProtocol { required init(someParameter: Int) { //这里是构造器的实现部分 } } //使用 required 修饰符可以确保所有子类也必须提供此构造器实现,从而也能符合协议。值得注意的是:如果类已经被标记为 final ,那么不需要在协议构造器的实现中使用 required 修饰符,因为 final 类不 能有子类;如果一个子类重写了父类的指定构造器,并且该构造器满足了某个协议的要求,那么该构造器的实现需要同时标 注 required 和 override 修饰符: protocol someProtocol { init() } class SomeSuperClass { init() { //这里是构造器的实现部分 } } class SomeSubClass : SomeSuperClass , someProtocol { //因为采纳协议 + required //因为继承父类 + override required override init (){ //这里是构造器实现的部分 } }
true
7e0749095c1134c79bb75788b3b90a84d39f9b95
Swift
johnkriston/CarGame
/NextScene1.swift
UTF-8
2,223
2.859375
3
[]
no_license
// // NextScene1.swift // CarGame // // Created by John Kriston on 7/13/16. // Copyright © 2016 John Kriston. All rights reserved. // import SpriteKit class NextScene1: SKScene { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(size: CGSize) { super.init(size: size) backgroundColor = SKColor.blackColor() var bubble: SKSpriteNode! var text: SKLabelNode! var text1: SKLabelNode! var text2: SKLabelNode! var bubbletwo: SKSpriteNode! let background = SKSpriteNode(imageNamed: "road") background.size = CGSizeMake(size.width, size.height) background.position = CGPoint(x: size.width/2, y: size.height/2) background.zPosition = 0 addChild(background) let drivingcar = SKSpriteNode(imageNamed: "car123") drivingcar.size = CGSizeMake(125, 75) drivingcar.position = CGPoint(x: 550, y: 75) drivingcar.zPosition = 1 addChild(drivingcar) bubbletwo = SKSpriteNode(imageNamed: "bubble") bubbletwo.size = CGSizeMake(200, 200) bubbletwo.position = CGPoint(x: 125,y: 75 ) bubbletwo.zPosition = 1 addChild(bubbletwo) text = SKLabelNode(fontNamed: "ChalkboardSE-Bold") text.fontSize = 13 text.zPosition = 2 text.fontColor = SKColor.blackColor() text.position = CGPoint(x: 0, y: 15) text.text = "Let's use Dijkstra's" bubbletwo.addChild(text) text1 = SKLabelNode(fontNamed: "ChalkboardSE-Bold") text1.fontSize = 13 text1.zPosition = 2 text1.fontColor = SKColor.blackColor() text1.position = CGPoint(x: 0, y: 0) text1.text = "algorithm!" bubbletwo.addChild(text1) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { transitionToNewScreen() } func transitionToNewScreen(){ let reveal = SKTransition.fadeWithDuration(0.5) let nextScene = GameScene(size: self.size) self.view!.presentScene(nextScene, transition: reveal) } }
true
4aa6f126c49935c4c0401d4a36bc960402cf81dd
Swift
SDGGiesbrecht/SDGCornerstone
/Sources/SDGGeometry/CGPoint.swift
UTF-8
1,035
2.609375
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* CGPoint.swift This source file is part of the SDGCornerstone open source project. https://sdggiesbrecht.github.io/SDGCornerstone Copyright ©2016–2023 Jeremy David Giesbrecht and the SDGCornerstone project contributors. Soli Deo gloria. Licensed under the Apache Licence, Version 2.0. See http://www.apache.org/licenses/LICENSE-2.0 for licence information. */ import Foundation #if canImport(CoreGraphics) import CoreGraphics // Not included in Foundation on iOS. #endif import SDGMathematics extension CGPoint { // MARK: - Conversions #if canImport(CoreGraphics) internal init(_ point: TwoDimensionalPoint<Double>) { self = CGPoint(x: CGFloat(point.x), y: CGFloat(point.y)) } #endif } #if canImport(CoreGraphics) extension CGPoint: @unchecked Sendable, TwoDimensionalPointProtocol { // MARK: - PointProtocol public typealias Vector = CGVector // MARK: - TwoDimensionalPointProtocol @inlinable public init(_ x: Vector.Scalar, _ y: Vector.Scalar) { self.init(x: x, y: y) } } #endif
true
40a805b09e0c69ee60971bef38f836bffec4c1c2
Swift
rfwl/test
/prod/zdios1/zdios04h_TwoVC/zdios03/字典输入法/键盘/KeyboardViewController.swift
UTF-8
4,944
2.65625
3
[]
no_license
// // KeyboardViewController.swift // ZiDianKeyboard // // Created by Richard Feng on 27/11/16. // Copyright © 2016 Wanlou Feng. All rights reserved. // ///https://stackoverflow.com/questions/26180822/swift-adding-constraints-programmatically // import UIKit class KeyboardViewController: UIInputViewController { //======================================================================== // Data Members let toolbarView : ToolbarView = ToolbarView() let contentView: KeyLevelView = KeyLevelView() //======================================================================== // overrides override func viewDidLoad() { super.viewDidLoad() Commander.contentView = contentView Commander.textDocumentProxy = self.textDocumentProxy Commander.keyboardViewController = self Configuration.compute() loadToolbarAndContentViews() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateContentViewHeight() Commander.reportViewTransition() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.view.layoutIfNeeded() Commander.drawDefault() } //======================================================================== // Add and layout toolbar and content view var contentViewHeightConstraint:NSLayoutConstraint? func loadToolbarAndContentViews(){ self.toolbarView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.toolbarView) self.toolbarView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.toolbarView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true self.toolbarView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true self.toolbarView.heightAnchor.constraint(equalToConstant: Configuration.Toolbar_Height).isActive = true //------------------------------------------------------------------ self.contentView.translatesAutoresizingMaskIntoConstraints = false //self.contentView.backgroundColor = UIColor.red self.view.addSubview(self.contentView) //self.contentView.topAnchor.constraint(equalTo: self.toolbarView.topAnchor, constant: Configuration.Toolbar_Height).isActive = true self.contentView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.contentView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true self.contentView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true contentViewHeightConstraint = self.contentView.heightAnchor.constraint(equalToConstant: 120 ) } func updateContentViewHeight(){ let dif:CGFloat = self.view.frame.height.subtracting(Configuration.Toolbar_Height) contentViewHeightConstraint?.constant = dif contentViewHeightConstraint!.isActive = true self.view.layoutIfNeeded() } //======================================================================== // Operations: will be called from commander func gotoNextIMe(){ self.advanceToNextInputMode(); } func closeIME(){ self.dismissKeyboard(); } //======================================================================== } // end of class /* // The next is required to give right height to content view after screen rotations. //self.view.layoutIfNeeded() //let dif:CGFloat = self.view.frame.height.subtracting( self.toolbarHeight) // This line must be in viewDidAppear() since it has used self.frame.height. //print("viewDidLayoutSubviews") // //constraint!.constant = 120 //self.view.layoutIfNeeded() //var mNumberKeyLevel:[KeyLevel]? = buildKeyLevelArrayFromCommaSeparatedString(numberKeyLevelDefinition) //var mAlphabetKeyLevel:[KeyLevel]? = buildKeyLevelArrayFromCommaSeparatedString(alphabetKeyLevelDefinition) //let mSymbolKeyLevel:[KeyLevel]? = buildKeyLevelArrayFromCommaSeparatedString(symbolKeyLevelDefinition) //contentView.drawKeyLevelArray(mSymbolKeyLevel) let numberKeyLevelDefinition:String = "0,1,2,3,4,5,6,7,8,9,+,-,*,/,=,comma, ,?" let alphabetKeyLevelDefinition:String = "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,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,+,-,*,/,=,comma" let symbolKeyLevelDefinition:String = "!,@,#,$,%,^,&,*,(,),_,+,{,},[,],<,>,/,comma, ," func buildKeyLevelArrayFromCommaSeparatedString(_ css:String) -> [KeyLevel]? { let ary = css.characters.split{$0 == ","}.map(String.init) if ary.count<1 {return nil} var lvls:[KeyLevel]=[KeyLevel]() for i in 0..<ary.count { var txt=ary[i] if txt == "comma" {txt = ","} //if txt == "" {continue} let lvl:KeyLevel = KeyLevel() lvl.level = 2 lvl.text = txt lvls.append(lvl) } if lvls.count > 0 { return lvls } return nil } */
true
c6f545799534a5a19f77a8ed26998f0dee532579
Swift
xuejianyong/IOS-AImergence
/AImergence2/ImagineModel002.swift
UTF-8
3,091
2.6875
3
[]
no_license
// // WorldScene1.swift // AImergence // // Created by Olivier Georgeon on 11/02/16. // CC0 No rights reserved. // import SceneKit class ImagineModel002: ImagineModel001 { var leftFlippableNode: SCNFlipTileNode? var rightFlippableNode: SCNFlipTileNode? override func imagine(experience: Experience) { switch experience.hashValue { case 00: robotNode.feelLeft() if leftFlippableNode == nil { leftFlippableNode = createFlipTileNode(tileColor(experience), position: robotNode.positionCell(robotNode.robot.cellLeft()) + tileYOffset, direction: .south) leftFlippableNode?.appear(0.2) } else { leftFlippableNode?.colorize(tileColor(experience), delay: 0.2) } spawnExperienceNode(experience, position: robotNode.positionCell(robotNode.robot.cellLeft()) + tileYOffset, delay: 0.2) case 01: robotNode.feelLeft() if leftFlippableNode == nil { leftFlippableNode = createFlipTileNode(tileColor(experience), position: robotNode.positionCell(robotNode.robot.cellLeft()) + tileYOffset) leftFlippableNode?.appearAndFlip(false, delay: 0.2) } else { leftFlippableNode?.colorizeAndFlip(tileColor(experience), clockwise: false, delay: 0.2) } rightFlippableNode?.flip(delay: 0.2) spawnExperienceNode(experience, position: robotNode.positionCell(robotNode.robot.cellLeft()) + tileYOffset, delay: 0.2) case 10: robotNode.feelRight() if rightFlippableNode == nil { rightFlippableNode = createFlipTileNode(tileColor(experience), position: robotNode.positionCell(robotNode.robot.cellRight()) + tileYOffset, direction: .south) rightFlippableNode?.appear(0.2) } else { rightFlippableNode?.colorize(tileColor(experience), delay: 0.2) } spawnExperienceNode(experience, position: robotNode.positionCell(robotNode.robot.cellRight()) + tileYOffset, delay: 0.2) case 11: robotNode.feelRight() if rightFlippableNode == nil { rightFlippableNode = createFlipTileNode(tileColor(experience), position: robotNode.positionCell(robotNode.robot.cellRight()) + tileYOffset) rightFlippableNode?.appearAndFlip(delay: 0.2) } else { rightFlippableNode?.colorizeAndFlip(tileColor(experience), delay: 0.2) } leftFlippableNode?.flip(false, delay: 0.2) spawnExperienceNode(experience, position: robotNode.positionCell(robotNode.robot.cellRight()) + tileYOffset, delay: 0.2) default: break } } func createFlipTileNode(_ color: UIColor?, position: SCNVector3, direction:Compass = .north) -> SCNFlipTileNode { let node = SCNFlipTileNode(color: color, direction: direction) node.position = position worldNode.addChildNode(node) return node } }
true
82d49521ae175aea5fa8880929e703dfc471764f
Swift
albebaubles/ABControls
/ABControls/ABGradientRadial.swift
UTF-8
1,671
2.59375
3
[ "MIT" ]
permissive
// // ABGradientRadial.swift // ABControls // // Created by Alan Corbett on 8/14/18. // Copyright © 2018 AlbeBaubles LLC. All rights reserved. // import UIKit @IBDesignable public class ABGradientRadial: ABControl { public var colors: CFArray = [UIColor.green.cgColor, UIColor.yellow.cgColor] as CFArray { didSet { setNeedsDisplay() } } @IBInspectable public var radius: CGFloat = 340 / 2 { didSet { setNeedsDisplay() } } /// required for dev time required public init(frame: CGRect) { super.init(frame: frame) invalidateIntrinsicContentSize() } /// require for runtime required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) #if !TARGET_INTERFACE_BUILDER sharedInit() #endif } override public func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() sharedInit() } private func sharedInit() { isUserInteractionEnabled = false } override public func draw(_ rect: CGRect) { // Setup view let locations = [0.0, 1.0] as [CGFloat] let center = CGPoint(x: self.bounds.size.width / 2, y: self.bounds.size.height / 2) // Prepare a context and create a color space let context = UIGraphicsGetCurrentContext()! context.saveGState() let colorSpace = CGColorSpaceCreateDeviceRGB() // Create gradient object from our color space, color components and locations let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: locations) // Draw a gradient context.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: radius, options: CGGradientDrawingOptions(rawValue: 0)) context.restoreGState() } }
true
516aa785d1b17147eb325694b8ee2a1f0ff9273b
Swift
helje5/SwiftObjCBridge
/Tests/SwiftObjCBridgeTests/SwiftObjCBridgeTests.swift
UTF-8
1,928
2.546875
3
[]
no_license
// // Created by Helge Heß on 2019-01-30. // Copyright © 2019 ZeeZide GmbH. All rights reserved. // import XCTest @testable import SwiftObjCBridge final class SwiftObjCBridgeTests: XCTestCase { func testClassLookup() throws { let udc = ObjC.NSUserDefaults XCTAssertNotNil(udc.handle) } func testClassMethodLookup() throws { let call = ObjC.NSUserDefaults.alloc // <= No () yet! print("Callable:", call) XCTAssertNotNil(call.instance.handle) XCTAssertEqual(call.baseName, "alloc") } func testClassMethodInvocation() throws { let udNew = ObjC.NSUserDefaults.alloc() // <= Now with () ! print("instance:", udNew) XCTAssertNotNil(udNew.handle) } func testClassMethodInvocation2() throws { let ud = ObjC.NSUserDefaults.standardUserDefaults() print("instance:", ud) XCTAssertNotNil(ud.handle) } func testInstanceMethodInvocation() throws { let ud = ObjC.NSUserDefaults.standardUserDefaults() let domains = ud.volatileDomainNames() XCTAssertNotNil(domains.handle) } func testMethodWithArg() throws { let ma = ObjC.NSArray.alloc().`init`() let ma2 = ma.arrayByAddingObject("Hello") print("★:", ma2) } func testCallableClass() throws { let ms = ObjC.NSMutableArray() ms.addObject("Happy") ms.addObject("Birthday") print("★★★:", ms) } static var allTests = [ ("testClassLookup", testClassLookup), ("testClassMethodLookup", testClassMethodLookup), ("testClassMethodInvocation", testClassMethodInvocation), ("testClassMethodInvocation2", testClassMethodInvocation2), ("testInstanceMethodInvocation", testInstanceMethodInvocation), ("testMethodWithArg", testMethodWithArg), ] }
true
17bdcd0bb7b800d1cbe8cc940161bf7ee726214a
Swift
RohanMannem/FourLife
/FourLife/Excercise/ExerciseObject.swift
UTF-8
587
2.796875
3
[]
no_license
// // ExerciseObject.swift // FourLife // // Created by Rohan Mannem on 3/19/18. // Copyright © 2018 DeAnza. All rights reserved. // import UIKit class ExerciseObject: NSObject { var iName = "" var iImage = UIImage(named: "") var iDesc = "" var iCheck = false // Date Info (Needed for History) var iDate : Date init(iName: String, iImage: UIImage, iDesc: String, iCheck: Bool, iDate: Date) { self.iName = iName self.iImage = iImage self.iDesc = iDesc self.iCheck = iCheck self.iDate = iDate } }
true
62187176357781a208cdd9bb9f77c2f9d2884eab
Swift
prashuk/iOS-InterviewQues
/HigherOrderFunction.playground/Contents.swift
UTF-8
3,946
4.4375
4
[]
no_license
import Foundation import UIKit // Use these functions to operate on Swift collection types such as Array, set or Dictionary. let nums: [Int] = [2,3,4,5,4,7,2,6,8,9] // Map // Use map to loop over a collection and apply the same operation to each element in the collection. // Multiply every number by 10 var mulBy10: [Int] = [] for num in nums { mulBy10.append(num * 10) } print(mulBy10) // OR WITH MAP var mulBy10Map: [Int] = [] mulBy10Map = nums.map({ a in a * 10 }) mulBy10Map = nums.map({ $0 * 10 }) mulBy10Map = nums.map { $0 * 10 } print(mulBy10Map) // Get index as well with enumerated mulBy10Map.enumerated().map { (index, element) in print("Element \(element) is at index \(index)") } // Replace a with (key, value) if it is a map // --------------------------------------------------------------- // // Filter // Use filter to loop over a collection and return an Array containing only those elements that match an include condition. // Get only even numbers var evenNums: [Int] = [] for num in nums { if num % 2 == 0 { evenNums.append(num) } } print(evenNums) // OR WITH FILTER var evenNumsFilter: [Int] = [] evenNumsFilter = nums.filter({ a in a % 2 == 0 }) evenNumsFilter = nums.filter({ $0 % 2 == 0 }) evenNumsFilter = nums.filter { $0 % 2 == 0 } print(evenNumsFilter) let numMoreThan5 = nums.filter({ $0 > 5 }) print(numMoreThan5) // Replace a with (key, value) if it is a map // $0 is the key, $1 is the value for closure expressions // --------------------------------------------------------------- // // Reduce // Use reduce to combine all items in a collection to create a single new value. // Get sum of all numbers var sum = 0 for num in nums { sum += num } print(sum) // OR BY REDUCE sum = nums.reduce(0, { x, y in x + y }) sum = nums.reduce(100, { x, y in x + y }) sum = nums.reduce(0, { $0 + $1 }) sum = nums.reduce(0) { $0 + $1 } sum = nums.reduce(0, +) print(sum) /* This reduce function will iterate four times. Initial value is 0, x is 0, y is 1 → returns x+y . So, initial value or Result becomes 1. Initial value or Result is 1, x is 1, y is 2 → returns x+y . So, initial value or Result becomes 3 . Initial value or Result is 3, x is 3, y is 3→ returns x+y . So, initial value or Result becomes 6. Initial value or Result is 6, x is 6, y is 4→ returns x+y . So, initial value or Result becomes 10 */ let codes = ["abc","def","ghi"] let mergeText = codes.reduce("", +) print(mergeText) let bookAmount = ["harrypotter": 100.0, "junglebook": 1000.0] var books = "" books = bookAmount.reduce("Books are ") { x, y in x + y.key + " " } var amount = 0.0 amount = bookAmount.reduce(0) { x, y in x + y.value } books = bookAmount.reduce("Books are ") { $0 + $1.key + " " } amount = bookAmount.reduce(0) { $0 + $1.value } amount = bookAmount.reduce(0) { $0 + $1.1 } print("\(books). Total price \(amount)") // --------------------------------------------------------------- // // FlatMap // Flatmap is used to flatten a collection of collections. But before flattening the collection, we can apply map to each elements. // Update all letters to uppercase and combine all arrays in one let strs = [["abc","def","ghi"],["abc","def","ghi"]] let newStrs = strs.flatMap { $0.map { $0.uppercased() } } print(newStrs) /* [“abc”,”def”,”ghi”].map { $0.uppercased() } - step 1 [“abc”,”def”,”ghi”].map { $0.uppercased() } - step 2 */ // --------------------------------------------------------------- // // All combine let arr = [[1,2,3,4], [5,6]] var ans = arr.flatMap{$0}.map{$0 * 10}.filter{$0 % 2 == 0} print(ans.reduce(0, +)) // --------------------------------------------------------------- // // Compact Map // Returns an array containing the non-nil results of calling the given transformation with each element of this sequence. let array = [1, 2, nil, 4, nil, 5, 6] let compactArray = array.compactMap { $0 } print(compactArray)
true
f2c27891c16c7efd0cdeb5e088f94655ef3ac1e9
Swift
luximetr/ShopApp
/ShopApp/PresentationLayer/Helpers/Models/Appearance/Appearance.swift
UTF-8
1,505
2.796875
3
[]
no_license
// // Appearance.swift // ShopApp // // Created by Oleksandr Orlov on 26/7/20. // Copyright © 2020 Deskera. All rights reserved. // import SwiftUI struct Appearance { // MARK: - Properties let background: Background let text: Text let statusBar: StatusBar let navigation: Navigation let tabBar: TabBar let action: ActionType let divider: DividerType let scrollIndicator: ScrollIndicator let keyboard: Keyboard // MARK: - Types struct Background { let primary: Color let secondary: Color let shadow: Color } struct Text { let primary: Color let secondary: Color let disruptive: Color let positive: Color } struct StatusBar { let style: StatusBarStyle } struct Navigation { let background: Color let tint: Color let shadow: Color } struct TabBar { let background: Color let selectedTint: Color let unselectedTint: Color let shadow: Color } struct ActionType { let primary: Action let secondary: Action let positive: Action } struct Action { let background: Color let title: Color let shadow: Color } struct DividerType { let primary: Divider let disruptive: Divider } struct Divider { let background: Color } struct ScrollIndicator { let style: UIScrollView.IndicatorStyle } struct Keyboard { let style: UIKeyboardAppearance } } let appearance = AppearancesFactory().createAppearance(type: .light)
true
237847ce33e90a7649c57fa357d40663687f5250
Swift
appssemble/Parchment
/Parchment/Protocols/PagingMenuDataSource.swift
UTF-8
200
2.78125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import Foundation public protocol PagingMenuDataSource: AnyObject { func pagingItemBefore(pagingItem: PagingItem) -> PagingItem? func pagingItemAfter(pagingItem: PagingItem) -> PagingItem? }
true
6b5d4757060a47d9c4a5e62d220f246350255683
Swift
davidmfry/MemeMe
/MemeMe/MemeTableView.swift
UTF-8
1,953
2.546875
3
[]
no_license
// // MemeTableView.swift // MemeMe // // Created by David on 3/11/15. // Copyright (c) 2015 David Fry. All rights reserved. // import UIKit class MemeTableView: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var memes: [Meme]! override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self self.tableView.dataSource = self // This code does not work, but in the lesson it said to add this in // let object = UIApplication.sharedApplication().delegate // let appDelegate = object as AppDelegate // memes = appDelegate.memes } override func viewDidAppear(animated: Bool) { } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (UIApplication.sharedApplication().delegate as AppDelegate).memes.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("TABLECELL", forIndexPath: indexPath) as UITableViewCell cell.imageView?.image = (UIApplication.sharedApplication().delegate as AppDelegate).memes[indexPath.row].memedImage cell.textLabel?.text = (UIApplication.sharedApplication().delegate as AppDelegate).memes[indexPath.row].topTitle return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "toMemeDetailView" { let detailVC = segue.destinationViewController as MemeDetailViewController var memeIndex = self.tableView.indexPathForSelectedRow()?.row detailVC.savedMeme = (UIApplication.sharedApplication().delegate as AppDelegate).memes[memeIndex!] } } }
true
9c31e3f17db55c621ada520686b2f16e02476f4c
Swift
appycoda/ToDoList
/To Do List/FirstViewController.swift
UTF-8
1,757
2.8125
3
[]
no_license
// // FirstViewController.swift // To Do List // // Created by Abdullah Alharbi on 3/9/17. // Copyright © 2017 shwares. All rights reserved. // import UIKit class FirstViewController: UIViewController , UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var itemTable: UITableView! var items: [String] = [] public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell") cell.textLabel?.text = items[indexPath.row] return cell } override func viewDidLoad() { super.viewDidLoad() } // This function is to let the data appear in first view controller override func viewDidAppear(_ animated: Bool) { let itemsObject = UserDefaults.standard.object(forKey: "item") if let tempItems = itemsObject as? [String] { items = tempItems } // to update the screen itemTable.reloadData() } // to delete a row from tableView func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCellEditingStyle.delete { items.remove(at: indexPath.row) itemTable.reloadData() UserDefaults.standard.set(items, forKey: "item") } } }
true
561151f68cbf7576d1a21fb02cb5e3720083fce8
Swift
wanchun2012/Algorithm
/Swift/Solution20.swift
UTF-8
373
3.796875
4
[]
no_license
import Foundation extension String { var lettersOnly: String { return components(separatedBy: NSCharacterSet.letters.inverted).joined(separator: "") } var isPalindrome: Bool { return String(characters.reversed()).lettersOnly.lowercased() == lettersOnly.lowercased() } } let s = "A man, a plan, a canal: Panama" print(s.isPalindrome)
true
88e5b82b142458c0ecb3589258df7e534904a4af
Swift
vickyvck/frontend_group2
/Kaidee/comment.swift
UTF-8
2,982
2.53125
3
[]
no_license
// // comment.swift // try // // Created by Admin on 4/8/2560 BE. // Copyright © 2560 Admin. All rights reserved. // import UIKit class comment: UIViewController, UITextViewDelegate { var Array = ["5","4","3","2","1"] // @IBAction func onCancel(_ sender: Any) { // self.dismiss(animated: true, completion: nil) // } @IBOutlet weak var productPic: UIImageView! @IBOutlet weak var sellerID: UILabel! @IBOutlet weak var orderID: UILabel! @IBOutlet weak var comment: UITextView! @IBOutlet weak var rateSeg: UISegmentedControl! // @IBOutlet weak var shipSeg: UISegmentedControl! @IBOutlet weak var menuBtn: UISegmentedControl! @IBAction func menu(_ sender: Any) { if (menuBtn.selectedSegmentIndex==0){ self.performSegue(withIdentifier: "toHome", sender: sender) }else if (menuBtn.selectedSegmentIndex==1){ self.performSegue(withIdentifier: "toProfile", sender: sender) }else if (menuBtn.selectedSegmentIndex==2){ self.performSegue(withIdentifier: "toWish", sender: sender) }else if (menuBtn.selectedSegmentIndex==3){ self.performSegue(withIdentifier: "toSell", sender: sender) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textViewDidChange(_ textView: UITextView) { } func textViewDidEndEditing(_ textView: UITextView) { } func textFieldShouldReturn(_ textField: UITextField) -> Bool { // Hide the keyboard. textField.resignFirstResponder() return true } @IBAction func commentSubmit(_ sender: Any) { print(rateSeg.titleForSegment(at: rateSeg.selectedSegmentIndex) ?? 5) print(comment.text!) self.performSegue(withIdentifier: "toProfile", sender: sender) } /* // 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. } */ // func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { //// if pickerView==Picker1{ // return Array[row] //// } //// else {return Array1[row]} // } // // func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { // return Array.count // } // // public func numberOfComponents(in pickerView: UIPickerView) -> Int{ // return 1 // } }
true
4909b38fd2313a6ee8a151585bf7542a81313c83
Swift
wkicior/mandayFaktura
/mandayFaktura/VAT/View Controllers/VatRatesTableViewDelegate.swift
UTF-8
2,735
2.71875
3
[ "MIT", "CC-BY-4.0" ]
permissive
// // VatRatesTableViewDelegate.swift // mandayFaktura // // Created by Wojciech Kicior on 10.05.2018. // Copyright © 2018 Wojciech Kicior. All rights reserved. // import Foundation import AppKit fileprivate enum CellIdentifiers { static let vatRateCell = "vatRateCellId" static let defaultRateCell = "defaultRateCellId" } class VatRatesTableViewDelegate: NSObject, NSTableViewDataSource, NSTableViewDelegate { let vatRatesTableView: NSTableView var vatRates: [VatRate] init(vatRatesTableView: NSTableView, vatRates: [VatRate]) { self.vatRatesTableView = vatRatesTableView self.vatRates = vatRates super.init() } func numberOfRows(in tableView: NSTableView) -> Int { return vatRates.count } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let vatRate = vatRates[row] if tableColumn == tableView.tableColumns[0] { let text: String = vatRate.literal let cellIdentifier: String = CellIdentifiers.vatRateCell if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? NSTableCellView { cell.textField?.stringValue = text return cell } } else if tableColumn == tableView.tableColumns[1] { let cellIdentifier: String = CellIdentifiers.defaultRateCell let isDefault = vatRate.isDefault if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? NSTableCellView { let button = cell.subviews[0] as? NSButton button!.tag = row button!.state = isDefault ? NSControl.StateValue.on : NSControl.StateValue.off return cell } } return nil } func addVatRate() { self.vatRates.append(VatRate(value: 0.00, literal: "")) self.vatRatesTableView.reloadData() } func getSelectedVatRate() -> VatRate? { let selectedRowNumber = vatRatesTableView.selectedRow if selectedRowNumber != -1 { return vatRates[selectedRowNumber] } return nil } func updateVatRate(_ vatRate: VatRate) { let selectedRowNumber = vatRatesTableView.selectedRow if selectedRowNumber != -1 { vatRates[selectedRowNumber] = vatRate self.vatRatesTableView.reloadData() } } func setVatRates(_ vatRates: [VatRate]) { self.vatRates = vatRates self.vatRatesTableView.reloadData() } }
true
33156ed69f2e1c1146a8cc1fd3bde3a9eeb5b696
Swift
noraoni/noraoniswift
/NoraONI/EscapeViewController.swift
UTF-8
5,050
2.5625
3
[]
no_license
// // EscapeViewController.swift // NoraONI // // Created by AGA TOMOHIRO on 2020/09/24. // import UIKit import CoreLocation class EscapeViewController: UIViewController { var time: [Int] = [10,00,00] @IBOutlet weak var timeLabel: UILabel! let arcLayer = CAShapeLayer() let circleLayer = CAShapeLayer() var rad: CGFloat = 100.0 var Angle = CGFloat() // ロケーションマネージャ var locationManager: CLLocationManager! // コンパスの針 override func viewDidLoad() { super.viewDidLoad() self.navigationItem.hidesBackButton = true // Do any additional setup after loading the view. let count = time[0]*60+time[1] timeLabel.text = String(format: "%02d", time[0]) + ":" + String(format: "%02d", time[1]) + ":" + String(format: "%02d", time[2]) //1秒ごとに時間をtimerメソッドを呼び出す。 Timer.scheduledTimer(timeInterval: 0.01, target: self, selector:#selector(timer) , userInfo: nil, repeats: true) Timer.scheduledTimer(timeInterval: TimeInterval(count), target: self, selector:#selector(Atimer) , userInfo: nil, repeats: false) // ロケーションマネージャ生成 locationManager = CLLocationManager() // ロケーションマネージャのデリゲート設定 locationManager.delegate = self // 角度の取得開始 locationManager.startUpdatingHeading() drawArc() } @objc func Atimer(){ performSegue(withIdentifier: "EscapeResultView", sender: nil) } @objc func timer(){ if (time[0] == 0 && time[1] == 0 && time[2] == 0) { timeLabel.text = "終了" } else { if time[2] > 0 { //秒数が0以上の時秒数を-1 time[2] -= 1 } else { //秒数が0の時 time[2] += 99 if time[1] > 0 { //分が0以上の時、分を-1 time[1] -= 1 } else { //分が0の時、+59分、時間-1 time[1] += 59 time[0] -= 1 } } timeLabel.text = String(format: "%02d", time[0]) + ":" + String(format: "%02d", time[1]) + ":" + String(format: "%02d", time[2]) } } func drawArc() { let angle: CGFloat = CGFloat(2.0 * Double.pi / 6) let start: CGFloat = CGFloat(-Double.pi / 2.0) - angle // 開始の角度 let end: CGFloat = start - angle // 終了の角度 let path: UIBezierPath = UIBezierPath() let arcCenter: CGPoint = CGPoint(x: 50, y: 50) let circlePath: UIBezierPath = UIBezierPath(); circlePath.move(to: arcCenter) circlePath.addArc(withCenter: arcCenter, radius: rad, startAngle: 0, endAngle: CGFloat(-Double.pi * 2.0), clockwise: false) circleLayer.frame = CGRect(x: self.view.center.x-50, y: self.view.center.y-50, width: 100, height: 100) circleLayer.fillColor = UIColor.lightGray.cgColor circleLayer.path = circlePath.cgPath self.view.layer.addSublayer(circleLayer) path.move(to: arcCenter) path.addArc(withCenter: arcCenter, radius: rad, startAngle: start, endAngle: end, clockwise: false) arcLayer.frame = CGRect(x: self.view.center.x-50, y: self.view.center.y-50, width: 100, height: 100) arcLayer.fillColor = UIColor.black.cgColor arcLayer.path = path.cgPath self.view.layer.addSublayer(arcLayer) } } extension EscapeViewController:CLLocationManagerDelegate{ // 角度の更新で呼び出されるデリゲートメソッド func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { let oniAngle = CGFloat(60 - 90) // コンパスの針の方向計算 let tabAngle = CGFloat(newHeading.magneticHeading) if oniAngle > tabAngle{ Angle = oniAngle - tabAngle }else{ Angle = CGFloat(360) - tabAngle + oniAngle print(Angle) } print(Angle) rotateArc(angle: Angle) } private func rotateArc(angle:CGFloat) { var fromVal: CGFloat = angle var toVal: CGFloat = angle fromVal = -angle toVal = -angle let animation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation") animation.isRemovedOnCompletion = false animation.fillMode = CAMediaTimingFillMode.forwards animation.fromValue = fromVal animation.toValue = toVal arcLayer.add(animation, forKey: "animation") } }
true
c18d11228a5deeb203dad641de6cbb3ec049e0d1
Swift
jhb15/NoteBook_IOS
/NoteBook/NoteBook/ViewControllers/NewNoteController.swift
UTF-8
2,023
2.71875
3
[]
no_license
// // NewNoteController.swift // NoteBook // // Created by (Student Number: 140159095) on 02/04/2019. // Copyright © 2019 Aberystwyth Univerity. All rights reserved. // import UIKit import CoreData class NewNoteController: UIViewController { @IBOutlet weak var noteTitle: UITextField! @IBOutlet weak var noteContent: UITextView! var managedContext: NSManagedObjectContext? override func viewDidLoad() { super.viewDidLoad() guard let delegate = UIApplication.shared.delegate as? AppDelegate else { print("error - unable to access failure") exit(EXIT_FAILURE) } managedContext = delegate.persistentContainer.viewContext } @IBAction func newNote(_ sender: UIBarButtonItem) { print("Adding New Note!") let note = Note(entity: Note.entity(), insertInto: managedContext) note.title = noteTitle.text note.content = noteContent.text note.created_at = Date(); note.updated_at = Date() //TODO Add Links do { try managedContext?.save() print("note added") } catch let error as NSError { print("error with \(error)") } dismiss(animated: true, completion: nil) } @IBAction func cancelNote(_ sender: UIBarButtonItem) { print("Canceling Add Note!") dismiss(animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) super.touchesBegan(touches, with: event) } }
true
9ffe335c8bf152b91f78c62c125f62e4e3fe9d01
Swift
mikispase/FootbalTeamsSwiftUI
/FootballSwiftUI/Views/TeamCardView.swift
UTF-8
2,262
2.96875
3
[]
no_license
// // TeamCardView.swift // FootballSwiftUI // // Created by Dimitar Spasovski on 9/22/21. // import SwiftUI struct TeamCardView: View { typealias ChantPlayBackHandler = (_ team:Team) -> Void let team:Team var handler:ChantPlayBackHandler var body: some View { VStack(alignment:.leading) { HStack(alignment:.top,spacing: 12){ Image(team.id.badge) .resizable() .scaledToFit() .frame(width: 50, height: 50) VStack(alignment: .leading, spacing: 6){ Text(team.name) .font(.system(size: 18, weight: .bold)) Text("Founded \(team.founded)") .font(.system(size: 12, weight: .light)) Text("Current \(team.manager.job.rawValue) \(team.manager.name)") .font(.system(size: 10, weight: .light)) Text(team.info) .font(.system(size: 12, weight: .medium)) } Spacer() Button { handler(team) } label: { Image(systemName: team.isPlaying ? "pause.circle.fill" : "play.circle.fill") .resizable() .scaledToFit() } .frame(maxWidth:40,maxHeight: .infinity, alignment: .center) } } // .modifier(TeamCardModifiers(teamType: team.id)) .applyTeamCardStyle(teamType: team.id) } } struct TeamCardView_Previews: PreviewProvider { static var previews: some View { Group { TeamCardView(team: Team.dummyData.first!,handler: { _ in }) .previewLayout(PreviewLayout.fixed(width: 400, height: 150)) .padding() .previewDisplayName("Team Card Preview") TeamCardView(team: Team.dummyData.last!, handler: { _ in }) .previewLayout(PreviewLayout.fixed(width: 400, height: 150)) .padding() .previewDisplayName("Team Card Preview") } } }
true
0724149211eec55eb59382e4c61d50b74405ceb6
Swift
Soomet/BiometricAuthenticator
/BiometricAuthenticator/View/InputPasscodeKeyboardView/InputPasscodeKeyboardView.swift
UTF-8
4,370
2.90625
3
[]
no_license
// // InputPasscodeKeyboardView.swift // BiometricAuthenticator // // Created by Sumit Joshi on 2019/05/11. // Copyright © 2019 Sumit Joshi. All rights reserved. // import Foundation import UIKit // MEMO: Protocol to make change while the button is tapped protocol InputPasscodeKeyboardDelegate: NSObjectProtocol { // Pass the numbers from 0-9 as a string when tapped func inputPasscodeNumber(_ numberOfString: String) // Delete the number if delete button is pressed func deletePasscodeNumber() // Start Biometric Authentic if the device supports the technology func executeLocalAuthentication() } class InputPasscodeKeyboardView: CustomViewBase { weak var delegate: InputPasscodeKeyboardDelegate? // Add the haptic feedback when button pressed private let buttonFeedbackGenerator: UIImpactFeedbackGenerator = { let generator: UIImpactFeedbackGenerator = UIImpactFeedbackGenerator(style: .light) generator.prepare() return generator }() // Passcode lock number buttons // MEMO: its not "weak" because its connected through "Outlet Collection"ß用いて接続しているのでweakはけつけていません @IBOutlet private var inputPasscodeNumberButtons: [UIButton]! // Button for Local Authentication @IBOutlet private weak var executeLocalAuthenticationButton: UIButton! // Button for passcode lock delete button @IBOutlet private weak var deletePasscodeNumberButton: UIButton! // MARK: - Initializer required init(frame: CGRect) { super.init(frame: frame) setupInputPasscodeKeyboardView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupInputPasscodeKeyboardView() } // MARK: - Function func shouldEnabledLocalAuthenticationButton(_ result: Bool = true) { executeLocalAuthenticationButton.isEnabled = result executeLocalAuthenticationButton.superview?.alpha = (result) ? 1.0 : 0.3 } // MARK: - Private Function @objc private func inputPasscodeNumberButtonTapped(sender: UIButton) { guard let superView = sender.superview else { return } executeButtonAnimation(for: superView) buttonFeedbackGenerator.impactOccurred() self.delegate?.inputPasscodeNumber(String(sender.tag)) } @objc private func deletePasscodeNumberButtonTapped(sender: UIButton) { guard let superView = sender.superview else { return } executeButtonAnimation(for: superView) buttonFeedbackGenerator.impactOccurred() self.delegate?.deletePasscodeNumber() } @objc private func executeLocalAuthenticationButtonTapped(sender: UIButton) { guard let superView = sender.superview else { return } executeButtonAnimation(for: superView) buttonFeedbackGenerator.impactOccurred() self.delegate?.executeLocalAuthentication() } private func setupInputPasscodeKeyboardView() { inputPasscodeNumberButtons.enumerated().forEach { let button = $0.element button.addTarget(self, action: #selector(self.inputPasscodeNumberButtonTapped(sender:)), for: .touchDown) } deletePasscodeNumberButton.addTarget(self, action: #selector(self.deletePasscodeNumberButtonTapped(sender:)), for: .touchDown) executeLocalAuthenticationButton.addTarget(self, action: #selector(self.executeLocalAuthenticationButtonTapped(sender:)), for: .touchDown) } private func executeButtonAnimation(for targetView: UIView, completionHandler: (() -> ())? = nil) { // MEMO: Show the user interaction response without the feel of delay through animation UIView.animateKeyframes(withDuration: 0.16, delay: 0.0, options: [.allowUserInteraction, .autoreverse], animations: { UIView.addKeyframe(withRelativeStartTime: 0.2, relativeDuration: 1.0, animations: { targetView.alpha = 0.5 }) UIView.addKeyframe(withRelativeStartTime: 1.0, relativeDuration: 1.0, animations: { targetView.alpha = 1.0 }) }, completion: { finished in completionHandler?() }) } }
true
1d535578502a2e0bc0baf6e21ecd561a6d760bc2
Swift
huinme/xcsample
/sample/Sources/Models/DataStore.swift
UTF-8
7,951
3.09375
3
[]
no_license
// // DataStore.swift // sample // // Created by huin on 2017/08/20. // Copyright © 2017年 www.huin.me. All rights reserved. // import Foundation class DataStore: NSObject { @objc static func fetchChapters() -> [Chapter] { var chapters: [Chapter] = [] let nagano = Author(name: "永野 哲久", profileImageName: "7gano") let shu223 = Author(name: "堤 修一", profileImageName: "shu223") let sonson = Author(name: "吉田 悠一", profileImageName: "sonson_tw") let ikesyo = Author(name: "池田 翔", profileImageName: "ikesyo") let huin = Author(name: "坂田 晃一", profileImageName: "huin") let cockscomb = Author(name: "加藤 尋樹", profileImageName: "cockscomb") let jeffsuke = Author(name: "川邉 雄介", profileImageName: "jeffsuke") let k_katsumi = Author(name: "岸川 克己", profileImageName: "k_katsumi") let tokorom = Author(name: "所 友太", profileImageName: "tokorom") let chap1 = Chapter(number: 1, title: "iOS 11の概要", lead:"iOS 11の全容、新機能と変更点の概要を解説して確証の詳細へつなげます。", author: nagano) chapters.append(chap1) let chap2 = Chapter(number: 2, title: "ARKit", lead:"ARKiは非常に注目されているフレームワークなのですでに多くの「動かしてみた」記事が出ていますが、本章ではそこから踏み込んだ機能や実装方法も紹介します。", author: shu223) chapters.append(chap2) let chap3 = Chapter(number: 3, title: "Core ML", lead:"機械学習をアプリケーションに応用する際の問題の定義, モデル設計, 最適化, 評価, Core MLを使った実装までをシンプルなケースで解説します。", author: sonson) chapters.append(chap3) let chap4 = Chapter(number: 4, title: "Swift 4の新機能とアップデート", lead:"Swift 4でFoundationに導入されるCodableプロトコルとSmart KeyPathsは、Swiftらしい型安全な仕組みをiOSプログラミングにもたらしてくれます(もう文字列キーに不安を感じることはありません!)。これらの新機能を使いこなして、より簡潔で安全なコードを書いていきましょう。", author: ikesyo) chapters.append(chap4) let chap5 = Chapter(number: 5, title: "Xcode 9の新機能", lead:"今年発表されたXcode 9は待望のリファクタリング機能に加えて、より分かりやすくなったビルドエラーやシミュレータの複数実行など、開発効率を確実にあげる機能が多く追加されています。Xcodeはアプリ開発者の誰もが利用するツールなので、これらの新機能をなるべく網羅して説明したいと思ってます。", author: huin) chapters.append(chap5) let chap6 = Chapter(number: 6, title: "Drag and Drop", lead:"iOS 11で追加されるDrag and Dropは、アプリ内あるいはアプリ間で、これまでになく直感的にデータを受け渡すことができます。Drag and DropのようなUIはどのようなアプリでも当たり前に利用できることが期待されるでしょう。本章ではUIKitのDrag and Drop APIを最大限に活用して、効果的なUIを実装する方法について説明します。", author: cockscomb) chapters.append(chap6) let chap7 = Chapter(number: 7, title: "Files と Document Based Application", lead:"iOS 11で大きく強化されることになったファイルやドキュメントに関わる数々のAPIは、これまでのアプリ中心なiOSの世界に、ファイルを中心とした新しい軸をもたらします。ファイルを介したアプリ間の連携は、これまでにない相乗効果を生み出すでしょう。この章ではファイルやドキュメントに関するiOS 11の新機能を広く取り上げ、どのように実装するかを紹介します。", author: cockscomb) chapters.append(chap7) let chap8 = Chapter(number: 8, title: "UIKitのガイドラインの変更点とAutoLayoutの新機能、アップデート", lead:"AutoLayoutの変更はUIKitの変更点が深く関わるので(特にLarge Titles、Navigation Barあたり)、その点も含む見た目関連をまとめて解説します。", author: jeffsuke) chapters.append(chap8) let chap9 = Chapter(number: 9, title: "Core NFC", lead:"Suicaが読み取れるのか、ユニークなIDを読み取れるのか、など「これができて、これができない」という点を整理してCore NFCを解説します。iOS 11の中でも面白い機能なので楽しみです。", author: k_katsumi) chapters.append(chap9) let chap10 = Chapter(number: 10, title: "PDFKit", lead:"macOS では10.4から搭載されていたPDFKitがiOSでも使えるようになりました。詳細に解説します。", author: k_katsumi) chapters.append(chap10) let chap11 = Chapter(number: 11, title: "SiriKit", lead:"徐々に採用ケースが増えてきたSiriKitをiOS 11における新機能と合わせて解説します。", author: k_katsumi) chapters.append(chap11) let chap12 = Chapter(number: 12, title: "HomeKit入門とiOS 11における新機能", lead:"まずはHomeKit入門でHomeKitの基礎を解説してから、iOS 11の新機能を解説します。実際にHomeKit対応製品と連携させてiOS11ではこういうことが実現できるようになるという内容の予定です。", author: tokorom) chapters.append(chap12) let chap13 = Chapter(number: 13, title: "Metal 2", lead:"どういう切り口で書くか具体的には検討中ですが、本書では「普段からGPUまわりにゴリゴリに触れている既存Metalユーザー向け」というよりも、「これまでOpenGLやMetalといったレイヤーに直接触れる機会があまりなかったiOSエンジニア向け」に、Metalのレイヤーをいじれるとこういう場面で役立つ、という切り口からMetal 2の実装方法を解説していこうかなと考えています。", author: shu223) chapters.append(chap13) let chap14 = Chapter(number: 14, title: "Audio/Media関連 新フレームワークとアップデート", lead:"iOS 11で追加になったMusicKit、AirPlay2を中心にAudio/Media関連のアップデートをiPhone Core Audio プログラミングの続編としても読めるような形で書きます!(Core Audio本改定まだー?が聞こえてくる) MusicKit, AirPlay 2, その他の変更点", author: nagano) chapters.append(chap14) return chapters } }
true
0eab5840713b92ec37380c0b4e85a265c659c399
Swift
makotthi/RestaurantSearcher
/RestaurantSearcher/RestaurantSearcher/Model/APIClient/APIClient.swift
UTF-8
1,695
3.171875
3
[]
no_license
import UIKit class APIClient { // レストランのデータをぐるなびAPIから受け取る func receiveRestaurants(_ url: URL, _ handler: @escaping (Result<StoreDataArray, Error>) -> Void) { // リクエストに必要な情報を生成 let req = URLRequest(url: url) // データ転送を管理するためのセッションを生成 let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main) // リクエストをタスクとして登録 let task = session.dataTask(with: req, completionHandler: { (data, _, error) in // セッションを終了 session.finishTasksAndInvalidate() // API通信に失敗した時のエラーハンドリング if let error = error { handler(.failure(error)) return } guard let data = data else { return } // do try catch エラーハンドリング do { // JSONDecoderのインスタンスを生成 let decoder = JSONDecoder() // 受け取ったjsonデータをパースして格納 let json = try decoder.decode(StoreDataArray.self, from: data) print("ヒット件数:\(String(describing: json.total_hit_count))") // クロージャを実行 handler(.success(json)) } catch { print("エラーが出ました") handler(.failure(error)) } }) // ダウンロード開始 task.resume() } }
true
9582a70df75e1754abdbc2abd9a0350e7c04535e
Swift
gudbrandtandberg/SunSeeker
/SolarComputations/SunCalculator.swift
UTF-8
6,021
2.65625
3
[]
no_license
// // SunPositionCalculator.swift // // // Created by Gudbrand Tandberg on 26/09/15. // // import Foundation import CoreLocation import UIKit let x0 = CGFloat(0.0) let w = CGFloat(180.0) let xn = CGFloat(180.0) let y0 = CGFloat(0.0) let h = CGFloat(90.0) let yn = CGFloat(90.0) func generateSinePointList() -> SunTrajectory { let now = JulianDate(date: NSDate()) let formatter = NSDateFormatter() formatter.dateFormat = "dd MM yyyy HH:mm" let startDate = JulianDate(date: formatter.dateFromString("16 04 2016 05:55")!) let endDate = JulianDate(date: formatter.dateFromString("16 04 2016 17:54")!) var trajectory = SunTrajectory() var dates = [JulianDate]() var i : Int let numPoints = 12 * 60 //onc sample a minute let dx = w / CGFloat(numPoints-1) //let timeSpan = endDate.JD - startDate.JD let timeSpan = Double(12*60*60) let dt = timeSpan / Double(numPoints-1) for i in 1...numPoints { //spatial point var x = x0 + CGFloat(i-1) * dx let arg = CGFloat(M_PI) * x / w let y = h * sin(arg) let newPoint = CGPointMake(x, y) //temporal point var newDate = startDate.date.dateByAddingTimeInterval(Double(i) * dt) var newJD = JulianDate(date: newDate) trajectory.addSpaceTimePoint(newJD , p: newPoint) } return trajectory } public class SunCalculator { var coordinateRect = CGRectMake(x0, y0, w, h) var trajectories : [SunTrajectory] var observerLatitude : Angle var observerLongitude : Angle var julianDate : JulianDate let perihelion = Angle(degrees: 102.9372) let obliquity = Angle(degrees: 23.45) let oneEighty = Angle(degrees: 180.0) let h_0 = -0.83 let M_0 = 357.5291 let M_1 = 0.98560028 let J_2000 = 2451545.0 let theta_0 = 280.1600 let theta_1 = 360.9856235 let C_1 = 1.9148 let A_2 = -2.4680 let J_0 = 0.0009 let J_1 = 0.0053 let J_2 = -0.0069 let J_3 = 1.0000000 let secondsPerDay = 60.0 * 60 * 24 let julianDateFormat = "g" var currentTimezoneOffset : NSTimeInterval { return NSTimeInterval(NSTimeZone.localTimeZone().secondsFromGMT) } public init(location : CLLocation, julianDate : JulianDate) { observerLongitude = Angle(degrees: location.coordinate.longitude) observerLatitude = Angle(degrees: location.coordinate.latitude) self.julianDate = julianDate self.trajectories = [generateSinePointList()] } public init(location : CLLocation) { observerLongitude = Angle(degrees: location.coordinate.longitude) observerLatitude = Angle(degrees: location.coordinate.latitude) self.julianDate = JulianDate() trajectories = [generateSinePointList()] } func meanAnomaly(julianDate : JulianDate) -> Angle { return Angle(degrees: M_0 + (M_1 * (julianDate.JD - J_2000))) } func center(meanAnomaly : Angle) -> Angle { var C = C_1 * sin(meanAnomaly) C += 0.0200 * sin(2 * meanAnomaly) C += 0.0003 * sin(3 * meanAnomaly) return Angle(degrees: C) } func eclipticalLongitude(meanAnomaly: Angle, center: Angle) -> Angle { return (meanAnomaly + center + perihelion + oneEighty) } func ascention(eclipticalLongitude: Angle) -> Angle { return Angle(radians: atan(tan(eclipticalLongitude) * cos(obliquity))) } func declination(eclipticalLongitude: Angle) -> Angle { return Angle(radians: asin(sin(obliquity) * sin(eclipticalLongitude))) } func siderealTime(julianDate: JulianDate, longitude: Angle) -> Angle { return Angle(degrees: theta_0 + theta_1 * (julianDate.JD - J_2000) + longitude.degrees) } func hourAngle(siderealTime: Angle, ascention: Angle) -> Angle { return (siderealTime - ascention) } func azimuth(hourAngle: Angle, latitude: Angle, declination: Angle) -> Angle { return Angle(radians: atan(sin(hourAngle) / (cos(hourAngle) * sin(latitude) - tan(declination) * cos(latitude)))) } func altitude(hourAngle: Angle, latitude: Angle, declination: Angle) -> Angle { return Angle(radians: asin(sin(latitude) * sin(declination) + cos(latitude) * cos(declination) * cos(hourAngle))) } public func getRiseSetTimes() -> (NSDate, NSDate) { var n_star = (julianDate.JD - 2451545.0009 + observerLongitude.degrees / 360) var n = floor(n_star + 1/2) var J_star = 2451545.0009 - observerLongitude.degrees / 360 + n var M = meanAnomaly(julianDate) var C = center(M) var l = eclipticalLongitude(M, center: C) var d = declination(l) var J_transit = J_star + 0.0053 * sin(M) - 0.0069 * sin(2 * l) var hourAngle = acos((sin(h_0.radians) - sin(observerLatitude) * sin(d)) / (cos(observerLatitude) * cos(d))).degrees var J_set = J_transit + hourAngle / 360 var J_rise = J_transit - hourAngle / 360 return (dateFromJulianDate(J_rise), dateFromJulianDate(J_set)) } func dateFromJulianDate(jd: Double) -> NSDate { let fractionalDay = jd % 1 var JDN = Int(floor(jd)) var secondsToCorrect = secondsPerDay / 2 if (fractionalDay <= 0.5) { //the JDN floor(jd) is correct secondsToCorrect += fractionalDay * secondsPerDay } else { //the JDN floor(jd) is one day too early JDN += 1 secondsToCorrect -= (1 - fractionalDay) * secondsPerDay } let JDNString = String(format: "%d", JDN) let formatter = NSDateFormatter() formatter.dateFormat = julianDateFormat var noonOnCorrectDay = formatter.dateFromString(JDNString)! secondsToCorrect += currentTimezoneOffset return noonOnCorrectDay.dateByAddingTimeInterval(secondsToCorrect) } public func getSunPosition(day : JulianDate) -> (Angle, Angle) { return (Angle(degrees: 0.0), Angle(degrees: 0.0)) } public func getSunPosition() -> (Angle, Angle) { var M = meanAnomaly(julianDate) var C = center(M) var λ = eclipticalLongitude(M, center: C) var α = ascention(λ) var δ = declination(λ) var θ = siderealTime(julianDate, longitude: observerLongitude) var H = hourAngle(θ, ascention: α) var A = azimuth(H, latitude: observerLatitude, declination: δ) var h = altitude(H, latitude: observerLatitude, declination: δ) return (A, h) } }
true
1f9b9e8a7ea9b67b4b70bfb259f871259515a908
Swift
adolfhoathyla/cheesecake
/Cheesecake/Utils/Extensions/UIView+Extension.swift
UTF-8
1,771
2.640625
3
[]
no_license
// // UIView+Extension.swift // Cheesecake // // Created by Athyla Beserra on 24/03/19. // Copyright © 2019 Athyla Beserra. All rights reserved. // import UIKit private var ActivityIndicatorViewAssociativeKey = "ActivityIndicatorViewAssociativeKey" private var ActivityIndicatorViewSize: CGFloat = 40.0 public extension UIView { var activityIndicatorView: UIActivityIndicatorView { get { if let activityIndicatorView = getAssociatedObject(&ActivityIndicatorViewAssociativeKey) as? UIActivityIndicatorView { return activityIndicatorView } else { self.setNeedsLayout() self.layoutIfNeeded() let activityIndicatorView = UIActivityIndicatorView(frame: CGRect(x: self.center.x-(ActivityIndicatorViewSize/2), y: self.center.y-(ActivityIndicatorViewSize/2), width: ActivityIndicatorViewSize, height: ActivityIndicatorViewSize)) activityIndicatorView.style = .gray activityIndicatorView.color = .gray activityIndicatorView.hidesWhenStopped = true addSubview(activityIndicatorView) setAssociatedObject(activityIndicatorView, associativeKey: &ActivityIndicatorViewAssociativeKey, policy: .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return activityIndicatorView } } set { addSubview(newValue) setAssociatedObject(newValue, associativeKey: &ActivityIndicatorViewAssociativeKey, policy: .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } }
true
da8c353839fb6a83f028f473978716116e90fa02
Swift
ngo275/learn-swift
/Operator/Operator/main.swift
UTF-8
1,107
3.921875
4
[]
no_license
// // main.swift // Operator // // Created by ShuichiNagao on 10/9/16. // Copyright © 2016 ShuichiNagao. All rights reserved. // import Foundation // 中置関数をinfix // associativityは結合規則、left/right/noneがあって同じ優先順位のものがあったときにどっちを優先するかどうか // precendenceは優先順位(3 + 4 * 5 は右が優先されるよねってこと。precedenceが高い方が優先される) infix operator ≤ { associativity none precedence 130 } public func ≤ <T: Comparable>(lhs: T, rhs: T) -> Bool { return lhs <= rhs } let result = 3 ≤ 4 //print(result) let ar: Array<Int> infix operator ≠ { associativity none precedence 130 } public func ≠ <T: Comparable>(lhs: T, rhs: T) -> Bool { return lhs != rhs } print(3 ≠ 4) struct Person { let name: String let age: Int init(name: String, age: Int) { self.name = name self.age = age } } let A = Person(name: "Tom", age: 22) let B = Person(name: "John",age: 33) //print(A = B) print(A.age ≠ B.age)
true
62bb342c4794d313642dff3e52855bb1dc9eec03
Swift
SURYAKANTSHARMA/GithubBrowser
/GitBrowser/GitBrowser/Model/CacheManager.swift
UTF-8
4,203
2.828125
3
[]
no_license
// // CacheManager.swift // GitBrowser // // Created by Surya // Copyright © 2019 Github. All rights reserved. // import UIKit class CacheManager { struct Constants { // Cache Names static let kRepositoriesCacheName = "RepositoriesCache" static let kReadmeURLCacheName = "ReadmeURLCache" static let kReadmeDataCacheName = "ReadmeDataCache" static let kAvatarCacheName = "AvatarCache" // Cache Keys static let kRepositoriesDataSourceKey = "RepositoriesDataSource" } static let shared = CacheManager() private let repositoriesCache = Cache<String, RepositoriesList>(withName: Constants.kRepositoriesCacheName) private let readmeURLCache = Cache<Int, String>(withName: Constants.kReadmeURLCacheName) private let readmeDataCache = Cache<Int, Data>(withName: Constants.kReadmeDataCacheName) private let avatarCache = Cache<Int, Data>(withName: Constants.kAvatarCacheName) func repositoriesListViewModelDatasource(_ completion: @escaping (([RepositoriesListViewModel]) -> Void)) { guard let repositoriesDatasource = repositoriesCache.object(forKey: Constants.kRepositoriesDataSourceKey) else { NetworkManager().fetchTrendingRepositories({ [weak self] (datasource: RepositoriesList?) in if let datasource = datasource { self?.repositoriesCache.setObject(datasource, forKey: Constants.kRepositoriesDataSourceKey) } completion(datasource?.repositoryListViewModelDataSource() ?? []) }) return } completion(repositoriesDatasource.repositoryListViewModelDataSource()) } func avatarImage(for repositoryID: Int, avatarSourceURL: URL, _ completion: @escaping ((UIImage?) -> Void)) { guard let avatarImageData = avatarCache.object(forKey: repositoryID) else { NetworkManager().fetchAvatar(from: avatarSourceURL, { [weak self] (data: Data?) in if let imageData = data { self?.avatarCache.setObject(imageData, forKey: repositoryID) completion(UIImage(data: imageData)) } else { completion(nil) } }) return } completion(UIImage(data: avatarImageData)) } private func readmeURL(for repositoryID: Int, readmeSourceURL: URL, _ completion: @escaping ((String?) -> Void)) { guard let readmeFileURL = readmeURLCache.object(forKey: repositoryID) else { NetworkManager().fetchReadmeURL(from: readmeSourceURL, { [weak self] (result: String?) in if let readmeURLString = result { self?.readmeURLCache.setObject(readmeURLString, forKey: repositoryID) } completion(result) }) return } completion(readmeFileURL) } func readmeData(for repositoryID: Int, readmeSourceURL: URL, _ completion: @escaping ((Data?) -> Void)) { readmeURL(for: repositoryID, readmeSourceURL: readmeSourceURL) { [weak self] (readmeURLString: String?) in guard let urlString = readmeURLString, let readmeURL = URL(string: urlString) else { print("Error: Could not download readme data, failed to get the readme url") completion(nil) return } let cachedReadmeData = self?.readmeDataCache.object(forKey: repositoryID) // Return cached data initially, if available if let _ = cachedReadmeData { completion(cachedReadmeData) } // Fetch latest data and return if cached and fresh data differs NetworkManager().fetchReadmeData(from: readmeURL, { [weak self] (result: Data?) in if let downloadedReadmeData = result { self?.readmeDataCache.setObject(downloadedReadmeData, forKey: repositoryID) // Make sure we do not reload the webview if it's not changed if downloadedReadmeData != cachedReadmeData { completion(result) } } else { completion(result) } }) } } func repositoryDetailsViewModel(for repositoryID: Int) -> RepositoryDetailsViewModel? { guard let repositoriesDatasource = repositoriesCache.object(forKey: "RepositoriesDataSource") else { return nil } return repositoriesDatasource.repositoryDetailsViewModel(for: repositoryID) } }
true
b31d6bc1f11e4c32167479ab5f941d7c2411a445
Swift
Voxsie/004-006_2021
/Lesson4/Presentation/FeedPresentation/LoginViewController.swift
UTF-8
2,284
3.015625
3
[]
no_license
// // LoginViewController.swift // Lesson4 // // // import UIKit class LoginViewController: UIViewController { //IBOOutlets and vars @IBOutlet weak var loginTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! var feedId: Int = -1 @IBAction func loginButton(_ sender: Any) { if (loginTextField.text == "voxsie@gmail.com" && passwordTextField.text == "123") { feedId = 0 pushing() } else if (loginTextField.text == "admin" && passwordTextField.text == "admin") { feedId = 1 pushing() } else if (loginTextField.text == "admin1" && passwordTextField.text == "admin1") { feedId = 2 pushing() } else { IncorrectData(with: nil, description: nil) } } @IBAction func signupButton(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let nextVC = storyboard.instantiateViewController(withIdentifier: "SignupViewController") as! SignupViewController nextVC.modalPresentationStyle = .fullScreen present(nextVC, animated: true, completion: nil) } @IBOutlet weak var signupLabel: UILabel! //funcs override func viewDidLoad() { super.viewDidLoad() loginTextField.autocorrectionType = .no passwordTextField.clearButtonMode = . whileEditing } private func pushing() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let nextVC = storyboard.instantiateViewController(withIdentifier: "TabBar") as! UITabBarController nextVC.modalPresentationStyle = .fullScreen present(nextVC, animated: true, completion: nil) } private func IncorrectData(with title: String?, description: String?) { let alertController = UIAlertController(title: "Error", message: "Login/Password is incorrect", preferredStyle: .alert) let dismissAction = UIAlertAction(title: "Close", style: .destructive) {action in alertController.dismiss(animated: true, completion: nil)} alertController.addAction(dismissAction) present(alertController, animated: true, completion: nil) } }
true
7f84af792d296f393e51abd038ee7c4155893797
Swift
ZikeX/JDKit
/Extensions/UIWindow.swift
UTF-8
426
2.640625
3
[]
no_license
import UIKit extension UIWindow { /// ZJaDe: Creates and shows UIWindow. The size will show iPhone4 size until you add launch images with proper sizes. convenience init(viewController: UIViewController, backgroundColor: UIColor) { self.init(frame: UIScreen.main.bounds) self.rootViewController = viewController self.backgroundColor = backgroundColor self.makeKeyAndVisible() } }
true
0a9062a14822791197f9e2013a2b6191a522eecb
Swift
erick100f/EXCurriculum
/EXCurriculum/Extensions/UIImage+Extension.swift
UTF-8
735
2.8125
3
[]
no_license
// // UIImage+Extensions.swift // EXCurriculum // // Created by Erick Cienfuegos on 10/4/19. // Copyright © 2019 Erick Cienfuegos. All rights reserved. // import UIKit public extension UIImageView { func load(_ url: URL){ DispatchQueue.global().async { [weak self] in if let data = try? Data(contentsOf: url), let image = UIImage(data: data) { DispatchQueue.main.async { self?.image = image } }else { self?.image = UIImage(named: "noImage") } } } func load(url: URL?){ guard let url = url else { self.image = UIImage(named: "noImage") return } load(url) } }
true
11c94a0fcd1f6f3936426022de613da8f77d6a0f
Swift
timbaev/TDD
/DemoTests/ViewControllers/PlaceList/ViewModels/PlaceListViewModel.swift
UTF-8
1,554
2.90625
3
[]
no_license
// // PlaceListViewModel.swift // DemoTests // // Created by Timur Shafigullin on 16/01/2019. // Copyright © 2019 Timur Shafigullin. All rights reserved. // import Foundation class PlaceListViewModel { // MARK: - Instance Properties fileprivate var placeService: PlaceService fileprivate var datasource: [PlaceCellModel] = [] fileprivate var dataModel: [Place]! { didSet { self.configureDatasource() self.configureProperties() } } // MARK: - fileprivate(set) var numberOfRows = 0 fileprivate(set) var showError: ((String) -> ())? // MARK: - var viewDidLoad: (() -> ())? // MARK: - Instance Methods fileprivate func configureDatasource() { self.datasource = self.dataModel.map { PlaceCellModel(place: $0) } } fileprivate func configureProperties() { self.numberOfRows = self.datasource.count } // MARK: - fileprivate func fetchPlaces() { self.placeService.fetch(success: { places in self.dataModel = places }, error: { message in self.showError?(message) }) } // MARK: - func placeCellModel(at indexPath: IndexPath) -> PlaceCellModel { return self.datasource[indexPath.row] } // MARK: - Initializers init(placeService: PlaceService) { self.placeService = placeService self.viewDidLoad = { [unowned self] in self.fetchPlaces() } } }
true
16e2158475eeb7ecd943a0f2e4cf6b511f7dd815
Swift
nbpapps/ImageLoading
/Tests/ImageLoadingTests/ImageLoadingTests.swift
UTF-8
953
2.71875
3
[ "MIT" ]
permissive
import XCTest @testable import ImageLoading final class ImageLoadingTests: XCTestCase { func test_GetImageWithoutUrl_NilResult() { let imageCache = ImageCache.shared let imageFromCache = imageCache.loadedImageFor(URL(string: "https://www.google.com")!) XCTAssertNil(imageFromCache, "Image should be nil") } func test_ImageCacheSet_GetSameImage() { let imageCache = ImageCache.shared let image = UIImage(systemName: "xmark")! let url = URL(fileURLWithPath: "url") imageCache.setLoadedImage(image, for: url) let loadedImage = imageCache.loadedImageFor(url)! XCTAssertEqual(image, loadedImage, "original image and loadedImage image are not the same") } static var allTests = [ ("test_ImageCacheSet_GetSameImage", test_ImageCacheSet_GetSameImage), ("test_GetImageWithoutUrl_NilResult",test_GetImageWithoutUrl_NilResult) ] }
true
810b1c7c3bd45c8255565f852ccf440929319c49
Swift
eBardX/XestiMonitors
/Sources/Core/CoreLocation/StandardLocationMonitor.swift
UTF-8
7,511
2.765625
3
[ "MIT" ]
permissive
// // StandardLocationMonitor.swift // XestiMonitors // // Created by J. G. Pusey on 2018-03-21. // // © 2018 J. G. Pusey (see LICENSE.md) // import CoreLocation /// /// A `StandardLocationMonitor` instance monitors the device for changes to its /// current location. /// @available(watchOS 3.0, *) public class StandardLocationMonitor: BaseMonitor { /// /// Encapsulates changes to the device’s current location. /// public enum Event { /// /// Location updates will no longer be deferred. The associated value, /// if non-`nil`, contains the reason deferred location updates could /// not be delivered. /// case didFinishDeferredUpdates(Error?) /// /// Location updates have been paused. /// case didPauseUpdates /// /// Location updates have been resumed. /// case didResumeUpdates /// /// The current location has been updated. /// case didUpdate(Info) } /// /// Encapsulates information associated with a standard location monitor /// event. /// public enum Info { /// /// The error encountered in attempting to obtain the current location. /// case error(Error) /// /// The latest location data. /// case location(CLLocation) } /// /// Initializes a new `StandardLocationMonitor`. /// /// - Parameters: /// - queue: The operation queue on which the handler executes. /// - handler: The handler to call when the current location of the /// device changes. /// public init(queue: OperationQueue, handler: @escaping (Event) -> Void) { self.adapter = .init() self.handler = handler self.locationManager = LocationManagerInjector.inject() self.queue = queue super.init() self.adapter.didFail = handleDidFail #if os(iOS) || os(macOS) self.adapter.didFinishDeferredUpdates = handleDidFinishDeferredUpdates #endif #if os(iOS) self.adapter.didPauseLocationUpdates = handleDidPauseLocationUpdates #endif #if os(iOS) self.adapter.didResumeLocationUpdates = handleDidResumeLocationUpdates #endif self.adapter.didUpdateLocations = handleDidUpdateLocations self.locationManager.delegate = self.adapter } #if os(iOS) || os(watchOS) /// /// The type of user activity associated with the location updates. /// @available(watchOS 4.0, *) public var activityType: CLActivityType { get { return locationManager.activityType } set { locationManager.activityType = newValue } } #endif #if os(iOS) || os(watchOS) /// /// A Boolean value indicating whether the app should receive location /// updates when suspended. /// @available(watchOS 4.0, *) public var allowsBackgroundLocationUpdates: Bool { get { return locationManager.allowsBackgroundLocationUpdates } set { locationManager.allowsBackgroundLocationUpdates = newValue } } #endif #if os(iOS) || os(macOS) /// /// A Boolean value indicating whether the device supports deferred /// location updates. /// public var canDeferUpdates: Bool { return type(of: locationManager).deferredLocationUpdatesAvailable() } #endif /// /// The accuracy of the location data. /// public var desiredAccuracy: CLLocationAccuracy { get { return locationManager.desiredAccuracy } set { locationManager.desiredAccuracy = newValue } } /// /// The minimum distance (measured in meters) the device must move /// horizontally before a location update is generated. /// public var distanceFilter: CLLocationDistance { get { return locationManager.distanceFilter } set { locationManager.distanceFilter = newValue } } /// /// The most recently reported location. /// /// The value of this property is nil if location updates have never been /// initiated. /// public var location: CLLocation? { return locationManager.location } #if os(iOS) /// /// A Boolean value indicating whether location updates may be paused /// automatically. /// public var pausesLocationUpdatesAutomatically: Bool { get { return locationManager.pausesLocationUpdatesAutomatically } set { locationManager.pausesLocationUpdatesAutomatically = newValue } } #endif #if os(iOS) /// /// A Boolean indicating whether the status bar changes its appearance when /// location services are used in the background. /// @available(iOS 11.0, *) public var showsBackgroundLocationIndicator: Bool { get { return locationManager.showsBackgroundLocationIndicator } set { locationManager.showsBackgroundLocationIndicator = newValue } } #endif #if os(iOS) /// /// Defers the delivery of location updates until the specified criteria /// are met. /// /// - Parameters: /// - distance: The distance (in meters) from the current location that /// must be traveled before location update delivery /// resumes. /// - timeout: The amount of time (in seconds) from the current time /// that must pass before location update delivery resumes. /// public func allowDeferredUpdates(untilTraveled distance: CLLocationDistance, timeout: TimeInterval) { locationManager.allowDeferredLocationUpdates(untilTraveled: distance, timeout: timeout) } #endif #if os(iOS) /// /// Cancels the deferral of location updates. /// public func disallowDeferredUpdates() { locationManager.disallowDeferredLocationUpdates() } #endif #if os(iOS) || os(tvOS) || os(watchOS) /// /// Requests the one-time delivery of the device’s current location. /// public func requestLocation() { locationManager.requestLocation() } #endif private let adapter: LocationManagerDelegateAdapter private let handler: (Event) -> Void private let locationManager: LocationManagerProtocol private let queue: OperationQueue private func handleDidFail(_ error: Error) { handler(.didUpdate(.error(error))) } #if os(iOS) || os(macOS) private func handleDidFinishDeferredUpdates(_ error: Error?) { handler(.didFinishDeferredUpdates(error)) } #endif #if os(iOS) private func handleDidPauseLocationUpdates() { handler(.didPauseUpdates) } #endif #if os(iOS) private func handleDidResumeLocationUpdates() { handler(.didResumeUpdates) } #endif private func handleDidUpdateLocations(_ locations: [CLLocation]) { if let location = locations.first { handler(.didUpdate(.location(location))) } } override public func cleanupMonitor() { locationManager.stopUpdatingLocation() super.cleanupMonitor() } override public func configureMonitor() { super.configureMonitor() #if os(iOS) || os(macOS) || os(watchOS) locationManager.startUpdatingLocation() #endif } }
true
a49e0a8fa2d3af66b5049a30a708f53cccbd3572
Swift
lesparragoza/RandomUserCodingChallenge
/RandomUserList/RandomUserList/ViewControllers/UserListTableViewCell.swift
UTF-8
993
2.6875
3
[]
no_license
// // UserListTableViewCell.swift // RandomUserList // // Created by Luis Alejandro Esparragoza Sanchez on 01/01/2019. // Copyright © 2019 LuisEsparragoza. All rights reserved. // import UIKit import SDWebImage class UserListTableViewCell: UITableViewCell { @IBOutlet weak var userPic: UIImageView! @IBOutlet weak var fullName: UILabel! @IBOutlet weak var phoneNumber: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func configureCell(name: String, lastName: String, phone: String, imageUrl: String?){ fullName.text = lastName + ", " + name phoneNumber.text = phone if let url = imageUrl { userPic.sd_setImage(with: URL(string: url), placeholderImage: UIImage(named: "userPlaceholder")) } } }
true
bc20de451bf703e0ff874defa5278a067c1f1c36
Swift
Torsph/DynamicLayout
/Carthage/Checkouts/Spots/Sources/iOS/Library/Spotable.swift
UTF-8
4,349
2.6875
3
[ "MIT" ]
permissive
import UIKit import Brick public protocol Spotable: class { static var views: ViewRegistry { get } static var defaultView: UIView.Type { get set } static var defaultKind: String { get } weak var spotsDelegate: SpotsDelegate? { get set } var index: Int { get set } var component: Component { get set } var configure: (SpotConfigurable -> Void)? { get set } init(component: Component) func setup(size: CGSize) func append(item: ViewModel, completion: (() -> Void)?) func append(items: [ViewModel], completion: (() -> Void)?) func prepend(items: [ViewModel], completion: (() -> Void)?) func insert(item: ViewModel, index: Int, completion: (() -> Void)?) func update(item: ViewModel, index: Int, completion: (() -> Void)?) func delete(index: Int, completion: (() -> Void)?) func delete(indexes: [Int], completion: (() -> Void)?) func reload(indexes: [Int]?, completion: (() -> Void)?) func render() -> UIScrollView func layout(size: CGSize) func prepare() func scrollTo(@noescape includeElement: (ViewModel) -> Bool) -> CGFloat } public extension Spotable { var items: [ViewModel] { set(items) { component.items = items } get { return component.items } } /** - Parameter spot: Spotable - Parameter register: A closure containing class type and reuse identifer */ func registerAndPrepare(@noescape register: (classType: UIView.Type, withIdentifier: String) -> Void) { if component.kind.isEmpty { component.kind = Self.defaultKind } Self.views.storage.forEach { reuseIdentifier, classType in register(classType: classType, withIdentifier: reuseIdentifier) } if !Self.views.storage.keys.contains(component.kind) { register(classType: Self.defaultView, withIdentifier: component.kind) } var cached: UIView? component.items.enumerate().forEach { prepareItem($1, index: $0, cached: &cached) } } /** - Parameter index: The index of the item to lookup - Returns: A ViewModel at found at the index */ public func item(index: Int) -> ViewModel { return component.items[index] } /** - Parameter indexPath: The indexPath of the item to lookup - Returns: A ViewModel at found at the index */ public func item(indexPath: NSIndexPath) -> ViewModel { return component.items[indexPath.item] } /** - Returns: A CGFloat of the total height of all items inside of a component */ public func spotHeight() -> CGFloat { return component.items.reduce(0, combine: { $0 + $1.size.height }) } /** Refreshes the indexes of all items within the component */ public func refreshIndexes() { items.enumerate().forEach { items[$0.index].index = $0.index } } /** TODO: We should probably have a look at this method? Seems silly to always return 0.0 😁 - Parameter includeElement: A filter predicate to find a view model - Returns: Always returns 0.0 */ public func scrollTo(@noescape includeElement: (ViewModel) -> Bool) -> CGFloat { return 0.0 } /** Prepares a view model item before being used by the UI component - Parameter item: A view model - Parameter index: The index of the view model - Parameter spot: The spot that should be prepared - Parameter cached: An optional UIView, used to reduce the amount of different reusable views that should be prepared. */ public func prepareItem(item: ViewModel, index: Int, inout cached: UIView?) { cachedViewFor(item, cache: &cached) component.items[index].index = index guard let view = cached as? SpotConfigurable else { return } view.configure(&component.items[index]) if component.items[index].size.height == 0 { component.items[index].size.height = view.size.height } } /** Cache view for item kind - Parameter item: A view model - Parameter cached: An optional UIView, used to reduce the amount of different reusable views that should be prepared. */ func cachedViewFor(item: ViewModel, inout cache: UIView?) { let reuseIdentifer = item.kind.isPresent ? item.kind : component.kind let componentClass = self.dynamicType.views.storage[reuseIdentifer] ?? self.dynamicType.defaultView if cache?.isKindOfClass(componentClass) == false { cache = nil } if cache == nil { cache = componentClass.init() } } }
true
23fc933086b42a02ad89655a057a6e1d4a1ec09f
Swift
olivellaf/iOSBonsaisApp
/ElQuintoPino/Controllers/VC_LogsTableView.swift
UTF-8
2,929
2.59375
3
[]
no_license
// // VC_LogsTableView.swift // ElQuintoPino // // Created by Ferran Olivella on 6/3/15. // Copyright (c) 2015 Ferran Olivella. All rights reserved. // import UIKit // GLOBAL VARIABLES var logs = [String]() class VC_LogsTableView: UIViewController, UITableViewDelegate, UIActionSheetDelegate { @IBOutlet weak var tableLogsView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if NSUserDefaults.standardUserDefaults().objectForKey("logs") != nil { logs = NSUserDefaults.standardUserDefaults().objectForKey("logs") as [String] } tableLogsView.reloadData() } override func viewDidAppear(animated: Bool) { if NSUserDefaults.standardUserDefaults().objectForKey("logs") != nil { logs = NSUserDefaults.standardUserDefaults().objectForKey("logs") as [String] } tableLogsView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return logs.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell_log = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell_Log") cell_log.textLabel?.text = logs[indexPath.row] return cell_log } @IBAction func clearAllLogTable(sender: AnyObject) { // remove all directly TODO: try to show a dialog alert showActionSheet("¿Are you sure?", cancelButtonTitle: "cancel", destructiveButtonTitle: "Remove all") } func showActionSheet(title: String, cancelButtonTitle: String, destructiveButtonTitle: String) { var actionSheet = UIActionSheet( title: title, delegate: self, cancelButtonTitle: cancelButtonTitle, destructiveButtonTitle: destructiveButtonTitle // otherButtonTitles: otherButtonsTitles ) actionSheet.showInView(self.view) } func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { switch buttonIndex{ case 0: NSLog("Done"); logs.removeAll(keepCapacity: false) NSUserDefaults.standardUserDefaults().setObject(logs, forKey: "logs") tableLogsView.reloadData() break; case 1: NSLog("Cancel"); break; case 2: NSLog("Yes"); break; case 3: NSLog("No"); break; default: NSLog("Default"); break; //Some code here.. } } }
true
36b7042d52609eaab51b959447d74bc32b050097
Swift
phuongnguyen2359/VideoProcessing
/VideoProcessing/Shared/UIView+Decor.swift
UTF-8
521
2.578125
3
[]
no_license
// // UIView+Decor.swift // VideoProcessing // // Created by Tran Thi Cam Giang on 3/3/20. // Copyright © 2020 Tran Thi Cam Giang. All rights reserved. // import UIKit extension UIView { func addDashLineBorder(_ color: CGColor) { let newLayer = CAShapeLayer() newLayer.strokeColor = color newLayer.lineDashPattern = [2, 2] newLayer.frame = self.bounds newLayer.fillColor = nil newLayer.path = UIBezierPath(rect: self.bounds).cgPath self.layer.addSublayer(newLayer) } }
true
4f74f841bf2b3ae4b3a63d774b1682217b107c75
Swift
Ollstar/C4Examples
/C4Examples/Views04.swift
UTF-8
594
2.90625
3
[]
no_license
// // Views04.swift // C4Examples // // Created by Oliver Andrews on 2015-09-09. // Copyright © 2015 Slant. All rights reserved. // import C4 class Views04: CanvasController { var s1:Rectangle! var s2:Ellipse! override func setup() { setupShapes() s1.center = self.canvas.center s2.center = s1.center } func setupShapes() { let frame = Rect(0,0,100,100) self.s1 = Rectangle(frame: frame) self.canvas.add(s1) self.s2 = Ellipse(frame: frame) self.canvas.add(s2) } }
true
9dabb422543d987eba93a64260866fcca7610428
Swift
zlrs/XCBBuildServiceProxy
/Tests/MessagePackTests/BinaryTests.swift
UTF-8
3,249
2.671875
3
[ "Apache-2.0" ]
permissive
import Foundation import XCTest @testable import MessagePack class BinaryTests: XCTestCase { let payload = Data([0x00, 0x01, 0x02, 0x03, 0x04]) let packed = Data([0xc4, 0x05, 0x00, 0x01, 0x02, 0x03, 0x04]) func testPack() { XCTAssertEqual(MessagePackValue.pack(.binary(payload)), packed) } func testUnpack() throws { let unpacked = try MessagePackValue.unpack(packed) XCTAssertEqual(unpacked.value, .binary(payload)) XCTAssertEqual(unpacked.remainder.count, 0) } func testPackBinEmpty() { let value = Data() let expectedPacked = Data([0xc4, 0x00]) + value XCTAssertEqual(MessagePackValue.pack(.binary(value)), expectedPacked) } func testUnpackBinEmpty() throws { let data = Data() let packed = Data([0xc4, 0x00]) + data let unpacked = try MessagePackValue.unpack(packed) XCTAssertEqual(unpacked.value, MessagePackValue.binary(data)) XCTAssertEqual(unpacked.remainder.count, 0) } func testPackBin16() { let value = Data(count: 0xff) let expectedPacked = Data([0xc4, 0xff]) + value XCTAssertEqual(MessagePackValue.pack(.binary(value)), expectedPacked) } func testUnpackBin16() throws { let data = Data([0xc4, 0xff]) + Data(count: 0xff) let value = Data(count: 0xff) let unpacked = try MessagePackValue.unpack(data) XCTAssertEqual(unpacked.value, .binary(value)) XCTAssertEqual(unpacked.remainder.count, 0) } func testPackBin32() { let value = Data(count: 0x100) let expectedPacked = Data([0xc5, 0x01, 0x00]) + value XCTAssertEqual(MessagePackValue.pack(.binary(value)), expectedPacked) } func testUnpackBin32() throws { let data = Data([0xc5, 0x01, 0x00]) + Data(count: 0x100) let value = Data(count: 0x100) let unpacked = try MessagePackValue.unpack(data) XCTAssertEqual(unpacked.value, .binary(value)) XCTAssertEqual(unpacked.remainder.count, 0) } func testPackBin64() { let value = Data(count: 0x1_0000) let expectedPacked = Data([0xc6, 0x00, 0x01, 0x00, 0x00]) + value XCTAssertEqual(MessagePackValue.pack(.binary(value)), expectedPacked) } func testUnpackBin64() throws { let data = Data([0xc6, 0x00, 0x01, 0x00, 0x00]) + Data(count: 0x1_0000) let value = Data(count: 0x1_0000) let unpacked = try MessagePackValue.unpack(data) XCTAssertEqual(unpacked.value, .binary(value)) XCTAssertEqual(unpacked.remainder.count, 0) } func testUnpackInsufficientData() { let dataArray: [Data] = [ // only type byte Data([0xc4]), Data([0xc5]), Data([0xc6]), // type byte with no data Data([0xc4, 0x01]), Data([0xc5, 0x00, 0x01]), Data([0xc6, 0x00, 0x00, 0x00, 0x01]), ] for data in dataArray { do { _ = try MessagePackValue.unpack(data) XCTFail("Expected unpack to throw") } catch { XCTAssertEqual(error as? MessagePackUnpackError, .insufficientData) } } } }
true
4a75d02565509e2605ceb2d97d8759b6bc1fdbb5
Swift
FarhadAlipoor/Capp
/Capp/ًWebServices/WebServices.swift
UTF-8
3,919
2.671875
3
[]
no_license
// // WebServices.swift // Capp // // Created by tannaz on 11/29/17. // Copyright © 2017 Capp. All rights reserved. // import ReachabilitySwift import Alamofire import Arrow import UIKit struct WebServices { internal typealias Success = (_ response: JResponse?) -> () internal typealias Failure = (_ response: JResponse?) -> () static func isConnected(failure: Failure? = nil) -> Bool { // checking connection if (Reachability.init()!.connection == .none) { failure?(JResponse.notConnected) return false } return true } static func request(url: String, method: HTTPMethod = .post, params: [String: Any] = [:], resultType: ArrowParsable.Type? = nil, success: Success?, failure: Failure? , haveURLParams: Bool = false , needToken: Bool = true ) { var needToken = needToken let user = "Delfard" let password = "JEFuZHJvaWQk" let credentialData = "\(user):\(password)".data(using: String.Encoding.utf8)! let base64Credentials = credentialData.base64EncodedString(options: []) var headers: [String: String] = [ "Authorization": "Basic \(base64Credentials)" ] let encoding: ParameterEncoding? if haveURLParams { encoding = URLEncoding(destination: .queryString) } else { encoding = JSONEncoding.default } print(StoringData.loginToken) if needToken { headers = ["Token" : StoringData.loginToken! , "Authorization": "Basic \(base64Credentials)" ] } Alamofire.request( url, method: .post, parameters: params,encoding: encoding!, headers: headers).authenticate(user: user, password: password).responseJSON { response in print(response.request) print(response.result.value) switch response.result { case .success: if let json = response.result.value as? [String: Any] { print(json) if let headerToken = response.response?.allHeaderFields["Token"] as? String { StoringData.loginToken = headerToken } var jResponse = JResponse(resultType.self) jResponse.parse(response.result.value) if jResponse.isSuccess { print(jResponse) needToken = true success?(jResponse) } else { failure?(jResponse) } } break case .failure(let error): print(error) } } } static func cancelRequests(_ url: String) { Alamofire.SessionManager.default.session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) -> Void in Alamofire.SessionManager.cancelTasksByUrl(dataTasks as [URLSessionTask], url: url) Alamofire.SessionManager.cancelTasksByUrl(uploadTasks as [URLSessionTask], url: url) Alamofire.SessionManager.cancelTasksByUrl(downloadTasks as [URLSessionTask], url: url) } } } extension Alamofire.SessionManager { // cancel tasks by url fileprivate static func cancelTasksByUrl(_ tasks: [URLSessionTask], url: String) { for task in tasks { let hasPrefix = task.currentRequest?.url?.description.hasPrefix(url) if hasPrefix != nil && hasPrefix! == true { task.cancel() } } } }
true
d695ca2ea8e18749450a7f81f2579519448eb5b9
Swift
4alltecnologia/ios-utilities
/UtilitiesCore/Extensions/UITextField+Extension.swift
UTF-8
714
2.890625
3
[]
no_license
// // UITextField+Extension.swift // UtilitiesCore // // Created by Felipe Dias Pereira on 08/05/19. // Copyright © 2019 4all. All rights reserved. // import UIKit public extension UITextField { /// This functions is used to validate the textField.text /// with the validation functions also created in this framework /// /// - Parameter validationType: the validatorType to perform the validation /// - Returns: a swift 5 result type with error or the .text content string of self func validatedText(validationType: ValidatorType) -> Result<String, Error> { let validator = ValidatorFactory.validatorFor(type: validationType) return validator.validated(self.text ?? "") } }
true
b2e18d39914a2f8fd77a27e5afaaa9dded5e4c58
Swift
JordanDoczy/Graph
/Graph/GraphView.swift
UTF-8
3,581
2.84375
3
[ "Apache-2.0" ]
permissive
// // GraphView.swift // GraphingCalculator // // Created by Jordan Doczy on 11/3/15. // Copyright © 2015 Jordan Doczy. All rights reserved. // //for testing: https://www.desmos.com/calculator import UIKit import QuartzCore import SpriteKit protocol GraphViewDataSource: class{ func yForX(_ x:CGFloat) -> CGFloat? } @IBDesignable class GraphView : UIView { struct GestureRecognizer{ static let Scale = "scale" static let Pan = "pan" static let ResetOrigin = "resetOrigin" } fileprivate var axis = AxesDrawer(color: UIColor.darkGray) weak var dataSource:GraphViewDataSource? @IBInspectable var scale: CGFloat = 50 { didSet { setNeedsDisplay() } } var lineWidth: CGFloat = 1.0 var origin : CGPoint? { didSet{ setNeedsDisplay() } } func resetOrigin(){ origin = CGPoint(x: bounds.width/2, y: bounds.height/2) } func pan(_ gesture: UIPanGestureRecognizer){ if gesture.state == .changed{ let translation = gesture.translation(in: self) if origin != nil { origin = CGPoint(x: origin!.x + translation.x, y: origin!.y + translation.y) } gesture.setTranslation(CGPoint.zero, in: self) } } func scale(_ gesture: UIPinchGestureRecognizer){ if gesture.state == .changed{ scale /= gesture.scale gesture.scale = 1 } } override var bounds : CGRect { didSet{ setNeedsDisplay() } } var path = UIBezierPath() var point = CGPoint() var position:CGFloat = 0 { didSet{ point.x = CGFloat(position) if let y = getYForX(point.x){ point.y = y path.addLine(to: point) path.move(to: point) } } } let shapeLayer = CAShapeLayer() override func draw(_ rect: CGRect) { shapeLayer.removeFromSuperlayer() path.removeAllPoints() resetOrigin() axis.contentScaleFactor = contentScaleFactor axis.drawAxesInRect(bounds, origin: origin!, pointsPerUnit: scale) let x:CGFloat = 0; let y:CGFloat = getYForX(x) ?? origin!.y point.x = x point.y = y path.move(to: point) for x in 0...Int(bounds.width) { position = CGFloat(x) } let animation = CABasicAnimation(keyPath: "strokeEnd") animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) animation.duration = 2.8 animation.fromValue = 0 animation.toValue = 1 shapeLayer.add(animation, forKey: "strokeEndAnimation") shapeLayer.lineWidth = 1 shapeLayer.strokeColor = UIColor.darkGray.cgColor shapeLayer.strokeStart = 0 shapeLayer.strokeEnd = 1 shapeLayer.path = path.cgPath layer.addSublayer(shapeLayer) } fileprivate func getYForX(_ x:CGFloat) -> CGFloat?{ if let y = dataSource?.yForX((x-origin!.x)/scale) { if y.isNormal || y.isZero { return (-y*scale) + origin!.y } } return nil } fileprivate func getPath(start:CGPoint,end:CGPoint) -> UIBezierPath { let path = UIBezierPath() path.move(to: start) path.addLine(to: end) path.lineWidth = 1.0 return path } }
true
6a1e979ec98a0ec7d41da766e2b4031ff3ee0551
Swift
zwenza/spacewatch-ios
/SpaceWatch/Views/launch/LaunchListRowView.swift
UTF-8
931
3.0625
3
[]
no_license
// // LaunchListRowView.swift // SpaceWatch // // Created by David Jöch on 03.06.20. // Copyright © 2020 David Jöch. All rights reserved. // import SwiftUI struct LaunchListRowView: View { var title: String var location: String var body: some View { VStack(alignment: .leading) { Text(title) .font(.headline) Text(location) .font(.subheadline) } .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .leading) .padding() .background(ColorManager.containerBackgroundColor) .clipShape( RoundedRectangle(cornerRadius: 10) ) } } struct LaunchListRowView_Previews: PreviewProvider { static var previews: some View { LaunchListRowView(title: "Launch Name", location: "Location") .previewLayout(.fixed(width: 500, height: 50)) } }
true
7028bdd8679082d5b715f5155b82dbff14945466
Swift
Chen-Cherrypick/ass5
/Assignment_5/MovieCollectionViewCell.swift
UTF-8
773
3.109375
3
[]
no_license
// // MovieCollectionViewCell.swift // Assignment_5 // // Created by Chen Shoresh on 15/07/2021. // import UIKit class MovieCollectionViewCell: UICollectionViewCell { var imageURL: URL? { didSet { imageCell.image = nil fetchImage() } } @IBOutlet weak var name: UILabel! @IBOutlet weak var imageCell: UIImageView! @IBOutlet weak var year: UILabel! private func fetchImage() { if let url = imageURL { let urlContents = try? Data(contentsOf: url) if let imageData = urlContents { imageCell.contentMode = UIView.ContentMode.scaleToFill imageCell.image = UIImage(data: imageData) } } } }
true
b56eb6dd6d5a5d952f1c6e6333a8b732347eb87f
Swift
Magoxter/iOS_Applications
/Developed Applications/17:07/revisao swift/02_Nomenclatura.playground/Pages/10-Exercício Show.xcplaygroundpage/Contents.swift
UTF-8
1,133
4.09375
4
[]
no_license
//: ## Exercício – Vai ter show //: A exposição de animais do seu amigo terminou. Graças à sua ajuda, o evento foi um sucesso. Agora, ele vai organizar um show. Os ingressos estão à venda por $10 cada. O aluguel do lugar custa $50. A impressão dos cartazes do show custa $40. Ajude seu amigo a calcular se o show vai dar lucro ou prejuízo. // Number Of Tickets (Número de ingressos) 150 // Ticket Price (Preço do ingresso) 10 // Room Rental Fee (Aluguel do lugar) 50 // Poster Cost (Custo dos cartazes) 40 // Total Ticket Value (Total do valor dos ingressos) 150 * 10 // Total Expenses (Total de despesas) 1000 + 40 // Total Income Of Show (Total da receita do show) (150 * 10) - (1000 + 40) //: - callout(Exercise):\ //:(Exercício):\ //:Usando o código acima como referência, use instruções let para definir constantes que resolvam o problema do seu amigo.\ //:Coloque seu código abaixo. Para ajudar você a começar, a constante `numberOfTickets` já foi definida. let numberOfTickets = 150 //: //:[Anterior](@previous) | página 10 de 14 | [Na sequência: Exercício – Bilhetes de loteria](@next)
true
622da4e9bfcc31f52de701719abc0205d8cc600e
Swift
SudSharma/LeetcodeSolutionsInSwift
/Leetcode/Leetcode/Questions/575.DistributeCandies.swift
UTF-8
1,501
4.0625
4
[]
no_license
// // 575.DistributeCandies.swift // Leetcode // // Created by Sudarshan Sharma on 3/1/21. // Copyright © 2021 Sudarshan Sharma. All rights reserved. // /* Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them. Example 1: Input: candyType = [1,1,2,2,3,3] Output: 3 Explanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type. Example 2: Input: candyType = [1,1,2,3] Output: 2 Explanation: Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types. Example 3: Input: candyType = [6,6,6,6] Output: 1 Explanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type. Constraints: n == candyType.length 2 <= n <= 104 n is even. -105 <= candyType[i] <= 105 */ class DistributeCandies { func distributeCandies(_ candyType: [Int]) -> Int { let set = Set(candyType) return set.count > candyType.count/2 ? candyType.count/2 : set.count } }
true
0464803f7699b2eb185e509d47921a0022ab5905
Swift
yunihuang1112/Notification-Service-Example
/NotificationService/NotificationService.swift
UTF-8
3,743
2.546875
3
[]
no_license
// // NotificationService.swift // NotificationService // // Created by YUNI on 2018/12/20. // Copyright © 2018年 YUNI. All rights reserved. // import UserNotifications class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let bestAttemptContent = bestAttemptContent { func fail() { contentHandler(request.content) } guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else { return fail() } /* * actions */ let category: String = content.categoryIdentifier handleCategories(category: category) /* * preview image */ if let mediaUrl = content.userInfo["media-url"] as? String { guard let mediaData = NSData(contentsOf:NSURL(string: mediaUrl)! as URL) else { return fail() } guard let attachment = UNNotificationAttachment.create(data: mediaData, options: nil) else { return fail() } content.attachments = [attachment] } contentHandler(content.copy() as! UNNotificationContent) } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } fileprivate func handleCategories(category: String) { let liveViewAction = UNNotificationAction(identifier: "meow", title: "Meow", options: [UNNotificationActionOptions.foreground]) let contactAction = UNNotificationAction(identifier: "wang", title: "Wang", options: []) let categories = UNNotificationCategory(identifier: category, actions: [liveViewAction, contactAction], intentIdentifiers: [], options: []) UNUserNotificationCenter.current().setNotificationCategories([categories]) } } extension UNNotificationAttachment { static func create(data: NSData, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? { let fileManager = FileManager.default let folderName = ProcessInfo.processInfo.globallyUniqueString let fileIdentifier = folderName + ".png" let fileUrlPath = NSURL(fileURLWithPath: NSTemporaryDirectory()) let folderUrl = fileUrlPath.appendingPathComponent(folderName, isDirectory: true) do { try fileManager.createDirectory(at: folderUrl!, withIntermediateDirectories: true, attributes: nil) let fileUrl = folderUrl?.appendingPathComponent(fileIdentifier) try data.write(to: fileUrl!, options: []) let imageAttachment = try UNNotificationAttachment.init(identifier: fileIdentifier, url: fileUrl!, options: options) return imageAttachment } catch let error { print("notification service file error: \(error)") } return nil } }
true
51bc4e492d16d9523aede6da0a45ee705ded7499
Swift
momin96/iTraining
/RanchForcast/RanchForcast/NSRMainViewController.swift
UTF-8
1,142
2.53125
3
[]
no_license
// // NSRMainViewController.swift // RanchForcast // // Created by Nasir Ahmed Momin on 20/04/18. // Copyright © 2018 Nasir Ahmed Momin. All rights reserved. // import Cocoa class NSRMainViewController: NSViewController, NSTableViewDelegate { @IBOutlet weak var arrayController: NSArrayController! @IBOutlet weak var tableView: NSTableView! let fetcher = NSRScheduleFetcher() @objc dynamic var courses : [NSRCourse] = [] override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.doubleAction = #selector(openClass(_:)) fetcher.fetchCoursesUsingCompletionHandler { (result) in switch result { case .Success(let courses) : self.courses = courses case .Failure(let error) : NSAlert(error: error).runModal() self.courses = [] } } } @objc func openClass(_ sender : Any) { if let course = arrayController.selectedObjects.first as? NSRCourse { NSWorkspace.shared.open(course.url) } } }
true
ac3e0b5d93fdf873a98c9b0097332596715aba93
Swift
sergeykgh/Notes
/Notes/Supporting Views/EditableText.swift
UTF-8
1,160
3.125
3
[]
no_license
// // EditableText.swift // Notes // // Created by Sergey Korotkevich on 29/09/2019. // Copyright © 2019 Sergey Korotkevich. All rights reserved. // import SwiftUI import UIKit struct EditableText: UIViewRepresentable { @Binding var text: String let fontSize: CGFloat let showKeyboard: Bool func makeCoordinator() -> Coordinator { Coordinator(self) } func makeUIView(context: Context) -> UITextView { let view = UITextView() view.font = .systemFont(ofSize: fontSize) view.isScrollEnabled = true view.isEditable = true view.isUserInteractionEnabled = true view.delegate = context.coordinator if showKeyboard { view.becomeFirstResponder() } return view } func updateUIView(_ uiView: UITextView, context: Context) { uiView.text = text } class Coordinator: NSObject, UITextViewDelegate { var control: EditableText init(_ control: EditableText) { self.control = control } func textViewDidEndEditing(_ textView: UITextView) { control.text = textView.text } } }
true
b9a5ba6233445cb79e73913bf8d0643fedc3ce8c
Swift
ruddfawcett/swift
/UITableViewControllers/DemoTableViewController.swift
UTF-8
1,714
2.765625
3
[]
no_license
// // DemoTableViewController.swift // swift // // Created by Rudd Fawcett on 6/2/14. // Copyright (c) 2014 Rudd Fawcett. All rights reserved. // import UIKit class DemoTableViewController: UITableViewController { init(style: UITableViewStyle) { super.init(style: style) self.title = "TableViewController Demo" } init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nibName, bundle: nibBundle) } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String! { return "Section \(section)" } override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { return 5 } override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } override func tableView(_: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell") cell.textLabel.text = "Section: \(indexPath.section), Row: \(indexPath.row)" return cell } override func tableView(_: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated:true) let selectedCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell println(selectedCell.textLabel.text) } }
true
ace92e52cb5bc53fb121a4e868beab9213c986ed
Swift
gguby/wyth_2.0
/BoostMINI/BoostMINI/Libraries/ReactorKitSample/ViewControllerReactor.swift
UTF-8
3,280
2.96875
3
[]
no_license
// // ViewControllerReactor.swift // reactorKitSample // // Created by wsjung on 2017. 12. 15.. // Copyright © 2017년 wsjung. All rights reserved. // import ReactorKit import RxCocoa import RxSwift final class ViewControllerReactor : Reactor { enum Action { case updateQuery(String?) case loadNextPage } enum Mutation { case setQuery(String?) case setRepos([Repository], nextPage: Int?) case appendRepos([Repository], nextPage: Int?) case setLoadingNextPage(Bool) } struct State { var query: String? var repos: [Repository] = [] var nextPage: Int? var isLoadingNextPage: Bool = false } let initialState = State() fileprivate let githubService : GithubService init(service : GithubService) { self.githubService = service } func mutate(action: Action) -> Observable<Mutation> { switch action { case let .updateQuery(query) : return Observable.concat([ Observable.just(Mutation.setQuery(query)), self.githubService.search(query: query, page: 1) .takeUntil(self.action.filter(isUpdateQueryAction)) .map { list in Mutation.setRepos(list.items, nextPage: 2) }, ]) case .loadNextPage : guard !self.currentState.isLoadingNextPage else { return Observable.empty() } // prevent from multiple requests guard let page = self.currentState.nextPage else { return Observable.empty() } return Observable.concat([ Observable.just(Mutation.setLoadingNextPage(true)), self.githubService.search(query: self.currentState.query, page: page) .takeUntil(self.action.filter(isUpdateQueryAction)) .map { list in Mutation.setRepos(list.items, nextPage: page + 1) }, Observable.just(Mutation.setLoadingNextPage(false)), ]) } } func reduce(state: State, mutation: Mutation) -> State { switch mutation { case let .setQuery(query): var newState = state newState.query = query return newState case let .setRepos(repos, nextPage): var newState = state newState.repos = repos newState.nextPage = nextPage return newState case let .appendRepos(repos, nextPage): var newState = state newState.repos.append(contentsOf: repos) newState.nextPage = nextPage return newState case let .setLoadingNextPage(isLoadingNextPage): var newState = state newState.isLoadingNextPage = isLoadingNextPage return newState } } private func isUpdateQueryAction(_ action: Action) -> Bool { if case .updateQuery = action { return true } else { return false } } }
true
9973f65de5c29dabcd4b0c52580911606d526d56
Swift
AkroMD/NapoleonTask3-Singleton-
/SingletonAkro/ContactSingle.swift
UTF-8
3,438
3.328125
3
[]
no_license
import Foundation //Лучше вынести в отдельный файл класс //модель, потому что тут она лишняя //и становится сложнее ориентироваться в коде class Contact: NSObject, NSCoding{ enum Keys: String { case name = "Name" case lastName = "LastName" case tel = "Tel" } func encode(with coder: NSCoder) { coder.encode(name, forKey: Keys.name.rawValue) coder.encode(lastname, forKey: Keys.lastName.rawValue) coder.encode(tel, forKey: Keys.tel.rawValue) } required convenience init?(coder: NSCoder) { let name = coder.decodeObject(forKey: Keys.name.rawValue) as! String let lastname = coder.decodeObject(forKey: Keys.lastName.rawValue) as! String let tel = coder.decodeObject(forKey: Keys.tel.rawValue) as! String self.init(name: name,lastname: lastname,tel: tel) } // Пустые функции, которые ничего не делают? func save(){ } func load(){ } // После запятых надо как минимум ставить пробелы // Обычно для каждого свойства своя строка со своим типом // а не все свйоства в одной строке // И все поля не должны быть Optional, // потому что нам нет смысла сохранять контакт // в котором нет никакой информации var name,lastname,tel: String? // Много где забываешь пробел после функции, перед фигурной скобкой // Т.е. у тебя вот так: // init(name: String?, lastname: String?, tel: String?){ // А надо вот так: // init(name: String?, lastname: String?, tel: String?) { init(name: String?, lastname: String?, tel: String?){ self.name = name self.lastname = lastname self.tel = tel } } // Опять пробел потерялся class Contacts{ private static var contacts = [Contact]() private static let key = "mycontact" static var kind = 0; private init(){} static func save(){ let data = try! NSKeyedArchiver.archivedData(withRootObject: contacts, requiringSecureCoding: false) UserDefaults.standard.set(data, forKey: key) } // Не жалей переносов строк после функций, тогда код // будет намного читаемее // И функции с большой буквы очень грубая ошибка) static func load() { guard let data = UserDefaults.standard.data(forKey: key) else { return } guard let codeDate = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) else { return } contacts = codeDate as! [Contact] } static func Add(contact: Contact){ contacts.append(contact) } static func Change(index: Int, contact: Contact){ contacts[index] = contact } static func Delete(index: Int){ contacts.remove(at: index) } static func Lenght() -> Int { contacts.count } static func getContact(index: Int) -> Contact { contacts[index] } }
true
bc17336ff94a89a10ba0f00a6e6bf60020ae4818
Swift
JELGT2011/COVIZE-iOS-App
/Pitch Events/CompanyProfile.swift
UTF-8
1,108
2.515625
3
[]
no_license
// // CompanyProfile.swift // Pitch Events // // Created by Cameron Jones on 3/22/15. // Copyright (c) 2015 Covize. All rights reserved. // import Foundation import CoreData class CompanyProfile: NSManagedObject, Printable{ @NSManaged var name: String? @NSManaged var email: String? @NSManaged var company_name: String? @NSManaged var industry: String? @NSManaged var locale: String? @NSManaged var female_founder: Bool @NSManaged var ethnic_founder: Bool @NSManaged var prefer_local: Bool @NSManaged var prefer_industry: Bool @NSManaged var sort_event_start: Bool @NSManaged var sort_registration_deadline: Bool @NSManaged var capital_goal: String? @NSManaged var fundraising: String? @NSManaged var push_new_setting: Bool @NSManaged var push_favorite_setting: Bool override var description: String { return "Company Name: \(company_name), Email: \(email)\n" } func getURLLocale() -> String{ var loc = locale!.stringByReplacingOccurrencesOfString(" ", withString: "") return loc } }
true
f79440b5308877222fc0bd48bc9052ef25deaae8
Swift
olgusirman/GithubSwiftUIExample
/GithubCombineExample/UserView/UserView.swift
UTF-8
741
2.609375
3
[]
no_license
// // UserView.swift // GithubCombineExample // // Created by Olgu on 6.03.2020. // Copyright © 2020 Aspendos IT. All rights reserved. // import SwiftUI struct UserView: View { @ObservedObject var viewModel = UserViewModel() @State private var token = "" var body: some View { VStack { TextField("Personal Access Token", text: $token) Button(action: { }) { HStack { Image(systemName: "signature") Text("Login") }.padding() } }.padding() } } struct UserView_Previews: PreviewProvider { static var previews: some View { UserView() } }
true
2de5f91c214d7004a70c74ee0ecd765ed83d8a0e
Swift
nate-parrott/PatternPicker
/PatternPicker/HueSlider.swift
UTF-8
841
2.953125
3
[ "MIT" ]
permissive
// // HueSlider.swift // PatternPicker // // Created by Nate Parrott on 11/15/15. // Copyright © 2015 Nate Parrott. All rights reserved. // import UIKit class HueSlider: UIImageView { override func willMoveToWindow(newWindow: UIWindow?) { super.willMoveToWindow(newWindow) render() contentMode = .ScaleToFill } func render() { let pixels = UnsafeMutablePointer<PixelData>.alloc(256) for i in 0..<256 { var r: Float = 0 var g: Float = 0 var b: Float = 0 HSVtoRGB(&r, &g, &b, Float(i) / 255.0 * 360, 1, 1) pixels[i] = PixelData(a: 255, r: UInt8(r*Float(255.0)), g: UInt8(g*Float(255.0)), b: UInt8(b*Float(255.0))) } self.image = imageFromARGB32Bitmap(pixels, width: 256, height: 1) pixels.destroy() } }
true
5ea99c9e9c5e61c5025b0937664ec6711bd9081a
Swift
Naxyoh/Kata
/Diamonds/FunctionnalApproach/FunctionnalApproach.playground/Contents.swift
UTF-8
1,845
3.671875
4
[]
no_license
func createSequence(for letter: Character) -> String { (UnicodeScalar("A").value...UnicodeScalar(String(letter))!.value) .compactMap { UnicodeScalar($0) } .map { String($0) } .joined() } func createRow(index: Int, letter: String) -> String { letter + String(repeating: " ", count: index == 0 ? 0 : 2 * (index - 1) + 1) + letter + "," } func addLeadingSpaces(index: Int, letter: Substring) -> String { String(repeating: " ", count: index) + String(letter) } func printDiamonds(for letter: Character) { let sequence = createSequence(for: letter) let rows = sequence .map(String.init) .enumerated() .map(createRow) let formattedRows = rows .reduce("", +) .dropFirst() .split(separator: ",") let leadingSpacedRows = formattedRows .reversed() .enumerated() .map(addLeadingSpaces) .reversed() let upperPart = leadingSpacedRows .reduce([[String]](), { [($0.first ?? []) + [$1]] }) let pyramid = upperPart .flatMap { [$0, $0.dropLast().reversed()] } .joined(separator: []) .joined(separator: "\n") print(pyramid) } // PrintDiamonds for 'A' returns 'A' //printDiamonds(for: "A") == "A" // Sequence //printDiamonds(for: "C") == "ABC" // Repeats //printDiamonds(for: "C") == "ABBCC" // Introduce new lines //printDiamonds(for: "C") == "A\nBB\nCC" // Introduce leading spaces //printDiamonds(for: "B") == " A\nBB" //printDiamonds(for: "C") == " A\n BB\nCC" // Introduce spacing between letters //printDiamonds(for: "B") == " A\nB B" //printDiamonds(for: "C") == " A\n B B\nC C" // Symetric //printDiamonds(for: "B") == " A\nB B\n A" //printDiamonds(for: "C") == " A\n B B\nC C\n B B\n A" printDiamonds(for: "G")
true
6b559376c5d5d35fb894c2c46a37829e084f55a9
Swift
achimk/flow-coordinators
/FlowCoordinators/FlowCoordinators/ViewControllers/ViewController.swift
UTF-8
943
2.6875
3
[ "MIT" ]
permissive
// // Created by Joachim Kret on 23/06/2020. // Copyright © 2020 Joachim Kret. All rights reserved. // import UIKit open class ViewController: UIViewController { private(set) var appearFirstTime = true open override func viewWillAppear(_ animated: Bool) { if appearFirstTime { viewWillAppearFirstTime(animated) } super.viewWillAppear(animated) } open func viewWillAppearFirstTime(_ animated: Bool) { assert(appearFirstTime, "Should only be called on first time!") } open override func viewDidAppear(_ animated: Bool) { if appearFirstTime { viewDidAppearFirstTime(animated) appearFirstTime = false } super.viewDidAppear(animated) } open func viewDidAppearFirstTime(_ animated: Bool) { assert(appearFirstTime, "Should only be called on first time!") } }
true
a6bd996324f74e0f5e09be83bbb61fe65661029f
Swift
SteamedBunX/Fetch_ios
/Fetch/UI/Onboarding/ProgressBar/ProgressBarView.swift
UTF-8
2,029
2.8125
3
[]
no_license
// // ProgressBarView.swift // Fetch // // Created by Alvin Andino on 3/24/20. // Copyright © 2020 Digital Products. All rights reserved. // import UIKit final class ProgressBarView: UIStackView { private enum Constants { static let spacing: CGFloat = 5.0 } var viewModel: ProgressBarViewModel? { didSet { bindToViewModel() } } private var isProgressFilled: Bool { return viewModel?.isProgressFilled ?? false } private var currentIndex: Int { return viewModel?.currentIndex ?? 0 } private var numberOfSegments: Int { return viewModel?.numberOfSegments ?? 0 } private var validIndexes: Range<Int> { return 0..<numberOfSegments } required init(coder: NSCoder) { super.init(coder: coder) setupStackView() bindToViewModel() } private func setupStackView() { spacing = Constants.spacing distribution = .fillEqually } private func bindToViewModel() { viewModel?.updateProgressBar = updateSegments reloadSegments() } private func reloadSegments() { clearSegments() setupSegments() } private func clearSegments() { arrangedSubviews.forEach { $0.removeFromSuperview() } } private func setupSegments() { validIndexes .map { _ in ProgressBarSegmentView() } .enumerated() .forEach { index, view in view.isEnabled = isEnabled(atIndex: index) addArrangedSubview(view) } } private func updateSegments() { arrangedSubviews .map { $0 as? ProgressBarSegmentView } .enumerated() .forEach { (index, view) in view?.isEnabled = isEnabled(atIndex: index) } } private func isEnabled(atIndex index: Int) -> Bool { return isProgressFilled && index < currentIndex || index == currentIndex } }
true
9e8af58f7e7c077e5de7036fc71b04744d8b4ae0
Swift
virendragit/swift_algorithms
/swift_algos/swift_algos/LongestSubtringWithOutRepeating.swift
UTF-8
763
3.21875
3
[]
no_license
// // LongestSubtringWithOutRepeating.swift // swift_algos // // Created by Virendra Gupta on 4/20/20. // Copyright © 2020 sample. All rights reserved. // class Solution { func lengthOfLongestSubstring(_ str: String) -> Int { var characterDict = [Character:Int]() var maxLength = 0 var lastRepeatPos = -1 var i = 0 for c in str{ if (characterDict[c] != nil) && (characterDict[c]! > lastRepeatPos) { lastRepeatPos = characterDict[c]! } maxLength = max(i - lastRepeatPos, maxLength) characterDict[c] = i i += 1 } return maxLength } } //Solution().lengthOfLongestSubstring("abcdabcbb")
true
1900cf20f3a03359d063374df5de35f321c5b6ef
Swift
raviprajapat1/MVVMSwift
/MVVMSwift/NetworkManager/EndPoints/EndPoints.swift
UTF-8
1,250
2.84375
3
[]
no_license
// // EndPoints.swift // Swift_MVVM_Boilerplate // // Created by Ravi on 20/02/20. // Copyright © 2019 Systango. All rights reserved. // import Foundation protocol BaseURL { static var baseURL: String { get } } enum APIBuilder { struct APIBuilderConstants { static let ApiScheme = "https" static let ApiHost = "domain-name.com" } } extension APIBuilder: BaseURL { static var baseURL: String { return "\(APIBuilder.APIBuilderConstants.ApiScheme)://\(APIBuilder.APIBuilderConstants.ApiHost)" } } public enum UserApi { case login case signup } extension UserApi: EndPointType { var module: String { return "/restApi" } var path: String { switch self { case .login: return "/login" case .signup: return "/signup" } } var httpMethod: HTTPMethod { switch self { case .login: return .post case .signup: return .post } } var task: HTTPTask { switch self { case .login: return .request case .signup: return .request } } var headers: [String: String]? { return nil } }
true
ad5ac6c24ad2b9706b413e91241211c73c9bf162
Swift
VKaban/Swift
/MemeMe/ViewController.swift
UTF-8
5,216
2.53125
3
[]
no_license
// // ViewController.swift // MemeMe // // Created by Vital Milky on 27.09.16. // Copyright © 2016 Vital Milky. All rights reserved. // import UIKit class ViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate { struct Meme { var topText: String var bootomText: String var image: UIImage var memedImage: UIImage } @IBOutlet weak var imagePickerView: UIImageView! @IBOutlet weak var Pick: UIButton! @IBOutlet weak var Camera: UIButton! @IBOutlet weak var topTextfield: UITextField! @IBOutlet weak var bottomTextfield: UITextField! var activeTextfield: UITextField! let memeTextAttributes = [ NSStrokeColorAttributeName : UIColor.black, NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName : UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!, NSStrokeWidthAttributeName : -5.0, ] as [String : Any] override func viewDidLoad() { topTextfield.delegate = self topTextfield.defaultTextAttributes = memeTextAttributes bottomTextfield.delegate = self bottomTextfield.defaultTextAttributes = memeTextAttributes declareTextfields() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) Camera.isEnabled = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func pickAnImageFromAlbum(_ sender: AnyObject) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.allowsEditing = false imagePicker.sourceType = .photoLibrary self.present(imagePicker, animated: true, completion: nil) } @IBAction func pickAnImageFromCamera (sender: AnyObject) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.allowsEditing = false imagePicker.sourceType = .camera self.present(imagePicker, animated: true, completion: nil) } func imagePickerControllerDidCancel(_: UIImagePickerController){ dismiss(animated: true, completion: nil) } func imagePickerController(_: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){ if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { //imagePickerView.contentMode = .scaleAspectFill imagePickerView.image = pickedImage declareTextfields() } dismiss(animated: true, completion: nil) } func textFieldDidBeginEditing(_ textField: UITextField) { textField.clearsOnBeginEditing = false activeTextfield = textField } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func declareTextfields(){ topTextfield.clearsOnBeginEditing = true topTextfield.text = "Top" topTextfield.textAlignment = .center bottomTextfield.clearsOnBeginEditing = true bottomTextfield.text = "Bottom" bottomTextfield.textAlignment = .center } func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if (activeTextfield.isEqual(bottomTextfield)){ if self.view.frame.origin.y == 0{ self.view.frame.origin.y -= keyboardSize.height } } } } func keyboardWillHide(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y != 0{ self.view.frame.origin.y += keyboardSize.height } } } func generateMemedImag () -> UIImage{ self.navigationController?.isToolbarHidden = true self.navigationController?.isNavigationBarHidden = true UIGraphicsBeginImageContext(self.view.frame.size) view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true) let memedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return memedImage self.navigationController?.isToolbarHidden = false self.navigationController?.isNavigationBarHidden = false } func save() { let meme = Meme(topText: topTextfield.text!, bootomText: bottomTextfield.text!, image: imagePickerView.image!, memedImage: generateMemedImage()) } }
true
905e3735469a3589cee98a05611e62c13c23aedb
Swift
abdullahsalah96/On-the-Map-iOS-Nanodegree
/On the Map/Controller/MapViewController.swift
UTF-8
4,854
2.59375
3
[]
no_license
// // MapViewController.swift // On the Map // // Created by Abdalla Elshikh on 4/24/20. // Copyright © 2020 Abdalla Elshikh. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() configureView() } func configureView(){ self.mapView.delegate = self self.tabBarController?.navigationItem.hidesBackButton = true self.tabBarController?.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(logoutIsPressed)) self.tabBarController?.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_addpin"), style: .plain, target: self, action: #selector(addNewPin)) refreshData() } func refreshData(){ User.getStudentsLocations(completionHandler: displayLocations(data:error:)) } @IBAction func refreshPressed(_ sender: Any) { refreshData() } func displayPinsOnMap(){ //parse data //if there are pins remove them from map if self.mapView.annotations.count > 0 { self.mapView.removeAnnotations(self.mapView.annotations) } let locations = StudentsModel.data var annotations = [MKPointAnnotation]() for dictionary in locations { let lat = CLLocationDegrees(dictionary.latitude) let long = CLLocationDegrees(dictionary.longitude) // The lat and long are used to create a CLLocationCoordinates2D instance. let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long) let first = dictionary.firstName let last = dictionary.lastName let mediaURL = dictionary.mediaURL // Here we create the annotation and set its coordiate, title, and subtitle properties let annotation = MKPointAnnotation() annotation.coordinate = coordinate annotation.title = "\(first) \(last)" annotation.subtitle = mediaURL // Finally we place the annotation in an array of annotations. annotations.append(annotation) } // When the array is complete, we add the annotations to the map. self.mapView.addAnnotations(annotations) self.mapView.reloadInputViews() } @objc func logoutIsPressed(){ User.logout(completionHandler: { (success, error) in if success{ self.tabBarController?.navigationController?.popViewController(animated: true) }else{ self.showAlert(title: "Server Error", message: "Couldn't logout") } }) } func showAlert(title: String, message: String) { let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) alertVC.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alertVC, animated: true) } func displayLocations(data: StudentsLocations?, error: Error?){ if let data = data{ StudentsModel.data = data.results //display pins on map displayPinsOnMap() }else{ //error fetching data showAlert(title: "Server Error", message: "Cannot fetch data") } } @objc func addNewPin(){ performSegue(withIdentifier: "PostNewPin", sender: nil) } } extension MapViewController{ //customize pins func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let reuseId = "pin" var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) pinView?.isEnabled = true pinView!.canShowCallout = true pinView?.animatesDrop = true pinView!.pinTintColor = .red pinView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) return pinView } else { pinView!.annotation = annotation } return pinView } // This delegate method is implemented to respond to taps. as to direct to media type func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if control == view.rightCalloutAccessoryView { let app = UIApplication.shared if let toOpen = view.annotation?.subtitle! { app.open(URL(string: toOpen)!, options: [:], completionHandler: nil) } } } }
true
caf283c57734ecd3c86cb7e1c20d7c7d36abb8c2
Swift
a20251313/swiftGame
/swiftGame/MyPlayground.playground/section-1.swift
UTF-8
458
3.453125
3
[]
no_license
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" let triple:Int->Int = { (number:Int) in let result = 3 * number number; return number; } triple(3) let listOfnumbers = 1...5 var sum = 0 for atNum in listOfnumbers { sum += atNum; } sum var j = 2; for var i = 0;i < 5;++i{ j += j*i } j let frame = CGRect(x: 0, y: 0, width: 150, height: 150); //let customView = CheckBox(frame:frame);
true