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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
779619096486af0ffdb5443260b03dce19b7cc9a
|
Swift
|
halfwaychair/ark-ios-monitor
|
/ArkMonitor/models/Server.swift
|
UTF-8
| 1,352
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
//
// Server.swift
// ArkMonitor
//
// Created by Andrew on 2017-09-14.
// Copyright © 2017 vrlc92. All rights reserved.
//
import UIKit
struct CustomServer: Equatable {
static func ==(lhs: CustomServer, rhs: CustomServer) -> Bool {
return lhs.name == rhs.name
}
let name : String
let ipAddress : String
let port : Int
let isSSL : Bool
init(_ name: String, ipAddress: String, port: Int, isSSL: Bool) {
self.name = name
self.ipAddress = ipAddress
self.port = port
self.isSSL = isSSL
}
init?(dictionary: [String : AnyObject]) {
guard let name = dictionary["name"] as? String,
let ipAddress = dictionary["ipAdress"] as? String,
let port = dictionary["port"] as? Int,
let isSSL = dictionary["isSSL"] as? Bool
else {
print("Failed to Create CustomServer")
return nil
}
self.name = name
self.ipAddress = ipAddress
self.port = port
self.isSSL = isSSL
}
public func dictionary() -> [String : AnyObject] {
return ["name": name as AnyObject, "ipAdress": ipAddress as AnyObject, "port": port as AnyObject, "isSSL": isSSL as AnyObject]
}
}
| true
|
0483975a491a569717fce9496f53f2b291762500
|
Swift
|
Andy1984/Earthquake
|
/Earthquake/MapViewController.swift
|
UTF-8
| 2,202
| 2.765625
| 3
|
[] |
no_license
|
//
// MapViewController.swift
// Earthquake
//
// Created by mac on 2018/10/26.
// Copyright © 2018 YWC. All rights reserved.
//
import UIKit
import GoogleMaps
class MapViewController: UIViewController {
private let focusFeature:Feature
private let otherFeatures:[Feature]
private var mapView:GMSMapView!
//Init
init(focusFeature:Feature, otherFeatures:[Feature]) {
self.focusFeature = focusFeature
self.otherFeatures = otherFeatures
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Google Map"
}
// Create map
override func loadView() {
guard let coordinates = Geometry.parseCoordinates(focusFeature.geometry?.coordinates) else {
return
}
let camera = GMSCameraPosition.camera(withLatitude: coordinates.latitude, longitude: coordinates.longitude, zoom: 6.0)
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
view = mapView
let selectedMarker = self.createMarker(feature: self.focusFeature)
mapView.selectedMarker = selectedMarker
for feature in self.otherFeatures {
_ = self.createMarker(feature: feature)
}
}
func createMarker(feature:Feature) -> GMSMarker? {
guard let coordinates = Geometry.parseCoordinates(feature.geometry?.coordinates) else {
return nil
}
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: coordinates.latitude, longitude: coordinates.longitude)
if let property = feature.properties {
marker.title = property.place
if let millisecond = property.time {
let second = TimeInterval(millisecond) / 1000
let timeDate = Date(timeIntervalSince1970: second)
let timeString = timeDate.description
marker.snippet = timeString
}
marker.map = mapView
}
return marker
}
}
| true
|
cce4891063d143aafba8d6060dfee9cb7b10c55a
|
Swift
|
lvsti/Juggler
|
/Juggler/PullRequest.swift
|
UTF-8
| 477
| 2.640625
| 3
|
[] |
no_license
|
//
// PullRequest.swift
// Juggler
//
// Created by Tamas Lustyik on 2019. 06. 10..
// Copyright © 2019. Tamas Lustyik. All rights reserved.
//
import Foundation
enum PullRequestKind: String, Codable {
case gitHub
}
protocol PullRequest {
var kind: PullRequestKind { get }
var id: String { get }
var title: String? { get }
var url: URL { get }
var remote: Git.Remote { get }
var sourceBranch: Git.Branch { get }
var targetBranch: Git.Branch { get }
}
| true
|
53d77147ba23229b0b7d05fc36d071ad6a2ff4e5
|
Swift
|
mormo17/weather-app-leavingstone
|
/WeatherApp/WeatherApp/Pages/Today/Models/TodayViewModelConstructor.swift
|
UTF-8
| 838
| 2.703125
| 3
|
[] |
no_license
|
//
// TodayViewModelConstructor.swift
// WeatherApp
//
// Created by Mariam Ormotsadze on 9/6/21.
//
import Foundation
class TodayViewModelConstructor{
public static func construct(from item: WeatherData) -> TodayViewModel {
return TodayViewModel(city: item.name,
countryCode: item.sys.country,
iconName: item.weather.first!.icon,
temperature: item.main.temp,
mainDescription: item.weather.first!.main,
cloudiness: item.clouds.all,
humidity: item.main.humidity,
pressure: item.main.pressure,
windSpeed: item.wind.speed,
windDirection: item.wind.deg)
}
}
| true
|
7a518614e326b9e80eb8a139ca4c8f2d1da9d03f
|
Swift
|
hartlco/Icro
|
/Icro/View/LoginView.swift
|
UTF-8
| 2,701
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// Created by Martin Hartl on 13.06.19.
// Copyright © 2019 Martin Hartl. All rights reserved.
//
import SwiftUI
struct LoginView: View {
@ObservedObject private var viewModel: LoginViewModel
init(viewModel: LoginViewModel) {
self.viewModel = viewModel
}
var body: some View {
NavigationView {
List {
Section(footer: Text("LOGINVIEWCONTROLLER_TEXTFIELDINFO_TEXT").lineLimit(nil)) {
TextField("LOGINVIEWCONTROLLER_TEXTFIELD_PLACEHOLDER",
text: $viewModel.loginString)
.disableAutocorrection(true)
.autocapitalization(UITextAutocapitalizationType.none)
viewModel.infoMessage.map {
Text($0)
}
.lineLimit(nil)
.font(.footnote)
}
Section {
LoginButton(loading: $viewModel.isLoading,
enabled: viewModel.buttonActivated,
label: Text(viewModel.buttonString)) {
self.viewModel.login()
}
}
}
.listStyle(GroupedListStyle())
.navigationBarItems(leading:
Button(action: {
self.viewModel.didDismiss()
}, label: {
Text("ITEMNAVIGATOR_MOREALERT_CANCELACTION")
})
)
.navigationBarTitle(Text("LOGINVIEWCONTROLLER_TITLE"))
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct LoginButton: View {
@Binding var loading: Bool
var enabled: Bool
var label: Text
var action: () -> Void
var body: some View {
HStack {
Button(action: {
self.action()
}, label: {
label
})
.disabled(!enabled)
Spinner(loading: $loading)
}
}
}
struct Spinner: UIViewRepresentable {
@Binding var loading: Bool
func makeUIView(context: UIViewRepresentableContext<Spinner>) -> UIActivityIndicatorView {
let indicator = UIActivityIndicatorView(style: .medium)
return indicator
}
func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext<Spinner>) {
if loading {
uiView.startAnimating()
} else {
uiView.stopAnimating()
}
}
}
#if DEBUG
struct LoginView_Previews: PreviewProvider {
static var previews: some View {
LoginView(viewModel: LoginViewModel())
}
}
#endif
| true
|
caa0aab15d69560f1eb3765c6e87318be0918a7f
|
Swift
|
EduardoTT/HealthChallenge
|
/Health/Health/AreaPoints.swift
|
UTF-8
| 3,550
| 2.890625
| 3
|
[] |
no_license
|
//
// AreaPoints.swift
// Health
//
// Created by Pietro Ribeiro Pepe on 7/25/15.
// Copyright (c) 2015 Eduardo Tolmasquim. All rights reserved.
//
import SpriteKit
class AreaPoints : NSMutableDictionary{
//var points = [[CGPoint]]();
//var shapes =
func insertNewArea(points : [CGPoint], shape : CGMutablePathRef, id : String){
if(self[id] == nil){
var pointsMatrix = Array<Array<CGPoint>>();
pointsMatrix.append(points);
var shapesArray = Array<CGMutablePathRef>();
shapesArray.append(shape);
self[id] = NSMutableDictionary(objects: [pointsMatrix as! AnyObject,shapesArray as AnyObject], forKeys: ["points","shapes"]);
}
else{
var shapes = ((self[id] as! NSMutableDictionary)["shapes"] as! Array<CGMutablePathRef>)
shapes.append(shape);
var pointsMatrix = ((self[id] as! NSMutableDictionary)["points"] as! Array<Array<CGPoint>>);
pointsMatrix.append(points);
}
}
func calculateAreas()->NSMutableDictionary{
var areaDict = NSMutableDictionary();
for (id,dict) in self{
var totalArea : CGFloat = 0;
let pointsMatrix = (dict as! NSMutableDictionary)["points"] as! Array<Array<CGPoint>>;
let shapes = (dict as! NSMutableDictionary)["shapes"] as! Array<CGMutablePathRef>;
for (var i:Int=0; i<pointsMatrix.count; i++){
totalArea += calculateArea(shapes[i], points: pointsMatrix[i]);
}
areaDict.setObject(totalArea, forKey: id as! String);
}
return areaDict;
}
private func calculateArea(path : CGMutablePathRef, points : [CGPoint]) -> CGFloat{
let areaRect = CGPathGetBoundingBox(path);
let origin = CGPoint(x: ceil(areaRect.origin.x), y: ceil(areaRect.origin.y))
let end = CGPoint(x: floor(areaRect.maxX),y: floor(areaRect.maxY));
let areaBox = CGRect(origin: origin, size: CGSize(width: end.x-origin.x, height: end.y-origin.y));
var pointsMatrix = Array<Array<Bool>>();
var i:CGFloat = 0; var j:CGFloat = 0;
for(i=0;i < areaBox.width; i++){
for(j=0;j < areaBox.height; j++){
pointsMatrix[Int(i)][Int(j)] = false;
}
}
for point in points{
pointsMatrix[Int(point.x-origin.x)][Int(point.y-origin.y)] = true;
}
var area : CGFloat;
var totalArea : CGFloat = 0;
var onArea : Bool;
var value : Bool;
var lastValue = false;
for(j=0; j < areaBox.height; j++){
onArea = false;
area=0;
for(i=0; i < areaBox.width; i++){
value = pointsMatrix[Int(i)][Int(j)];
if(onArea){ //Inside area of image
if(!value){
area++;
}
else{
if(!lastValue){
onArea = false;
totalArea += area;
area = 0;
}
else{
//Continuidade de barreira
}
}
}
else{ //outside area of image
if(value){
onArea=true;
}
}
lastValue = value;
}
}
return totalArea;
}
}
| true
|
62969f7c6a0ce242406eedfd331d6ae4d5ea7421
|
Swift
|
ainopara/Swift-on-ECS
|
/Swift-on-ECS/Manager/_SystemMetadata/Abstract/_VariantSystemMetadata.swift
|
UTF-8
| 684
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// _VariantSystemMetadata.swift
// Swift-on-ECS
//
// Created by WeZZard on 12/17/17.
//
import SwiftExt
/// `_VariantSystemMetadata` represents the metadata of a system.
///
internal protocol _VariantSystemMetadata: Hashable {
associatedtype Handler
var name: String { get set }
var isEnabled: Bool { get set }
var handler: Handler { get }
var handlerIdentifier: FunctionIdentifier { get }
}
extension _VariantSystemMetadata {
internal static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.handlerIdentifier == rhs.handlerIdentifier
}
internal var hashValue: Int { return handlerIdentifier.hashValue }
}
| true
|
6a7ee0c32c9ff65bc49572a4de8413aecd59d77a
|
Swift
|
meganpng/electricle
|
/Electricle/SignUpController.swift
|
UTF-8
| 7,920
| 2.703125
| 3
|
[] |
no_license
|
//
// SignUpController.swift
// Electricle
//
// Created by P. Megan on 28/1/21.
//
import UIKit
import CoreData
import Foundation
class SignUpController: UIViewController{
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
super.touchesBegan(touches, with: event)
}
@IBOutlet weak var userNameField: UITextField!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var phoneField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var confirmField: UITextField!
let userController:UserController = UserController()
override func viewDidLoad() {
super.viewDidLoad()
}
//this redirects the user back to the home page
@IBAction func Cancel(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
//this submits the sign up details
@IBAction func onSubmit(_ sender: Any) {
let email = emailField.text!.trimmingCharacters(in: .whitespaces)
let username = userNameField.text!.trimmingCharacters(in: .whitespaces)
let name = nameField.text!.trimmingCharacters(in: .whitespaces)
let phoneno = phoneField.text!.trimmingCharacters(in: .whitespaces)
let password = passwordField.text!.trimmingCharacters(in: .whitespaces)
let confirmpwd = confirmField.text!.trimmingCharacters(in: .whitespaces)
let emptyBool:Bool = checkFields(email: email, username: username, name: name, phoneno: phoneno, pwd: password, confirmpwd: confirmpwd)
let numberBool:Bool = validatePhoneNumber(phoneno: phoneno)
let flag:Bool = userController.validateUserEmail(input: email)
//this sends a empty fields alert if the fields are empty
if(emptyBool == true){
let dialogMessage = UIAlertController(title: "Empty Fields", message: "Please fill up all fields.", preferredStyle: .alert)
// Create OK button with action handler
let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
print("Ok button tapped")
})
//Add OK button to a dialog message
dialogMessage.addAction(ok)
// Present Alert to
self.present(dialogMessage, animated: true, completion: nil)
}
//this sends an alert if the email entered exists in the database
else if(flag == false){
emailField.text = ""
userNameField.text = ""
nameField.text = ""
phoneField.text = ""
passwordField.text = ""
let dialogMessage = UIAlertController(title: "Email Already Exists", message: "Please log in instead.", preferredStyle: .alert)
// Create OK button with action handler
let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
print("Ok button tapped")
})
//Add OK button to a dialog message
dialogMessage.addAction(ok)
// Present Alert to
self.present(dialogMessage, animated: true, completion: nil)
}
//this sends an alert if the number is incorrect
else if(numberBool == false){
let dialogMessage = UIAlertController(title: "Invalid Number", message: "Please enter valid number.", preferredStyle: .alert)
// Create OK button with action handler
let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
print("Ok button tapped")
})
//Add OK button to a dialog message
dialogMessage.addAction(ok)
// Present Alert to
self.present(dialogMessage, animated: true, completion: nil)
}
//this sends an alert if the two password fields do not match
else if(password != confirmpwd){
phoneField.text = ""
passwordField.text = ""
let dialogMessage = UIAlertController(title: "Passwords Do Not Match", message: "Please enter the same password in the password and confirm password fields.", preferredStyle: .alert)
// Create OK button with action handler
let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
print("Ok button tapped")
})
//Add OK button to a dialog message
dialogMessage.addAction(ok)
// Present Alert to
self.present(dialogMessage, animated: true, completion: nil)
}
else{
//this adds the user and current user to the database and redirects the user to the home page
print("\(email), \(username), \(name), \(phoneno), \(password)")
let userobject = User(email: email, username: username, name: name, phoneno: phoneno, password: password)
let currentobject = CurrentUser(email: email, username: username, name: name, phoneno: phoneno, password: password)
userController.AddUser(newUser: userobject)
userController.AddCurrentUser(newCurrentUser: currentobject)
let storyboard = UIStoryboard(name: "Electricle", bundle: nil)
let vc = storyboard.instantiateViewController(identifier: "Electricle") as UIViewController
vc.modalPresentationStyle = .fullScreen //try without fullscreen
present(vc, animated: true, completion: nil)
}
}
//this resets the fields
@IBAction func onReset(_ sender: Any) {
emailField.text = ""
userNameField.text = ""
nameField.text = ""
phoneField.text = ""
passwordField.text = ""
confirmField.text = ""
}
//this checks if the fields are empty
func checkFields(email:String, username:String, name:String, phoneno:String, pwd:String, confirmpwd:String) -> Bool{
let dataList:[String] = [email, username, name, phoneno, pwd, confirmpwd]
for d in dataList{
if(d.count == 0){
return true
}
}
return false
}
//this validates the phone number
func validatePhoneNumber(phoneno:String) ->Bool{
let flag:Bool = validateIsNumber(phoneno: phoneno)
if(phoneno.count != 8){
return false
}
else if(flag == false){
return false
}
else if(phoneno.prefix(1) != "6" && phoneno.prefix(1) != "8" && phoneno.prefix(1) != "9"){
return false
}
return true
}
//this checks if letters were entered
func validateIsNumber(phoneno:String)->(Bool){
let charArray: Array<Character> = Array(phoneno)
for char in charArray {
if Int(String(char)) == nil {
return false
}
}
return true
/*
let charArray:Array<Character> = Array(phoneno)
let numberArray:Array<Character> = Array(arrayLiteral: "0", "1", "2","3","4","5","6","7","8","9")
var flag:Bool = false
for c in charArray{
var bool:Bool = false
for n in numberArray{
if(c == n){
bool = true
break
}
}
if(bool == true){
flag = true
}
else{
flag = false
}
}
if(flag == true){
return true
}
else{
return false
}
*/
}
}
| true
|
64b74ed90ddd35b403e7daad0049eba87c08eac8
|
Swift
|
alb3rtobq/iOS
|
/Tarea#3/Tarea#3/Models/Item.swift
|
UTF-8
| 578
| 2.546875
| 3
|
[] |
no_license
|
//
// Item.swift
// Tarea#3
//
// Created by user169046 on 3/22/20.
// Copyright © 2020 user169046. All rights reserved.
//
import Foundation
struct Item {
var identifier = NSUUID().uuidString
//var imageName : String
var name: String
var number: String
var date = Date()
var unit: String
var priority: String
//init(imageName: String, name: String, number: String, date: Date) {
// self.imageName = imageName
//self.name = name
//self.number = number
// self.date = date
//}
}
| true
|
23c52a2b4e217c5fd6e93b97ee4913f1f76e0953
|
Swift
|
GuihAntunes/Swift200
|
/Swift200_Day7_1_DatePicker.AlertViewController.Date/Swift200_Day7_1_DatePicker.AlertViewController.Date/Arredondador.swift
|
UTF-8
| 1,020
| 2.96875
| 3
|
[] |
no_license
|
//
// Arredondador.swift
// Swift200_Day4_1_TextViewSwitchSegment
//
// Created by Swift on 01/10/16.
// Copyright © 2016 Guihsoft. All rights reserved.
//
import UIKit
class Arredondador: NSObject {
// @IBInspectable aviso o interface builder que essa variável pode
// ser alterada no storyboard
// Não pode ser Optional. Precisa de valor padrão
@IBInspectable var raio:CGFloat = 10
@IBOutlet var alvos:[UIView]? {
didSet{
// Garantimos que existe um vetor com minhas
// views conectadas, senão não preciso fazer nada e retorno
guard let alvosAtuais = alvos else {
return
}
// Pegamos cada uma das views num loop
// e pedimos para arredondar
for alvo in alvosAtuais {
// VIIISH 😎
alvo.layer.cornerRadius = raio
}
}
}
}
| true
|
2ac477a414813d84720f0570f6070f23b84347c2
|
Swift
|
subhajit1609/Acronym
|
/AcronymApplication/Controller/AcronymSearchViewController.swift
|
UTF-8
| 1,305
| 2.734375
| 3
|
[] |
no_license
|
//
// AcronymSearchViewController.swift
// AcronymApplication
//
import UIKit
/// This class will contain the attributes and behaviours for module
class AcronymSearchViewController: UIViewController {
var presenter: AcronymSearchPresentable?
override func viewDidLoad() {
super.viewDidLoad()
AcronymSearchBuilder().configure(viewController: self)
(self.view as? AcronymSearchView)?.configureView()
(self.view as? AcronymSearchView)?.delegate = self
}
deinit { print("AcronymSearchViewController") }
}
private extension AcronymSearchViewController {
/// Fetch the data and reload the view.
func loadAcronymList(searchText: String) {
presenter?.getAcronymList(inputStr: searchText)
}
}
extension AcronymSearchViewController: AcronymSearchViewControllerListener {
func displayMessages(viewModels: [AcronymModel]) {
DispatchQueue.main.async {
(self.view as? AcronymSearchView)?.updateAcronymSearchViewModel(viewModels: viewModels)
}
}
func displayErrorMessages(error: Error) {
}
}
extension AcronymSearchViewController: AcronymSearchTextProtocol {
func acronymsSearchTex(searchText: String) {
loadAcronymList(searchText: searchText.capitalized)
}
}
| true
|
725fdcbec0af68a40ee0ce2eabce2ad7a4f9ed2e
|
Swift
|
Hayden32/ios-afternoon-project-view-controller-transitions-friends
|
/Friends/Friends/View Controller/FriendsTableViewController.swift
|
UTF-8
| 1,587
| 2.609375
| 3
|
[] |
no_license
|
//
// FriendsTableViewController.swift
// Friends
//
// Created by Hayden Hastings on 5/23/19.
// Copyright © 2019 Hayden Hastings. All rights reserved.
//
import UIKit
class FriendsTableViewController: UITableViewController, UINavigationControllerDelegate {
let friendsModel = FriendsModel()
let navigationControllerDelegate = NavigationControllerDelegate()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.delegate = self
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return friendsModel.friends.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FriendsCell", for: indexPath)
guard let imageCell = cell as? FriendsTableViewCell else { return cell }
let image = friendsModel.friends[indexPath.row]
imageCell.friends = image
return cell
}
// 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?) {
if let indexPath = tableView.indexPathForSelectedRow {
navigationControllerDelegate.sourceCell = tableView.cellForRow(at: indexPath) as? FriendsTableViewCell
}
}
}
| true
|
10f60422650d1e0dac247e45e5b4825a368651ea
|
Swift
|
arpit-garg-1995/TriviaApp
|
/TriviaApp/Controller/CricketerViewController.swift
|
UTF-8
| 2,760
| 2.96875
| 3
|
[] |
no_license
|
//
// CricketerViewController.swift
// TriviaApp
//
// Created by Arpit Garg on 18/12/20.
// Copyright © 2020 Arpit Garg. All rights reserved.
//
import UIKit
class CricketerViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
private let options = ["A) Sachin Tendulkar", "B) Virat Kolli", "C) Adam Gilchirst", "D) Jacques Kallis"]
private var selectedCellPos:Int?
private var model:GameModel?
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
@IBAction func nextAction(_ sender: UIButton) {
if let pos = selectedCellPos{
model?.cricketer = options[pos]
if let storyboard = self.storyboard,let secondViewController = storyboard.instantiateViewController(identifier: "ColorsViewController") as? ColorsViewController, let navigation = self.navigationController{
secondViewController.passsStruct(model: model!); //passStruct
navigation.pushViewController(secondViewController, animated: true)
}
}else{
showAlert()
}
}
private func showAlert(){
let alert = UIAlertController(title: "Error", message: "Select atleast one option", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func passsStruct(model:GameModel){
self.model = model
}
}
extension CricketerViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell") //standardCell
cell.textLabel!.text = options[indexPath.row]
cell.selectionStyle = .none
return cell
}
}
extension CricketerViewController: UITableViewDelegate{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath){
if cell.accessoryType == .checkmark{
cell.accessoryType = .none
selectedCellPos = nil
}else{
cell.accessoryType = .checkmark
selectedCellPos = indexPath.row
}
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
}
| true
|
8b7516e0d63da642f8e81aa8ca00ea6f678402e5
|
Swift
|
teslatess/testApp
|
/testApp/WalletModule/ContainerViewController.swift
|
UTF-8
| 3,051
| 2.75
| 3
|
[] |
no_license
|
//
// ContainerViewController.swift
// testApp
//
// Created by kkerors on 09.05.2021.
//
import Foundation
import UIKit
class ContainerViewController: UIViewController {
private weak var controller: UIViewController!
private weak var menuViewController: UIViewController!
private var isMove = false
override func viewDidLoad() {
configureWalletViewController()
}
private func configureWalletViewController() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let walletViewController = storyboard.instantiateViewController(withIdentifier: "WalletViewController") as! WalletViewController
walletViewController.delegate = self
controller = walletViewController
view.addSubview(controller.view)
addChild(controller)
}
private func configureMenuViewController() {
if menuViewController == nil {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let menuController = storyboard.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController
menuController.delegate = self
menuViewController = menuController
view.insertSubview(menuViewController.view, at: 0)
addChild(menuViewController)
}
}
private func showMenuViewController(_ shouldMove: Bool) {
if shouldMove {
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.8,
initialSpringVelocity: 0,
options: .curveEaseInOut) {
self.controller.view.frame.origin.x = self.controller.view.frame.width/2
self.controller.view.frame.origin.y = self.controller.view.frame.height/5
self.controller.view.layer.cornerRadius = 14
self.controller.view.layer.masksToBounds = true
} completion: { finished in
//
}
} else {
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.8,
initialSpringVelocity: 0,
options: .curveEaseInOut) {
self.controller.view.frame.origin.x = 0
self.controller.view.frame.origin.y = 0
self.controller.view.layer.cornerRadius = 0
} completion: { finished in
//
}
}
}
}
// MARK: MenuViewControllerDelegate
extension ContainerViewController: MenuViewControllerDelegate {
func hideMenu() {
isMove = !isMove
showMenuViewController(isMove)
}
}
// MARK: WalletViewControllerDelegate
extension ContainerViewController: WalletViewControllerDelegate {
func toggleMenu() {
configureMenuViewController()
isMove = !isMove
showMenuViewController(isMove)
}
}
| true
|
8be58e1fcfe3fe0ac09dca537f4cf92e1f7acd28
|
Swift
|
comfortable-panda/ComfortablePandA-iOS
|
/ComfortablePandA/modules/Updater.swift
|
UTF-8
| 646
| 2.6875
| 3
|
[] |
no_license
|
//
// Updater.swift
// ComfortablePandA
//
// Created by das08 on 2020/10/19.
//
import Foundation
func toggleIsFinished(kadaiList: [Kadai], kid: String) -> [Kadai] {
var toggledKadaiList = [Kadai]()
for var kadaiEntry in kadaiList {
if kadaiEntry.id == kid {
if kadaiEntry.isFinished { BadgeCount.shared.badgeCount += 1 }
else{ BadgeCount.shared.badgeCount -= 1 }
kadaiEntry.isFinished = !kadaiEntry.isFinished
}
toggledKadaiList.append(kadaiEntry)
}
Saver.shared.saveKadaiListToStorage(kadaiList: toggledKadaiList)
return toggledKadaiList
}
| true
|
4e327660472df0b5129dab797cd72b18826b703d
|
Swift
|
cristipetra/CPLabelSwitch
|
/CPLabelSwitch/Classes/LabelSwitchBackView.swift
|
UTF-8
| 873
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// LabelSwitchBackView.swift
// CPLabelSwitch
//
// Created by Cristian Petra on 06/12/2018.
//
import Foundation
import UIKit
class LabelSwitchBackView: UIView {
var gradientLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.isHidden = true
return layer
}()
var imageView: UIImageView = {
let view = UIImageView()
view.contentMode = .scaleAspectFill
view.isHidden = true
return view
}()
override var frame: CGRect {
didSet {
gradientLayer.frame = bounds
imageView.frame = bounds
}
}
init() {
super.init(frame: .zero)
addSubview(imageView)
layer.addSublayer(gradientLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
4661b70a003e57103fcfbb85a5e956dfdb904f7e
|
Swift
|
heji233/LiteChart
|
/Sources/RadarChart/RadarBackgroundViewConfigure.swift
|
UTF-8
| 1,232
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
//
// RadarBackgroundViewConfigure.swift
// LiteChart
//
// Created by 刘洋 on 2020/6/22.
// Copyright © 2020 刘洋. All rights reserved.
//
import Foundation
struct RadarBackgroundViewConfigure {
let radarLineColor: LiteChartDarkLightColor
let radarLightColor: LiteChartDarkLightColor
let radarUnlightColor: LiteChartDarkLightColor
let radarLayerCount: Int
let angleOfPoints: [Double]
}
extension RadarBackgroundViewConfigure {
private init() {
self.radarLineColor = .init(lightUIColor: .gray, darkUIColor: .white)
self.radarLightColor = .init(lightUIColor: .white, darkUIColor: .black)
self.radarUnlightColor = .init(lightUIColor: .lightGray, darkUIColor: .white)
self.radarLayerCount = 1
self.angleOfPoints = [-90, 30, 150]
}
static let emptyConfigure = RadarBackgroundViewConfigure()
var locationOfPoints: [RadarChartLabelLocation] {
self.angleOfPoints.map({
if $0 == 90 {
return .bottom
} else if $0 == -90 {
return .top
} else if $0 > 90 {
return .left
} else {
return .right
}
})
}
}
| true
|
a5dd12e7af1aa05a0039e2e19b73b4fc437256f3
|
Swift
|
SergeyParfenoff/YandexCup
|
/Clock/Clock/main.swift
|
UTF-8
| 1,345
| 3.375
| 3
|
[] |
no_license
|
//
// main.swift
// Clock
//
// Created by Sergey on 07.11.2020.
//
import Foundation
var startHH: Int?
var startMM: Int?
var endHH: Int?
var endMM: Int?
if let input = readLine() {
let parts = input.split(separator: " ")
if parts.count == 2 {
let startParts = parts[0].split(separator: ":")
startHH = Int(startParts[0])
startMM = Int(startParts[1])
let endParts = parts[1].split(separator: ":")
endHH = Int(endParts[0])
endMM = Int(endParts[1])
}
}
if let startHH = startHH,
let startMM = startMM,
let endHH = endHH,
let endMM = endMM {
let startAngle = angle(startHH, startMM)
let endAngle = angle(endHH, endMM)
let startAngleTrunc = startAngle.truncatingRemainder(dividingBy: 360)
var swipeAngle = (endAngle - startAngle).truncatingRemainder(dividingBy: 360)
if swipeAngle == 0 {
swipeAngle = 0
} else if swipeAngle < 0 {
swipeAngle += 360
}
var more12hours = 0
if endAngle >= startAngle {
more12hours = (endAngle - startAngle) >= 360 ? 1 : 0
} else {
more12hours = ((720 - startAngle) + endAngle) >= 360 ? 1 : 0
}
print("\(startAngleTrunc) \(swipeAngle) \(more12hours)")
}
func angle(_ HH: Int, _ MM: Int) -> Double {
return Double(HH) * 30 + Double(MM) * 0.5
}
| true
|
4279795cf6953edb7ff015e2f97dcddfebd1df7d
|
Swift
|
DeepikaRamesh1510/Library
|
/Library/Common/Extension/TableExtension.swift
|
UTF-8
| 1,319
| 2.71875
| 3
|
[] |
no_license
|
//
// TableViewControllerExtension.swift
// FullLibrary
//
// Created by user on 14/12/19.
// Copyright © 2019 user. All rights reserved.
//
import UIKit
extension UITableView {
func setEmptyMessage(_ message: String) {
let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
messageLabel.text = message
messageLabel.textColor = .black
messageLabel.numberOfLines = 2
messageLabel.textAlignment = .center
messageLabel.font = UIFont(name: "TrebuchetMS", size: 15)
messageLabel.sizeToFit()
self.backgroundView = messageLabel
self.separatorStyle = .none
}
func displayLoadingSpinner() {
let spinner = UIActivityIndicatorView(style: .medium)
spinner.color = .systemGray
spinner.startAnimating()
spinner.frame = CGRect(x: 0, y: 0, width: 20, height: 0)
spinner.center = CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2)
self.backgroundView = spinner
self.separatorStyle = .none
}
func setTableViewFooter(view: UIView = UIView()) {
self.tableFooterView = view
}
func dismissTableViewOnDrag() {
self.keyboardDismissMode = .onDrag
}
func restore() {
self.backgroundView = nil
self.separatorStyle = .singleLine
}
}
| true
|
3a5b353f1e80e4e111ca82c796e110fe094c1ad6
|
Swift
|
samwong000/YellowSub
|
/YellowSub/GameOverScene.swift
|
UTF-8
| 1,368
| 2.65625
| 3
|
[] |
no_license
|
//
// GameOverScene.swift
// YellowSub
//
// Created by Sam Wong on 19/01/2015.
// Copyright (c) 2015 sam wong. All rights reserved.
//
import SpriteKit
class GameOverScene: SKScene {
var viewController:GameViewController?
var colorBackground:SKColor! = SKColor(red: 12/255, green: 77/255, blue: 105/255, alpha: 1.0)
//Init
override func didMoveToView(view: SKView) {
let nodeLabel = SKLabelNode(fontNamed: "Lobster 1.4")
nodeLabel.text = "game over"
nodeLabel.fontSize = 50
nodeLabel.fontColor = SKColor.whiteColor()
nodeLabel.position = CGPointMake(self.frame.width/2, self.frame.height/3*2)
nodeLabel.alpha = 0.0
nodeLabel.runAction(SKAction.fadeAlphaTo(1.0, duration: 1.0))
self.addChild(nodeLabel)
let spriteFace = SKSpriteNode(imageNamed: "diver")
spriteFace.size = CGSizeMake(spriteFace.size.width/2, spriteFace.size.height/2)
spriteFace.position = CGPointMake(self.frame.width/2, -spriteFace.size.height/2)
spriteFace.runAction(SKAction.moveToY(spriteFace.size.height/2, duration: 0.7))
self.addChild(spriteFace)
self.backgroundColor = self.colorBackground
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
viewController?.presentGameScene()
}
}
| true
|
4c4dc6569b3f68ac3efcd3b360cd70ca7704962f
|
Swift
|
volonbolon/ideal-octo-parakeet
|
/IdealOctoParakeet/IdealOctoParakeet/MoviesTableViewController.swift
|
UTF-8
| 2,196
| 2.671875
| 3
|
[] |
no_license
|
//
// MoviesTableViewController.swift
// IdealOctoParakeet
//
// Created by Ariel Rodriguez on 1/26/16.
// Copyright © 2016 Ariel Rodriguez. All rights reserved.
//
import UIKit
class MoviesTableViewController: UITableViewController {
let movies:[[String:AnyObject]]
required init?(coder aDecoder: NSCoder) {
let bundle = NSBundle.mainBundle()
let contentURL = bundle.URLForResource("content", withExtension: "plist")
let content = NSDictionary(contentsOfURL: contentURL!)!
self.movies = content.objectForKey("movies") as! [[String:AnyObject]]
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.movies.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("moviesCell", forIndexPath: indexPath)
let movie = self.movies[indexPath.row]
cell.textLabel?.text = movie["title"] as? String
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let identifier = segue.identifier
if identifier == Constants.SegueIdentifier.ShowMovieDetail {
let selectedIndexPath = self.tableView.indexPathForSelectedRow
let movie = self.movies[selectedIndexPath!.row]
let dvc = segue.destinationViewController as! MovieInfoViewController
dvc.movie = movie
}
}
}
| true
|
b66e343e5d29bfb9445d2b2d125a8e5bca9f7cab
|
Swift
|
ajunlonglive/HopperBus-iOS
|
/HopperBus/Controllers/AboutViewController.swift
|
UTF-8
| 5,985
| 2.625
| 3
|
[] |
no_license
|
//
// AboutViewController.swift
// HopperBus
//
// Created by Tosin Afolabi on 27/01/2015.
// Copyright (c) 2015 Tosin Afolabi. All rights reserved.
//
import UIKit
enum AboutSection: Int {
case Team = 0, DISE, Apps
static let count = 3
}
class BaseAboutViewController: GAITrackedViewController {
var type: AboutSection {
return .Team
}
}
class AboutViewController: GAITrackedViewController {
// MARK: - Properties
var currentIndex = 0
var currentTitle = ""
lazy var titleLabel: UILabel = {
let label = UILabel()
label.text = "About The Developers - Team"
let fontSize: CGFloat = iPhone6Or6Plus ? 18.0 : 16.0
label.font = UIFont(name: "Montserrat", size: fontSize)
label.textColor = UIColor.HopperBusBrandColor()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var dismissButton: UIButton = {
let button = UIButton()
button.setTitle("\u{274C}", forState: .Normal)
button.setTitleColor(UIColor.HopperBusBrandColor(), forState: .Normal)
button.titleLabel?.font = UIFont(name: "Entypo", size: 50.0)
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: "onDismissButtonTap", forControlEvents: .TouchUpInside)
return button
}()
lazy var pageViewController: UIPageViewController = {
let pageViewController = UIPageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil)
pageViewController.delegate = self
pageViewController.dataSource = self
pageViewController.view.backgroundColor = UIColor.whiteColor()
let vc: UIViewController = AboutTeamViewController()
pageViewController.setViewControllers([vc], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
return pageViewController
}()
lazy var pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.numberOfPages = AboutSection.count
pageControl.pageIndicatorTintColor = UIColor(red:0.157, green:0.392, blue:0.494, alpha: 1)
pageControl.currentPageIndicatorTintColor = UIColor(red:0.392, green:0.871, blue:0.733, alpha: 1)
pageControl.translatesAutoresizingMaskIntoConstraints = false
return pageControl
}()
override func viewDidLoad() {
super.viewDidLoad()
screenName = "About"
view.backgroundColor = UIColor.whiteColor()
view.addSubview(titleLabel)
view.addSubview(dismissButton)
view.addSubview(pageControl)
pageViewController.didMoveToParentViewController(self)
addChildViewController(pageViewController)
pageViewController.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pageViewController.view)
layoutViews()
}
func layoutViews() {
let views = [
"titleLabel": titleLabel,
"dismissButton": dismissButton,
"pageControl": pageControl,
"containerView": pageViewController.view
]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-15-[titleLabel]-20-[dismissButton(30)]-10-|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-16-[pageControl]", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-15-[dismissButton(30)]", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[titleLabel][pageControl]-10-[containerView]-20-|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[containerView]|", options: [], metrics: nil, views: views))
}
// MARK: - Actions
func onDismissButtonTap() {
dismissViewControllerAnimated(true, completion: nil);
}
}
// MARK: - UIPageViewController DataSource & Delegate
extension AboutViewController: UIPageViewControllerDelegate, UIPageViewControllerDataSource {
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let vc = viewController as! BaseAboutViewController
switch vc.type {
case .Team:
return nil
case .DISE:
return AboutTeamViewController()
case .Apps:
return AboutDiseViewController()
}
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
let vc = viewController as! BaseAboutViewController
switch vc.type {
case .Team:
return AboutDiseViewController()
case .DISE:
return AboutAppsViewController()
case .Apps:
return nil
}
}
func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [UIViewController]) {
let previousVC = pendingViewControllers.first as! BaseAboutViewController
currentIndex = previousVC.type.rawValue
switch previousVC.type {
case .Team:
currentTitle = "About The Developers - Team"
case .DISE:
currentTitle = "About The Developers - DISE"
case .Apps:
currentTitle = "About The Developers - Apps"
}
}
func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed {
pageControl.currentPage = currentIndex
titleLabel.text = currentTitle
}
}
}
| true
|
6e484feaa65ad793610743b89b7411c036c0290b
|
Swift
|
AnyChart/AnyChart-iOS
|
/AnyChart-iOS/core/anychart_core_Point.swift
|
UTF-8
| 3,456
| 2.640625
| 3
|
[] |
no_license
|
// class
/**
*
*/
extension anychart.core {
public class Point: JsObject {
//override init() {
// super.init()
//}
public override init() {
super.init()
//return Point(jsBase: "new anychart.core.Point()")
//super.init(jsBase: "new anychart.core.Point()")
}
public override init(jsBase: String) {
super.init()
JsObject.variableIndex += 1
self.jsBase = "point\(JsObject.variableIndex)"
APIlib.sharedInstance.jsDelegate?.jsAddLine(jsLine: self.jsBase + " = " + jsBase + ";")
}
public func instantiate() -> anychart.core.Point {
return anychart.core.Point(jsBase: "new anychart.core.point()")
}
override public func getJsBase() -> String {
return jsBase;
}
/**
* Checks the existence of the current point (by index) in dataset.
*/
public func exists() {
APIlib.sharedInstance.jsDelegate?.jsAddLine(jsLine: self.jsBase + ".exists();")
}
/**
* Fetches a field value from point data row by its name.
*/
public func get(field: String) {
APIlib.sharedInstance.jsDelegate?.jsAddLine(jsLine: "\(self.jsBase).get(\(JsObject.wrapQuotes(value: field)));")
}
/**
* Getter for the chart which current point belongs to.
*/
public func getChart() -> anychart.core.SeparateChart {
return anychart.core.SeparateChart(jsBase: self.jsBase + ".getChart()")
}
/**
* Getter for the point index in chart or series.
*/
public func getIndex() {
APIlib.sharedInstance.jsDelegate?.jsAddLine(jsLine: self.jsBase + ".getIndex();")
}
/**
* Getter for the statistics value by key.
*/
public func getStat(key: anychart.enums.Statistics) {
APIlib.sharedInstance.jsDelegate?.jsAddLine(jsLine: "\(self.jsBase).getStat(\((key != nil) ? key.getJsBase() : "null"));")
}
/**
* Getter for the statistics value by key.
*/
public func getStat(key: String) {
APIlib.sharedInstance.jsDelegate?.jsAddLine(jsLine: "\(self.jsBase).getStat(\(JsObject.wrapQuotes(value: key)));")
}
/**
* Getter for the hover point state.
*/
public func hovered() {
APIlib.sharedInstance.jsDelegate?.jsAddLine(jsLine: self.jsBase + ".hovered();")
}
/**
* Setter for hover point state.
*/
public func hovered(enabled: Bool) -> anychart.core.Point {
APIlib.sharedInstance.jsDelegate?.jsAddLine(jsLine: "\(self.jsBase).hovered(\(enabled));")
return self
}
/**
* Getter for the select point state.
*/
public func selected() {
APIlib.sharedInstance.jsDelegate?.jsAddLine(jsLine: self.jsBase + ".selected();")
}
/**
* Setter for select point state.
*/
public func selected(enabled: Bool) -> anychart.core.Point {
APIlib.sharedInstance.jsDelegate?.jsAddLine(jsLine: "\(self.jsBase).selected(\(enabled));")
return self
}
/**
* Sets the field of the point data row to the specified value.
*/
public func set(field: String, value: String) -> anychart.core.Point {
APIlib.sharedInstance.jsDelegate?.jsAddLine(jsLine: "\(self.jsBase).set(\(JsObject.wrapQuotes(value: field)), \(JsObject.wrapQuotes(value: value)));")
return self
}
}
}
| true
|
13bd8cc52b2741c589c7cb0e7c412bce44258e66
|
Swift
|
YakinikuOishii/note
|
/note/DrawView.swift
|
UTF-8
| 2,423
| 2.734375
| 3
|
[] |
no_license
|
//
// DrawView.swift
// note
//
// Created by 笠原未来 on 2018/05/21.
// Copyright © 2018年 笠原未来. All rights reserved.
//
import UIKit
class DrawView: UIView {
var penColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0)
var penSize: CGFloat = 3.0
var path: UIBezierPath!
var lastDrawImage: UIImage?
var editMode: Bool = true
var canvas = UIImageView()
override func awakeFromNib() {
super.awakeFromNib()
canvas.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height)
canvas.backgroundColor = .clear
self.addSubview(canvas)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if editMode == true {
let currentPoint = touches.first!.location(in: self)
path = UIBezierPath()
path?.lineWidth = penSize
path?.lineCapStyle = CGLineCap.round
path?.lineJoinStyle = CGLineJoin.round
path?.move(to: currentPoint)
}else{
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if editMode == true {
let currentPoint = touches.first!.location(in: self)
path?.addLine(to: currentPoint)
drawLine(path: path)
}else{
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if editMode == true {
let currentPoint = touches.first!.location(in: self)
path.addLine(to: currentPoint)
drawLine(path: path)
lastDrawImage = canvas.image
}else{
}
}
func drawLine(path: UIBezierPath) {
UIGraphicsBeginImageContext(canvas.frame.size)
if lastDrawImage != nil {
lastDrawImage?.draw(at: CGPoint.zero)
}
penColor.setStroke()
path.stroke()
canvas.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
func snapShot() -> UIImage {
// スクリーンショットを取得
UIGraphicsBeginImageContext(bounds.size)
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
| true
|
34b16916456edc87b027c0289aa2cd9670fa944b
|
Swift
|
music4play/autumn
|
/AutumnFramework/AutumnFramework/source/lib/extensions/UIView.swift
|
UTF-8
| 527
| 2.703125
| 3
|
[] |
no_license
|
/*
* __ ____ _ __
* / / / / /_(_) /__
* / /_/ / __/ / (_-<
* \____/\__/_/_/___/
*
* Utils & Extensions for Swiift Projects..
* Written by Ciathyza
*/
import UIKit
extension UIView
{
/**
* Captures an image of the current screen.
*/
public func captureScreen() -> UIImage
{
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
drawHierarchy(in: bounds, afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
| true
|
522094cf6ef6849d522c59b0055dbdfdcead3a33
|
Swift
|
bsh0137/TIL
|
/doit_swift_practice/HelloWorld/HelloWorld/ViewController.swift
|
UTF-8
| 631
| 2.640625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// HelloWorld
//
// Created by 백성현 on 2021/07/24.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate{
@IBOutlet var textField: UITextField!
@IBOutlet var text: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// textField.delegate = self
}
@IBAction func btnSend(_ sender: Any) {
text.text = "\(textField.text!) 씨 반갑습니다."
}ㅂ
// func textFieldShouldClear(_ textField: UITextField) -> Bool {
// return true
// }
}
| true
|
a90e4b84eb8c4074c58e27721a93252aff5f535e
|
Swift
|
objecthub/swift-lispkit
|
/Sources/LispKit/Runtime/ImportSet.swift
|
UTF-8
| 7,302
| 2.703125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// ImportSet.swift
// LispKit
//
// Created by Matthias Zenger on 26/09/2016.
// Copyright © 2016 ObjectHub. All rights reserved.
//
// 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.
//
///
/// An import set specifies what bindings are being imported into an environment and whether
/// they need to be renamed. An import set specifies the imports implicitly. It can be expanded
/// in a context into an explicit list of potentially renamed symbol references for a library.
///
public indirect enum ImportSet: Equatable, CustomStringConvertible {
case library(Expr)
case only([Symbol], ImportSet)
case except(Set<Symbol>, ImportSet)
case prefix(Symbol, ImportSet)
case rename([Symbol : Symbol], ImportSet)
/// Constructs an import set from an expression for a given context.
public init?(_ importSet: Expr, in context: Context) {
switch importSet {
case .pair(.symbol(context.symbols.only), .pair(let baseSet, let idents)):
var identList = idents
var inclSym = [Symbol]()
while case .pair(.symbol(let sym), let next) = identList {
inclSym.append(sym)
identList = next
}
guard identList.isNull else {
return nil
}
if let importSet = ImportSet(baseSet, in: context) {
self = .only(inclSym, importSet)
return
}
case .pair(.symbol(context.symbols.except), .pair(let baseSet, let idents)):
var identList = idents
var exclSym = Set<Symbol>()
while case .pair(.symbol(let sym), let next) = identList {
exclSym.insert(sym)
identList = next
}
guard identList.isNull else {
return nil
}
if let root = ImportSet(baseSet, in: context) {
self = .except(exclSym, root)
return
}
case .pair(.symbol(context.symbols.prefix),
.pair(let baseSet, .pair(.symbol(let ident), .null))):
if let root = ImportSet(baseSet, in: context) {
self = .prefix(ident, root)
return
}
case .pair(.symbol(context.symbols.rename), .pair(let baseSet, let idents)):
var renameList = idents
var renamings = [Symbol : Symbol]()
while case .pair(let renaming, let next) = renameList {
switch renaming {
case .symbol(let sym):
renamings[sym] = sym
case .pair(.symbol(let from), .pair(.symbol(let to), .null)):
renamings[from] = to
default:
return nil
}
renameList = next
}
guard renameList.isNull else {
return nil
}
if let root = ImportSet(baseSet, in: context) {
self = .rename(renamings, root)
return
}
case .pair(_, _):
var libraryName = importSet
while case .pair(let component, let next) = libraryName {
switch component {
case .symbol(_), .fixnum(_), .flonum(_):
break
default:
return nil
}
libraryName = next
}
guard libraryName.isNull else {
return nil
}
self = .library(importSet)
return
default:
break
}
return nil
}
/// `expand` returns, for this import set, a reference to the library from which definitions
/// are imported. In addition, a mapping is returned that maps renamed definitions to the
/// definitions as exported by the library.
public func expand(in context: Context) throws -> (Library, [Symbol : Symbol])? {
switch self {
case .library(let name):
guard let library = try context.libraries.lookup(name) else {
return nil
}
_ = try library.allocate()
var imports = [Symbol : Symbol]()
for export in library.exported {
imports[export] = export
}
return (library, imports)
case .only(let restricted, let importSet):
guard let (library, currentImports) = try importSet.expand(in: context) else {
return nil
}
var imports = [Symbol : Symbol]()
for restrict in restricted {
guard let export = currentImports[restrict] else {
return nil
}
imports[restrict] = export
}
return (library, imports)
case .except(let excluded, let importSet):
guard let (library, currentImports) = try importSet.expand(in: context) else {
return nil
}
var imports = [Symbol : Symbol]()
for currentImport in currentImports.keys {
if !excluded.contains(currentImport) {
imports[currentImport] = currentImports[currentImport]
}
}
return (library, imports)
case .prefix(let prefix, let importSet):
guard let (library, currentImports) = try importSet.expand(in: context) else {
return nil
}
var imports = [Symbol : Symbol]()
for currentImport in currentImports.keys {
imports[context.symbols.prefix(currentImport, with: prefix)] =
currentImports[currentImport]
}
return (library, imports)
case .rename(let renamings, let importSet):
guard let (library, currentImports) = try importSet.expand(in: context) else {
return nil
}
var imports = [Symbol : Symbol]()
for currentImport in currentImports.keys {
imports[renamings[currentImport] ?? currentImport] = currentImports[currentImport]
}
return (library, imports)
}
}
public var description: String {
switch self {
case .library(let expr):
return expr.description
case .only(let symbols, let importSet):
return "(only \(symbols) from \(importSet))"
case .except(let symbols, let importSet):
return "(except \(symbols) from \(importSet))"
case .prefix(let sym, let importSet):
return "(prefix \(sym) for \(importSet))"
case .rename(let map, let importSet):
return "(rename \(map) from \(importSet))"
}
}
public static func ==(_ left: ImportSet, _ right: ImportSet) -> Bool {
switch (left, right) {
case (.library(let e1), .library(let e2)):
return e1 == e2
case (.only(let s1, let is1), .only(let s2, let is2)):
return s1 == s2 && is1 == is2
case (.except(let s1, let is1), .except(let s2, let is2)):
return s1 == s2 && is1 == is2
case (.prefix(let s1, let is1), .prefix(let s2, let is2)):
return s1 == s2 && is1 == is2
case (.rename(let m1, let is1), .rename(let m2, let is2)):
return m1 == m2 && is1 == is2
default:
return false
}
}
}
| true
|
57f541aea2fb85f0adaae59624d6fb2158dd108f
|
Swift
|
zoharIOS/Swift-IOS-Projects
|
/Tbl_Pick1/MyPicker/MyPicker/SecondViewController.swift
|
UTF-8
| 842
| 2.984375
| 3
|
[] |
no_license
|
import UIKit
class SecondViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
let stuff = [
"Apple",
"Seven",
"Heart",
"Cherry",
"Diamond",
"Clubs",
"Spades",
"Jackpot"
]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return stuff.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return stuff[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print("\(component), \(row): \(stuff[row])")
}
}
| true
|
b02a10ba0a5a9b9eb330284ee2aba5462785b0dc
|
Swift
|
konradcr/100-Days-of-SwiftUI
|
/Challenge06-PeopleMet/PeopleMet/AddContactView.swift
|
UTF-8
| 3,769
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
//
// AddContactView.swift
// PeopleMet
//
// Created by Konrad Cureau on 06/07/2021.
//
import SwiftUI
enum ActiveSheet: Identifiable {
case camera, library
var id: Int {
hashValue
}
}
struct AddContactView: View {
@Environment(\.presentationMode) var presentationMode
@State var activeSheet: ActiveSheet?
@State private var name = ""
@State private var image: Image?
@State private var inputImage: UIImage?
var iconImage: Image {
guard let image = image else { return Image(systemName: "person.crop.circle")}
return image
}
var body: some View {
VStack {
HStack(alignment: .top) {
Button(action: { self.presentationMode.wrappedValue.dismiss() }) {
Text("Cancel")
}
Spacer()
Text("Add a person")
.font(.headline)
Spacer()
Button(action: { saveData() }) {
Text("Done")
.bold()
}
}
.padding()
iconImage
.resizable()
.scaledToFit()
.frame(width: 200, height: 200, alignment: .center)
.foregroundColor(.gray)
HStack {
Button(action: { activeSheet = .camera }) {
VStack {
Image(systemName: "camera")
.padding()
.background(Color.blue.opacity(0.3))
.foregroundColor(.blue)
.font(.title)
.clipShape(Circle())
}
}
Button(action: { activeSheet = .library }) {
VStack {
Image(systemName: "photo.on.rectangle")
.padding()
.background(Color.blue.opacity(0.3))
.foregroundColor(.blue)
.font(.title)
.clipShape(Circle())
}
}
}
TextField("Name", text: $name)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
.disableAutocorrection(true)
Spacer()
}
.sheet(item: $activeSheet, onDismiss: loadImage) { item in
switch item {
case .camera:
ImagePicker(image: self.$inputImage, sourceType: .camera)
case .library:
ImagePicker(image: self.$inputImage, sourceType: .photoLibrary)
}
}
}
func loadImage() {
guard let inputImage = inputImage else { return }
image = Image(uiImage: inputImage)
}
func saveData() {
// Save contact in json file
let path = getDocumentsDirectory().appendingPathComponent("contacts.json")
let imageUnwrapp = inputImage ?? UIImage(systemName: "person.crop.circle")!
if let jpegPhoto = imageUnwrapp.jpegData(compressionQuality: 0.8) {
let newContact = Contact(photo: jpegPhoto, name: self.name)
appendContactToFile(newContact: newContact, filePath: path)
} else {
print("Failed to compress image")
}
// dismiss view
presentationMode.wrappedValue.dismiss()
}
func getDocumentsDirectory() -> URL {
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return path[0]
}
}
struct AddContactView_Previews: PreviewProvider {
static var previews: some View {
AddContactView()
}
}
| true
|
3fc45dbacb1cca8bfa778afb7fc6da5bf8551db1
|
Swift
|
AlexandreRobaert/Mensagens
|
/Mensagens/CorBackgroundViewController.swift
|
UTF-8
| 1,000
| 2.59375
| 3
|
[] |
no_license
|
//
// CorDaBordaViewController.swift
// Mensagens
//
// Created by Alexandre Robaert on 01/04/21.
//
import UIKit
class CorBackgroundViewController: BaseViewController {
private var isHiddenBorder = false
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadViews()
}
@IBAction func ocultarBorda(_ sender: UISwitch) {
viewBorder.backgroundColor = sender.isOn ? .white : .clear
isHiddenBorder = !sender.isOn
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
let vc = segue.destination as! ResultViewController
vc.isHiddenBorder = isHiddenBorder
}
}
extension CorBackgroundViewController: ColorPickerDelegate {
func applyColor(_ color: UIColor) {
view.backgroundColor = color
mensagem.viewColorBackground = color
}
}
| true
|
b294ee6fdcd984c354ccf1fabf74b0cf9ced1429
|
Swift
|
marcos1262/ios-recruiting-brazil
|
/ConcreteChallenge/ConcreteChallenge/Scene/Favorites/FavoritesView.swift
|
UTF-8
| 1,398
| 2.84375
| 3
|
[] |
no_license
|
//
// FavoritesView.swift
// ConcreteChallenge
//
// Created by Marcos Santos on 12/01/20.
// Copyright © 2020 Marcos Santos. All rights reserved.
//
import UIKit
class FavoritesView: UIView, ViewCode {
lazy var loadingView = LoadingView()
lazy var emptyView = EmptyView()
lazy var tableView = UITableView()
.set(\.backgroundColor, to: .clear)
.set(\.separatorStyle, to: .none)
required override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
func setupSubviews() {
addSubview(tableView)
addSubview(loadingView)
addSubview(emptyView)
}
func setupLayout() {
tableView.fillToSuperview()
loadingView.fillToSuperview()
emptyView.fillToSuperview()
}
// MARK: View updates
func setLoadingLayout() {
loadingView.isHidden = false
loadingView.start()
emptyView.isHidden = true
tableView.isHidden = true
}
func setEmptyLayout() {
loadingView.isHidden = true
loadingView.stop()
emptyView.isHidden = false
tableView.isHidden = true
}
func setShowLayout() {
loadingView.isHidden = true
loadingView.stop()
emptyView.isHidden = true
tableView.isHidden = false
}
}
| true
|
c1f3f7a5a370639ba175d42fbd23f2fc9beb3499
|
Swift
|
vidsgithub/Chase
|
/Chase/SchoolActivities.swift
|
UTF-8
| 1,314
| 2.625
| 3
|
[] |
no_license
|
//
// SchoolActivities.swift
// Chase
//
// Created by Shingade on 4/20/18.
// Copyright © 2018 com.abc. All rights reserved.
//
import UIKit
import Unbox
class SchoolActivities: NSObject, Unboxable {
var ExtraCurricularActivites:[String] = [String]()
var schoolSports:[String] = [String]()
var boysSports:[String] = [String]()
var girlsSports:[String] = [String]()
var coedSports:[String] = [String]()
// unboxing for json
required init(unboxer: Unboxer) {
if let extraAct:String = unboxer.unbox(key: "extracurricular_activities") {
self.ExtraCurricularActivites = extraAct.components(separatedBy: ",")
}
if let schoolSports:String = unboxer.unbox(key: "school_sports") {
self.schoolSports = schoolSports.components(separatedBy: ",")
}
if let boysSports:String = unboxer.unbox(key: "psal_sports_boys") {
self.boysSports = boysSports.components(separatedBy: ",")
}
if let girlsSports:String = unboxer.unbox(key: "psal_sports_girls") {
self.girlsSports = girlsSports.components(separatedBy: ",")
}
if let coedSports:String = unboxer.unbox(key: "psal_sports_coed") {
self.coedSports = coedSports.components(separatedBy: ",")
}
}
}
| true
|
8f7cfefc4772cd39c852957e5715a9bf449a1981
|
Swift
|
NIKMC/GuessTheSong
|
/GuessTheSong/Model/Level.swift
|
UTF-8
| 396
| 2.890625
| 3
|
[] |
no_license
|
//
// Level.swift
// GuessTheSong
//
// Created by Ivan Nikitin on 28/04/2018.
// Copyright © 2018 Иван Никитин. All rights reserved.
//
import Foundation
class Level {
var id: Int
var status: StatusLevel
init(_ idLevel: Int,_ statusLevel: StatusLevel) {
self.id = idLevel
self.status = statusLevel
}
}
enum StatusLevel: String {
case running, closed, done
}
| true
|
440d6c38ee8d7689b6fc77886acceda279f6c24b
|
Swift
|
waqassultancheema/AlgoGithub
|
/Algo/Algo/SecondApproach.swift
|
UTF-8
| 8,178
| 3.796875
| 4
|
[] |
no_license
|
//
// SecondApproach.swift
// Algo
//
// Created by Waqas Sultan on 2/12/19.
// Copyright © 2019 Waqas Sultan. All rights reserved.
//
import UIKit
public final class LinkedList<T> {
/// Linked List's Node Class Declaration
public class LinkedListNode<T> {
var value: T
var next: LinkedListNode?
weak var previous: LinkedListNode?
public init(value: T) {
self.value = value
}
}
/// Typealiasing the node class to increase readability of code
public typealias Node = LinkedListNode<T>
/// The head of the Linked List
private(set) var head: Node?
/// Computed property to iterate through the linked list and return the last node in the list (if any)
public var last: Node? {
guard var node = head else {
return nil
}
while let next = node.next {
node = next
}
return node
}
/// Computed property to check if the linked list is empty
public var isEmpty: Bool {
return head == nil
}
/// Computed property to iterate through the linked list and return the total number of nodes
public var count: Int {
guard var node = head else {
return 0
}
var count = 1
while let next = node.next {
node = next
count += 1
}
return count
}
/// Default initializer
public init() {}
/// Subscript function to return the node at a specific index
///
/// - Parameter index: Integer value of the requested value's index
public subscript(index: Int) -> T {
let node = self.node(at: index)
return node.value
}
/// Function to return the node at a specific index. Crashes if index is out of bounds (0...self.count)
///
/// - Parameter index: Integer value of the node's index to be returned
/// - Returns: LinkedListNode
public func node(at index: Int) -> Node {
assert(head != nil, "List is empty")
assert(index >= 0, "index must be greater than 0")
if index == 0 {
return head!
} else {
var node = head!.next
for _ in 1..<index {
node = node?.next
if node == nil {
break
}
}
assert(node != nil, "index is out of bounds.")
return node!
}
}
/// Append a value to the end of the list
///
/// - Parameter value: The data value to be appended
public func append(_ value: T) {
let newNode = Node(value: value)
append(newNode)
}
/// Append a copy of a LinkedListNode to the end of the list.
///
/// - Parameter node: The node containing the value to be appended
public func append(_ node: Node) {
let newNode = node
if let lastNode = last {
newNode.previous = lastNode
lastNode.next = newNode
} else {
head = newNode
}
}
/// Append a copy of a LinkedList to the end of the list.
///
/// - Parameter list: The list to be copied and appended.
public func append(_ list: LinkedList) {
var nodeToCopy = list.head
while let node = nodeToCopy {
append(node.value)
nodeToCopy = node.next
}
}
/// Insert a value at a specific index. Crashes if index is out of bounds (0...self.count)
///
/// - Parameters:
/// - value: The data value to be inserted
/// - index: Integer value of the index to be insterted at
public func insert(_ value: T, at index: Int) {
let newNode = Node(value: value)
insert(newNode, at: index)
}
/// Insert a copy of a node at a specific index. Crashes if index is out of bounds (0...self.count)
///
/// - Parameters:
/// - node: The node containing the value to be inserted
/// - index: Integer value of the index to be inserted at
public func insert(_ newNode: Node, at index: Int) {
if index == 0 {
newNode.next = head
head?.previous = newNode
head = newNode
} else {
let prev = node(at: index - 1)
let next = prev.next
newNode.previous = prev
newNode.next = next
next?.previous = newNode
prev.next = newNode
}
}
/// Insert a copy of a LinkedList at a specific index. Crashes if index is out of bounds (0...self.count)
///
/// - Parameters:
/// - list: The LinkedList to be copied and inserted
/// - index: Integer value of the index to be inserted at
public func insert(_ list: LinkedList, at index: Int) {
if list.isEmpty { return }
if index == 0 {
list.last?.next = head
head = list.head
} else {
let prev = node(at: index - 1)
let next = prev.next
prev.next = list.head
list.head?.previous = prev
list.last?.next = next
next?.previous = list.last
}
}
/// Function to remove all nodes/value from the list
public func removeAll() {
head = nil
}
/// Function to remove a specific node.
///
/// - Parameter node: The node to be deleted
/// - Returns: The data value contained in the deleted node.
@discardableResult public func remove(node: Node) -> T {
let prev = node.previous
let next = node.next
if let prev = prev {
prev.next = next
} else {
head = next
}
next?.previous = prev
node.previous = nil
node.next = nil
return node.value
}
/// Function to remove the last node/value in the list. Crashes if the list is empty
///
/// - Returns: The data value contained in the deleted node.
@discardableResult public func removeLast() -> T {
assert(!isEmpty)
return remove(node: last!)
}
/// Function to remove a node/value at a specific index. Crashes if index is out of bounds (0...self.count)
///
/// - Parameter index: Integer value of the index of the node to be removed
/// - Returns: The data value contained in the deleted node
@discardableResult public func remove(at index: Int) -> T {
let node = self.node(at: index)
return remove(node: node)
}
}
class Node {
var data: Int
var leftNode: Node?
var rightNode: Node?
init(data: Int,
leftNode: Node? = nil,
rightNode: Node? = nil) {
self.data = data
self.leftNode = leftNode
self.rightNode = rightNode
}
}
class Answer {
func getAnswer() {
let root:Node = Node(data: 2)
root.leftNode = Node(data: 1)
root.rightNode = Node(data: 3)
root.leftNode?.leftNode = Node(data: 0)
root.leftNode?.rightNode = Node(data: 7)
root.rightNode?.leftNode = Node(data: 9)
root.rightNode?.rightNode = Node(data: 1)
levelOrderQueue(root)
}
func levelOrderQueue(_ root:Node) {
var array = Array<Node>()
var levelNodes = 0
var depth = 0
array.append(root)
while !array.isEmpty {
levelNodes = array.count
print("At depth = \(depth)")
while levelNodes > 0 {
let value:Node = array.remove(at: 0)
print("-> \(value.data) ")
if let node = value.leftNode {
array.append(node)
}
if let node = value.rightNode {
array.append(node)
}
levelNodes = levelNodes - 1
}
depth = depth + 1
}
}
}
| true
|
6e8b1c2eb289bbd5c4cf2fe5652ea3afee676504
|
Swift
|
mmrobert/RobotsPencils
|
/RobotsPencils/MyDesign/ExampleUsage.swift
|
UTF-8
| 653
| 2.921875
| 3
|
[] |
no_license
|
//
// ExampleUsage.swift
// RobotsPencils
//
// Created by boqian cheng on 2020-08-25.
// Copyright © 2020 boqiancheng. All rights reserved.
//
import Foundation
class ExampleUsage {
func saveData() {
// saving 'RPAnnotation' through 'RPComment'
let rPAnnotation = RPAnnotation()
let rPComment = RPComment()
rPComment.save(data: rPAnnotation, to: .restful)
// also saving 'RPComment'
rPComment.save(to: .restful)
}
}
struct RPAnnotation: DataType {
func encode(to encoder: Encoder) throws {
// the custom 'encode' function
// to match data format on server
}
}
| true
|
1b7933c802adb139a976d57e30d34812e8faac0d
|
Swift
|
RobbeRamon/park-valley
|
/ParkValley/View controllers/PrototypeSettingsViewController.swift
|
UTF-8
| 2,254
| 2.6875
| 3
|
[] |
no_license
|
//
// PrototypeSettingsViewController.swift
// ParkValley
//
// Created by Robbe on 01/01/2021.
//
import UIKit
class PrototypeSettingsViewController: UIViewController {
let garageModelController = GarageModelController()
let userModelController = UserModelController()
var status: StatusDTO? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func resetBackendClicked(_ sender: Any) {
let group = DispatchGroup()
group.enter()
userModelController.resetBackend(completion: {(status) in
if let status = status {
self.status = status
}
group.leave()
})
group.notify(queue: .main) {
if let status = self.status {
if status.success {
self.showPopup(
title: "Backend cleared",
message: "The backend is now cleared, the state has returned to the initial state with inital data.")
} else {
self.showPopup(
title: "Backend not cleared",
message: "Something went wrong.")
}
} else {
self.showPopup(
title: "Backend not cleared",
message: "Something went wrong.")
}
}
}
@IBAction func clearCacheClicked(_ sender: Any) {
garageModelController.removeHistoryFromFile()
showPopup(
title: "Cache cleared",
message: "Your cache is now cleared, the recently visited section should be empty now.")
}
// MARK: - Helper methods
/// Show a popup with a message and a title
private func showPopup(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default, handler: { _ in
// do nothing
}))
self.present(alert, animated: true, completion: nil)
}
}
| true
|
f3de4100d70a48a99a16e4153c8cb96cf1aa6ffe
|
Swift
|
thomas-e-cowern/DevMountain
|
/Week 3/Thursday/PokeCardsiOS23/PokeCardsiOS23/Controllers/ViewControllers/PokemonCardTableViewCell.swift
|
UTF-8
| 775
| 2.671875
| 3
|
[] |
no_license
|
//
// PokemonCardTableViewCell.swift
// PPokeCardsiOS23keCardsiOS23
//
// Created by Thomas Cowern New on 12/13/18.
// Copyright © 2018 Thomas Cowern New. All rights reserved.
//
import UIKit
class PokemonCardTableViewCell: UITableViewCell {
// MARK: - Properties
@IBOutlet weak var pokemonCardImageView: UIImageView!
var pokemonCard: PokemonCard? {
didSet {
updateViews()
}
}
// MARK: - Set up views
func updateViews() {
// make image appear
guard let pokemonCard = pokemonCard else { return }
PokemonCardController.fetchPokemonImage(with: pokemonCard) { (image) in
DispatchQueue.main.async {
self.pokemonCardImageView.image = image
}
}
}
}
| true
|
49114bd4ae6a0958f594d3a119e0cdda54e7834d
|
Swift
|
noahbass/learning-swift
|
/Calculator/Calculator/CalculatorOperation.swift
|
UTF-8
| 178
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// CalculatorOperation.swift
// Calculator
//
enum CalculatorOperation: String {
case add = "+"
case subtract = "-"
case multiply = "*"
case divide = "/"
}
| true
|
62e847fb6c85d0945f5fbf7c53786d20911be42e
|
Swift
|
KonstantinSmirnov/ios_calculator
|
/ios_calculator/ViewController.swift
|
UTF-8
| 4,715
| 2.8125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ios_calculator
//
// Created by Konstantin Smirnov on 07.01.2021.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var displayScreen: UILabel!
@IBOutlet var buttonsGray: [UIButton]!
@IBOutlet var buttonsOrange: [UIButton]!
@IBAction func pressedButton(sender: UIButton) {
calculate(input: sender.currentTitle!)
// Change button opacity and return it back in a while
sender.alpha = 0.9
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
sender.alpha = 1.0
}
// Play click sound
audioPlayer = try! AVAudioPlayer(contentsOf: clickSound)
audioPlayer.play()
}
var currentNumber: Float = 0.0
var storedNumber: Float = 0.0
var lastResult: Float = 0.0
var memorizedAction: String = ""
var decimalBase: Float = 0
let digitsArray: [String] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ]
let mathActionsArray: [String] = ["+", "-", "×", "÷"]
// Load click sound and prepare to use it
let clickSound = URL(fileURLWithPath: Bundle.main.path(forResource: "keyboard-click", ofType: "wav")!)
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Establish visual appearance
for button in buttonsGray {
button.layer.borderWidth = 0.5
button.layer.borderColor = #colorLiteral(red: 0.585175693, green: 0.5851898789, blue: 0.5851822495, alpha: 1)
}
for button in buttonsOrange {
button.layer.borderWidth = 0.5
button.layer.borderColor = #colorLiteral(red: 0.585175693, green: 0.5851898789, blue: 0.5851822495, alpha: 1)
}
refreshDisplay(number: currentNumber)
}
func calculate(input: String) {
if input == "AC" {
resetValues()
lastResult = 0
refreshDisplay(number: currentNumber)
} else if input == "," {
decimalBase = 0.1
refreshDisplay(number: currentNumber)
} else if input == "±" {
currentNumber = currentNumber * (-1)
refreshDisplay(number: currentNumber)
} else if input == "%" {
currentNumber = currentNumber / 100
decimalBase = 0.001
refreshDisplay(number: currentNumber)
} else if digitsArray.contains(input) {
if displayScreen.text!.count < 10 || currentNumber == 0 {
if decimalBase != 0 {
currentNumber = currentNumber + Float(input)! * decimalBase
decimalBase /= 10
} else {
currentNumber = currentNumber * 10 + Float(input)!
}
refreshDisplay(number: currentNumber)
}
} else if mathActionsArray.contains(input) {
if currentNumber == 0 {
currentNumber = lastResult
}
math(action: memorizedAction)
memorizedAction = input
currentNumber = 0
} else if input == "=" {
math(action: memorizedAction)
resetValues()
}
debug()
}
func math(action: String) {
switch action {
case "+":
storedNumber += currentNumber
case "-":
storedNumber -= currentNumber
case "×":
storedNumber *= currentNumber
case "÷":
storedNumber /= currentNumber
default:
storedNumber = currentNumber
}
lastResult = storedNumber
decimalBase = 0
refreshDisplay(number: storedNumber)
}
func resetValues() {
storedNumber = 0
currentNumber = 0
decimalBase = 0
memorizedAction = ""
}
func refreshDisplay(number: Float) {
//displayScreen.text = String(number)
if decimalBase == 0.1 {
displayScreen.text = String(format: "%.0f", number) + "."
} else if decimalBase < 0.1 {
displayScreen.text = String(format: "%g", number)
} else {
displayScreen.text = String(format: "%.0f", number)
}
}
func debug() {
// print("Display content: \(displayContent)")
print("Current number: \(currentNumber)")
print("Stored number: \(storedNumber)")
print("Memorized action: \(memorizedAction)")
print("Decimal base: \(decimalBase)")
}
}
| true
|
4b13aaac8feb2a4290128e9adfcfaae4d005f890
|
Swift
|
emannuelOC/breathe-app
|
/HeartRate/FrameExtractor.swift
|
UTF-8
| 4,238
| 2.65625
| 3
|
[] |
no_license
|
//
// FrameExtractor.swift
// HeartRate
//
// Created by emannuel.carvalho on 21/11/18.
// Copyright © 2018 emannuel.carvalho. All rights reserved.
//
import UIKit
import AVFoundation
public protocol FrameExtractorDelegate: class {
func captured(image: CIImage)
}
public class FrameExtractor: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
private var permissionGranted = false
private let sessionQueue = DispatchQueue(label: "session queue")
private let captureSession = AVCaptureSession()
private let context = CIContext()
public weak var delegate: FrameExtractorDelegate?
override public init() {
super.init()
checkPermission()
sessionQueue.async { [unowned self] in
self.configureSession()
self.captureSession.startRunning()
}
}
// MARK: AVSession configuration
private func checkPermission() {
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized:
permissionGranted = true
case .notDetermined:
requestPermission()
default:
permissionGranted = false
}
}
private func requestPermission() {
sessionQueue.suspend()
AVCaptureDevice.requestAccess(for: .video) { [unowned self] granted in
self.permissionGranted = granted
self.sessionQueue.resume()
}
}
private func configureSession() {
guard permissionGranted else { return }
captureSession.sessionPreset = .medium
guard let captureDevice = selectCaptureDevice() else { return }
turnOnTorch(device: captureDevice)
guard let captureDeviceInput = try? AVCaptureDeviceInput(device: captureDevice) else { return }
guard captureSession.canAddInput(captureDeviceInput) else { return }
captureSession.addInput(captureDeviceInput)
let videoOutput = AVCaptureVideoDataOutput()
videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue.main)
guard captureSession.canAddOutput(videoOutput) else { return }
captureSession.addOutput(videoOutput)
guard let connection = videoOutput.connection(with: .video) else { return }
guard connection.isVideoOrientationSupported else { return }
guard connection.isVideoMirroringSupported else { return }
connection.videoOrientation = .portrait
connection.isVideoMirrored = true
}
private func turnOnTorch(device: AVCaptureDevice) {
if device.hasTorch {
do {
try device.lockForConfiguration()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
do {
try device.setTorchModeOn(level: 0.0)
} catch {
print(error)
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
do {
try device.setTorchModeOn(level: 1.0)
} catch {
print(error)
}
}
device.unlockForConfiguration()
} catch {
print(error)
}
}
}
private func selectCaptureDevice() -> AVCaptureDevice? {
return AVCaptureDevice.devices().filter {
$0.hasMediaType(.video) &&
$0.position == .back
}.first
}
// MARK: Sample buffer to UIImage conversion
private func imageFromSampleBuffer(sampleBuffer: CMSampleBuffer) -> CIImage? {
guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil }
let ciImage = CIImage(cvPixelBuffer: imageBuffer)
return ciImage
}
public func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let ciImage = imageFromSampleBuffer(sampleBuffer: sampleBuffer) else { return }
DispatchQueue.main.async { [unowned self] in
self.delegate?.captured(image: ciImage)
}
}
}
| true
|
cdd3a5ceff297cdf2770e62085b5f03020673aa7
|
Swift
|
jeffkalmanek/iOSUdacityProjects
|
/Optionals.playground/Pages/About Nil Values.xcplaygroundpage/Contents.swift
|
UTF-8
| 1,326
| 4.125
| 4
|
[] |
no_license
|
//: ## Optionals
//: Nil is disallowed in most Swift types
//var x: Int
//x = nil
//
//struct Book {
// let title: String
// let author: String
//}
//
//var c: Book
//c = nil
//
//var a: Any
//a = "hello"
//a = nil
////: Cool! Except, sometimes we need nil values.
////: 1. A function that cannot return a value
var y: Int
var s1: String
var s2: String
s1 = "123"
s2 = "ABC"
//y = Int(s1)
//y = Int(s2)
//: 2. Properties that cannot or should not be initialized when an instance is created
struct Villain {
let name: String
var evilScheme: String?
}
let villain = Villain(name: "Billy", evilScheme: nil)
//: [Next](@next)
var q: Int?
var t1: String
t1 = "ABC"
q = Int(t1)
enum Genre: String {
case country, blues, folk
}
struct Artist {
let name: String
var primaryGenre: Genre?
}
struct Song {
let title: String
let released: Int
var artist: Artist?
}
func getArtistGenre(song: Song) -> String {
init(name: String, species: String, tailLength:Int?) {
self.name = name
self.species = species
if let tailLength = tailLength {
self.tail = Tail(length: tailLength)
} else {
self.tail = nil
}
}
return Song.init(title: <#T##String#>, released: <#T##Int#>, artist: <#T##Artist?#>)
}
| true
|
9ef5fc4eb0cdd02988204b7b760bd768ce400a8c
|
Swift
|
miguelius/practice-swift
|
/Games/CookieCrunch/CookieCrunch/CookieCrunch/Array2D.swift
|
UTF-8
| 683
| 3.578125
| 4
|
[
"MIT"
] |
permissive
|
//
// Array2D.swift
// CookieCrunch
//
// Created by Domenico on 11/8/14
//
// Struct is a generic
struct Array2D<T>{
let columns:Int
let rows:Int
private var array : Array<T?>
init(columns:Int, rows:Int){
self.columns = columns
self.rows = rows
// It creates a regular Swift Array with a count of rows × columns and sets all these elements to nil.
array = Array<T?>(count:rows*columns, repeatedValue:nil)
}
subscript(column: Int, row: Int) -> T? {
get {
return self.array[row*columns + column]
}
set {
self.array[row*columns + column] = newValue
}
}
}
| true
|
cc7cc14125e0f0e19050adb230792fa17911fa76
|
Swift
|
Mohit9322/MVVMArchitecture
|
/MVVMiOSArch/Source/ViewModel/MediaUploadViewModel.swift
|
UTF-8
| 1,874
| 2.578125
| 3
|
[] |
no_license
|
//
// MediaUploadViewModel.swift
// WatchMyBack
//
// Created by Chetu on 8/13/18.
// Copyright © 2018 LocatorTechnologies. All rights reserved.
//
import Foundation
import Alamofire
open class MediaUploadViewModel {
public init(){}
/// - Parameters:
//saveMediaParameter: parameter for webservice call,
//mediaData: data for api call,
//uploadedMediaType: type of media,
//fileName: file name
/// - completion: callback
func callSecureServiceForUploadMedia(saveMediaParameter: SaveMediaParameter, mediaData: Data, uploadedMediaType: SelectedMediaType, fileName: String, completionHandler:@escaping(_ registerationResponse: String?, _ error: NetworkServiceError?)->Void){
ApplicationState.sharedAppState.appDataStore.serviceForUploadMedia(mediaData: mediaData, uploadMediaType: uploadedMediaType, nameOfFile: fileName, saveMediaParameter: saveMediaParameter) { (registerResponse, error) in
completionHandler(registerResponse, error)
}
}
/*
@description : Method is being used for download media for corresponding media ID
Parameters:
id: Which media is being used to download,
completionHandler: completion block is being used for callback,
error: will hold the error if occurs
return : Void
*/
func downloadMedia(id: String, completionHandler:@escaping(_ downloadResponse: Data?, _ error: NetworkServiceError?)->Void) {
ApplicationState.sharedAppState.appDataStore.downloadData(id: id) { (downloadResponse, error) in
completionHandler(downloadResponse, error)
}
}
/*
@description : Method is being used to cancel all the requests
Parameters: N/A
return : N/A
*/
func cancelAllRequest(){
ApplicationState.sharedAppState.appDataStore.cancelAllRequest()
}
}
| true
|
c219887479e274871a27dabaaa3ecaeb9ac44ada
|
Swift
|
OneDuoKeng/swift----
|
/SWIFT-笔记2018:11/swift--UIKit实例/swift--UITableView实例/NestedScrollView-master/NestedSliding/NestedSliding/ViewController.swift
|
UTF-8
| 2,576
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// NestedSliding
//
// Created by wangcong on 2018/9/7.
// Copyright © 2018年 wangcong. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "identifier")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath)
switch indexPath.row {
case 0:
cell.textLabel?.text = "单个tab数据未填充满屏幕"
case 1:
cell.textLabel?.text = "单个tab数据填充满屏幕,未填充满外层ScrollView contentSize"
case 2:
cell.textLabel?.text = "单个tab填充满"
case 3:
cell.textLabel?.text = "多个tab部分数据填充屏幕,部分未填充"
case 4:
cell.textLabel?.text = "上述情况外的其他多个tab情况"
default:
cell.textLabel?.text = "其他包含顶部horizontal滑动情况"
}
cell.textLabel?.font = UIFont.systemFont(ofSize: 18)
cell.textLabel?.textColor = UIColor.darkText
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let vc = NestedSlidingViewController()
switch indexPath.row {
case 0:
vc.type = .singleTabNotFillScreen
case 1:
vc.type = .singleTabFillScreenNotFillContentSize
case 2:
vc.type = .single
case 3:
vc.type = .multiTabPartFill
case 4:
vc.type = .multiTab
default:
vc.type = .multiTabOtherHeaderView
}
self.present(vc, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
}
| true
|
c050d928ae8e05188cd24ce66cbc86122a36b5e5
|
Swift
|
muddybarefeet/life-diary
|
/Moodlet.swift
|
UTF-8
| 1,036
| 3.03125
| 3
|
[] |
no_license
|
//
// Moodlet.swift
// lifeDiary
//
// Created by Anna Rogers on 8/3/16.
// Copyright © 2016 Anna Rogers. All rights reserved.
//
import Foundation
import CoreData
class Moodlet: NSManagedObject {
convenience init(mood: Float, stored_externally: Bool, context : NSManagedObjectContext){
if let ent = NSEntityDescription.entityForName("Moodlet", inManagedObjectContext: context){
self.init(entity: ent, insertIntoManagedObjectContext: context)
self.mood = mood
self.stored_externally = stored_externally
self.created_at = NSDate()
} else {
fatalError("Unable to find Entity name!")
}
}
var humanReadableAge : String{
get {
let fmt = NSDateFormatter()
fmt.timeStyle = .NoStyle
fmt.dateStyle = .ShortStyle
fmt.doesRelativeDateFormatting = true
fmt.locale = NSLocale.currentLocale()
return fmt.stringFromDate(created_at!)
}
}
}
| true
|
9e3bf2dec2b4c0f9f3baa3ea790b62ad53646196
|
Swift
|
jonasbeckers/vapor-example
|
/Sources/Library/Controllers/SpotifyController.swift
|
UTF-8
| 2,899
| 2.78125
| 3
|
[] |
no_license
|
//
// ItunesController.swift
// vapor-example
//
// Created by Jonas Beckers on 25/12/16.
//
//
import Vapor
import HTTP
final class SpotifyController {
let drop: Droplet
init(drop: Droplet) {
self.drop = drop
}
func index(_ request: Request) throws -> ResponseRepresentable {
let user = try? request.user()
return try drop.view.make("spotify", ["authenticated": user != nil])
}
func search(_ request: Request) throws -> ResponseRepresentable {
if let searchTerm = request.query?["searchTerm"]?.string, searchTerm != "" {
let result = try drop.client.get("https://api.spotify.com/v1/search?type=artist&q=\(searchTerm)")
if let items = result.json?["artists", "items"]?.array {
var artists = Array<Artist>()
for item in items {
if let object = item.object, let name = object["name"]?.string, let id = object["id"]?.string {
let artist = Artist(id: id, name: name)
artists.append(artist)
}
}
return artists.makeResponse(for: request)
}
throw SpotifyError.apiError(page: "artists")
}
throw SpotifyError.emptySearchTerm
}
func detail(_ request: Request) throws -> ResponseRepresentable {
if let id = request.parameters["id"]?.string {
let result = try drop.client.get("https://api.spotify.com/v1/artists/\(id)")
if let object = result.json?.node, let name = object["name"]?.string, let id = object["id"]?.string, let popularity = object["popularity"]?.int, let followers = object["followers", "total"]?.int, let genres = object["genres"]?.array {
let artist = Artist(id: id, name: name, popularity: popularity, followers: followers)
artist.imageUrl = object["images"]?.pathIndexableArray?[2].object?["url"]?.string
artist.spotifyLink = object["href"]?.string
artist.genres = genres.flatMap { $0.string }
return artist.makeResponse(for: request)
}
}
throw SpotifyError.artistNotFound
}
}
enum SpotifyError: Error {
case apiError(page: String)
case emptySearchTerm
case artistNotFound
var message: String {
switch self {
case .apiError:
return "unknown error"
case .emptySearchTerm:
return "the searchterm cannot be empty"
case .artistNotFound:
return "the artist does not exist"
}
}
func jsonError() throws -> JSON {
return try JSON(Node(node: ["error": true, "message": message]))
}
}
| true
|
13f6c2ce7eef119861f4dbb72b0b3414867615ef
|
Swift
|
victorGomez88/S.A.M
|
/S.A.M/S.A.M/ServicesManager/StoriesService/StoriesService.swift
|
UTF-8
| 1,594
| 2.765625
| 3
|
[] |
no_license
|
//
// StoriesService.swift
// S.A.M
//
// Created by Victor Gomez on 15/11/2020.
// Copyright © 2020 Victor Gomez. All rights reserved.
//
import Foundation
import RxSwift
class StoriesService {
//MARK: - /stories
/// Obtain stories list
func getStoriesList(inputModel: StoriesInputModel?) -> Observable<StoriesModel> {
Observable.create { observer in
BaseServiceManager.doGetRequest(params: inputModel?.obtainParamsDict(),
url: APIConstants.Endpoints.Stories.storiesList) {
dataResponse in
do {
let decoder = JSONDecoder()
let storyModel = try decoder.decode(StoriesModel.self, from: dataResponse)
observer.onNext(storyModel)
} catch let error {
observer.onError(error)
print("Error message: " + error.localizedDescription)
}
observer.onCompleted()
} failure: { (error) in
print(error)
}
return Disposables.create {}
}
}
//MARK: - /stories/{storyId}
/// Obtain specific story
/// - Parameter storyID: desired story id
func getStory(with storyID: Int) {
BaseServiceManager.doGetRequest(params: nil,
url: String(format:APIConstants.Endpoints.Stories.story, String(storyID)))
{ success in
} failure: { (error) in
print(error)
}
}
}
| true
|
b12462e59aaeaeed53ae62d0130b3bacee634f0e
|
Swift
|
Appsaurus/Swiftest
|
/Sources/Swiftest/SwiftStdlib/Extensions/Collection/RangeReplaceableCollection+Stack.swift
|
UTF-8
| 539
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
//
// RangeReplaceableCollection+Stack.swift
// Pods
//
// Created by Brian Strobach on 4/20/16.
// Copyright © 2018 Appsaurus
//
/// RangeReplaceableCollection based Stack(LIFO) implementation
public typealias Stack = RangeReplaceableCollection
public extension Stack {
mutating func push(_ newElement: Element) {
self.append(newElement)
}
mutating func pop() -> Element? {
return self.remove(at: lastIndex)
}
func peekAtStack() -> Element? {
return self[safe: lastIndex]
}
}
| true
|
70a3147e43ab016dbac9fba3fd9eea7f3fb6aed9
|
Swift
|
stripe/stripe-terminal-ios
|
/Example/Example/Value1MultilineCell.swift
|
UTF-8
| 592
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// Value1MultilineCell.swift
// Example
//
// Created by Brian Cooke on 9/11/20.
// Copyright © 2020 Stripe. All rights reserved.
//
import Static
/**
Same as Static.Value1Cell, but supports wrapping in the text label if needed.
*/
class Value1MultilineCell: UITableViewCell, Cell {
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
self.textLabel?.numberOfLines = 0
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| true
|
239f316779c8c85ffbea36f42253436dbd9e80dc
|
Swift
|
Radhach9027/MyHotelsDemo
|
/MyHotels/IBDesignables/CustomRatingView.swift
|
UTF-8
| 5,493
| 2.75
| 3
|
[] |
no_license
|
// CustomRatingView.swift
// MyHotels
// Created by radha chilamkurthy on 08/03/21.
import UIKit
@objc public protocol RatingViewDelegate {
func ratingView(_ ratingView: CustomRatingView, didChangeRating newRating: Float)
}
@IBDesignable
open class CustomRatingView: UIView {
@IBInspectable open var starCount: Int = 5
@IBInspectable open var offImage: UIImage?
@IBInspectable open var onImage: UIImage?
@IBInspectable open var halfImage: UIImage?
@IBInspectable open var rating: Float = 0 {
didSet {
rating = min(Float(starCount), rating)
updateRating()
}
}
@IBInspectable open var halfStarsAllowed: Bool = true
@IBInspectable open var editable: Bool = true
@objc open weak var delegate: RatingViewDelegate?
var stars: [UIImageView] = []
override open var semanticContentAttribute: UISemanticContentAttribute {
didSet {
updateTransform()
}
}
private var shouldUseRightToLeft: Bool {
return UIView.userInterfaceLayoutDirection(for: semanticContentAttribute)
== .rightToLeft
}
override init(frame: CGRect) {
super.init(frame: frame)
customInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func awakeFromNib() {
super.awakeFromNib()
customInit()
}
override open func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
customInit()
}
func customInit() {
if offImage == nil {
offImage = UIImage(systemName: "star", compatibleWith: self.traitCollection)
}
if onImage == nil {
onImage = UIImage(systemName: "star.fill", compatibleWith: self.traitCollection)
}
if halfImage == nil {
halfImage = UIImage(systemName: "star.leadinghalf.fill", compatibleWith: self.traitCollection)
}
guard let offImage = offImage else {
assert(false, "offImage is not set")
return
}
var i = 1
while i <= starCount {
let iv = UIImageView(image: offImage)
addSubview(iv)
stars.append(iv)
i += 1
}
layoutStars()
updateRating()
updateTransform()
}
override open func layoutSubviews() {
super.layoutSubviews()
layoutStars()
}
private func updateTransform() {
transform = shouldUseRightToLeft
? CGAffineTransform.init(scaleX: -1, y: 1)
: .identity
}
private func layoutStars() {
guard !stars.isEmpty, let offImage = stars.first?.image else {
return
}
let halfWidth = offImage.size.width/2
let distance = (bounds.size.width - (offImage.size.width * CGFloat(starCount))) / CGFloat(starCount + 1) + halfWidth
for (index, iv) in stars.enumerated() {
iv.frame = CGRect(x: 0, y: 0, width: offImage.size.width, height: offImage.size.height)
iv.center = CGPoint(
x: CGFloat(index + 1) * distance + halfWidth * CGFloat(index),
y: self.frame.size.height/2
)
}
}
func handleTouches(_ touches: Set<UITouch>) {
let touch = touches.first!
let touchLocation = touch.location(in: self)
var i = starCount - 1
while i >= 0 {
let imageView = stars[i]
let x = touchLocation.x;
if x >= imageView.center.x {
rating = Float(i) + 1
return
} else if x >= imageView.frame.minX && halfStarsAllowed {
rating = Float(i) + 0.5
return
}
i -= 1
}
rating = 0
}
func updateRating() {
guard !stars.isEmpty else {
return
}
var i = 1
while i <= Int(rating) {
let star = stars[i-1]
star.image = onImage
i += 1
}
if i > starCount {
return
}
if rating - Float(i) + 1 >= 0.5 {
let star = stars[i-1]
star.image = halfImage
i += 1
}
while i <= starCount {
let star = stars[i-1]
star.image = offImage
i += 1
}
}
}
extension CustomRatingView {
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard editable else { return }
handleTouches(touches)
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard editable else { return }
handleTouches(touches)
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard editable else { return }
handleTouches(touches)
guard let delegate = delegate else { return }
delegate.ratingView(self, didChangeRating: rating)
}
}
@objc extension CustomRatingView {
@objc public enum FillDirection: Int {
case automatic
case leftToRight
case rightToLeft
}
}
| true
|
d37240c8c5a7a8321303f42d457a11c12590c3dd
|
Swift
|
Swift-Aramis/SwiftAlgoTest
|
/SwiftAlgoTest/SwiftAlgoTest/DailyPractice.swift
|
UTF-8
| 7,301
| 4.1875
| 4
|
[] |
no_license
|
//
// DailyPractice.swift
// SwiftAlgoTest
//
// Created by jiajue on 2021/10/20.
//
import Foundation
class DailyPractice {
//MARK: - 40. 最小的k个数
/**
题目:给定一个长度为 n 的可能有重复值的数组,找出其中不去重的最小的 k 个数。例如数组元素是 4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4(任意顺序皆可)。
要求:空间复杂度 O(n),时间复杂度 O(nlogn)
*/
/**
解题思路:
1、对数组排序;(快排)
2、取出前k个元素
核心考察点:快速排序
*/
func GetLeastNumbers_Solution(_ input: [Int], _ k: Int) -> [Int] {
// 0、特殊情况
if input.count <= k {
return input
}
// 1、对数组排序
var sortedArray = input
// quickSort(&sortedArray, k, left: 0, right: sortedArray.count - 1)
quickSort(&sortedArray, left: 0, right: sortedArray.count - 1)
// 2、取出前k个元素
return Array(sortedArray.prefix(k))
}
// a、非完整快排
func quickSort(_ array: inout [Int], _ k: Int, left: Int, right: Int) {
let pivot = array[left]
var l = left, r = right
while l < r {
// 注意:先移动右指针!!!
while l < r, array[r] >= pivot {
r -= 1
}
while l < r, array[l] <= pivot {
l += 1
}
array.swapAt(l, r)
}
array.swapAt(left, l)
// 左侧数据不足,需往后继续扩大排序范围
if l < k {
quickSort(&array, k, left: l + 1, right: right)
}
// 左侧数据超出,需往前缩小排序范围
if l > k {
quickSort(&array, k, left: left, right: l - 1)
}
}
// b、完整快排
func quickSort(_ array: inout [Int], left: Int, right: Int) {
if left >= right {
return
}
let pivot = array[left]
var l = left, r = right
while l < r {
// 注意:先移动右指针!!!
while l < r, array[r] >= pivot {
r -= 1
}
while l < r, array[l] <= pivot {
l += 1
}
array.swapAt(l, r)
}
array.swapAt(left, l)
// 左侧递归
quickSort(&array, left: left, right: l - 1)
// 右侧递归
quickSort(&array, left: l + 1, right: right)
}
}
//MARK: - 146. LRU 缓存机制
/**
题目:运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。
实现 LRUCache 类:
LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。
当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?
*/
/**
分析:
LRU 缓存淘汰算法就是一种常用策略。LRU 的全称是 Least Recently Used。
也就是说我们认为最近使用过的数据应该是是「有用的」,
很久都没用过的数据应该是无用的,内存满了就优先删那些很久没用过的数据。
因为显然 cache 必须有顺序之分,以区分最近使用的和久未使用的数据;
而且我们要在 cache 中查找键是否已存在;
如果容量满了要删除最后一个数据;
每次访问还要把数据插入到队头。
哈希表查找快,但是数据无固定顺序;链表有顺序之分,插入删除快,但是查找慢。
所以结合一下,形成一种新的数据结构:哈希链表。
LRU 缓存算法的核心数据结构就是哈希链表,双向链表和哈希表的结合体。
思想很简单,就是借助哈希表赋予了链表快速查找的特性嘛:
可以快速查找某个 key 是否存在缓存(链表)中,同时可以快速删除、添加节点。
“为什么必须要用双向链表”? 因为我们需要删除操作。
删除一个节点不光要得到该节点本身的指针,也需要操作其前驱节点的指针,而双向链表才能支持直接查找前驱,保证操作的时间复杂度
*/
class DNode {
var key: Int
var value: Int
var prev: DNode?
var next: DNode?
init(key: Int, value: Int) {
self.key = key
self.value = value
}
}
protocol DoubleLinkProtocol {
func addFirst(_ node: DNode)
func remove(_ node: DNode)
func removeLast() -> DNode?
var size: Int { get }
}
class DoubleLinkList: DoubleLinkProtocol {
private var count: Int = 0
private var head: DNode = DNode(key: 0, value: 0)
private var tail: DNode = DNode(key: 0, value: 0)
init() {
head.next = tail
tail.prev = head
}
// 头插
func addFirst(_ node: DNode) {
let headNext = head.next
head.next = node
headNext?.prev = node
node.prev = head
node.next = headNext
count += 1
}
// 删除指定节点
func remove(_ node: DNode) {
node.prev?.next = node.next
node.next?.prev = node.prev
count -= 1
}
// 删除尾结点,并返回该节点
func removeLast() -> DNode? {
guard let last = tail.prev else {
return nil
}
remove(last)
return last
}
var size: Int {
return count
}
}
class LRUCache {
private var capacity: Int = 0
// key -> DNode(key, val)
private var hashMap: [Int: DNode]
// node(k1, v1) <-> Node(k2, v2)...
private var cache: DoubleLinkList
init(_ capacity: Int) {
self.capacity = capacity
self.hashMap = [Int: DNode]()
self.cache = DoubleLinkList()
}
func get(_ key: Int) -> Int {
if !hashMap.keys.contains(key) {
return -1
}
guard let node = hashMap[key] else {
return -1
}
put(key, node.value)
return node.value
}
func put(_ key: Int, _ value: Int) {
let node = DNode(key: key, value: value)
if hashMap.keys.contains(key) {
// 删除旧的节点
if let oldNode = hashMap[key] {
cache.remove(oldNode)
}
} else {
// cache达到最大容量
if cache.size == capacity {
// 删除最后结点
if let last = cache.removeLast() {
// 删除映射
hashMap.removeValue(forKey: last.key)
}
}
}
// 头插
cache.addFirst(node)
// 新建映射
hashMap[key] = node
}
}
| true
|
68e4892ba3cdf93d39cba11b10702e9021591172
|
Swift
|
joel-meng/expensee
|
/Expensee/CoreData/Repository/CategoriesRepository.swift
|
UTF-8
| 5,865
| 2.75
| 3
|
[] |
no_license
|
//
// CategoriesRepository.swift
// Expensee
//
// Created by Jun Meng on 29/4/20.
// Copyright © 2020 Jun Meng. All rights reserved.
//
import Foundation
import CoreData
protocol RepositoryProtocol {
var context: NSManagedObjectContext? { get }
func perform(action: @escaping () -> Void)
var workerContext: NSManagedObjectContext { get }
func save(worker context: NSManagedObjectContext) throws
}
extension RepositoryProtocol {
func perform(action: @escaping () -> Void) {
context?.performChanges(block: action)
}
func save(worker workerContext: NSManagedObjectContext) throws {
try workerContext.save()
try context?.save()
}
var workerContext: NSManagedObjectContext {
let workerContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
workerContext.parent = context
return workerContext
}
}
protocol CategoriesRepositoryProtocol: RepositoryProtocol {
func save(_ category: CategoryDTO) -> Future<CategoryDTO>
func fetchAll() -> Future<[CategoryDTO]>
func fetchAllWithTransactions() -> Future<[CategoryDTO: [TransactionDTO]]>
func fetch(by id: UUID) -> Future<CategoryDTO?>
func update(by categoryDTO: CategoryDTO) -> Future<CategoryDTO>
}
final class CategoriesRepository: CategoriesRepositoryProtocol {
let context: NSManagedObjectContext?
init(context: NSManagedObjectContext?) {
self.context = context
}
func save(_ category: CategoryDTO) -> Future<CategoryDTO> {
let future = Future<CategoryDTO>()
let context = workerContext
let inserted = ExpenseCategory.insert(category: category, into: context)
let categoryDTO = CategoryDTO(name: inserted.name, color: inserted.color, budget: inserted.budget.map {
BudgetDTO(currency: $0.currency, limit: $0.limit)
}, uid: category.uid)
do {
try save(worker: context)
future.resolve(with: categoryDTO)
} catch {
future.reject(with: error)
}
return future
}
func fetchAll() -> Future<[CategoryDTO]> {
let future = Future<[CategoryDTO]>()
let context = workerContext
do {
let fetched = try ExpenseCategory.fetchAll(from: context)
let categoriesDTO = fetched.map {
CategoryDTO(name: $0.name, color: $0.color,
budget: $0.budget.map {
BudgetDTO(currency: $0.currency, limit: $0.limit)
}, uid: $0.uid)
}
future.resolve(with: categoriesDTO)
} catch {
future.reject(with: error)
}
return future
}
func fetchAllWithTransactions() -> Future<[CategoryDTO: [TransactionDTO]]> {
let future = Future<[CategoryDTO: [TransactionDTO]]>()
let context = workerContext
do {
let fetched = try ExpenseCategory.fetchAll(from: context)
let result = fetched.map { category -> (CategoryDTO, [TransactionDTO]) in
let categoryDTO = CategoryDTO(name: category.name,
color: category.color,
budget: category.budget.map { BudgetDTO(currency: $0.currency, limit: $0.limit) },
uid: category.uid)
let transactionsDTO = category.transactions?.map {
TransactionDTO(amount: $0.amount,
date: $0.date,
currency: $0.currency,
uid: $0.uid,
originalAmount: $0.originalAmount,
originalCurrency: $0.originalCurrency)
} ?? []
return (categoryDTO, transactionsDTO)
}
try save(worker: context)
future.resolve(with: Dictionary(uniqueKeysWithValues: result))
} catch {
future.reject(with: error)
}
return future
}
func fetch(by id: UUID) -> Future<CategoryDTO?> {
let future = Future<CategoryDTO?>()
let context = workerContext
let fetched = ExpenseCategory.find(by: id, in: context).map {
CategoryDTO(name: $0.name, color: $0.color, budget: $0.budget.map {
BudgetDTO(currency: $0.currency, limit: $0.limit)
}, uid: $0.uid)
}
do {
try save(worker: context)
future.resolve(with: fetched)
} catch {
future.reject(with: error)
}
return future
}
func update(by categoryDTO: CategoryDTO) -> Future<CategoryDTO> {
let future = Future<CategoryDTO>()
let context = workerContext
let found = ExpenseCategory.find(by: categoryDTO.uid, in: context)
found?.setValue(categoryDTO.color, forKey: "color")
found?.setValue(categoryDTO.name, forKey: "name")
if let currency = categoryDTO.budget?.currency, let limit = categoryDTO.budget?.limit {
if found?.budget == nil {
let newBudget = ExpenseBudget.insert(budget: BudgetDTO(currency: currency, limit: limit), into: context)
found?.setValue(newBudget, forKey: "budget")
}
found?.budget?.setValue(currency, forKey: "currency")
found?.budget?.setValue(limit, forKey: "limit")
}
if categoryDTO.budget == nil && found?.budget != nil {
found?.setValue(nil, forKey: "budget")
}
do {
try save(worker: context)
future.resolve(with: categoryDTO)
} catch {
future.reject(with: error)
}
return future
}
}
| true
|
045c67331a7ae7f13aba2d7ee2e7d02d86e9c299
|
Swift
|
AdrianMinnich/UK_task
|
/Recruitment-iOSTests/NetworkingManagerTests.swift
|
UTF-8
| 4,688
| 2.59375
| 3
|
[] |
no_license
|
//
// NetworkingManagerTests.swift
// Recruitment-iOSTests
//
// Created by Adrian Minnich on 17/08/2021.
// Copyright © 2021 Untitled Kingdom. All rights reserved.
//
import XCTest
@testable import Recruitment_iOS
class NetworkingManagerTests: XCTestCase {
override func setUp() {
}
override func tearDown() {
}
func testShouldDownloadItems() {
var expectedItems: [ItemGeneralModel] = []
expectedItems.append(ItemGeneralModel(id: "2", name: "Item2", color: UIColor.red, preview: "Lorem ipsum dolor sit amet, consectetur adipiscing elit."))
expectedItems.append(ItemGeneralModel(id: "1", name: "Item1", color: UIColor.green, preview: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dictum eu velit vel ultrices. Ut vulputate scelerisque erat, ut mollis nibh convallis feugiat."))
expectedItems.append(ItemGeneralModel(id: "4", name: "Item4", color: UIColor.blue, preview: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dictum eu velit vel ultrices. Ut vulputate scelerisque erat, ut mollis nibh convallis feugiat. Maecenas vulputate tortor in odio egestas bibendum a quis erat."))
expectedItems.append(ItemGeneralModel(id: "3", name: "Item3", color: UIColor.yellow, preview: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dictum eu velit vel ultrices. Ut vulputate scelerisque erat, ut mollis nibh convallis feugiat. Maecenas vulputate tortor in odio egestas bibendum a quis erat. Proin volutpat turpis vestibulum elementum congue. Sed vitae sem purus. Morbi placerat sapien eget leo mattis molestie."))
expectedItems.append(ItemGeneralModel(id: "5", name: "Item5", color: UIColor.purple, preview: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dictum eu velit vel ultrices. Ut vulputate scelerisque erat, ut mollis nibh convallis feugiat. Maecenas vulputate tortor in odio egestas bibendum a quis erat. Proin volutpat turpis vestibulum elementum congue. "))
let expectation = expectation(description: "downloadItems gets items and runs the callback")
NetworkingManager.sharedManager.downloadItems() { result in
switch result {
case .success(let items):
XCTAssertNotNil(items)
XCTAssertEqual(items, expectedItems)
expectation.fulfill()
case .failure(let error):
XCTFail("downloadItems failed: \(error)")
}
}
waitForExpectations(timeout: 2) { error in
if let error = error {
XCTFail("waitForExpectation failed: \(error)")
}
}
}
func testShouldDownloadItemWithID() {
let expectedItem = ItemDetailsModel(id: "1", name: "Item1", color: UIColor.green, desc: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer a lacus felis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nullam dignissim facilisis quam et malesuada. Sed imperdiet ipsum ut elit porttitor gravida. Nulla a lectus lorem. Proin sed volutpat risus. Aenean malesuada, nisl id finibus pellentesque, nunc felis pulvinar tellus, in commodo nisl urna et leo. Donec ac ante tortor. Pellentesque consequat tellus nec pellentesque euismod. Mauris euismod, leo auctor aliquet lacinia, dui est pulvinar nulla, fermentum dapibus felis leo nec est. Fusce ultrices, risus at ullamcorper cursus, leo sapien mattis arcu, vitae facilisis massa lacus et libero. Etiam sollicitudin augue porttitor tristique convallis. Aenean imperdiet, tortor dictum tristique ullamcorper, nulla nulla convallis tellus, sit amet luctus purus augue ac leo.")
let expectation = expectation(description: "downloadItem gets item with given ID and runs the callback")
NetworkingManager.sharedManager.downloadItemWithID("1") { result in
switch result {
case .success(let item):
XCTAssertNotNil(item)
XCTAssertEqual(item.name, expectedItem.name)
XCTAssertEqual(item.color, expectedItem.color)
XCTAssertEqual(item.id, expectedItem.id)
XCTAssertEqual(item.desc, expectedItem.desc)
expectation.fulfill()
case .failure(let error):
XCTFail("downloadItemWithID failed: \(error.localizedDescription)")
}
}
waitForExpectations(timeout: 2) { error in
if let error = error {
XCTFail("waitForExpectation failed: \(error.localizedDescription)")
}
}
}
}
| true
|
bc418ad92d50b02e43a464afddcbdf57e747a1f0
|
Swift
|
ivaanteo/Stock-Portfolio
|
/Stock Portfolio/Controller/StockSearchTableViewController.swift
|
UTF-8
| 3,004
| 2.625
| 3
|
[] |
no_license
|
//
// StockSearchTableViewController.swift
// Stock Portfolio
//
// Created by Ivan Teo on 28/6/20.
// Copyright © 2020 Ivan Teo. All rights reserved.
//
import UIKit
import SwiftUI
import SwipeCellKit
class StockSearchTableViewController: UITableViewController {
@ObservedObject var searchManager = SearchManager()
var name: String?
var symbol: String?
@IBOutlet weak var searchBar: UISearchBar!
@IBAction func doneButtonPressed(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
searchManager.delegate = self
searchBar.delegate = self
tableView.register(UINib(nibName: "StockSearchResultTableViewCell", bundle: nil), forCellReuseIdentifier: "stockSearchResultsCell")
tableView.keyboardDismissMode = .onDrag
searchBar.becomeFirstResponder()
}
// MARK: - Table View Data Source Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchManager.stockDetails.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "stockSearchResultsCell", for: indexPath) as! StockSearchResultTableViewCell
cell.nameLabel.text = searchManager.stockDetails[indexPath.item].name
cell.symbolLabel.text = searchManager.stockDetails[indexPath.item].symbol
return cell
}
//MARK: - Table View Delegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let currentCell = tableView.cellForRow(at: indexPath) as! StockSearchResultTableViewCell
if let safeSymbol = currentCell.symbolLabel.text{
self.symbol = safeSymbol}
if let safeName = currentCell.nameLabel.text{
self.name = safeName}
performSegue(withIdentifier: "goToDetails", sender: self)
tableView.deselectRow(at: indexPath, animated: true)
}
//MARK: - Segue Methods
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToDetails"{
let destinationVC = segue.destination as! DetailsViewController
destinationVC.name = self.name
destinationVC.symbol = self.symbol
}
}
}
//MARK: - Search Bar Delegate Methods
extension StockSearchTableViewController:UISearchBarDelegate{
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if let keyword = searchBar.text{
searchManager.fetchData(keyword: keyword)
}
searchBar.resignFirstResponder()
}
}
//MARK: - Search Manager Delegate Methods
extension StockSearchTableViewController:SearchManagerDelegate{
func updatedSearchResults() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
| true
|
09d3c4ca6290cf7c6e5330a8a5c87914c575d41f
|
Swift
|
khanhpoeta/NewsApi
|
/News/Providers/ServiceApis/News/ResponseModel/RequestResponse.swift
|
UTF-8
| 511
| 2.578125
| 3
|
[] |
no_license
|
//
// RequestResponse.swift
// News
//
// Created by Kent Nguyen on 9/15/20.
// Copyright © 2020 NeAlo. All rights reserved.
//
import UIKit
import ObjectMapper
struct ArticalResponse<T:BaseMappable>: Mappable {
init?(map: Map) {
}
var data: [T]? = []
var totalResults: Int = 0
var code:Int = 0
mutating func mapping(map: Map) {
code <- map["code"]
totalResults <- map["totalResults"]
data <- map["articles"]
}
}
| true
|
a2281ba0ffe68c6d10c7025857dafc5f34620989
|
Swift
|
alviranw15/PokeApp
|
/PokeApp/Classes/Network/Response/PokemonDetail/DAOPokemonDetailGenerationI.swift
|
UTF-8
| 655
| 2.921875
| 3
|
[] |
no_license
|
//
// DAOPokemonDetailGenerationI.swift
//
// Created by Alvira Nurhaliza on 18/08/21
// Copyright (c) . All rights reserved.
//
import Foundation
struct DAOPokemonDetailGenerationI: Codable {
enum CodingKeys: String, CodingKey {
case redBlue = "red-blue"
case yellow
}
var redBlue: DAOPokemonDetailRedBlue?
var yellow: DAOPokemonDetailYellow?
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
redBlue = try container.decodeIfPresent(DAOPokemonDetailRedBlue.self, forKey: .redBlue)
yellow = try container.decodeIfPresent(DAOPokemonDetailYellow.self, forKey: .yellow)
}
}
| true
|
4bf745cb707797e3615215bea8b287110627b479
|
Swift
|
HarshavardhanK/IOU
|
/IOU/View/CustomCellTableViewCell.swift
|
UTF-8
| 1,594
| 2.5625
| 3
|
[] |
no_license
|
//
// CustomCellTableViewCell.swift
// IOU
//
// Created by Harshavardhan K K on 18/08/18.
// Copyright © 2018 Harshavardhan K. All rights reserved.
//
import UIKit
class CustomCellTableViewCell: UITableViewCell {
//@IBOutlet weak var backgroundImageView: UIImageView?
// @IBOutlet weak var netAmount: UILabel?
@IBOutlet weak var name: UILabel!
// @IBOutlet weak var amount: UILabel!
@IBOutlet weak var backgroundCardView: UIView!
private let colors = ["#74b9ff", "#0984e3", "#fab1a0", "#00cec9", "#10ac84", "#2e86de", "#e74c3c"]
func chooseColor() -> UIColor {
let index = Int(arc4random_uniform(10) % UInt32(colors.count))
return UIColor.init(hexString: colors[index], alpha: 0.9)
}
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 createCard() {
contentView.backgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
backgroundCardView.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
backgroundCardView.backgroundColor = .white
backgroundCardView.layer.cornerRadius = 8
backgroundCardView.layer.masksToBounds = false
backgroundCardView.layer.shadowOffset = CGSize(width: 0, height: 0)
backgroundCardView.layer.shadowOpacity = 0.9
}
}
| true
|
a62b129f80d7c82c0075e04509ae3331bb20b468
|
Swift
|
oldltoboss/pinterest_v2
|
/lto_pinterest/ViewController.swift
|
UTF-8
| 5,506
| 2.5625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Piratarest
//
// Created by Alumno on 31/01/19.
// Copyright © 2019 Alumno. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red:61/255, green:91/255, blue:151/255, alpha:1)
view.addSubview(inputContainerView)
inputContainerView.addSubview(nametxtField)
inputContainerView.addSubview(emailtxtField)
inputContainerView.addSubview(passtxtField)
nametxtField.topAnchor.constraint(equalTo: inputContainerView.topAnchor).isActive = true
nametxtField.widthAnchor.constraint(equalTo:inputContainerView.widthAnchor).isActive = true
nametxtField.heightAnchor.constraint(equalTo:inputContainerView.heightAnchor, multiplier:1/3).isActive = true
nametxtField.leftAnchor.constraint(equalTo:inputContainerView.leftAnchor).isActive=true
emailtxtField.topAnchor.constraint(equalTo: nametxtField.bottomAnchor).isActive = true
emailtxtField.widthAnchor.constraint(equalTo:inputContainerView.widthAnchor).isActive = true
emailtxtField.heightAnchor.constraint(equalTo:inputContainerView.heightAnchor, multiplier:1/3).isActive = true
emailtxtField.leftAnchor.constraint(equalTo:inputContainerView.leftAnchor).isActive=true
passtxtField.topAnchor.constraint(equalTo: emailtxtField.bottomAnchor).isActive = true
passtxtField.widthAnchor.constraint(equalTo:inputContainerView.widthAnchor).isActive = true
passtxtField.heightAnchor.constraint(equalTo:inputContainerView.heightAnchor, multiplier:1/3).isActive = true
passtxtField.isSecureTextEntry = true
passtxtField.leftAnchor.constraint(equalTo:inputContainerView.leftAnchor).isActive=true
//contraints for input
inputContainerView.centerXAnchor.constraint(equalTo:view.centerXAnchor).isActive=true
inputContainerView.centerYAnchor.constraint(equalTo:view.centerYAnchor).isActive=true
inputContainerView.heightAnchor.constraint(equalToConstant: 250 ).isActive=true
inputContainerView.widthAnchor.constraint(equalTo: view.widthAnchor,constant:-40).isActive=true
view.addSubview(firstBtn)
//firstBtn.centerXAnchor.constraint(equalTo:view.centerXAnchor).isActive=true
//firstBtn.centerYAnchor.constraint(equalTo:view.centerYAnchor).isActive=true
firstBtn.topAnchor.constraint(equalTo:inputContainerView.bottomAnchor,constant:20).isActive=true
firstBtn.heightAnchor.constraint(equalToConstant: 50 ).isActive=true
//firstBtn.widthAnchor.constraint(equalTo: view.widthAnchor,constant:-40).isActive=true
firstBtn.leftAnchor.constraint(equalTo:inputContainerView.leftAnchor).isActive=true
firstBtn.rightAnchor.constraint(equalTo:inputContainerView.rightAnchor).isActive=true
// Do any additional setup after loading the view, typically from a nib.*/
}
@objc func clickfun() {
print("Tus datos son:")
print("Usuario: " + nametxtField.text!)
print("Email: " + emailtxtField.text!)
print("Password: " + passtxtField.text!)
// create the alert
/* let alert = UIAlertController(title: "Info", message: "Usuario: " + nametxtField.text! + "Email: " + emailtxtField.text! + "Password: " + passtxtField.text!)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)*/
let alert = UIAlertController(title: "Alert", message: "Usuario: " + nametxtField.text! + " -Email: " + emailtxtField.text! + " -Password: " + passtxtField.text!, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
let nametxtField : UITextField = {
let tf = UITextField()
tf.translatesAutoresizingMaskIntoConstraints = false
tf.placeholder = "Name"
tf.backgroundColor = .white
return tf
}()
let emailtxtField : UITextField = {
let tf = UITextField()
tf.translatesAutoresizingMaskIntoConstraints = false
tf.placeholder = "email"
tf.backgroundColor = .white
return tf
}()
let passtxtField : UITextField = {
let tf = UITextField()
tf.translatesAutoresizingMaskIntoConstraints = false
tf.placeholder = "password"
tf.backgroundColor = .white
return tf
}()
let inputContainerView : UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints=false
view.backgroundColor = .white
view.layer.cornerRadius=5
view.layer.masksToBounds = true
return view
}()
let firstBtn : UIButton={
let ub = UIButton()
ub.backgroundColor = UIColor(red:81/255,green:101/255,blue:151/255,alpha:1)
ub.setTitle("Button", for: .normal)
ub.translatesAutoresizingMaskIntoConstraints=false
ub.addTarget(self, action:#selector(clickfun), for: .touchUpInside)
return ub
}()
}
| true
|
b22c3130b4c845a05a030ae58e76f7cacd557be5
|
Swift
|
rileytestut/Harmony
|
/Harmony/Operations/ServiceOperation.swift
|
UTF-8
| 4,020
| 2.6875
| 3
|
[] |
no_license
|
//
// ServiceOperation.swift
// Harmony
//
// Created by Riley Testut on 3/6/19.
// Copyright © 2019 Riley Testut. All rights reserved.
//
import Roxas
class ServiceOperation<R, E: Error>: Operation<R, Error>
{
var requiresAuthentication = true
private let task: (@escaping (Result<R, E>) -> Void) -> Progress?
private var retryDelay: TimeInterval = 1.0
private var didAttemptReauthentication = false
private var taskProgress: Progress?
override var isAsynchronous: Bool {
return true
}
init(coordinator: SyncCoordinator, task: @escaping (@escaping (Result<R, E>) -> Void) -> Progress?)
{
self.task = task
super.init(coordinator: coordinator)
}
override func main()
{
super.main()
self.performTask()
}
}
private extension ServiceOperation
{
func performTask()
{
guard !self.isCancelled else {
self.result = .failure(GeneralError.cancelled)
self.finish()
return
}
guard self.coordinator.isAuthenticated || !self.requiresAuthentication else {
self.coordinator.authenticate { (result) in
switch result
{
case .success:
self.performTask()
case .failure(let error):
self.result = .failure(error)
self.finish()
}
}
return
}
self.taskProgress = self.task() { (result) in
let result = result.mapError { $0 as Error }
// We must append .self to our Error enum cases for pattern matching to work.
// Otherwise, the compiler (incorrectly) defaults to using normal enum pattern matching
// and won't call our custom pattern matching operator.
// https://bugs.swift.org/browse/SR-1121
do
{
_ = try result.get()
if let progress = self.taskProgress
{
// Ensure progress is completed.
progress.completedUnitCount = progress.totalUnitCount
}
self.result = result
self.finish()
}
catch ServiceError.rateLimitExceeded.self
{
guard self.retryDelay < 60 else {
self.result = result
self.finish()
return
}
print("Retrying request after delay:", self.retryDelay)
self.progress.completedUnitCount = 0
DispatchQueue.global().asyncAfter(deadline: .now() + self.retryDelay) {
self.retryDelay = self.retryDelay * 2
self.performTask()
}
}
catch AuthenticationError.tokenExpired.self where !self.didAttemptReauthentication && self.requiresAuthentication
{
self.didAttemptReauthentication = true
self.coordinator.authenticate() { (authResult) in
switch authResult
{
case .success:
self.performTask()
case .failure:
// Set result to whatever the result was prior to reauthentication attempt.
self.result = result
self.finish()
}
}
}
catch
{
self.result = result
self.finish()
}
}
if let progress = self.taskProgress
{
self.progress.addChild(progress, withPendingUnitCount: 1)
}
}
}
| true
|
197b588d0588835f792efc7f09e657b1fb0db6ca
|
Swift
|
LarryGensch/SwiftDefaults
|
/SwiftDefaults/Classes/SwiftDefaults.swift
|
UTF-8
| 4,209
| 2.90625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// SwiftDefaults.swift
// SwiftDefaults
//
// Created by Larry Gensch on 3/22/19.
// Copyright © 2019 Larry Gensch. All rights reserved.
//
import Foundation
/// Base class for all SwiftDefaults code
public class SwiftDefaults {
public let defaults : UserDefaults
private static var defaultList = [UserDefaults:SwiftDefaults]()
private static var syncObject = NSObject()
/// Return a `SwiftDefaults` instance for the given `UserDefaults` instance.
///
/// - Parameters:
/// - userDefaults: The `UserDefaults` instance associated with the returned instance
/// - Returns: The `SwiftDefaults` instance
public static func defaults(for userDefaults: UserDefaults) -> SwiftDefaults {
objc_sync_enter(syncObject)
defer { objc_sync_exit(syncObject) }
if let found = defaultList[userDefaults] {
return found
}
let defaults = SwiftDefaults(userDefaults)
defaultList[userDefaults] = defaults
return defaults
}
/// Manually initialize a `SwiftDefaults` instance
///
/// It is not recommended that clients call this method directly, unless there
/// is a need to have multiple instances of `SwiftDefaults` for the same
/// `UserDefaults` instance.
///
/// - Parameters:
/// - defaults: The `UserDefaults` instance associated with the returned value
public init(_ defaults: UserDefaults) {
self.defaults = defaults
}
/// Clear all SwiftDefaults, optionally allowing exceptions
///
/// - Parameter except: Array containing keys that will not be removed.
/// Pass `nil` if you want all keys removed.
public func destroyAll(except: [String]? = nil) {
let except = Set(except ?? [String]())
objc_sync_enter(keyValueSync)
defer { objc_sync_exit(keyValueSync) }
Set(keyValueTypes.keys)
.subtracting(except)
.forEach {
defaults.removeObject(forKey: $0)
keyValueTypes.removeValue(forKey: $0)
}
Set(keyValues.keys)
.subtracting(except)
.forEach {
defaults.removeObject(forKey: $0)
keyValues.removeValue(forKey: $0)
}
}
enum Error : LocalizedError {
case existingTypeForKey(NativeType.Type)
var localizedDescription: String {
switch self {
case .existingTypeForKey(let type):
return "Different type (\(type)) already exists for key"
}
}
}
var keyValueTypes = [String:NativeType.Type]()
var keyValueSync = NSObject()
var keyValues = [String:NSHashTable<AnyObject>]()
func addValue<T: NativeType>(_ value: NativeValue<T>) -> Bool {
let type = T.self
let key = value.key
objc_sync_enter(keyValueSync)
defer { objc_sync_exit(keyValueSync) }
if let existingType = keyValueTypes[key],
existingType != type {
return false
}
keyValueTypes[key] = type
if let hash = keyValues[key] {
hash.add(value)
} else {
let hash = NSHashTable<AnyObject>.weakObjects()
hash.add(value)
keyValues[key] = hash
}
return true
}
func removeValue<T: NativeType>(_ value: NativeValue<T>) {
let key = value.key
let type = T.self
objc_sync_enter(keyValueSync)
defer { objc_sync_exit(keyValueSync) }
keyValueTypes.removeValue(forKey: key)
guard let hash = keyValues[key] else { return }
hash.remove(value)
}
func destroyValue<T: NativeType>(_ value: NativeValue<T>) {
let key = value.key
let type = T.self
objc_sync_enter(keyValueSync)
defer { objc_sync_exit(keyValueSync) }
keyValueTypes.removeValue(forKey: key)
guard let hash = keyValues[key] else { return }
for value in hash.allObjects {
if let value = value as? NativeValue<T> {
value.markAsDestroyed()
}
}
}
/// Only used for testing
public static var isTesting = false
}
| true
|
bbd4b839df037c687d332260a3f569adb2796657
|
Swift
|
osperling/Cocktailomat
|
/Cocktailomat/Model/CocktailBrain.swift
|
UTF-8
| 1,614
| 2.859375
| 3
|
[] |
no_license
|
//
// CocktailBrain.swift
// Cocktailomat
//
// Created by Christian Schuck on 30.10.20.
// Copyright © 2020 Oliver Sperling. All rights reserved.
//
import UIKit
import Just
struct Cocktailbrain {
var behaelter = ["","","",""]
var fuellung = [0,0,0,0]
var fuellungInML=[0,0,0,0]
var pos = [0,0,0,0]
var glas = 0
var connection = false
mutating func setGlas(glas: Int){
self.glas = glas
}
mutating func setFuellung(behaelter:[String]){
self.behaelter = behaelter
}
mutating func setFuellung(fuellung:[Int]){
self.fuellung = fuellung
}
mutating func calcML(){
for i in 0..<fuellung.count {
fuellungInML[i] = Int(Double(fuellung[i])/100*Double(glas))
}
}
mutating func makeCocktail() -> Bool{
calcML()
let url = "http://192.168.4.1/pump?p1=\(fuellungInML[0])&p2=\(fuellungInML[1])&p3=\(fuellungInML[2])&p4=\(fuellungInML[3])&p1_pos=\(pos[0])&p2_pos=\(pos[1])&p3_pos=\(pos[2])&p4_pos=\(pos[3])"
return urlRequest(URL(string: url)!)
}
func urlRequest(_ url: URL) -> Bool{
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
}
task.resume()
return true
}
mutating func establishConnection() -> Bool{
let url = "http://192.168.4.1/connect"
if(Just.get(url, timeout: 0.5).statusCode == 200){
return true
}else{
return false
}
}
}
| true
|
ed494341bfd154b3bfdcbb1a2959a6689d889066
|
Swift
|
WimukthiRajapaksha/AutoDirect-App
|
/Auto Direct/Util/UIView.swift
|
UTF-8
| 1,744
| 2.96875
| 3
|
[] |
no_license
|
//
// UIView.swift
// Auto Direct
//
// Created by User on 4/21/20.
// Copyright © 2020 autoDirect. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
func round(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
func addBlackGradientLayerInForeground(frame: CGRect, colors:[UIColor]){
let gradient = CAGradientLayer()
gradient.frame = frame
gradient.colors = colors.map{$0.cgColor}
self.layer.addSublayer(gradient)
}
func addBlackGradientLayerInBackground(frame: CGRect, colors:[UIColor]){
let gradient = CAGradientLayer()
gradient.frame = frame
gradient.colors = colors.map{$0.cgColor}
self.layer.insertSublayer(gradient, at: 0)
}
func gradient(width: CGFloat, height: CGFloat, colors: [CGColor]) {
let gradient = CAGradientLayer()
gradient.frame = CGRect(x: 0, y: 0, width: width, height: height)
gradient.colors = colors
self.layer.insertSublayer(gradient, at: 0)
}
func gradientToSuperView(width: CGFloat, height: CGFloat, colors: [CGColor]) {
let gradient = CAGradientLayer()
gradient.frame = CGRect(x: 1, y: 0, width: width, height: height)
gradient.colors = colors
self.layer.insertSublayer(gradient, at: 0)
}
func rotate(angle: CGFloat) {
let radians = angle / 180.0 * CGFloat.pi
let rotation = self.transform.rotated(by: radians)
self.transform = rotation
}
}
| true
|
713f87590ce7b33ed73d7d7fbc3dcfb78060c52a
|
Swift
|
tbointeractive/bytes
|
/Example/bytesTests/Specs/SemanticVersionSpec.swift
|
UTF-8
| 11,731
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
//
// SemanticVersionSpec.swift
// bytes
//
// Created by Cornelius Horstmann on 11.12.16.
// Copyright © 2016 TBO INTERACTIVE GmbH & Co. KG. All rights reserved.
//
import bytes
import Quick
import Nimble
class SemanticVersionSpec: QuickSpec {
override func spec() {
describe("init") {
it("should store all properties") {
let version = SemanticVersion(major: 1, minor: 2, patch: 3, prereleaseIdentifiers: ["4","b"])
expect(version.major) == 1
expect(version.minor) == 2
expect(version.patch) == 3
expect(version.prereleaseIdentifiers) == ["4","b"]
}
}
describe("initWithString") {
it("should parse a full version string") {
let version = SemanticVersion("1.2.3")
expect(version!.major) == 1
expect(version!.minor) == 2
expect(version!.patch) == 3
expect(version!.prereleaseIdentifiers) == []
}
it("should parse a version string with leading or trailing whitespaces") {
let version = SemanticVersion(" 1.2.3 ")
expect(version).toNot(beNil())
expect(version!.major) == 1
expect(version!.minor) == 2
expect(version!.patch) == 3
expect(version!.prereleaseIdentifiers) == []
}
it("should parse just a major version string") {
let version = SemanticVersion("1")!
expect(version.major) == 1
expect(version.minor) == 0
expect(version.patch) == 0
expect(version.prereleaseIdentifiers) == []
}
it("should parse just a major and minor version string") {
let version = SemanticVersion("1.2")!
expect(version.major) == 1
expect(version.minor) == 2
expect(version.patch) == 0
expect(version.prereleaseIdentifiers) == []
}
it("should parse a version string with prerelease labels") {
let version = SemanticVersion("1.2.3-beta.1")
expect(version!.major) == 1
expect(version!.minor) == 2
expect(version!.patch) == 3
expect(version!.prereleaseIdentifiers) == ["beta","1"]
}
it("should return nil for an invalid string") {
let version = SemanticVersion("a")
expect(version).to(beNil())
}
}
describe("description") {
it("should return a describing string") {
let version = SemanticVersion("1.2.3")
expect(version?.description) == "1.2.3"
expect("\(version!)") == "1.2.3"
}
it("should work with prerelease information") {
let version = SemanticVersion("1.2.3-beta.1")
expect(version?.description) == "1.2.3-beta.1"
}
}
describe("equals") {
it("should be euqal if the objects are equal") {
let a = SemanticVersion(major: 1, minor: 2, patch: 3, prereleaseIdentifiers: ["alpha"])
let b = SemanticVersion(major: 1, minor: 2, patch: 3, prereleaseIdentifiers: ["alpha"])
expect(a==b).to(beTrue())
}
it("should not be true if the prerelease labels are different") {
let a = SemanticVersion(major: 1, minor: 2, patch: 3, prereleaseIdentifiers: ["alpha"])
let b = SemanticVersion(major: 1, minor: 2, patch: 3, prereleaseIdentifiers: ["beta"])
expect(a==b).to(beFalse())
}
it("should not be true if the version integers arent the same") {
let a = SemanticVersion(major: 1, minor: 2, patch: 3, prereleaseIdentifiers: ["alpha"])
let b = SemanticVersion(major: 1, minor: 2, patch: 4, prereleaseIdentifiers: ["alpha"])
expect(a==b).to(beFalse())
}
}
describe("smaller than") {
it("should return true if the major version is smaller") {
let version = SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["alpha", "beta","20"])
expect(version < SemanticVersion(major: 3, minor: 2, patch: 3)) == true
}
it("should return false if the major version is greater") {
let version = SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["alpha", "beta","20"])
expect(SemanticVersion(major: 3, minor: 2, patch: 3) < version) == false
}
it("should return true if the major is the same but the minor is smaller") {
let version = SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["alpha", "beta","20"])
expect(version < SemanticVersion(major: 2, minor: 4, patch: 5)) == true
}
it("should return false if the major is the same but the minor is greater") {
let version = SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["alpha", "beta","20"])
expect(SemanticVersion(major: 2, minor: 4, patch: 5) < version) == false
}
it("should return true if major and minor are equal but the patch is smaller") {
let version = SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["alpha", "beta","20"])
expect(version < SemanticVersion(major: 2, minor: 3, patch: 5)) == true
}
it("should return false if major and minor are equal but the patch is greater") {
let version = SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["alpha", "beta","20"])
expect(SemanticVersion(major: 2, minor: 3, patch: 5) < version) == false
}
context("with equal major, minor and patch version"){
it("should return false if only the other version has prerelease labels") {
let version = SemanticVersion(major: 2, minor: 3, patch: 4)
expect(version < SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["a"])) == false
expect(SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["a"]) < version) == true
}
it("should return true if the first prerelease label is a smaller number") {
let version = SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["1"])
expect(version < SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["2"])) == true
expect(SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["2"]) < version) == false
}
it("should return true if the first prerelease label is a smaller string") {
let version = SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["aa"])
expect(version < SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["ab"])) == true
expect(version < SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["aab"])) == true
expect(version < SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["b"])) == true
expect(SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["b"]) < version) == false
}
it("should return true if the first label is a number while the other version has a string") {
let version = SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["1"])
expect(version < SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["a"])) == true
expect(SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["a"]) < version) == false
}
it("should return true if the first label is the same while the other version has more preresease labels") {
let version = SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["a"])
expect(version < SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["a","b"])) == true
expect(SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["a","b"]) < version) == false
}
}
it("should return true if major, minor and patch are equal, but it has prerelease labels") {
let version = SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["a"])
expect(version < SemanticVersion(major: 2, minor: 3, patch: 4)) == true
expect(SemanticVersion(major: 2, minor: 3, patch: 4) < version) == false
}
it("should return true if major, minor and patch are equal, bit is has less prerelease labels than the other") {
let version = SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["b"])
expect(version < SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["b","c"])) == true
expect(SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["b","c"]) < version) == false
expect(version < SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["a","c"])) == false
expect(SemanticVersion(major: 2, minor: 3, patch: 4, prereleaseIdentifiers: ["a","c"]) < version) == true
}
it("should return false if both versions are equal") {
expect(SemanticVersion(major: 2, minor: 3, patch: 4) < SemanticVersion(major: 2, minor: 3, patch: 4)) == false
}
it("should respect the testcases on the semver.org page") {
expect(SemanticVersion("1.0.0")! < SemanticVersion("2.0.0")!) == true
expect(SemanticVersion("2.0.0")! < SemanticVersion("2.1.0")!) == true
expect(SemanticVersion("2.1.0")! < SemanticVersion("2.1.2")!) == true
expect(SemanticVersion("1.0.0-alpha")! < SemanticVersion("1.0.0")!) == true
expect(SemanticVersion("1.0.0-alpha")! < SemanticVersion("1.0.0-alpha.1")!) == true
expect(SemanticVersion("1.0.0-alpha.1")! < SemanticVersion("1.0.0-alpha.beta")!) == true
expect(SemanticVersion("1.0.0-alpha.beta")! < SemanticVersion("1.0.0-beta")!) == true
expect(SemanticVersion("1.0.0-beta")! < SemanticVersion("1.0.0-beta.2")!) == true
expect(SemanticVersion("1.0.0-beta.2")! < SemanticVersion("1.0.0-beta.11")!) == true
expect(SemanticVersion("1.0.0-beta.11")! < SemanticVersion("1.0.0-rc.1")!) == true
expect(SemanticVersion("1.0.0-rc.1")! < SemanticVersion("1.0.0")!) == true
}
}
describe("greater than") {
// scince greater and smaller are implemented the same way
// and actually greater than actually calls smaller than with
// swiched attributes we just use a very short test here
it("return the oposite of smaller than") {
expect(SemanticVersion("1.0.0")! > SemanticVersion("2.0.0")!) == false
expect(SemanticVersion("2.0.0")! > SemanticVersion("1.0.0")!) == true
}
}
}
}
| true
|
a75a7b443f5e5752290eca78aa29b6e22f5d48a1
|
Swift
|
pwyq/EthicaBeacon
|
/ED_TEST/EddystoneViewController.swift
|
UTF-8
| 2,253
| 2.625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// EddystoneViewController.swift
// ED_TEST
//
// Created by yanqing on 6/8/17.
// Copyright © 2017 EthicaData. All rights reserved.
//
import UIKit
class EddystoneViewController: UIViewController, EddystoneScannerDelegate {
@IBOutlet weak var descriptionLabel: UITextView!
@IBOutlet weak var scanSwitchLabel: UISwitch!
@IBOutlet weak var scanStateLabel: UITextField!
var eddystoneBeaconScanner: EddystoneScanner!
override func viewDidLoad() {
super.viewDidLoad()
print("Enter Scanning View Controller")
descriptionLabel.isScrollEnabled = false
self.eddystoneBeaconScanner = EddystoneScanner()
self.eddystoneBeaconScanner!.delegate = self
self.eddystoneBeaconScanner!.startEddystoneScanning()
}
func didFindBeacon(_ beaconScanner: EddystoneScanner, beaconInfo: BeaconInfo) {
NSLog("FIND: %@", beaconInfo.description)
}
func didLoseBeacon(_ beaconScanner: EddystoneScanner, beaconInfo: BeaconInfo) {
NSLog("LOST: %@", beaconInfo.description)
}
func didUpdateBeacon(_ beaconScanner: EddystoneScanner, beaconInfo: BeaconInfo) {
NSLog("UPDATE: %@", beaconInfo.description)
}
func didObserveURLBeacon(_ beaconScanner: EddystoneScanner, URL: Foundation.URL, RSSI: Int) {
print("URL: \(URL) RSSI: \(RSSI)")
}
@IBAction func scanSwitch(_ sender: UISwitch) {
scanStateLabel.text = sender.isOn ? "Stop Scanning" : "Start Scanning"
if sender.isOn {
print("-- Prepares to scan for Eddystone Beacon --")
self.eddystoneBeaconScanner.startEddystoneScanning()
print("== Eddystone scanning is ON ==")
}
else {
if self.eddystoneBeaconScanner.centralManager.isScanning {
print("-- Prepares to stop Eddystone scan --")
self.eddystoneBeaconScanner.centralManager.stopScan()
print("== Eddstone scanning is OFF ==")
}
}
}
@IBAction func returnToMain() {
print("Return to previous VC.")
eddystoneBeaconScanner.stopEddystoneScanning()
dismiss(animated: true, completion: nil)
}
}
| true
|
709157e95cad92e09a843b5139eeee64bce24739
|
Swift
|
dubeboy/Merchant
|
/Sources/Internal/Log/LoggerOutput.swift
|
UTF-8
| 348
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
public protocol LoggerOutput {
func log(_ message: String?)
}
public class STDOutLogger: LoggerOutput {
public static let instance: LoggerOutput = STDOutLogger()
private init() {}
public func log(_ message: String? = "") {
#if DEBUG
print(message ?? "")
#endif
}
}
| true
|
1336ca9182f2ab64a64af133b8ea01ad5284675f
|
Swift
|
azureplus/FFProbe
|
/Sources/FFProbe/Streams/VideoStream.swift
|
UTF-8
| 1,775
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
public final class VideoStream: BaseStream {
public override var type: CodecType { return .video }
public let codec: VideoCodec
public let duration: MediaDuration?
public let bitRate: BitRate?
public let dimensions: (width: Int, height: Int)
public let aspectRatio: AspectRatio
public let frameRate: FrameRate
public let bitDepth: Int?
public required init(_ any: AnyStream) throws {
guard let codec = VideoCodec(rawValue: any.rawCodec) else {
throw VideoStreamError.unknownCodec(any.rawCodec)
}
self.codec = codec
duration = any.duration
bitRate = any.bitRate
guard let dimensions = any.dimensions else {
throw VideoStreamError.missingDimensions
}
self.dimensions = dimensions
guard let aspectRatio = any.aspectRatio else {
throw VideoStreamError.missingAspectRatio
}
self.aspectRatio = aspectRatio
guard let frameRate = any.frameRate else {
throw VideoStreamError.missingFrameRate
}
self.frameRate = frameRate
bitDepth = any.bitDepth
try! super.init(any)
}
}
extension VideoStream: CustomStringConvertible {
public var description: String {
var desc = "\(Swift.type(of: self))(index: \(index), codec: \(codec)"
if let duration = self.duration {
desc += ", duration: \(duration)"
}
if let bitRate = self.bitRate {
desc += ", bitRate: \(bitRate)"
}
desc += ", dimensions: \(dimensions), aspectRatio: \(aspectRatio), frameRate: \(frameRate)"
if let bitDepth = self.bitDepth {
desc += ", bitDepth: \(bitDepth)"
}
return desc + ")"
}
}
| true
|
9ef7147b6fcc95ad309edb39f212b881cd8d40b0
|
Swift
|
kang77649119/ThreadDemo
|
/ThreadDemo/ThreadDemo/NSOperation/NSOperationVC.swift
|
UTF-8
| 11,520
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// NSOperationVC.swift
// ThreadDemo
//
// Created by 也许、 on 16/8/4.
// Copyright © 2016年 K. All rights reserved.
//
import UIKit
class NSOperationVC: UIViewController {
// 合并图片
@IBOutlet weak var mergeImg: UIImageView!
// 队列
var currentQueue:NSOperationQueue?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "NSOperation多线程"
self.view.backgroundColor = UIColor.whiteColor()
}
/**
NSBlockOperation + 主线程
*/
@IBAction func blockOperationMainThread(sender: UIButton) {
let operation = NSBlockOperation {
print("任务1-------", NSThread.currentThread())
}
operation.addExecutionBlock {
print("任务11------", NSThread.currentThread())
}
let operation2 = NSBlockOperation {
print("任务2-------", NSThread.currentThread())
}
let operation3 = NSBlockOperation {
print("任务3--------", NSThread.currentThread())
}
let queue = NSOperationQueue.mainQueue()
queue.addOperation(operation)
queue.addOperation(operation2)
queue.addOperation(operation3)
}
/**
NSBlockOperation + 其他线程
*/
@IBAction func blockOperationOtherThread(sender: UIButton) {
let operation = NSBlockOperation {
print("任务1-------", NSThread.currentThread())
}
operation.addExecutionBlock {
print("任务11------", NSThread.currentThread())
}
operation.addExecutionBlock {
print("任务11------", NSThread.currentThread())
}
let operation2 = NSBlockOperation {
print("任务2-------", NSThread.currentThread())
}
let operation3 = NSBlockOperation {
print("任务3--------", NSThread.currentThread())
}
let queue = NSOperationQueue()
queue.addOperation(operation)
queue.addOperation(operation2)
queue.addOperation(operation3)
}
/**
自定义NSOperation
*/
@IBAction func customNSOperation(sender: UIButton) {
let operation = CustomOperation()
let queue = NSOperationQueue()
queue.addOperation(operation)
}
/**
手动启动任务
默认在主线程执行,如果放在异步线程中,则会变成异步线程
*/
@IBAction func commonOperation(sender: UIButton) {
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) {
let operation = NSBlockOperation {
print("手动启动--任务1", NSThread.currentThread())
}
operation.addExecutionBlock({
print("手动启动线程---任务2", NSThread.currentThread())
})
operation.addExecutionBlock({
print("手动启动线程---任务3", NSThread.currentThread())
})
operation.addExecutionBlock({
print("手动启动线程---任务4", NSThread.currentThread())
})
operation.start()
}
}
/**
最大并发数
*/
@IBAction func maxConcurrentCount(sender: UIButton) {
let queue = NSOperationQueue()
// 为0时,任务不执行 为1时,串行队列
// queue.maxConcurrentOperationCount = 0
// > 1 并发队列
queue.maxConcurrentOperationCount = 2
queue.addOperationWithBlock {
print("任务1----", NSThread.currentThread())
NSThread.sleepForTimeInterval(1)
}
queue.addOperationWithBlock {
print("任务2----", NSThread.currentThread())
NSThread.sleepForTimeInterval(1)
}
queue.addOperationWithBlock {
print("任务3----", NSThread.currentThread())
NSThread.sleepForTimeInterval(1)
}
queue.addOperationWithBlock {
print("任务4----", NSThread.currentThread())
NSThread.sleepForTimeInterval(1)
}
queue.addOperationWithBlock {
print("任务5----", NSThread.currentThread())
NSThread.sleepForTimeInterval(1)
}
queue.addOperationWithBlock {
print("任务6----", NSThread.currentThread())
NSThread.sleepForTimeInterval(1)
}
queue.addOperationWithBlock {
print("任务7----", NSThread.currentThread())
NSThread.sleepForTimeInterval(1)
}
}
/**
任务开启
只有是串行时才会触发任务挂起
*/
@IBAction func operationStart(sender: UIButton) {
let queue = NSOperationQueue()
queue.maxConcurrentOperationCount = 1
queue.addOperationWithBlock {
for i in 0...5000 {
print("任务1--------", i ,NSThread.currentThread())
}
}
queue.addOperationWithBlock {
for i in 0...5000 {
print("任务2--------", i ,NSThread.currentThread())
}
}
queue.addOperationWithBlock {
for i in 0...5000 {
print("任务3--------", i ,NSThread.currentThread())
}
}
self.currentQueue = queue
}
/**
任务挂起
只有串行时才会触发任务挂起
*/
@IBAction func suspended(sender: UIButton) {
guard let queue = self.currentQueue else {
return
}
queue.suspended = !self.currentQueue!.suspended
}
/**
自定义NSOperation 如果不判断队列是否取消,队列中的任务不会被停止
*/
@IBAction func operationStart2(sender: UIButton) {
let queue = NSOperationQueue()
let operate = CustomOperation()
queue.addOperation(operate)
self.currentQueue = queue
}
/**
取消队列中的任务
*/
@IBAction func cancelOperate(sender: UIButton) {
self.currentQueue?.cancelAllOperations()
}
/**
普通NSOperation任务开启
*/
@IBAction func simpleNSOperationStart(sender: UIButton) {
let queue = NSOperationQueue()
queue.maxConcurrentOperationCount = 1
let operate = NSBlockOperation {
for i in 0...5000 {
print("任务1-------", i, NSThread.currentThread())
}
}
let operate2 = NSBlockOperation {
for i in 0...5000 {
print("任务2-------", i, NSThread.currentThread())
}
}
let operate3 = NSBlockOperation {
for i in 0...5000 {
print("任务3-------", i, NSThread.currentThread())
}
}
queue.addOperation(operate)
queue.addOperation(operate2)
queue.addOperation(operate3)
self.currentQueue = queue
}
/**
合并图片
*/
@IBAction func mergeImgs(sender: UIButton) {
// 并发队列
let queue = NSOperationQueue()
// 下载图片1任务
var img1:UIImage?
let operate = NSBlockOperation {
let url = NSURL(string: "http://i1.qhimg.com/dr/705_705_/t01328d16e673160411.png")
let data = NSData(contentsOfURL: url!)
img1 = UIImage(data: data!)
}
// 下载图片2任务
var img2:UIImage?
let operate2 = NSBlockOperation {
let url = NSURL(string: "http://images.takungpao.com/2013/0531/20130531103303406.jpg")
let data = NSData(contentsOfURL: url!)
img2 = UIImage(data: data!)
}
// 合并
let operate3 = NSBlockOperation {
// 合并图片
UIGraphicsBeginImageContext(self.mergeImg.bounds.size)
img1?.drawInRect(CGRectMake(0, 0, self.mergeImg!.frame.width * 0.5 , self.mergeImg!.frame.height))
img2?.drawInRect(CGRectMake(self.mergeImg!.frame.width * 0.5, 0, self.mergeImg.frame.width * 0.5, self.mergeImg.frame.height))
let mergeImg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// 在主队列中显示图片
NSOperationQueue.mainQueue().addOperationWithBlock({
self.mergeImg.image = mergeImg
})
}
// 确保合并操作在任务1和任务2之后执行,需要添加依赖
operate3.addDependency(operate)
operate3.addDependency(operate2)
queue.addOperation(operate)
queue.addOperation(operate2)
queue.addOperation(operate3)
}
/**
任务依赖
*/
@IBAction func operateDependency(sender: UIButton) {
let queue = NSOperationQueue()
let operate = NSBlockOperation {
for i in 0...50 {
print("任务1--------", i, NSThread.currentThread())
}
}
let operate2 = NSBlockOperation {
for i in 0...50 {
print("任务2--------", i, NSThread.currentThread())
}
}
let operate3 = NSBlockOperation {
for i in 0...50 {
print("任务3--------", i, NSThread.currentThread())
}
}
let operate4 = NSBlockOperation {
for i in 0...50 {
print("任务4--------", i, NSThread.currentThread())
}
}
let operate5 = NSBlockOperation {
for i in 0...50 {
print("任务5--------", i, NSThread.currentThread())
NSThread.sleepForTimeInterval(0.2)
}
}
// 任务3 依赖 任务1和任务2,表示任务3一定是在任务1和任务2执行完成后再执行
operate3.addDependency(operate)
operate3.addDependency(operate2)
queue.addOperation(operate)
queue.addOperation(operate2)
queue.addOperation(operate3)
queue.addOperation(operate4)
queue.addOperation(operate5)
}
/**
任务监听
*/
@IBAction func operateListening(sender: UIButton) {
let operate = NSBlockOperation {
for i in 0...500 {
print("执行任务", i, NSThread.currentThread())
}
}
operate.completionBlock = {
print("执行完成~~~~~~")
}
NSOperationQueue().addOperation(operate)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
f1e3b2a4aac11295010e8c1ec14dba242e45a0c1
|
Swift
|
Parrot-Developers/groundsdk-ios
|
/groundsdk/GroundSdk/Internal/Engine/Firmware/FirmwareDownloader.swift
|
UTF-8
| 9,860
| 2.5625
| 3
|
[] |
permissive
|
// Copyright (C) 2019 Parrot Drones SAS
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
// * Neither the name of the Parrot Company nor the names
// of its contributors may be used to endorse or promote products
// derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
import Foundation
/// Manages download of firmware update files.
class FirmwareDownloader {
/// State of the firmware downloader
enum State: CustomStringConvertible {
/// No download ongoing currently
case idle
/// Queued firmwares are being downloaded
case downloading
/// Debug description
var description: String {
switch self {
case .idle: return "idle"
case .downloading: return "downloading"
}
}
}
/// Latest download error
enum Error: CustomStringConvertible {
/// No error occurred
case none
/// Download was aborted
case aborted
/// Download failed due to some server error
case serverError
/// Debug description
var description: String {
switch self {
case .none: return "none"
case .aborted: return "aborted"
case .serverError: return "serverError"
}
}
}
/// Provides firmware downloader change notification
class Observer: NSObject {
/// The firmware downloader owning this observer.
private unowned let observable: FirmwareDownloader
/// Block that should be called when the firmware downloader changes
fileprivate var didChange: () -> Void
/// Constructor
///
/// - Parameters:
/// - observable: firmware downloader owning this observer
/// - didChange: block that should be called when the firmware downloader changes
init(observable: FirmwareDownloader, didChange: @escaping () -> Void) {
self.observable = observable
self.didChange = didChange
}
/// Unregister this observer
func unregister() {
observable.unregister(observer: self)
}
}
/// Engine owning this downloader
private unowned let engine: FirmwareEngine
/// Update REST Api
private let downloader: UpdateRestApi
/// Root folder to store the firmwares
private let firmwareFolder: URL
/// Queue of firmwares to be downloaded
private var downloadQueue: [FirmwareIdentifier] = []
/// Current request
private var currentRequest: CancelableCore?
/// Set of registered observers
private var observers: Set<Observer> = []
/// Current state
private(set) var state = State.idle
/// Latest download error.
private(set) var latestError = Error.none
/// Identifies currently downloaded firmware.
var currentDownload: FirmwareIdentifier? {
return downloadQueue.first
}
/// Current firmware download progress.
private(set) var progress = 0
/// Whether this downloader has changed
private var changed = false
/// Constructor
///
/// - Parameters:
/// - engine: the engine owning this object
/// - downloader: the downloader
/// - destinationFolder: root folder where downloaded firmwares should be stored
init(engine: FirmwareEngine, downloader: UpdateRestApi, destinationFolder: URL) {
self.engine = engine
self.downloader = downloader
self.firmwareFolder = destinationFolder
}
/// Queues a firmware for download.
///
/// The given firmware will be downloaded after all previously queued firmware download have successfully completed.
/// In case some queued download fails, then the downloader stops and all remaining queued downloads are discarded.
///
/// - Parameter firmwareIdentifier: identifier of the firmware to be downloaded
func queueForDownload(firmwareIdentifier: FirmwareIdentifier) {
if !downloadQueue.contains(firmwareIdentifier) {
downloadQueue.append(firmwareIdentifier)
}
processNextFirmware()
}
/// Registers an observer that will receive firmware downloader state change notifications.
///
/// - Parameter didChange: block that will be called when the downloader changes
/// - Returns: the observer.
///
/// - Note: `unregister()` should be called on the returned observer when not needed anymore.
func registerObserver(didChange: @escaping () -> Void) -> Observer {
let observer = Observer(observable: self, didChange: didChange)
observers.insert(observer)
return observer
}
/// Unregisters an observer
///
/// - Parameter observer: observer to unregister
private func unregister(observer: Observer) {
observers.remove(observer)
}
/// Downloads next firmware in queue.
private func processNextFirmware() {
guard currentRequest == nil else {
return
}
update(progress: 0)
var nextEntry: FirmwareStoreEntry?
while nextEntry == nil && !downloadQueue.isEmpty {
update(state: .downloading)
update(latestError: .none)
notifyUpdated()
nextEntry = engine.firmwareStore.getEntry(for: downloadQueue.first!)
if nextEntry == nil || nextEntry!.isLocal || nextEntry!.remoteUrl == nil {
downloadQueue.removeFirst()
nextEntry = nil
}
}
if let nextEntry = nextEntry {
let firmwareIdentifier = nextEntry.firmware.firmwareIdentifier
let remoteUrl = nextEntry.remoteUrl!
let destinationUrl = getDestinationUrl(for: firmwareIdentifier, name: remoteUrl.lastPathComponent)
currentRequest = downloader.downloadFirmware(
from: remoteUrl, to: destinationUrl,
didProgress: { [weak self] progress in
self?.update(progress: progress)
self?.notifyUpdated()
},
didComplete: { [weak self] status, url in
self?.currentRequest = nil
self?.downloadQueue.removeFirst()
if status == .success {
self?.engine.firmwareStore.changeRemoteFirmwareToLocal(
identifier: firmwareIdentifier, localUrl: url!)
} else {
self?.downloadQueue.removeAll()
self?.update(latestError: status == .canceled ? .aborted : .serverError)
}
self?.processNextFirmware()
})
} else {
update(state: .idle)
}
notifyUpdated()
}
/// Creates a destination url for a given firmware
///
/// A firmware in version X.Y.Z for model A will be stored in `firmwareFolder/A/X.Y.Z/name`.
///
/// - Parameters:
/// - identifier: the firmware identifier
/// - name: the name of the file
/// - Returns: an url where the given firmware should be downloaded.
private func getDestinationUrl(for identifier: FirmwareIdentifier, name: String) -> URL {
return firmwareFolder.appendingPathComponent(identifier.deviceModel.description, isDirectory: true)
.appendingPathComponent(identifier.version.description, isDirectory: true).appendingPathComponent(name)
}
/// Updates current downloaded update file progress.
///
/// - Parameter newValue: new progress value
private func update(progress newValue: Int) {
if progress != newValue {
progress = newValue
changed = true
}
}
/// Updates current downloader state.
///
/// - Parameter newValue: new state
private func update(state newValue: State) {
if state != newValue {
state = newValue
changed = true
}
}
/// Updates latest download error.
///
/// - Parameter newValue: new latest error
private func update(latestError newValue: Error) {
if latestError != newValue {
latestError = newValue
changed = true
}
}
/// Notifies all observers of download state change, iff state did change since last call to this method
private func notifyUpdated() {
if changed {
changed = false
observers.forEach { $0.didChange() }
}
}
}
| true
|
ccc6a1533f88168330ccadd6cc252479304c21a5
|
Swift
|
nanoxd/Nano
|
/Tests/NanoTests/Swift/Extensions/CollectionTests.swift
|
UTF-8
| 3,717
| 2.96875
| 3
|
[] |
no_license
|
@testable import Nano
import XCTest
final class CollectionTests: XCTestCase {
func test_anySatisfy() {
let collection = [1, 3, 5, 7, 10]
XCTAssertTrue(collection.anySatisfy { $0.isMultiple(of: 2) })
XCTAssertFalse(collection.anySatisfy { $0 == 15 })
}
func test_countWhere() {
let names = ["Rob", "Juan", "Kim", "Ari"]
XCTAssertEqual(
names.count(where: { $0.count > 3 }),
1
)
}
func test_eachPair() {
let numbers = [1, 2, 3, 4, 5]
let pairs = Array(numbers.eachPair())
XCTAssertEqual(pairs.first?.0, 1)
XCTAssertEqual(pairs.first?.1, 2)
XCTAssertEqual(pairs.last?.0, 4)
XCTAssertEqual(pairs.last?.1, 5)
}
func test_partitionBy() {
let wizards = ["Draco Malfoy", "Harry Potter", "Hermione Granger"]
let splitWizards = wizards.partition { wizard in
wizard.first == "H"
}
XCTAssertEqual(splitWizards.0, Array(wizards.dropFirst()))
XCTAssertEqual(splitWizards.1, [wizards[0]])
}
func test_strideByStep() {
let numbers = Array(1...10)
var oddNumberSequence = numbers.stride(by: 2)
XCTAssertEqual(oddNumberSequence.next(), 1)
XCTAssertEqual(oddNumberSequence.next(), 3)
XCTAssertEqual(oddNumberSequence.next(), 5)
XCTAssertEqual(oddNumberSequence.next(), 7)
XCTAssertEqual(oddNumberSequence.next(), 9)
XCTAssertNil(oddNumberSequence.next())
}
func test_strideByStep_fromStart() {
let numbers = Array(1...10)
var evenNumberSequence = numbers.stride(by: 2, from: 1)
XCTAssertEqual(evenNumberSequence.next(), 2)
XCTAssertEqual(evenNumberSequence.next(), 4)
XCTAssertEqual(evenNumberSequence.next(), 6)
XCTAssertEqual(evenNumberSequence.next(), 8)
XCTAssertEqual(evenNumberSequence.next(), 10)
XCTAssertNil(evenNumberSequence.next())
}
func test_strideByStep_toEnd() {
let numbers = Array(1...10)
var oddNumbersUpToFiveSequence = numbers.stride(by: 2, to: 5)
XCTAssertEqual(oddNumbersUpToFiveSequence.next(), 1)
XCTAssertEqual(oddNumbersUpToFiveSequence.next(), 3)
XCTAssertEqual(oddNumbersUpToFiveSequence.next(), 5)
XCTAssertNil(oddNumbersUpToFiveSequence.next())
}
func test_strideByStep_throughEnd() {
let numbers = Array(1...10)
var oddNumbersUpToFiveSequence = numbers.stride(by: 2, through: 5)
XCTAssertEqual(oddNumbersUpToFiveSequence.next(), 1)
XCTAssertEqual(oddNumbersUpToFiveSequence.next(), 3)
XCTAssertEqual(oddNumbersUpToFiveSequence.next(), 5)
XCTAssertNil(oddNumbersUpToFiveSequence.next())
}
func test_strideByStep_fromStart_throughEnd() {
let empty = [Int]()
var emptySequence = empty.stride(by: 2, from: 0, through: 10)
XCTAssertNil(emptySequence.next())
}
func test_subscript_safe() {
let numbers = [1, 2]
XCTAssertNotNil(numbers[safe: 1])
XCTAssertNil(numbers[safe: 2])
}
static var allTests = [
("test_anySatisfy", test_anySatisfy),
("test_countWhere", test_countWhere),
("test_eachPair", test_eachPair),
("test_partitionBy", test_partitionBy),
("test_strideByStep", test_strideByStep),
("test_strideByStep_fromStart", test_strideByStep_fromStart),
("test_strideByStep_toEnd", test_strideByStep_toEnd),
("test_strideByStep_throughEnd", test_strideByStep_throughEnd),
("test_strideByStep_fromStart_throughEnd", test_strideByStep_fromStart_throughEnd),
("test_subscript_safe", test_countWhere),
]
}
| true
|
d3485fae706b4047eae9bcbc01bf5817b17aa6fd
|
Swift
|
LondonAtlas/Protocol
|
/Protocol/ClassFinds.swift
|
UTF-8
| 2,576
| 3.46875
| 3
|
[] |
no_license
|
//
// ClassFinds.swift
// Protocol
//
// Created by Tom Marks on 18/09/2016.
// Copyright © 2016 Tom Marks. All rights reserved.
//
import Foundation
//**********************************************************************************************************************
// MARK: - Child Classes
// Recreating a function that does the exact same thing for multiple class is always going to lead to a bad time.
// It introduces a lot of code duplication which in the future would make debugging, and editing functionality
// very difficult.
extension Cat {
static func find(cats:[Cat], with id: NSUUID) -> [Cat] {
var foundCats = [Cat]()
for aCat in cats {
if aCat.id == id {
foundCats.append(aCat)
}
}
return foundCats
}
}
extension Dodge {
static func find(dodges:[Dodge], with id: NSUUID) -> [Dodge] {
var foundDodges = [Dodge]()
for aDodge in dodges {
if aDodge.id == id {
foundDodges.append(aDodge)
}
}
return foundDodges
}
}
extension Dog {
static func find(dogs:[Dog], with id: NSUUID) -> [Dog] {
var foundDogs = [Dog]()
for aDog in dogs {
if aDog.id == id {
foundDogs.append(aDog)
}
}
return foundDogs
}
}
extension Tesla {
static func find(teslas:[Tesla], with id: NSUUID) -> [Tesla] {
var foundTesla = [Tesla]()
for aTesla in teslas {
if aTesla.id == id {
foundTesla.append(aTesla)
}
}
return foundTesla
}
}
//**********************************************************************************************************************
// MARK: - Parent Classes
// Creating a single function for each parent class of different types is ok, however this can lead to problems
// once your code complexity grows.
extension Car {
static func find(cars:[Car], with id: NSUUID) -> [Car] {
var foundCars = [Car]()
for aCar in cars {
if aCar.id == id {
foundCars.append(aCar)
}
}
return foundCars
}
}
extension Pet {
static func find(pets:[Pet], with id: NSUUID) -> [Pet] {
var foundPets = [Pet]()
for aPet in pets {
if aPet.id == id {
foundPets.append(aPet)
}
}
return foundPets
}
}
| true
|
ad83788a7f7c4deb13ec256f8a5ef136e3976df3
|
Swift
|
jrasmusson/swift-arcade
|
/Starbucks/Source/StarBucks/HistoryTransaction.swift
|
UTF-8
| 698
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// HistoryTransaction.swift
// HistorySpike
//
// Created by Jonathan Rasmusson Work Pro on 2020-07-21.
// Copyright © 2020 Rasmusson Software Consulting. All rights reserved.
//
import Foundation
/*
let json = """
{
"transactions": [
{
"id": 699519475,
"type": "redeemed",
"amount": "150",
"processed_at": "2020-07-17T12:56:27-04:00"
}
]
}
"""
*/
struct History: Codable {
let transactions: [Transaction]
}
struct Transaction: Codable {
let id: Int
let type: String
let amount: String
let date: Date
enum CodingKeys: String, CodingKey {
case id
case type
case amount
case date = "processed_at"
}
}
| true
|
34e194c415db1674fcb88ae2d20283a2d03a5ce5
|
Swift
|
giolomsa/applicaster-iOS-assignment
|
/ApplicasteriOS/ApplicasteriOS/Models/MediaItem.swift
|
UTF-8
| 1,335
| 3.15625
| 3
|
[] |
no_license
|
//
// MediaItem.swift
// ApplicasteriOS
//
// Created by Gio Lomsa on 10/17/19.
// Copyright © 2019 Giorgi Lomsadze. All rights reserved.
//
import Foundation
//MARK:- Media item Type/Scale enums
enum MediaItemType: String{
case image = "image"
case video = "video"
}
enum MediaItemScale: String{
case small = "small"
case large = "large"
}
class MediaItem: Codable{
var src: String
var type: MediaItemType
var scale: MediaItemScale
var key: String
//MARK:- Coding key enum
enum CodingKeys:String, CodingKey{
case src = "src"
case type = "type"
case scale = "scale"
case key = "key"
}
//MARK:- encode/decode
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(String.self, forKey: .type)
self.type = MediaItemType.init(rawValue: type ) ?? .image
let scale = try container.decode(String.self, forKey: .scale)
self.scale = MediaItemScale.init(rawValue: scale ) ?? .small
self.src = try container.decode(String.self, forKey: .src)
self.key = try container.decode(String.self, forKey: .key)
}
func encode(to encoder: Encoder) throws {
}
}
| true
|
60a313103d01cddc4527c952755e41775ba574ae
|
Swift
|
kongmingstrap/ArchitectureExample-iOS
|
/CleanArchitectureExample/CleanArchitectureExample/Sources/TodoViewModel.swift
|
UTF-8
| 651
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// TodoViewModel.swift
// CleanArchitectureExample
//
// Created by tanaka.takaaki on 2017/03/21.
// Copyright © 2017年 tanaka.takaaki. All rights reserved.
//
import Foundation
public struct TodoViewModel {
let title: String?
let description: String?
let memo: String?
let type: TodoType.TaskType
let state: TodoType.State
let done: Bool
let expiredAt: Date?
init(model: TodoModel) {
title = model.title
description = model.description
memo = model.memo
type = model.type
state = model.state
done = model.done
expiredAt = model.expiredAt
}
}
| true
|
581959aaf3911cc61762a720c00784d0f8b7ba0b
|
Swift
|
cshung/Competition
|
/swift_competition/Sources/swift_competition/leetcode/letter_combinations_of_a_phone_number.swift
|
UTF-8
| 1,909
| 3.875
| 4
|
[] |
no_license
|
import Foundation
enum letter_combinations_of_a_phone_number {}
extension letter_combinations_of_a_phone_number {
class Solution {
struct MyCollection: Sequence {
let digits: String
func makeIterator() -> MyIterator {
return MyIterator(
items: Array(digits), currentIndex: Array(repeating: 0, count: digits.count),
done: digits.count == 0)
}
}
struct MyIterator: IteratorProtocol {
let items: [Character]
var currentIndex: [Int]
var done: Bool
mutating func next() -> [Character]? {
var map = [Character: [Character]]()
map[Array("2")[0]] = Array("abc")
map[Array("3")[0]] = Array("def")
map[Array("4")[0]] = Array("ghi")
map[Array("5")[0]] = Array("jkl")
map[Array("6")[0]] = Array("mno")
map[Array("7")[0]] = Array("pqrs")
map[Array("8")[0]] = Array("tuv")
map[Array("9")[0]] = Array("wxyz")
if done {
return nil
}
var answer: [Character] = []
for i in 0..<items.count {
let c = items[i]
let a = map[c]![currentIndex[i]]
answer.append(a)
}
var digit = items.count - 1
while true {
if currentIndex[digit] + 1 == map[items[digit]]!.count {
currentIndex[digit] = 0
digit = digit - 1
if digit == -1 {
done = true
break
}
} else {
currentIndex[digit] = currentIndex[digit] + 1
break
}
}
return answer
}
}
func letterCombinations(_ digits: String) -> [String] {
var answer: [String] = []
for item in MyCollection(digits: digits) {
answer.append(String(item))
}
return answer
}
}
static func main() {
print(Solution().letterCombinations("23"))
}
}
| true
|
8a3949beb269b44a98b7456b9c4ee45c267c7a2e
|
Swift
|
DougGregor/swift-package-manager
|
/Tests/UtilityTests/SimplePersistenceTests.swift
|
UTF-8
| 2,510
| 2.6875
| 3
|
[
"Apache-2.0",
"Swift-exception"
] |
permissive
|
/*
This source file is part of the Swift.org open source project
Copyright 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Basic
import TestSupport
import Utility
fileprivate class Foo: SimplePersistanceProtocol {
var int: Int
var path: AbsolutePath
let persistence: SimplePersistence
init(int: Int, path: AbsolutePath, fileSystem: FileSystem) {
self.int = int
self.path = path
self.persistence = SimplePersistence(
fileSystem: fileSystem,
schemaVersion: 1,
statePath: AbsolutePath.root.appending(component: "state.json")
)
}
func restore(from json: JSON) throws {
self.int = try json.get("int")
self.path = try AbsolutePath(json.get("path"))
}
func toJSON() -> JSON {
return JSON([
"int": int,
"path": path,
])
}
func save() throws {
try persistence.saveState(self)
}
func restore() throws -> Bool {
return try persistence.restoreState(self)
}
}
class SimplePersistenceTests: XCTestCase {
func testBasics() throws {
let fs = InMemoryFileSystem()
let stateFile = AbsolutePath.root.appending(component: "state.json")
let foo = Foo(int: 1, path: AbsolutePath("/hello"), fileSystem: fs)
// Restoring right now should return false because state is not present.
XCTAssertFalse(try foo.restore())
// Save and check saved data.
try foo.save()
let json = try JSON(bytes: fs.readFileContents(stateFile))
XCTAssertEqual(1, try json.get("version"))
XCTAssertEqual(foo.toJSON(), try json.get("object"))
// Modify local state and restore.
foo.int = 5
XCTAssertTrue(try foo.restore())
XCTAssertEqual(foo.int, 1)
XCTAssertEqual(foo.path, AbsolutePath("/hello"))
// Modify state's schema version.
let newJSON = JSON(["version": 2])
try fs.writeFileContents(stateFile, bytes: newJSON.toBytes())
do {
_ = try foo.restore()
XCTFail()
} catch SimplePersistence.Error.invalidSchemaVersion(let v){
XCTAssertEqual(v, 2)
}
}
static var allTests = [
("testBasics", testBasics),
]
}
| true
|
672cf621a0865ff033308f96417399b05e5c52d8
|
Swift
|
Jitlee/YunweitongIOS
|
/YunweitongIOS/EditingFieldViewController.swift
|
UTF-8
| 1,748
| 2.59375
| 3
|
[] |
no_license
|
//
// EditingFieldViewController.swift
// YunweitongIOS
//
// Created by 品佳 万 on 15/7/1.
// Copyright (c) 2015年 润图城. All rights reserved.
//
import UIKit
class EditingFieldViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
var fieldName: String!
var fieldLabel: String! {
didSet {
self.title = fieldLabel
}
}
var fieldValue: String!
private var value: String {
return textField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
override func viewDidLoad() {
super.viewDidLoad()
if fieldValue != "未设置" {
self.textField.text = fieldValue
}
self.textField.resignFirstResponder()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func save(sender: AnyObject) {
save()
}
func save() {
let center = NSNotificationCenter.defaultCenter()
let delegateObject = self.parentViewController?.navigationController
println("\(self.parentViewController?.navigationController?.presentedViewController)")
let notification = NSNotification(
name: KeyConfig.FieldChanged,
object: delegateObject,
userInfo: [
KeyConfig.FieldChangedKey: fieldName,
KeyConfig.FieldChangedValue: value
])
center.postNotification(notification)
self.parentViewController?.navigationController?.popViewControllerAnimated(true)
}
}
| true
|
6661ab4efabc2e0555516a15b6b6fca61495145d
|
Swift
|
SergisMund0/incredibleMovie
|
/incredibleMovieTests/DashboardInteractorTests.swift
|
UTF-8
| 6,629
| 2.84375
| 3
|
[] |
no_license
|
//
// DashboardInteractorTests.swift
// incredibleMovieTests
//
// Created by Sergio Garre on 12/12/2018.
// Copyright © 2018 Sergio Garre. All rights reserved.
//
import XCTest
@testable import incredibleMovie
class DashboardInteractorTests: XCTestCase {
var dashboardInteractor: DashboardInteractor!
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
super.setUp()
dashboardInteractor = DashboardInteractor()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
dashboardInteractor = nil
}
func testDatesFromServerAreCorrect() {
// 1. Test that the service is returning data and there is no error
let page = 3
var popularMoviesResults: [Result]?
var popularMoviesError: Error?
let expectation = self.expectation(description: "Loading")
dashboardInteractor.popularMovies(page: page) { (popularMovies, error) in
popularMoviesResults = popularMovies?.results
popularMoviesError = error
expectation.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
XCTAssertNil(popularMoviesError)
XCTAssertNotNil(popularMoviesResults)
// 2. Test that the format of the dates is correct
if let popularMoviesResults = popularMoviesResults {
let stringDatesAreValid = popularMoviesResults.allSatisfy({dashboardInteractor.isStringDateFormatValid($0.firstAirDate) == true})
XCTAssertTrue(stringDatesAreValid)
}
}
func testStringDatesHaveCorrectFormat() {
// 1. Test if the function returns an invalid state given a unexpected string date format
var unexpectedStringDateFormat = "2018-12-12T19:57:35.000Z" // "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
XCTAssertFalse(dashboardInteractor.isStringDateFormatValid(unexpectedStringDateFormat))
unexpectedStringDateFormat = "12/12/18" // "dd/MM/yy"
XCTAssertFalse(dashboardInteractor.isStringDateFormatValid(unexpectedStringDateFormat))
unexpectedStringDateFormat = "12.12.18" // "dd.MM.yy"
XCTAssertFalse(dashboardInteractor.isStringDateFormatValid(unexpectedStringDateFormat))
unexpectedStringDateFormat = "12-Dec-2018" // "dd-MMM-yyyy"
XCTAssertFalse(dashboardInteractor.isStringDateFormatValid(unexpectedStringDateFormat))
unexpectedStringDateFormat = "Dec 12,2018" // MMM dd,yyyy"
XCTAssertFalse(dashboardInteractor.isStringDateFormatValid(unexpectedStringDateFormat))
// 2. Test if the function returns a valid state given an expected string date format
let expectedStringDateFormat = "2018-12-12" // yyyy-MM-dd"
XCTAssertTrue(dashboardInteractor.isStringDateFormatValid(expectedStringDateFormat))
}
func testDateRangeIsValid() {
// 1. Test if the function returns an invalid state given a unexpected date range
var unexpectedDateRange = DateRange(minimumYearDate: "2017", maximumYearDate: "1977")
XCTAssertFalse(dashboardInteractor.isDateRangeValid(unexpectedDateRange))
unexpectedDateRange = DateRange(minimumYearDate: "20177", maximumYearDate: "19777")
XCTAssertFalse(dashboardInteractor.isDateRangeValid(unexpectedDateRange))
unexpectedDateRange = DateRange(minimumYearDate: "10", maximumYearDate: "20")
XCTAssertFalse(dashboardInteractor.isDateRangeValid(unexpectedDateRange))
// 2. Test if the function returns a valid state given an expected date range
let expectedDateRange = DateRange(minimumYearDate: "1964", maximumYearDate: "2018")
XCTAssertTrue(dashboardInteractor.isDateRangeValid(expectedDateRange))
}
func testFilterStringDates() {
// 1. Test if the function returns a nil state given a unexpected array of dates
let unexpectedStringDateFormatArray = ["11/08/17", "2018-12-12T19:57:35.000Z", "05-Jan-2015", "Dec 12,2018"]
let expectedDateRange = DateRange(minimumYearDate: "1930", maximumYearDate: "2018")
var dateRangeResult = dashboardInteractor.filterStringDates(unexpectedStringDateFormatArray, byDateRange: expectedDateRange)
XCTAssertNil(dateRangeResult)
// 2. Test if the function returns not nil state given an expected array of dates
let expectedStringDateFormatArray = ["2017-11-08", "1988-10-05", "2018-07-04", "2003-01-01"]
dateRangeResult = dashboardInteractor.filterStringDates(expectedStringDateFormatArray, byDateRange: expectedDateRange)
XCTAssertNotNil(dateRangeResult)
}
func testDateRange() {
let defaultDateRangeType = (minDate: FilterResources.minimumYearNumberString, maxDate: FilterResources.maximumYearNumberString)
// 1. Test if the function returns a default state given a unexpected array of dates
let unexpectedStringDateFormatArray = ["11/08/17", "2018-12-12T19:57:35.000Z", "05-Jan-2015", "Dec 12,2018"]
var dateRangeTypeResult = dashboardInteractor.getDateRange(from: unexpectedStringDateFormatArray)
XCTAssertTrue(dateRangeTypeResult == defaultDateRangeType)
// 2. Test if the function returns not default state given an expected array of dates
var expectedStringDateFormatArray = ["2017-11-08", "1988-10-05", "2018-07-04", "2003-01-01"]
dateRangeTypeResult = dashboardInteractor.getDateRange(from: expectedStringDateFormatArray)
XCTAssertFalse(dateRangeTypeResult == defaultDateRangeType)
// 3. Test if the function returns not default state given an expected array of dates and the range is correct
// The years are equals
expectedStringDateFormatArray = ["2018-11-08", "2018-10-05", "2018-07-04", "2018-01-01"]
dateRangeTypeResult = dashboardInteractor.getDateRange(from: expectedStringDateFormatArray)
XCTAssertFalse(dateRangeTypeResult == defaultDateRangeType)
// 4. Test if the function returns not default state given an expected array of dates and the range is correct
// The years are not equals
expectedStringDateFormatArray = ["2017-11-08", "1988-10-05", "2018-07-04", "2003-01-01"]
dateRangeTypeResult = dashboardInteractor.getDateRange(from: expectedStringDateFormatArray)
XCTAssertFalse(dateRangeTypeResult == defaultDateRangeType)
}
}
| true
|
40ece484d9a09c9d0f5b25be7cc43787b0e9e8b7
|
Swift
|
yoshiasoci/Weather-App
|
/WeatherApp/Controller/DetailWeatherCollectionController.swift
|
UTF-8
| 760
| 2.59375
| 3
|
[] |
no_license
|
//
// ImageCollectionViewCellController.swift
// WeatherApp
//
// Created by admin on 1/21/20.
// Copyright © 2020 admin. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class DetailWeatherCollectionController: UICollectionViewCell {
@IBOutlet weak var weatherImage: UIImageView!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var summaryLabel: UILabel!
func populateCell(weatherImageString: String, date: String, temperature: Double, summary: String) {
temperatureLabel.text = "\(Int(temperature))"
dateLabel.text = date
summaryLabel.text = summary
weatherImage.image = UIImage(named: weatherImageString)
}
}
| true
|
95d3df49be507f56bc74624c773a6c23007311f9
|
Swift
|
vanessa-bergen/WorkOut
|
/client/WorkOut/ScheduleView.swift
|
UTF-8
| 2,660
| 2.8125
| 3
|
[] |
no_license
|
//
// ScheduleView.swift
// WorkOut
//
// Created by Vanessa Bergen on 2020-06-17.
// Copyright © 2020 Vanessa Bergen. All rights reserved.
//
import SwiftUI
import EventKitUI
struct ScheduleView: View {
@EnvironmentObject var savedWorkouts: Workouts
@State private var selectedWorkout: Workout?
@State private var showingDropDown = false
@State private var isShowing = false
@State private var accessGranted = false
@State private var noAccess = false
var body: some View {
GeometryReader { geo in
VStack {
Text("Select Workout To Add To Calender")
DropDownView(selectedItem: self.$selectedWorkout, showingDropDown: self.$showingDropDown)
.frame(height: self.showingDropDown ? geo.size.height/2 : geo.size.height/7)
Button(action: {
self.isShowing.toggle()
}){
Text("Add to calendar")
.buttonStyle()
}
}
}
.onAppear(perform: self.schedule)
.sheet(isPresented: self.$isShowing) {
EKEventWrapper(isShowing: self.$isShowing, workout: self.selectedWorkout)
}
.alert(isPresented: self.$noAccess) {
Alert(
title: Text("No Access To Calendar"),
message: Text("Go to settings to allow access to calendar."),
dismissButton: .default(Text("Ok")))
}
}
func schedule() {
let status = EKEventStore.authorizationStatus(for: EKEntityType.event)
switch (status) {
case EKAuthorizationStatus.notDetermined:
requestAccessToCalendar()
case EKAuthorizationStatus.authorized:
accessGranted = true
case EKAuthorizationStatus.restricted, EKAuthorizationStatus.denied:
self.noAccess = true
@unknown default:
return
}
}
func requestAccessToCalendar() {
eventStore.requestAccess(to: EKEntityType.event, completion: {
(accessGranted: Bool, error: Error?) in
if accessGranted == true {
DispatchQueue.main.async(execute: {
self.accessGranted = true
})
} else {
DispatchQueue.main.async(execute: {
self.accessGranted = false
})
}
})
}
}
struct ScheduleView_Previews: PreviewProvider {
static var previews: some View {
ScheduleView()
}
}
| true
|
8dd242daa45c03f8b4e139eda355dabc1a030512
|
Swift
|
vivekraideveloper/ProductHunt
|
/Product Hunt/Controller/PostsVC.swift
|
UTF-8
| 5,850
| 2.5625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Product Hunt
//
// Created by Vivek Rai on 18/04/19.
// Copyright © 2019 Vivek Rai. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import SDWebImage
import SVProgressHUD
import AlamofireImage
class PostsVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: - Properties
var postsData = [PostsDataModel]()
var filteredPostData = [PostsDataModel]()
var inSearchMode = false
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var postTableView: UITableView!
// MARK: - Init
override func viewDidLoad() {
super.viewDidLoad()
postTableView.delegate = self
postTableView.dataSource = self
postTableView.tableFooterView = UIView(frame: .zero)
postTableView.rowHeight = 350
searchBar.delegate = self
searchBar.returnKeyType = UIReturnKeyType.done
fetchPosts(url: baseURL)
postTableView.reloadData()
}
// MARK: - Networking
func fetchPosts(url: String){
SVProgressHUD.show()
let parameters: Parameters = ["access_token": accessToken]
Alamofire.request(url, method : .get, parameters : parameters).responseJSON{
response in
if response.result.isSuccess{
print("Success! Got the posts data")
let postsJSON : JSON = JSON(response.result.value!)
for i in 0..<postsJSON["posts"].count{
let name = postsJSON["posts"][i]["name"].stringValue
let tagLine = postsJSON["posts"][i]["tagline"].stringValue
let commentCount = postsJSON["posts"][i]["comments_count"].intValue
let imageUrl = postsJSON["posts"][i]["thumbnail"]["image_url"].stringValue
let postId = postsJSON["posts"][i]["id"].stringValue
let userId = postsJSON["posts"][i]["user"]["id"].stringValue
let data = PostsDataModel(name: name, tagLine: tagLine, commentCount: commentCount, imageUrl: imageUrl, userId: userId, postId: postId)
self.postsData.append(data)
self.postTableView.reloadData()
SVProgressHUD.dismiss()
}
}else{
print("Error: \(String(describing: response.result.error))")
SVProgressHUD.dismiss()
return
}
}
}
// MARK: - UITableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if inSearchMode{
return filteredPostData.count
}
return postsData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PostsCell
var data = postsData[indexPath.row]
if inSearchMode{
data = filteredPostData[indexPath.row]
}
cell.nameLabel.text = data.name
cell.tagLineLabel.text = data.tagLine
cell.commentCountLabel.text = String(data.commentCount)
cell.downloadImage(withUrlString: data.imageUrl)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "comments", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "comments"{
let destinationVC = segue.destination as! CommentsVC
var data = postsData[(postTableView.indexPathForSelectedRow?.row)!]
if inSearchMode{
data = filteredPostData[(postTableView.indexPathForSelectedRow?.row)!]
}
destinationVC.user_id = data.userId
destinationVC.post_id = data.postId
}
}
// MARK: - FilterButton
@IBAction func filterButtonPressed(_ sender: Any) {
let alertVC = UIAlertController(title: "Product Hunt", message: "Enter the number of days before you want to see the posts", preferredStyle: .alert)
alertVC.addTextField { textField in
}
let okAction = UIAlertAction(title: "OK", style: .default) { action in
self.postsData.removeAll()
self.filteredPostData.removeAll()
if let textField = alertVC.textFields?.first,
let days = textField.text {
let filteredUrl = "https://api.producthunt.com/v1/categories/tech/posts?days_ago=\(days)"
self.fetchPosts(url: filteredUrl)
self.postTableView.reloadData()
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { action in
}
alertVC.addAction(okAction)
alertVC.addAction(cancelAction)
self.present(alertVC, animated: true, completion: nil)
}
}
// MARK: - UISearchBar
extension PostsVC: UISearchBarDelegate{
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
view.endEditing(true)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == ""{
inSearchMode = false
postTableView.reloadData()
view.endEditing(true)
}else{
inSearchMode = true
let text = searchBar.text!
filteredPostData = postsData.filter({$0.name.range(of: text) != nil || $0.tagLine.range(of: text) != nil})
postTableView.reloadData()
}
}
}
| true
|
2a9e03e4ca4714177fa68ee9560b62b033c1c2f7
|
Swift
|
WilliamPring/Party-Planner-IOS
|
/MyPartyPlanner/GeoCodeAPI.swift
|
UTF-8
| 1,284
| 3.09375
| 3
|
[] |
no_license
|
//
// GeoCodeAPI.swift
// MyPartyPlanner
//
// Created by Student on 2017-12-19.
// Copyright © 2017 Student. All rights reserved.
//
/*
Filename: GeoCodeAPI.swift
By: Naween M, William P, Denys P
Assignment: Assignment 3 Mobile iOS
Date: December 2, 2017
Description: This is for the RESTful API call to Google's Geocoding services so that
the program can retrieve the geographical coordinates of a particular location
*/
import Foundation
struct GeoCodeAPI {
private static let baseURLString = "https://maps.googleapis.com/maps/api/geocode/json?"
private static let APIKey = "AIzaSyD6TQPhIv8s9YNnFTnBkyIjJQT9t0yF9DQ"
static let session: URLSession = {
let config = URLSessionConfiguration.default
return URLSession(configuration: config)
}()
static func getGeoCodeGoogleURL(cityName: String) -> URL {
var components = URLComponents(string: baseURLString)!
var queryItems = [URLQueryItem]()
let baseParams = [
"address": cityName,
"key": APIKey,
]
for (key, value) in baseParams {
queryItems.append(URLQueryItem(name: key, value: value))
}
components.queryItems = queryItems
return components.url!
}
}
| true
|
3249d0d3ab4679e8128def41008c57926c16d17f
|
Swift
|
Kit123456789/StandardAlgorithms
|
/StandardAlgorithmsTests/SortingTest.swift
|
UTF-8
| 1,836
| 3.171875
| 3
|
[] |
no_license
|
//
// SortingTest.swift
// StandardAlgorithmsTests
//
// Created by Ropner, Kit (NA) on 13/11/2020.
//
import XCTest
class SortingTest: XCTestCase {
func testBubbleSortWithIntegerArrayReturnsSortedArray(){
//arrange
let sorting = Sorting()
let expected = [1,3,5,8]
//act
let result = sorting.bubbleSort(data: [5,1,8,3])
//assert
XCTAssertEqual(result, expected)
}
func testBubbleSortWithVariousIntegerArraysReturnsEachOneSorted(){
//arrange
let sorting = Sorting()
let testData = [(data: [6,4,1,2,9], expected: [1,2,4,6,9]), (data: [1,100,4,3,15], expected: [1,3,4,15,100]), (data: [], expected: [])]
//act
for test in testData{
let result = sorting.bubbleSort(data: test.data)
XCTAssertEqual(result, test.expected)
}
}
/* func testMergeSortWithIntegerArrayReturnsSortedArray(){
//arrange
let sorting = Sorting()
let expected = [1,3,4,5,6,10,13,32]
//act
let result = sorting.mergeSort(data: [5,4,3,6,32,10,1,13])
//assert
XCTAssertEqual(result, expected)
}
func testQuickSortWithIntegerArrayReturnsSortedArray(){
//arrange
let sorting = Sorting()
let expected = [2,3,5,7,9]
//act
let result = sorting.quickSort(data: [7,3,9,2,5])
//assert
XCTAssertEqual(result, expected)
}
*/
func testInsertionSortWithIntegerArrayReturnsSortedArray(){
//arrange
let sorting = Sorting()
let expected = [2,4,6,8,10,12]
//act
let result = sorting.insertionSort(data: [2,8,12,4,10,6])
//assert
XCTAssertEqual(result, expected)
}
}
| true
|
380b314fac81f3bfbf956a33d70448a99ceb006d
|
Swift
|
gilserrap/bitrise-api-client
|
/Bitrise/Classes/OpenAPIs/Models/V0SSHKeyUploadParams.swift
|
UTF-8
| 1,129
| 2.59375
| 3
|
[] |
no_license
|
//
// V0SSHKeyUploadParams.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public struct V0SSHKeyUploadParams: Codable {
/** The private part of the SSH key you would like to use */
public var authSshPrivateKey: String
/** The public part of the SSH key you would like to use */
public var authSshPublicKey: String
/** If it's set to true, the provided SSH key will be registered at the provider of the application */
public var isRegisterKeyIntoProviderService: Bool?
public init(authSshPrivateKey: String, authSshPublicKey: String, isRegisterKeyIntoProviderService: Bool? = nil) {
self.authSshPrivateKey = authSshPrivateKey
self.authSshPublicKey = authSshPublicKey
self.isRegisterKeyIntoProviderService = isRegisterKeyIntoProviderService
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case authSshPrivateKey = "auth_ssh_private_key"
case authSshPublicKey = "auth_ssh_public_key"
case isRegisterKeyIntoProviderService = "is_register_key_into_provider_service"
}
}
| true
|
5c272ae500e77a651635b7e99ea79cc1b593d327
|
Swift
|
EricDavenport/ZooAnimalsInClass
|
/ZooAnimals/BasicAnimalCellController.swift
|
UTF-8
| 1,817
| 2.90625
| 3
|
[] |
no_license
|
//
// BasicAnimalCellController.swift
// ZooAnimals
//
// Created by Eric Davenport on 11/19/19.
// Copyright © 2019 Alex Paul. All rights reserved.
//
import UIKit
class BasicAnimalCellController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var animals = [ZooAnimal]() {
didSet { // property observer - when property gets set 9 when animals is set ) - reload the tableView
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
loadDate()
}
func loadDate() {
animals = ZooAnimal.zooAnimals
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let detailVC = segue.destination as? AnimalDetailViewController,
let indexPath = tableView.indexPathForSelectedRow else {
fatalError("Unable to segue in BasicAnimalViewController")
}
let animal = animals[indexPath.row]
detailVC.animal = animal
}
}
extension BasicAnimalCellController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return animals.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "animalCell", for: indexPath)
// get current animal
let animal = animals[indexPath.row]
// configure cell to be "subtitle"
cell.textLabel?.text = animal.name
cell.detailTextLabel?.text = animal.origin
cell.imageView?.image = UIImage(named: animal.imageNumber.description)
return cell
}
}
| true
|
d0d237cf93733eb748211075ae764299aff247e6
|
Swift
|
georgid/tune_puzzle
|
/Example/PieceView.swift
|
UTF-8
| 716
| 2.9375
| 3
|
[] |
no_license
|
//
// PieceView.swift
// Example
//
// Created by Lucas Coelho on 1/29/17.
// Copyright © 2017 NSHint. All rights reserved.
//
import UIKit
class PieceView: UIView {
var piece: Piece!
override func draw(_ rect: CGRect) {
let height: CGFloat = 3
for note in piece.notes {
let xOrigin = rect.size.width * note.initialTime
let width = rect.size.width * note.finalTime - xOrigin
let yOrigin = rect.size.height - (rect.size.height * note.pitch)
let noteView = UIView(frame: CGRect(x: xOrigin, y: yOrigin, width: width, height: height))
noteView.backgroundColor = .white
addSubview(noteView)
}
}
}
| true
|
ff642298facebd46e73bb65d475ed5e87c64dc07
|
Swift
|
mohsinalimat/ScrollableSegmentedControl
|
/ScrollableSegmentedControlTests/ScrollableSegmentedControlTests.swift
|
UTF-8
| 3,147
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// ScrollableSegmentedControlTests.swift
// ScrollableSegmentedControlTests
//
// Created by Goce Petrovski on 10/11/16.
// Copyright © 2016 Pomarium. All rights reserved.
//
import XCTest
@testable import ScrollableSegmentedControl
class ScrollableSegmentedControlTests: XCTestCase {
let segmentedControl = ScrollableSegmentedControl()
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testNumberOfSegements() {
segmentedControl.insertSegment(withTitle: "segment 1", image: nil, at: 0)
segmentedControl.insertSegment(withTitle: "segment 2", image: nil, at: 0)
XCTAssertTrue(segmentedControl.numberOfSegments == 2, "Number of segments should be 2")
segmentedControl.removeSegment(at: 0)
XCTAssertTrue(segmentedControl.numberOfSegments == 1, "Number of segments should be 1")
}
func testSegementTitleContent() {
segmentedControl.insertSegment(withTitle: "segment 1", image: nil, at: 0)
segmentedControl.insertSegment(withTitle: "segment 3", image: nil, at: 1)
segmentedControl.insertSegment(withTitle: "segment 4", image: nil, at: 2)
segmentedControl.insertSegment(withTitle: "segment 2", image: nil, at: 1)
XCTAssertNotNil(segmentedControl.titleForSegment(at: 2))
XCTAssert(segmentedControl.titleForSegment(at:2)?.compare("segment 3") == ComparisonResult.orderedSame, "Title should be segment 3")
XCTAssertNotNil(segmentedControl.titleForSegment(at:-1))
XCTAssert(segmentedControl.titleForSegment(at:-1)?.compare("segment 1") == ComparisonResult.orderedSame, "Title should be segment 1")
XCTAssertNotNil(segmentedControl.titleForSegment(at:99))
XCTAssert(segmentedControl.titleForSegment(at:99)?.compare("segment 4") == ComparisonResult.orderedSame, "Title should be segment 4")
segmentedControl.removeSegment(at: 3)
XCTAssert(segmentedControl.titleForSegment(at:99)?.compare("segment 3") == ComparisonResult.orderedSame, "Title should be segment 3")
}
func testInternalNumberOfSegements(){
segmentedControl.insertSegment(withTitle: "segment 1", image: nil, at: 0)
segmentedControl.insertSegment(withTitle: "segment 2", image: nil, at: 1)
segmentedControl.insertSegment(withTitle: "segment 3", image: nil, at: 2)
let collectionView = segmentedControl.subviews[0] as? UICollectionView
XCTAssertNotNil(collectionView)
XCTAssert(collectionView?.numberOfSections == 1)
XCTAssert(collectionView?.numberOfItems(inSection: 0) == 3)
}
// func testPerformanceExample() {
// // This is an example of a performance test case.
// self.measure {
// // Put the code you want to measure the time of here.
// }
// }
}
| true
|
877ee703301c321cc9e369d78146f06c134e79c0
|
Swift
|
Snorfermino/carpo-driver
|
/carpo_driver/Model/MapView/CGDriverMarker.swift
|
UTF-8
| 683
| 2.671875
| 3
|
[] |
no_license
|
//
// CGDriverMarker.swift
// Rider
//
// Created by Đinh Anh Huy on 11/23/16.
// Copyright © 2016 Đinh Anh Huy. All rights reserved.
//
import UIKit
class CGDriverMarker: CGMarker {
convenience init(map: CGMapView, image: UIImage) {
self.init()
self.map = map
icon = UIImage(data: UIImagePNGRepresentation(image)!, scale: 2)
groundAnchor = CGPoint(x: 0.5, y: 0.5)
}
func changeSize(size : CGFloat) {
icon = icon?.resizeImage(newWidth: size)
}
func scaleSize(image: UIImage, size : CGFloat) {
icon = UIImage(data: UIImagePNGRepresentation(image)!, scale: CGFloat(size))
}
}
| true
|
befd3b59e606d03fa6955a9395e9b4aca5459a38
|
Swift
|
krantireddyp/sapient
|
/Lowe/Weather/Views/TemperatureListTableViewCell.swift
|
UTF-8
| 855
| 2.75
| 3
|
[] |
no_license
|
//
// TemperatureListTableViewCell.swift
// Lowe
//
//
import UIKit
class TemperatureListTableViewCell: UITableViewCell {
@IBOutlet weak var weatherLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
static var nib: UINib {
return UINib(nibName: identifier, bundle: nil)
}
static var identifier: String {
return String(describing: self)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func updateUI(list : List?) {
weatherLabel.text = list?.weather?.first?.main ?? ""
temperatureLabel.text = "\(list?.main?.temp ?? 0.0)"
}
}
| true
|
1db88b4d7f748c6449e73f3bae5526b2e87188ec
|
Swift
|
Subhra-iOS/SwiftUIDemo
|
/SwiftUIDemo/LandmarkList.swift
|
UTF-8
| 1,271
| 2.875
| 3
|
[] |
no_license
|
//
// LandmarkList.swift
// SwiftUIDemo
//
// Created by Subhra Roy on 25/10/19.
// Copyright © 2019 Subhra Roy. All rights reserved.
//
import SwiftUI
struct LandmarkList: View {
@EnvironmentObject private var userData : UserData
var body: some View {
NavigationView{
List {
Toggle(isOn: $userData.showFavoriteOnly) {
Text("Favorites only")
}
ForEach(self.userData.landmarks){ landmark in
if !self.userData.showFavoriteOnly || landmark.isFavorite {
NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
}
} .navigationBarTitle("Landmarks")
}
}
}
struct LandmarkList_Previews: PreviewProvider {
static var previews: some View {
ForEach(["iPhone 11 Pro Max"], id: \.self) { deviceName in
LandmarkList()
.previewDevice(PreviewDevice(rawValue: deviceName))
.previewDisplayName(deviceName)
}
.environmentObject(UserData())
}
}
| true
|
383248ad2f356b75a47170aaaa5aa0ade685b08f
|
Swift
|
dotuian/iOSSample
|
/PhotoAlbum/PhotoAlbum/controller/PhotoMainViewController.swift
|
UTF-8
| 12,635
| 2.53125
| 3
|
[] |
no_license
|
//
// PhotoViewController.swift
// PhotoAblum
//
// Created by 鐘紀偉 on 15/3/3.
// Copyright (c) 2015年 鐘紀偉. All rights reserved.
//
import UIKit
import CoreData
class PhotoMainViewController: UITableViewController {
let identifier = "photoIdentifier"
var items = [AlbumEntity]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "相册"
self.navigationItem.rightBarButtonItem = self.editButtonItem()
// 添加相册
let addAblumItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "handlerAddAblum")
self.navigationItem.leftBarButtonItem = addAblumItem
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// 每次页面重新载入时,重新加载数据
self.items.removeAll(keepCapacity: true)
// 查询数据
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
if let managedObjectContext = appDelegate.managedObjectContext {
// 查询的对象
let entityDiscription = NSEntityDescription.entityForName("AlbumEntity", inManagedObjectContext: managedObjectContext)
// 查询的请求
let fetchRequest = NSFetchRequest()
fetchRequest.entity = entityDiscription
// 排序
let sortDescriptor = NSSortDescriptor(key: "level", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
var error : NSError? = nil
// 查询获取数据
if var results = managedObjectContext.executeFetchRequest(fetchRequest, error: &error) {
// 遍历数据
for managedObject in results {
let userModel = managedObject as AlbumEntity
self.items.append(userModel)
}
}
}
self.tableView.reloadData()
}
func handlerAddAblum(){
let controller = UIAlertController(title: "新建相册", message: "请输入新建相册的名字!", preferredStyle: UIAlertControllerStyle.Alert)
// 用户名输入框
controller.addTextFieldWithConfigurationHandler({ (usernameTextField : UITextField!) -> Void in
usernameTextField.placeholder = "相册名"
})
// 新建相册
let addAblum = UIAlertAction(title: "新建", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
// 获取AlertController中文本框的数据
let albumName = (controller.textFields?[0] as UITextField).text
// 更新数据
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
if let managedObjectContext = appDelegate.managedObjectContext {
// 查询的对象
let entityDiscription = NSEntityDescription.entityForName("AlbumEntity", inManagedObjectContext: managedObjectContext)
// 查询的请求
let fetchRequest = NSFetchRequest()
fetchRequest.entity = entityDiscription
var error : NSError? = nil
// 获取既存数据的件数
var count = managedObjectContext.countForFetchRequest(fetchRequest, error: &error)
// 添加数据
let managedObject: AnyObject = NSEntityDescription.insertNewObjectForEntityForName("AlbumEntity", inManagedObjectContext: managedObjectContext)
let albumEntity = managedObject as AlbumEntity
albumEntity.albumName = albumName
albumEntity.albumType = "PHOTO"
albumEntity.level = count + 1
// 新建相册文件夹
FileUtils.createDirectory(albumName)
// 刷新页面的数据
self.items.append(albumEntity)
let indexPath = NSIndexPath(forRow: self.items.count - 1, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
}
// 数据持久化保存
appDelegate.saveContext()
})
// 取消新建相册
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})
controller.addAction(addAblum)
controller.addAction(cancelAction)
self.presentViewController(controller, animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.items.count
}
// 渲染UICollectionViewCell的内容
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier") as? UITableViewCell
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: self.identifier)
}
// 当前相册信息
let albumEntity = self.items[indexPath.row]
// 当前相册路径
let albumPath = FileUtils.getFullPathWithAlbum(albumEntity.albumName)
println("相册路径:\(albumPath)")
// 当前相册封面
let albumImageName = FileUtils.getFirstFileNameInDirectory(albumPath)
println("封面文件名:\(albumImageName)")
// 配置UICollectionViewCell的显示
var image : UIImage!
if albumImageName != nil {
image = UIImage(named: albumImageName!)
} else {
image = UIImage(named: "keep_dry-50.png")
}
cell!.imageView?.image = image
if image != nil {
let widthScale = 75 / image.size.width
let heightScale = 75 / image.size.height;
cell!.imageView?.transform = CGAffineTransformMakeScale(widthScale, heightScale);
// // 当子视图超出了父视图的大小时,超出的部分被剪切掉
// cell!.imageView?.clipsToBounds = true
// cell!.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
// cell!.imageView?.autoresizingMask = UIViewAutoresizing.None
}
// 相册名
cell!.textLabel?.text = albumEntity.albumName
// 相册中照片的个数
cell!.detailTextLabel?.text = String(FileUtils.getFileNamesWithAlbumName(albumEntity.albumName).count)
return cell!
}
// UITableView是否可以编辑
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
// 处理编辑UITableView
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// 删除UITableViewCell
if editingStyle == .Delete {
let model = self.items[indexPath.row]
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
if let managedObjectContext = appDelegate.managedObjectContext {
let entityDiscription = NSEntityDescription.entityForName("AlbumEntity", inManagedObjectContext: managedObjectContext)
let fetchRequest = NSFetchRequest()
fetchRequest.entity = entityDiscription
let predicate = NSPredicate(format: "%K = %@ and %K = %@", "albumName", model.albumName, "albumType", model.albumType)
fetchRequest.predicate = predicate
var error: NSError? = nil
if var results = managedObjectContext.executeFetchRequest(fetchRequest, error: &error) {
for managedObject in results {
let albumEntity = managedObject as AlbumEntity
managedObjectContext.deleteObject(albumEntity)
// Delete the row from the data source
self.items.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
// 数据持久化
appDelegate.saveContext()
}
} else if editingStyle == .Insert {
// 添加UITableViewCell
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
// UITableViewCell的高度
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return self.view.bounds.height / 6.0
}
// 点击UITableViewCell的处理
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let photoAlbumController = PhotoAlbumViewController()
photoAlbumController.photoAlbum = self.items[indexPath.row]
self.navigationController?.pushViewController(photoAlbumController, animated: true)
}
// Override to support rearranging the table view.
// 是否可以移动UITabelViewCell
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
var from = self.items[fromIndexPath.row]
var to = self.items[toIndexPath.row]
// 修改数据库中的数据
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
if let managedObjectContext = appDelegate.managedObjectContext {
let entityDescription = NSEntityDescription.entityForName("AlbumEntity", inManagedObjectContext: managedObjectContext)
let fetchRequest = NSFetchRequest()
fetchRequest.entity = entityDescription
let fromPredicate = NSPredicate(format: "%K = %@ and %K = %@ and %K = %@", "albumName", from.albumName, "albumType", from.albumType, "level", from.level as NSObject)
fetchRequest.predicate = fromPredicate
var error:NSError? = nil
var fromEntity : AlbumEntity? = nil
if var results = managedObjectContext.executeFetchRequest(fetchRequest, error: &error) {
for result in results {
fromEntity = result as? AlbumEntity
}
}
let toPredicate = NSPredicate(format: "%K = %@ and %K = %@ and %K = %@", "albumName", to.albumName, "albumType", to.albumType, "level", to.level as NSObject)
fetchRequest.predicate = toPredicate
var toEntity : AlbumEntity? = nil
if var results = managedObjectContext.executeFetchRequest(fetchRequest, error: &error) {
for result in results {
toEntity = result as? AlbumEntity
}
}
if fromEntity != nil && toEntity != nil {
let fromLevel = fromEntity?.level
fromEntity?.level = (toEntity?.level)!
toEntity?.level = fromLevel!
}
appDelegate.saveContext()
}
self.items.removeAtIndex(fromIndexPath.row)
self.items.insert(from, atIndex: toIndexPath.row)
tableView.moveRowAtIndexPath(fromIndexPath, toIndexPath: toIndexPath)
}
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
}
| true
|
eccf1b704a537942cbfb2e8eaaa3c4c31df5b5e4
|
Swift
|
renattoolopes/CleanApp
|
/Main/Decorators/MainQueueDispatchDecorator.swift
|
UTF-8
| 1,174
| 2.859375
| 3
|
[] |
no_license
|
//
// MainQueueDispatchDecorator.swift
// Main
//
// Created by Renato Lopes on 07/10/20.
// Copyright © 2020 Renato Lopes. All rights reserved.
//
import Foundation
import Domain
public final class MainQueueDispatchDecorator<T> {
private let instance: T
public init(_ instance: T) {
self.instance = instance
}
func dispatch(completion: @escaping () -> Void) {
guard Thread.isMainThread else { return DispatchQueue.main.async(execute: completion) }
completion()
}
}
extension MainQueueDispatchDecorator: AddAccount where T: AddAccount {
public func add(account: AddAccountModel, compleiton: @escaping AddAccountResult) {
instance.add(account: account) { [weak self] (result) in
self?.dispatch {
compleiton(result)
}
}
}
}
extension MainQueueDispatchDecorator: Authentication where T: Authentication {
public func auth(with model: AuthenticationModel, completion: @escaping AuthenticationResult) {
instance.auth(with: model) { [weak self] (result) in
self?.dispatch{
completion(result)
}
}
}
}
| true
|
b0da041fbaeaf19cd22a2e71e8e73dd6ef9a131c
|
Swift
|
pablomarcel/CoreDataBudget
|
/BudgetData/BudgetViewController.swift
|
UTF-8
| 1,770
| 2.640625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// BudgetData
//
// Created by Sam Meech-Ward on 2020-06-01.
// Copyright © 2020 meech-ward. All rights reserved.
//
import UIKit
class BudgetViewController: UIViewController {
@IBOutlet weak var budgetTitleTextField: UITextField!
@IBOutlet weak var budgetAmountTextField: UITextField!
@IBOutlet weak var tableView: UITableView!
var budgets: [Any] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func saveNewBudget(_ sender: Any) {
guard let budgetTitle = budgetTitleTextField.text else {
print("Invalid title")
return
}
guard let budgetAmountText = budgetAmountTextField.text else {
print("Invalid amount")
return
}
let budgetAmount = NSDecimalNumber(string: budgetAmountText)
budgetTitleTextField.text = ""
budgetAmountTextField.text = ""
// Save new budget
}
@IBSegueAction func openExpenses(_ coder: NSCoder) -> ExpenseViewController? {
let vc = ExpenseViewController(coder: coder)
guard let indexPath = tableView.indexPathForSelectedRow else {
return vc
}
let budget = budgets[indexPath.row]
vc?.budget = budget
tableView.deselectRow(at: indexPath, animated: true)
return vc
}
}
extension BudgetViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
budgets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let budget = budgets[indexPath.row]
return cell
}
}
| true
|
89e80498ed6d288eeecfba339746c349203bc043
|
Swift
|
ZHCcoder/HHPGNetWork
|
/HHPGNetWork/Classes/Core/PGSpiTarget.swift
|
UTF-8
| 1,748
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// PGSpiTarget.swift
// Alamofire
//
// Created by ios on 2019/6/13.
//
import Moya
import UIKit
/// PGSpiderTarget 是 PGSpider 发出网络请求的配置规则
public protocol PGSpiTarget {
/// 发出网络请求的基础地址字符串,默认返回 PGSpider 中配置的静态变量
var baseURL: String { get }
/// 网络请求的路径字符串
var path: String { get }
/// 网络请求的方式,默认返回get
var method: Moya.Method { get }
/// 网络请求参数
var parameters: [String: Any]? { get }
/// 网络请求头,默认返回 nil
var headers: [String: String]? { get }
/// 日志输出
var logEnable: Bool { get }
}
// MARK: - extensions
extension PGSpiTarget {
public var baseURL: String {
if PGSpiManager.manager.baseUrl == "" {
return self.baseURL
}
return PGSpiManager.manager.baseUrl
}
public var headers: [String: String]? {
return PGSpiManager.config.httpHeaders
}
public var startImmediately: Bool {
return PGSpiManager.config.startImmediately ?? true
}
public var logEnable: Bool {
return PGSpiManager.config.logEnable
}
}
extension PGSpiTarget {
/// 根据当前配置生成 URL
///
/// - Returns: URL: baseURL 生成的 url
/// - Throws: bathURL 或 path 不符合规则
func asURL() throws -> URL {
var base: String = baseURL
if base.count <= 0 {
base = "http://"
}
if let url = URL(string: base) {
return url
} else {
throw PGSpiError.requestException(exception: .invalidURL(baseURL: baseURL, path: path))
}
}
}
| true
|
de978a19541e851fbc96a3062b4eaa06da329429
|
Swift
|
jeremyzj/DLWaterfallLayout
|
/Example/DLCollectionViewWaterfallLayout/DLCollectionViewWaterfallCell.swift
|
UTF-8
| 1,078
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// DLCollectionViewWaterfallCell.swift
// DLCollectionViewWaterfallLayout_Example
//
// Created by magi on 2020/5/17.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import UIKit
class DLCollectionViewWaterfallCell: UICollectionViewCell {
var displayLabel: UILabel?
var displayString: String = ""
override init(frame: CGRect) {
super.init(frame: frame)
self.displayLabel = UILabel(frame: self.bounds)
self.displayLabel?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.displayLabel?.backgroundColor = UIColor.lightGray
self.displayLabel?.textColor = UIColor.white
self.displayLabel?.textAlignment = .center
self.addSubview(self.displayLabel!)
}
func setDisplayString(displayString: String) {
if self.displayString != displayString {
self.displayLabel?.text = displayString
self.displayString = displayString
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
d1691c1d5670f6204e0bec6d848746eab1703f14
|
Swift
|
caiquecharro/TesteSolutisIos
|
/teste/Cells/CellNegativo.swift
|
UTF-8
| 1,118
| 2.859375
| 3
|
[] |
no_license
|
//
// CellNegativo.swift
// teste
//
// Created by caique charro on 01/09/21.
//
import Foundation
import UIKit
class CellNegativa : UITableViewCell {
@IBOutlet weak var mainBackground: UIView!
@IBOutlet weak var shadowLayer: UIView!
@IBOutlet weak var lblDate: UILabel!
@IBOutlet weak var lblValor: UILabel!
@IBOutlet weak var lblDesc: UILabel!
func update(statement: StatementsResponse!){
setCard()
self.lblDesc.text = statement.descricao
self.lblDate.text = Utils.formattedDate(dateString: statement.data!)
self.lblValor.text = Utils.formattedValue(valor: statement.valor!)
}
func setCard() {
if mainBackground != nil {
self.mainBackground.layer.cornerRadius = self.mainBackground.frame.width/35.0
self.mainBackground.layer.masksToBounds = true
self.shadowLayer.layer.cornerRadius = self.shadowLayer.frame.width/35.0
self.shadowLayer.layer.masksToBounds = true
}
}
}
| true
|
ae5050daabe647f9b742c4c0cf3e076e9b1cb1b6
|
Swift
|
Mozzzle/NewsApp
|
/NewsApp/NewsApp/Application/CoordinatorProtocols.swift
|
UTF-8
| 1,111
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
//
// CoordinatorProtocol.swift
// NewsApp
//
// Created by Zagorovsky, Artem on 9/16/20.
// Copyright © 2020 Artem Zagorovski. All rights reserved.
//
import UIKit
protocol DetailsShowable {
var viewController: UIViewController? { get }
func showDetails(with viewModel: NewsViewModel)
}
extension DetailsShowable {
func showDetails(with viewModel: NewsViewModel) {
let newsDetailsCoordinator = NewsDetailsCoordinator()
let newsDetailsViewController = newsDetailsCoordinator.createViewController(with: viewModel)
viewController?.navigationController?.pushViewController(newsDetailsViewController, animated: true)
}
}
protocol ErrorShowable {
var viewController: UIViewController? { get }
func showAnError(error: Error)
}
extension ErrorShowable {
func showAnError(error: Error) {
let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alert.addAction(cancelAction)
viewController?.present(alert, animated: true)
}
}
| true
|
8c8f26b484420abd483b80ce161245b4ba946020
|
Swift
|
imdkhairul/DataStructure
|
/Contents.swift
|
UTF-8
| 4,639
| 3.765625
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
public struct Queue<T> {
fileprivate var array = [T]()
public var isEmpty: Bool {
return array.isEmpty
}
public var count: Int {
return array.count
}
public mutating func enqueue(_ element: T) {
array.append(element)
}
public mutating func dequeue() -> T? {
if isEmpty {
return nil
} else {
return array.removeFirst()
}
}
public var front: T? {
return array.first
}
}
// Binary Search Tree
class BstNode
{
var data = 0
var leftNode:BstNode?
var rightNode:BstNode?
}
func getNewNode(data:Int) -> BstNode
{
let node = BstNode()
node.data = data
return node
}
func insert(root:BstNode?,data:Int) ->BstNode?
{
if root == nil{
return getNewNode(data: data)
}
else if data <= (root?.data)!
{
root?.leftNode = insert(root: root?.leftNode, data: data)
}
else
{
root?.rightNode = insert(root: root?.rightNode, data: data)
}
return root
}
func search(root:BstNode?,data:Int) -> Bool
{
if root == nil
{
return false
}
if data == root?.data
{
return true
}
else if data <= (root?.data)!
{
return search(root: root?.leftNode, data: data)
}
else
{
return search(root: root?.rightNode, data: data)
}
}
func findMin(root:BstNode?) -> BstNode?
{
if root == nil
{
return nil
}
else if (root?.leftNode == nil)
{
return root
}
return findMin(root: root?.leftNode)
}
func findMax(root:BstNode?) -> Int?
{
if root == nil
{
return -1
}
else if (root?.rightNode == nil)
{
return root?.data
}
return findMax(root: root?.rightNode)
}
func findHeight(root:BstNode?) -> Int
{
if root == nil
{
return -1
}
else
{
return max(findHeight(root:root?.leftNode), findHeight(root:root?.rightNode)) + 1
}
}
func deleteNode(root:BstNode?,data:Int) -> BstNode?
{
var root = root
if root == nil
{
return root
}
else if data < (root?.data)!
{
root?.leftNode = deleteNode(root: root?.leftNode, data: data)
}
else if data > (root?.data)!
{
root?.rightNode = deleteNode(root: root?.rightNode, data: data)
}
else
{
// Case 1: No child
if root?.leftNode == nil && root?.rightNode == nil
{
root = nil
}
// Case 2: One child
else if root?.leftNode == nil
{
var temp = root
root = root?.rightNode
temp = nil
}
else if root?.rightNode == nil
{
var temp = root
root = root?.leftNode
temp = nil
}
else{
let temp = findMin(root: root?.rightNode)
root?.data = (temp?.data)!
root?.rightNode = deleteNode(root: root?.rightNode, data: (temp?.data)!)
}
}
return root
}
func levelOrder(root:BstNode?)
{
if root == nil
{
return
}
var queue:Queue<BstNode> = Queue.init()
queue.enqueue(root!)
while(!queue.isEmpty)
{
let node = queue.front
print((node?.data)!)
if node?.leftNode != nil
{
queue.enqueue((node?.leftNode)!)
}
if node?.rightNode != nil
{
queue.enqueue((node?.rightNode)!)
}
queue.dequeue()
}
}
func preOrderTraverSal(root:BstNode?)
{
if root == nil
{
return
}
print((root?.data)!)
preOrderTraverSal(root: root?.leftNode)
preOrderTraverSal(root: root?.rightNode)
}
func inOrderTraversal(root:BstNode?)
{
if root == nil
{
return
}
inOrderTraversal(root: root?.leftNode)
print((root?.data)!)
inOrderTraversal(root: root?.rightNode)
}
func postOrderTraversal(root:BstNode?)
{
if root == nil
{
return
}
postOrderTraversal(root: root?.leftNode)
postOrderTraversal(root: root?.rightNode)
print((root?.data)!)
}
var root:BstNode? = nil
root = insert(root: root, data: 50)
root = insert(root: root, data: 20)
root = insert(root: root, data: 10)
root = insert(root: root, data: 60)
root = insert(root: root, data: 70)
root = insert(root: root, data: 80)
search(root: root, data: 110)
findMin(root: root)
findMax(root: root)
inOrderTraversal(root: root)
findHeight(root: root)
deleteNode(root: root, data: 50)
levelOrder(root: root)
| true
|
40f65de695be2012092c21d38ab95a51a236072e
|
Swift
|
apple/swift
|
/validation-test/compiler_crashers_2_fixed/issue-54913.swift
|
UTF-8
| 1,357
| 2.8125
| 3
|
[
"Apache-2.0",
"Swift-exception"
] |
permissive
|
// RUN: %target-swift-frontend -emit-ir %s
// https://github.com/apple/swift/issues/54913
protocol Dismissable {
func dismiss(completion: @escaping () -> Void)
}
typealias Completion = (Dismissable?) -> Void
protocol Cancelable: AnyObject {
func cancel()
}
protocol Controller {
func asyncThing(completion: @escaping ((_ error: Error) -> Void)) -> Cancelable
}
public struct Message: Equatable {
public static let `default` = Message()
public init() {
}
public init(error: Error) {
self = .default
}
}
struct PresentAlert {
let message: Message
}
class Manager {
private let controller: Controller
init(controller: Controller) {
self.controller = controller
}
func present() {
let _: Completion = { (dismissable: Dismissable?) in
dismissable?.dismiss { [weak self] in
guard let sself = self else { return }
sself.controller.asyncThing { error in
let backupMessage = Message()
let mainMessage = Message(error: error)
let finalMessage = mainMessage != Message.default ? mainMessage : backupMessage
_ = PresentAlert(message: finalMessage)
}.cancel()
}
}
}
}
| true
|
e82a639b2d01a28fd534ab2cf80b4a387c2506fc
|
Swift
|
avorobjov/WeatherDemo
|
/Entities/Sources/Entities/Forecast.swift
|
UTF-8
| 711
| 3.453125
| 3
|
[] |
no_license
|
import Foundation
public struct Forecast {
public let city: String
public let timeZone: TimeZone
public let items: [ForecastItem]
public init(city: String, timeZone: TimeZone, items: [ForecastItem]) {
self.city = city
self.timeZone = timeZone
self.items = items
}
}
public struct ForecastItem {
public let date: Date
public let temperature: Double
public let weatherConditionId: Int
public let isDay: Bool
public init(date: Date, temperature: Double, weatherConditionId: Int, isDay: Bool) {
self.date = date
self.temperature = temperature
self.weatherConditionId = weatherConditionId
self.isDay = isDay
}
}
| true
|
5998e5f6aed592bf7f8ddc92c80d150d0e671ad3
|
Swift
|
fishmanlol/jokes
|
/jokes/Extensions/UIBarButtonItem.swift
|
UTF-8
| 598
| 2.6875
| 3
|
[] |
no_license
|
//
// UIBarButtonItem.swift
// jokes
//
// Created by tongyi on 2018/5/2.
// Copyright © 2018年 tongyi. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
class func itemWith(image: UIImage, highlightedImage: UIImage?, target: UIViewController, action: Selector) -> UIBarButtonItem {
let button = UIButton()
button.setBackgroundImage(image, for: .normal)
button.setBackgroundImage(highlightedImage, for: .highlighted)
button.addTarget(target, action: action, for: .touchUpInside)
return UIBarButtonItem(customView: button)
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.