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
15865e45e31bdc818422de189e0fef25d117efaf
Swift
boogoogle/learn
/ios/swift-playground.swift
UTF-8
5,112
4.21875
4
[]
no_license
import UIKit var str = "Hello, playground" let d: Double = 70 // 70.0 let f = 70 // 70 let fl: Float = 70 // 70.0 //print(d, f, fl) // 值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型,请显式转换。 let label = "the width is " let width = 34 let withLabel = label + String(width) let wl2 = label + "\(width)" //print(wl2) // 使用[]来创建数组和字典 var shoppingList = ["catfish", "water", "tulips", "blue paint"] var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] // 空数组或者字典,使用初始化语法。()表示初始化 let emptyArray = [String]() let empayDictionary = [String: Float]() // for in 遍历字典 //for key in shoppingList { // print(key) //} for(key,value) in occupations { // print(key, value) } // 条件&循环 let individualScores = [75, 43, 103, 87, 12] var teamScore = 0 var level = "Try again" for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } // 使用switch switch score { case 100: level = "Perfect!" case 80..<100: level = "Good" case 60..<80: level = "Not bad" default: level = "Come on" } // guard func sth(_ num: Int){ print("Start..") guard num > 10 else { print("小于10") return } } // Loops for i in 0...4 { print(i) } for i in 0..<5 { // do sth } // 如果你给by参数一个负数的话,那么stride就可以实现倒着数的功能。 for i in stride(from: 0, to: 10, by: 2) { print(i) } //print(teamScore) // 使用while循环 var n = 2 while n < 100 { n = n * 2 } // 或者 repeat { n += 2 } while n < 100 // print(n) //..< 来标识范围,也可以使用传统写法 for i in 0..<4{ // print(i) } // 可选值: 某个变量的值可能是具体的,或者 nil // 在类型后面加上一个问号(?)来标记该变量的值是可选的 var optionalString: String? = "Hello" //print(optionalString == nil) var optionalName: String? = "John Appleseed" var mightNil: String? = nil//"nice" if let name = mightNil { // 通过let来处理值缺失的情况 // 如果mightNil == nil,大括号内的内容就不会执行 print("Hello, \(name)") } // 函数和闭包 func func greet(name:String, day:String) -> String { return "Hello \(name), today is\(day)" } greet(name:"boo", day: "Saturday") // 使用元组: 让一个函数返回多个值,改元组的元素可以用名称或者数字来表示 func calcuteStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int){ var min = scores[0],max=scores[0],sum=0 for s in scores{ if min > s { min = s } if(max < s){ max = s } sum += s } return (min,max,sum) } let scores = [116,252,53,64,35,776,57,998] let res = calcuteStatistics(scores: scores) //print(res.min,res.max,res.sum) // 函数可以带有 **可变个数** 的参数 func sum0(numbers: Int...) -> Int{ var sum = 0 for n in numbers{ sum += n } return sum } // {} 创建一个匿名闭包,使用 in 关键字将参数和返回值乐行声明与包函数体进行分离 let sm = scores.map({ (number: Int) -> Int in let res = 3 * number if(number % 2 == 1) { return 0 } else { return res } }) //print(sm) // 对象和类 // 对象声明 class Shape { var n = 0; var name: String // 使用init来当构造函数 init(name: String) { self.name = name } // 在删除对象之前进行一些清理工作,可以使用deinit创建一个析构函数。 func description() -> String { return "A shape calld \(name) with \(n) sides" } } // 实例 let sp = Shape(name:"四边形") sp.n = 4 //print(sp.description()) // 子类, 通过override来重写父类方法 class RoundShape:Shape{ var radio:Int init(radio:Int, name:String){ self.radio = radio super.init(name:name) // 父类构造器在最后 } override func description() -> String { print("我是\(name),我的半径是\(radio)") return "round" } var perimeter: Double{ get { return Double(radio * 2) } set { // newValue 是新值 radio = Int(newValue / 2) } } } //let rspe = RoundShape(radio:22, name:"圆形") //rspe.description() // //print(rspe.perimeter) // 44.0 //rspe.perimeter = 10 //print(rspe.radio) // 5 // 枚举和结构体 struct Human { var name = "" var age = 0 var height = 0 func introduce() { print("\(name)的年龄是\(age)岁, 身高为\(height)厘米") } } var tonyStark = Human(name: "Iron Man", age: 58, height: 188) //tonyStark.introduce() // 协议和扩展 protocol flyable { func takeOff(speed: Int) } extension Human: flyable { func takeOff(speed: Int) { print("\(name) is flying at \(speed)") } } tonyStark.takeOff(speed: 800) // 泛型
true
4c5acca56d2498d789f581ec00749671c0bc612a
Swift
zacharyhaven82/NasaImage
/NasaImage/Classes/NIImageViewTableViewCell.swift
UTF-8
1,594
2.6875
3
[]
no_license
// // NIImageViewTableViewCell.swift // Nasa Image // // Created by Zachary Haven on 6/2/19. // Copyright © 2019 Zachary Haven. All rights reserved. // import UIKit import SwiftyJSON import WebKit class NIImageViewTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var webView: WKWebView! var videoURL: URL? { didSet { guard let url = videoURL else { return } webView.load(URLRequest(url: url)) } } override func awakeFromNib() { super.awakeFromNib() backgroundColor = .black tintColor = .white videoURL = nil // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setupCell(date: String, count: Int, isTop20: Bool) { self.titleLabel.text = (isTop20 ? "\(count)) " + date : date) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" guard let actualDate = dateFormatter.date(from: date) else { return } NasaImageService.callService(with: actualDate, success: {[weak self] value in let json = JSON(value) print("JSON: \(json)") guard let self = self else { return } if json["media_type"].string == "image", let hdURL = json["url"].string, let url = URL(string: hdURL) { self.videoURL = url } else if json["media_type"].string == "video", let hdURL = json["url"].string, let url = URL(string: hdURL) { self.videoURL = url } }, failure: { error in print(error) }) } }
true
98b457f56efe46b13018f59eb407b6c13a21db70
Swift
spanglerware/Re.Me.Swift.App
/ReminderItem.swift
UTF-8
988
3.046875
3
[]
no_license
// // ReminderItem.swift // Re.Me // // Created by Scott Spangler on 5/16/15. // Copyright (c) 2015 SpanglerWare. All rights reserved. // import Foundation struct ReminderItem { var title: String var alarmTime: NSDate var frequency: String var UUID: String var days: [Bool] var timeFrom: String var timeTo: String var active: Bool init(frequency: String, title: String, UUID: String, days: [Bool], timeFrom: String, timeTo: String) { self.frequency = frequency self.title = title self.UUID = UUID self.days = days self.timeFrom = timeFrom self.timeTo = timeTo //let freqTime: Double = (frequency as NSString).doubleValue * 60 let freqTime = 10.0 alarmTime = NSDate(timeIntervalSinceNow: freqTime) self.active = false } var isOverdue: Bool { return (NSDate().compare(self.alarmTime) == NSComparisonResult.OrderedDescending) } }
true
447e613885df3d7b46caa0e12b7f656de54db86d
Swift
Brojowski/ios-github-browser
/ios-github-browser/FilesTableViewController.swift
UTF-8
1,720
2.578125
3
[]
no_license
// // FilesTableViewController.swift // ios-github-browser // // Created by Alex Gajowski on 4/9/19. // Copyright © 2019 alex. All rights reserved. // import UIKit class FilesTableViewController: UITableViewController { private var _files = [File]() weak var gist: GistSerializable! override func viewDidLoad() { self.navigationItem.title = gist.name Octokit().gist(id: gist.id) {res in switch (res) { case .success(let gist): self._files = Array(gist.files.values) DispatchQueue.main.async{ self.tableView.reloadData() } case .failure(let err): print(err) } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return _files.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "fileIdentifier", for: indexPath) cell.textLabel?.text = _files[indexPath.row].filename return cell } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let codeVC = segue.destination as! CodeViewController codeVC.file = _files[tableView.indexPathForSelectedRow!.row] } }
true
9afd8235a6a31bfa3b01920f3c7105062aff60bf
Swift
alexkotebk/SwiftFlickrSearcher3
/SwiftFlickrSearcher3/PhotoDetailViewController.swift
UTF-8
2,122
2.546875
3
[]
no_license
// // PhotoDetailViewController.swift // SwiftFlickrSearcher3 // // Created by suraj poudel on 27/07/2016. // Copyright © 2016 suraj poudel. All rights reserved. // import Foundation import UIKit class PhotoDetailViewController:UIViewController{ //MARK:- IBOutlets @IBOutlet var photoImageView:UIImageView! @IBOutlet var titleLabel:UILabel! @IBOutlet var userNameLabel:UILabel! @IBOutlet var userAvatarImageView:UIImageView! @IBOutlet var favoriteButton:UIButton! var downloader = FlickrPhotoDownloader.sharedInstance() var photo:Photo? override func viewDidLoad() { super.viewDidLoad() userAvatarImageView.layer.cornerRadius = CGRectGetWidth(userAvatarImageView.frame) / 2 userAvatarImageView.layer.borderWidth = 1 userAvatarImageView.layer.borderColor = UIColor.blackColor().CGColor if let unwrappedPhoto = photo{ configureForPhoto(unwrappedPhoto) } } func configureForPhoto(aPhoto:Photo){ titleLabel.text = aPhoto.title downloader.setImageFromURLString(aPhoto.fullURLString, toImageView: photoImageView) userNameLabel.text = aPhoto.owner.name ?? aPhoto.owner.userID if let iconString = aPhoto.owner.iconURLString{ downloader.setImageFromURLString(iconString, toImageView: userAvatarImageView) }else{ userAvatarImageView.image = UIImage(named: "rwdevcon-logo") } configureFavoriteButtonColorBasedOnPhoto(aPhoto) } func configureFavoriteButtonColorBasedOnPhoto(aPhoto:Photo){ if aPhoto.isFavorite { favoriteButton.tintColor = UIColor.redColor() } else { favoriteButton.tintColor = UIColor.lightGrayColor() } } @IBAction func toggleFavoriteStatus(){ if let unwrappedPhoto = photo{ unwrappedPhoto.isFavorite = !unwrappedPhoto.isFavorite CoreDataStack.sharedInstance().saveMainContext() configureFavoriteButtonColorBasedOnPhoto(unwrappedPhoto) } } }
true
cb10dbe966a57f28590c24bb9705ee1310598cd9
Swift
seanwohc/SWEmptyPlaceHolderView
/SWEmptyPlaceHolderView/ViewController.swift
UTF-8
1,853
2.90625
3
[ "MIT" ]
permissive
// // ViewController.swift // SWEmptyPlaceHolderView // // Created by Sean on 21/12/2020. // import UIKit class ViewController: UIViewController { var array: [String] = ["1", "2", "3", "4", "5"] var swEmptyPlaceHolderView: SWEmptyPlaceHolderView! @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.swEmptyPlaceHolderView = SWEmptyPlaceHolderView() self.view.addFullscreenView(swEmptyPlaceHolderView, bottom: 48) self.swEmptyPlaceHolderView.configureView(image: UIImage(named: "binoculars"), text: "SWEmptyPlaceHolderView") self.setupTableView() self.reloadTable() } func setupTableView() { self.tableView.delegate = self self.tableView.dataSource = self self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } @IBAction func toggleEmptyView(_ sender: UISwitch) { if sender.isOn{ self.array = ["1", "2", "3", "4", "5"] }else{ self.array = [] } self.reloadTable() } func reloadTable() { self.swEmptyPlaceHolderView.isHidden = !self.array.isEmpty self.tableView.reloadData() } } extension ViewController: UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = array[indexPath.row] return cell } }
true
f3d5cbc8a806af5318ad30990e528a878c9ade7c
Swift
CoderDream/Swift_Practice
/Year2018Week44/BasicGrammar_Self.playground/Contents.swift
UTF-8
1,064
4.375
4
[ "MIT" ]
permissive
import Cocoa //self关键字 //Swift中的self和OC中的self基本一样. self指当前对象 //如果self在对象方法中代表当前对象. 但是在类方法中没有self class Person { var name:String = "qbs"; var age:Int = 30; //当参数名称和属性名称一模一样时, //无法区分哪个是参数哪个是属性 //这个时候可以通过self明确的来区分参数和属性 func setName(name:String, age:Int) { //默认情况下, _name和_age前面有一个默认的self关键字, //因为所有变量都需要先定义再使用 //而setName方法中并没有定义过_name和_age, //而是在属性中定义的, 所以setName中访问的其实是属性, //编译器默认帮我们在前面加了一个self. // _name = name; // _age = age; self.name = name; self.age = age; } func show() { print("name = \(name) age = \(age)") } } var p = Person(); p.setName(name: "xy", age: 20); p.show(); //输出结果: name = xy age = 20
true
1aa23b300393eb1ebc709c114afe371d080f7b58
Swift
alexito4/AdventOfCode
/AdventCode2017.playground/Pages/04.xcplaygroundpage/Contents.swift
UTF-8
2,039
3.765625
4
[]
no_license
//: [Previous](@previous) import Foundation var str = "Hello, playground" print(str) //: # Input let content = testData() let list = content.split(separator: "\n") //: # Part 1 func countValidPassphrases(_ list: [String]) -> Int { func isValidPassphrase(_ phrase: String) -> Bool { let words = phrase.split(separator: " ") let originalCount = words.count let nonRepeated = Set(words) let nonRepeatedCount = nonRepeated.count return originalCount == nonRepeatedCount } return list .filter({ isValidPassphrase($0) }) .count } countValidPassphrases(["aa bb cc dd ee"]) ==> 1 countValidPassphrases(["aa bb cc dd aa"]) ==> 0 countValidPassphrases(["aa bb cc dd aaa"]) ==> 1 countValidPassphrases(list.map(String.init)) //: # Part 2 func countValidPassphrases2(_ list: [String]) -> Int { func isValidPassphrase(_ phrase: String) -> Bool { let words = phrase.split(separator: " ").map(String.init) for (i, word) in words.enumerated() { let letters = countLetters(word) for other in words[i.advanced(by: 1)...] { guard word != other else { return false } guard word.count == other.count else { continue } let otherLetters = countLetters(other) if letters == otherLetters { return false } } } return true } return list .filter({ isValidPassphrase($0) }) .count } countValidPassphrases2(["abcde fghij"]) ==> 1 countValidPassphrases2(["abcde xyz ecdab"]) ==> 0 countValidPassphrases2(["a ab abc abd abf abj"]) ==> 1 countValidPassphrases2(["iiii oiii ooii oooi oooo"]) ==> 1 countValidPassphrases2(["oiii ioii iioi iiio"]) ==> 0 countValidPassphrases2(list.map(String.init)) print("DONE") //: [Next](@next)
true
ebaa398e150be8e0d2845bac2e15829190356b3c
Swift
markotl88/FlowrSpot
/FlowrSpot/Scenes/FlowerDetails/FlowerDetailsInteractor.swift
UTF-8
1,270
2.984375
3
[]
no_license
// // FlowerDetailsInteractor.swift // FlowrSpot // // Created by Marko Stajic on 01/05/2020. // Copyright © 2020 PovioLabs. All rights reserved. // import Foundation protocol FlowerDetailsBusinessLogic { func fetchFlower() func fetchFlowerSightings() } class FlowerDetailsInteractor { var flowerId: Int? var presenter: FlowerDetailsPresentationLogic? var getFlowerDetailsWorker = GetFlowerDetailsWorker() var getFlowerSigtingsWorker = GetFlowerSightingsWorker() } // MARK: - Business Logic extension FlowerDetailsInteractor: FlowerDetailsBusinessLogic { func fetchFlower() { guard let flowerId = flowerId else { return } getFlowerDetailsWorker.execute(flowerId: flowerId, success: { (flower) in self.presenter?.presentFlower(flower) }, failure: { error in self.presenter?.presentFlowerError(error) }) } func fetchFlowerSightings() { guard let flowerId = flowerId else { return } getFlowerSigtingsWorker.execute(flowerId: flowerId, success: { (sightings) in self.presenter?.presentSightings(sightings) }, failure: { error in self.presenter?.presentFlowerError(error) }) } }
true
59b91fb3ec792c0a594774b1ae14c36995f79bf5
Swift
mc3747/19_SwiftBase
/1_SwiftBase/2_基础语法(mc).playground/Pages/16_类.xcplaygroundpage/Contents.swift
UTF-8
1,352
4.0625
4
[]
no_license
//: [Previous](@previous) import Foundation //1_类 /* 与结构体相比,类还有如下的附加功能: 继承允许一个类继承另一个类的特征 类型转换允许在运行时检查和解释一个类实例的类型 析构器允许一个类实例释放任何其所被分配的资源 引用计数允许对一个类的多次引用 */ struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? } let tenEighty = VideoMode() tenEighty.interlaced = true tenEighty.name = "1080i" tenEighty.frameRate = 25.0 //2_属性观察器 /* 可以在以下位置添加属性观察器: 自定义的存储属性 继承的存储属性 继承的计算属性 */ //willSet 在新的值被设置之前调用 //didSet 在新的值被设置之后调用 class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { print("将 totalSteps 的值设置为 \(newTotalSteps)") } didSet { if totalSteps > oldValue { print("增加了 \(totalSteps - oldValue) 步") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 stepCounter.totalSteps = 360 stepCounter.totalSteps = 896
true
7f90a5d4cb21dea214a7cf08559da59e5a078c54
Swift
hubertme/Login-HandsOn
/Login-HandsOn/ViewModel/LoginViewModel.swift
UTF-8
1,249
2.921875
3
[]
no_license
// // LoginViewModel.swift // Login-HandsOn // // Created by Hubert Wang on 04/04/2019. // Copyright © 2019 Hubert Wang. All rights reserved. // import Foundation import UIKit import RxSwift class LoginViewModel { // MARK: - Attributes let model: LoginModel = LoginModel() let disposeBag = DisposeBag() // MARK: - Binding attributes let isSuccess: Variable<Bool> = Variable(false) let isLoading: Variable<Bool> = Variable(false) let errorMessage: Variable<String?> = Variable(nil) // MARK: - View models let emailViewModel = EmailViewModel() let passwordViewModel = PasswordViewModel() // MARK: - Methods func validateCredentials() -> Bool { return emailViewModel.validateCredentials() && passwordViewModel.validateCredentials() } func loginUser() { // Initialised model with loaded value model.email = emailViewModel.data.value model.password = passwordViewModel.data.value self.isLoading.value = true // Do all server request here print("Login attempted with email: \(model.email) pass: \(model.password)!") self.isSuccess.value = true self.errorMessage.value = nil } }
true
353bd5ed431b3364a321f45234f9490fc96b5441
Swift
darthpelo/presentations
/mobiquity/mvp_protocol/example/MvprotocolExample/MvprotocolExample/ModelService.swift
UTF-8
1,187
2.921875
3
[ "MIT" ]
permissive
// // ModelService.swift // MvprotocolExample // // Created by Alessio Roberto on 07/02/2017. // Copyright © 2017 Alessio Roberto. All rights reserved. // import Foundation final class ModelService { // Only for demo purpose, it will be a DB or Web API private var model = Model() class var sharedInstance: ModelService { struct Singleton { static let instance = ModelService() } return Singleton.instance } func updateModel(userName: Bool, passWord: Bool, userNameValid isValid: Bool) { model.usernameIsEmpty = userName model.passwordIsEmpty = passWord model.usernameIsValid = isValid } func update(userName: Bool) { model.usernameIsEmpty = userName } func update(passWord: Bool) { model.passwordIsEmpty = passWord } func update(usernameValid: Bool) { model.usernameIsValid = usernameValid } func userName() -> Bool { return model.usernameIsEmpty } func passWord() -> Bool { return model.passwordIsEmpty } func userNameIsValid() -> Bool { return model.usernameIsValid } }
true
91a4046e4f564fa8a79b34156beff123567d0246
Swift
aishaImperialDigital/WageSpoon_iOS
/Wagespoon/Wagespoon/WageSpoonParent/ApplicationBO/Appearance.swift
UTF-8
613
2.546875
3
[]
no_license
// // Appearance.swift // Wagespoon // // Created by gqgnju on 9/08/17. // Copyright © 2017 Developer. All rights reserved. // class Appearance: NSObject { // MARK: Properties public var apearence_id: String? public var apearence_name: String? public var apearence_pic: String? override init() { apearence_id = "" apearence_name = "" apearence_pic = "" } func setAppearance(appearance: Appearance) { apearence_id = appearance.apearence_id apearence_name = appearance.apearence_name apearence_pic = appearance.apearence_pic } }
true
47fd729e9edc4992e285f4347333fb1d14bbbca3
Swift
ashishvpatel123/MemorablePlaces
/MemorablePlaces/ViewController.swift
UTF-8
6,372
2.75
3
[]
no_license
// // ViewController.swift // MemorablePlaces // // Created by IMCS2 on 2/23/19. // Copyright © 2019 IMCS2. All rights reserved. // import UIKit import MapKit import CoreData class LocationInfo { var title : String = "" var discription : String = "" var latitude : Double = 0.0 var longitude : Double = 0.0 init(title: String,discription: String,latitude : Double,longitude: Double) { self.title = title self.discription = discription self.latitude = latitude self.longitude = longitude } } class ViewController: UIViewController , MKMapViewDelegate { var locationInfos = [LocationInfo]() @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() let regionRadius: CLLocationDistance = 1000 //Do any additional setup after loading the view let initialLocation = CLLocation(latitude: 32.900854, longitude: -96.969862) let coordinateRegion = MKCoordinateRegion(center: initialLocation.coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius) mapView.setRegion(coordinateRegion, animated: true) getDataFromCoreData() for location in locationInfos { putAnnaotaionToMap(locationinfo: location) } //added gesture recognizer to the screen let uiLongPress = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressAction(gustureRecognizer:))) uiLongPress.minimumPressDuration = 2.0 mapView.addGestureRecognizer(uiLongPress) } // longPress adding annotation into the map @objc func longPressAction(gustureRecognizer : UIGestureRecognizer){ print("long presed") let touchPoint = gustureRecognizer.location(in: self.mapView) let coordinates = mapView.convert(touchPoint, toCoordinateFrom: self.mapView) alertView(coordinates : coordinates) } // alert view to get location information func alertView(coordinates : CLLocationCoordinate2D){ let alert = UIAlertController(title: "Add Location", message: "Please Enter Title and Discription", preferredStyle: .alert) alert.addTextField { (textFiled ) in textFiled.placeholder = "Title" } alert.addTextField { (textFiled) in textFiled.placeholder = "Discription" } let actionCancle = UIAlertAction(title: "Cancle", style: .destructive, handler: nil) let actionSave = UIAlertAction(title: "Save", style: .default) { (_) in let titleTextField = alert.textFields?[0].text! //print(titleTextField) let subTitleTextField = alert.textFields?[1].text! //print(subTitleTextField) //return (titleTextField,subTitleTextField)] let locationInfo = LocationInfo(title: titleTextField!, discription: subTitleTextField!, latitude: coordinates.latitude, longitude: coordinates.longitude) self.putAnnaotaionToMap(locationinfo: locationInfo) } alert.addAction(actionCancle) alert.addAction(actionSave) self.present(alert, animated: true, completion: nil) } //carating annotaion to map func putAnnaotaionToMap(locationinfo : LocationInfo){ let annotation = MKPointAnnotation() annotation.title = locationinfo.title annotation.subtitle = locationinfo.discription print("iin anotation \(locationinfo.longitude) and \(locationinfo.latitude)") annotation.coordinate = CLLocationCoordinate2D(latitude: locationinfo.latitude,longitude: locationinfo.longitude) saveToCoreData(locationInfo: locationinfo) mapView.addAnnotation(annotation) } //saving to coredatabase func saveToCoreData(locationInfo : LocationInfo) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let entity = NSEntityDescription.entity(forEntityName: "Locations", in: context) let newLocationInfo = NSManagedObject(entity: entity!, insertInto: context) newLocationInfo.setValue(locationInfo.title, forKey: "title") newLocationInfo.setValue(locationInfo.discription, forKey: "discription") newLocationInfo.setValue(locationInfo.longitude, forKey: "longitude") newLocationInfo.setValue(locationInfo.latitude, forKey: "latitude") do { try context.save() print("Data Saved") } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } } func getDataFromCoreData(){ guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return} let managedContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Locations") do { let locations = try managedContext.fetch(fetchRequest) for eachLocation in locations{ print("blog from persistance \(String(describing: eachLocation.value(forKey: "title")))") locationInfos.append(LocationInfo(title: eachLocation.value(forKey: "title") as! String, discription: eachLocation.value(forKey: "discription") as! String, latitude: eachLocation.value(forKey: "latitude") as! Double, longitude: eachLocation.value(forKey: "longitude") as! Double)) // blogsdata.insert(data(title: String(describing: eachBlog.value(forKey: "title")!),content: String(describing: eachBlog.value(forKey: "content")!)) // , at: 0) } print(locationInfos) } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } } }
true
23de6f426ef7e5c2f7650e19458ab43075e36a85
Swift
allensu02/EveryBodyAthletics
/EveryBodyAthletics/Custom Views/Views/EBAWorkoutView.swift
UTF-8
5,328
2.625
3
[]
no_license
// // EBAWorkoutView.swift // EveryBodyAthletics // // Created by Allen Su on 2020/11/28. // Copyright © 2020 Allen Su. All rights reserved. // import UIKit import AVKit import AVFoundation import FirebaseStorage class EBAWorkoutView: UIView { var headerLabel: EBATitleLabel! var nameLabel: EBATitleLabel! var exercise: Exercise! var student: Student! var finishButton: EBAButton! var currentClass: EBAClass! var station: Int! var player: AVPlayer! var videoURL: URL! var playerLayer: AVPlayerLayer! override init(frame: CGRect) { super.init(frame: .zero) configureUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(student: Student, currentClass: EBAClass, station: Int) { super.init(frame: .zero) self.student = student self.currentClass = currentClass self.station = station configureUI() } func configureUI () { configureHeaderLabel() configureNameLabel() configureFinishButton() configureAVPlayer() } func configureHeaderLabel () { headerLabel = EBATitleLabel(textAlignment: .center, fontSize: 50) headerLabel.numberOfLines = 0 headerLabel.text = "Workout of the Day for \(student.name)" self.addSubview(headerLabel) NSLayoutConstraint.activate([ headerLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 40), headerLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 200), headerLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -200), headerLabel.heightAnchor.constraint(equalToConstant: 60) ]) } func configureNameLabel () { nameLabel = EBATitleLabel(textAlignment: .center, fontSize: 50) nameLabel.numberOfLines = 0 nameLabel.text = "Exercise Name" self.addSubview(nameLabel) NSLayoutConstraint.activate([ nameLabel.topAnchor.constraint(equalTo: headerLabel.bottomAnchor, constant: 30), nameLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 200), nameLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -200), nameLabel.heightAnchor.constraint(equalToConstant: 60) ]) } func configureFinishButton () { finishButton = EBAButton(backgroundColor: Colors.red, title: "Finish Workout") finishButton.titleLabel?.font = UIFont(name: Fonts.liberator, size: 40) self.addSubview(finishButton) NSLayoutConstraint.activate([ finishButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -40), finishButton.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 200), finishButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -200), finishButton.heightAnchor.constraint(equalToConstant: 80) ]) } func configureAVPlayer() { let videoPlayer = UIView(frame: .zero) self.addSubview(videoPlayer) videoPlayer.translatesAutoresizingMaskIntoConstraints = false videoPlayer.backgroundColor = .white let backgroundImage = UIImageView(frame: videoPlayer.bounds) backgroundImage.contentMode = .scaleAspectFit videoPlayer.insertSubview(backgroundImage, at: 0) NSLayoutConstraint.activate([ videoPlayer.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 20), videoPlayer.bottomAnchor.constraint(equalTo: finishButton.topAnchor, constant: -30), videoPlayer.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 200), videoPlayer.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -200) ]) let playerView = EBAPlayerView() videoPlayer.addSubview(playerView) playerView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ playerView.leadingAnchor.constraint(equalTo: videoPlayer.leadingAnchor), playerView.trailingAnchor.constraint(equalTo: videoPlayer.trailingAnchor), playerView.heightAnchor.constraint(equalTo: videoPlayer.widthAnchor, multiplier: 16/9), playerView.centerYAnchor.constraint(equalTo: videoPlayer.centerYAnchor) ]) let fileManager = FileManager.default let documentDir = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let localFile = documentDir.appendingPathComponent("downloadedVid.mov") let storageRef = Storage.storage().reference(withPath: "Quick Feet.mov") storageRef.write(toFile: localFile) { (url, error) in if let error = error { print("error: \(error.localizedDescription)") return } if let url = url { self.videoURL = url playerView.play(with: self.videoURL) } } } @objc func dismissKeyboard () { self.endEditing(true) } }
true
ce54798d884b8deba4e0700dc29b6171daa1f0d3
Swift
mihar-22/mylogbook-ios
/Mylogbook/Supervisor.swift
UTF-8
1,881
2.765625
3
[]
no_license
import CoreStore import SwiftyJSON // MARK: Supervisor class Supervisor: NSManagedObject, SoftDeletable, Syncable { var uniqueIDValue: NSNumber { get { return NSNumber(integerLiteral: Int(self.id)) } set(id) { self.id = Int64(truncating: id) } } } // MARK: Image extension Supervisor { enum ImageSize: String { case regular = "" case display = "-display" } func image(ofSize size: ImageSize) -> UIImage { let gender = (self.gender == "M") ? "male" : "female" var name = "supervisor-\(gender)" if isAccredited { name += "-certified" } name += size.rawValue return UIImage(named: name)! } } // MARK: Importable extension Supervisor: Importable { typealias ImportSource = JSON static let uniqueIDKeyPath = "id" func update(from source: JSON, in transaction: BaseDataTransaction) throws { name = source["name"].string! gender = source["gender"].string! isAccredited = source["is_accredited"].bool! updatedAt = source["updated_at"].string!.utc(format: .dateTime) deletedAt = source["deleted_at"].string?.utc(format: .dateTime) } } // MARK: Resourcable extension Supervisor: Resourceable { static let resource = "supervisors" func toJSON() -> [String: Any] { return [ "name": name, "gender": gender, "is_accredited": isAccredited ? 1 : 0 ] } } // MARK: Core Data Properties extension Supervisor { @NSManaged public var id: Int64 @NSManaged public var name: String @NSManaged public var gender: String @NSManaged public var trips: NSSet? @NSManaged public var isAccredited: Bool @NSManaged public var updatedAt: Date @NSManaged public var deletedAt: Date? }
true
b3f33c45cf5942ce13faa6d5a3826deaaccb8bba
Swift
lionsom/XiOS
/Swift/01 Swift基础学习/05 枚举/MyPlayground.playground/Pages/004.嵌套枚举.xcplaygroundpage/Contents.swift
UTF-8
372
3.09375
3
[ "Apache-2.0" ]
permissive
import Foundation enum Character { enum Weapon { case Bow case Sword case Lance case Dagger } enum Helmet { case Wooden case Iron case Diamond } case Thief case Warrior case Knight } let character = Character.Thief let weapon = Character.Weapon.Bow let helmet = Character.Helmet.Iron
true
8e33a03d1a848760d870e3ad1be91330181eebef
Swift
deepal15/Project
/Knockout/Knockout/ViewModels/AddTeamsViewModel.swift
UTF-8
880
2.9375
3
[]
no_license
// // AddTeamsViewModel.swift // Knockout // // import Foundation import CoreData final class AddTeamsViewModel { // MARK: - Properties private var teams: [Team] = [] private var databaseManager: DatabaseManager? // MARK: - Init init(context: NSManagedObjectContext) { databaseManager = DatabaseManager(managedObjectContext: context) } // MARK: - Functions func addTeamToDB(name: String) { databaseManager?.addTeam(name: name) teams = getAllTeamsFromDB() ?? [] } @discardableResult func getAllTeamsFromDB() -> [Team]? { self.teams = databaseManager?.getAllTeams() ?? [] return self.teams } func getNumberOfRows() -> Int { return teams.count } func getTeam(at index: Int) -> Team { return teams[index] } }
true
6ef0583314c5ed12d89bfb0c1e333193b69f0abe
Swift
Balasnest/MovieApp
/PlacesApp/APIHelper/APIHelper.swift
UTF-8
881
2.6875
3
[]
no_license
// // APIHelper.swift // PlacesApp // // Created by Sumit Ghosh on 29/09/18. // Copyright © 2018 Sumit Ghosh. All rights reserved. // import UIKit class APIHelper: NSObject { static let sharedInstance = APIHelper() func getPlaceData(complitionHandler: @escaping(MovieData?,Error?) -> Void) -> Void { let Url = URL(string: "\(NetworkConfiguration.BASE_URL)\(NetworkConfiguration.API_KEY)") URLSessionManager.shared.getRequest(with: Url!) { (data, error) in if error != nil { complitionHandler(nil, error) } else { do { let response = try JSONDecoder().decode(MovieData.self, from: data! as Data) complitionHandler(response, error) } catch let error { print(error) } } } } }
true
285b8d614f07d3ff845f52a0c2fe44f9757ce6b2
Swift
ArtemChaykovsky/GooglePlacesTest
/GooglePlacesTestProject/Model/Network/NetworkService.swift
UTF-8
1,308
2.734375
3
[]
no_license
// // NetworkService.swift // GooglePlacesTestProject // // Created by Artem Chaykovsky on 8/7/17. // Copyright © 2017 Onix-Systems. All rights reserved. // import UIKit import Alamofire let apiKey = "AIzaSyD7MEz0aLK96kC3qB2HZpgPip_W3cYlhm4" let baseUrl = "https://maps.googleapis.com/maps/api/" class NetworkService { static let shared:NetworkService = NetworkService() func fetchPlaces(searchValue:String,completion:@escaping (Result<Any>)->()) { let escaped = searchValue.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" performRequest(url: baseUrl + "place/autocomplete/json?input=\(escaped)&key=\(apiKey)" ) { (result) in completion(result) } } func getPlaceDetais(_ place:Place, completion:@escaping (Result<Any>)->()) { performRequest(url: baseUrl + "place/details/json?placeid=\(place.place_id ?? "")&key=\(apiKey)") { (result) in completion(result) } } fileprivate func performRequest(url:String,completion:@escaping (Result<Any>)->()) { Alamofire.request(url).responseJSON { (response) in completion(response.result) } } func cancelAll() { Alamofire.SessionManager.default.session.getAllTasks { (tasks) in tasks.forEach{$0.cancel() } } } }
true
6729f836227a11b699ce3ef657369507d1bd009a
Swift
AkimuneKawa/PracticeFlux
/PracticeFlux/Flux/ActionCreator.swift
UTF-8
2,193
3.15625
3
[]
no_license
// // ActionCreator.swift // PracticeFlux // // Created by 河明宗 on 2021/01/08. // Copyright © 2021 河明宗. All rights reserved. // import Foundation import GitHub enum Action { case addRepositories([Repository]) case clearRepositories case setSelectedRepository(Repository) case setFavoriteRepositories([Repository]) } final class ActionCreator { private let dispacher: Dispatcher private let apiSession: GitHubApiRequestable private let localCache: LocalCacheable init( dispacher: Dispatcher = .shared, apiSession: GitHubApiRequestable = GitHubApiSession.shared, localCache: LocalCacheable = LocalCache.shared ) { self.dispacher = dispacher self.apiSession = apiSession self.localCache = localCache } } // MARK: Search extension ActionCreator { func searchRepositories(query: String, page: Int) { apiSession.searchRepositories(query: query, page: page) { [dispacher] result in switch result { case let .success((repositories, _)): dispacher.dispatch(.addRepositories(repositories)) case let .failure(error): print(error) } } } func clearRepositories() { dispacher.dispatch(.clearRepositories) } } // MARK: Favorite extension ActionCreator { func addFavoriteRepository(_ repository: Repository) { let repositories = localCache[.favorites] + [repository] localCache[.favorites] = repositories dispacher.dispatch(.setFavoriteRepositories(repositories)) } func removeFavoriteRepository(_ repository: Repository) { let repositories = localCache[.favorites].filter { $0.id != repository.id } localCache[.favorites] = repositories dispacher.dispatch(.setFavoriteRepositories(repositories)) } func loadFavoriteRepositories() { dispacher.dispatch(.setFavoriteRepositories(localCache[.favorites])) } } // MARK: Others extension ActionCreator { func setSearchRepository(_ repository: Repository) { dispacher.dispatch(.setSelectedRepository(repository)) } }
true
fd55f93c1ffb87855b7b70f5a60c3a69571bb62d
Swift
parthjdabhi/nsscreencast
/210-cool-text-effects-part-2/TextEffects/TextEffects/TypingTextEffectView.swift
UTF-8
1,502
2.5625
3
[ "MIT" ]
permissive
// // TypingTextEffectView.swift // TextEffects // // Created by Ben Scheirman on 2/23/16. // Copyright © 2016 NSScreencast. All rights reserved. // import UIKit class TypingTextEffectView : TextEffectView { var letterDuration: NSTimeInterval = 0.25 var letterDelay: NSTimeInterval = 0.1 override func processGlyphLayer(layer: CAShapeLayer, atIndex index: Int) { layer.opacity = 0 layer.fillColor = UIColor.darkGrayColor().CGColor layer.lineWidth = 0 let opacityAnim = CABasicAnimation(keyPath: "opacity") opacityAnim.fromValue = 0 opacityAnim.toValue = 1 opacityAnim.duration = letterDuration let rotateAnim = CABasicAnimation(keyPath: "transform.rotation") rotateAnim.fromValue = -M_PI / 4.0 rotateAnim.toValue = 0 rotateAnim.duration = letterDuration / 2.0 let scaleAnim = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnim.values = [1.4, 0.9, 1.0] scaleAnim.keyTimes = [0, 0.75, 1.0] scaleAnim.duration = letterDuration let group = CAAnimationGroup() group.animations = [opacityAnim, rotateAnim, scaleAnim] group.duration = letterDuration group.beginTime = CACurrentMediaTime() + Double(index) * letterDelay group.fillMode = kCAFillModeForwards group.removedOnCompletion = false layer.addAnimation(group, forKey: "animationGroup") } }
true
cf7e57fd70976c53eda3dcbc331c41bb37de2c7f
Swift
monstudval/ios-TD6
/DemoCoreData2/StudentsTableViewController.swift
UTF-8
9,402
2.734375
3
[]
no_license
// // StudentsTableViewController.swift // DemoCoreData2 // // Created by Derbalil on 2017-10-04. // Copyright © 2017 Derbalil. All rights reserved. // import UIKit import CoreData var studentsList: [Student] = [] let dataBaseController = DataBaseController() class StudentsTableViewController: UITableViewController { @IBOutlet var myTableView: UITableView! let context = DataBaseController().getContext() 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() //dataBaseController.addStudent(fullName: "Steve Blair", age: 26) //dataBaseController.addStudent(fullName: "Samy Raymmond", age: 35) //dataBaseController.addStudent(fullName: "Alain Jackson", age: 41) //dataBaseController.deleteStudent(fullName: "Michel Claude", age: 55) //dataBaseController.updateStudent(fullName: "Michel Claude", age: 55) if studentsList.count == 0 { for student in dataBaseController.getStudents(){ studentsList.append(student) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Click button Add Student @IBAction func btnAddStudent(_ sender: Any) { let alertController = UIAlertController(title: "Add New Student", message: nil, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Save", style: .default, handler: { alert in let fullNameField = alertController.textFields![0] as UITextField let ageField = alertController.textFields![1] as UITextField if fullNameField.text != "", ageField.text != "" { // add student to the database dataBaseController.addStudent(fullName: fullNameField.text!, age: Int(ageField.text!)!) let newStudent = NSEntityDescription.insertNewObject(forEntityName: "Student", into: self.context) as! Student newStudent.setValue(fullNameField.text!, forKey: "fullName") newStudent.setValue(Int16(ageField.text!)!, forKey: "age") studentsList.removeAll() for student in dataBaseController.getStudents(){ studentsList.append(student) } self.myTableView.reloadData() }else{ //display error print("error") } })) // add text field alertController.addTextField(configurationHandler: { (textField) -> Void in textField.placeholder = "Full Name" textField.textAlignment = .center }) alertController.addTextField(configurationHandler: { (textField) -> Void in textField.placeholder = "Age" textField.textAlignment = .center }) present(alertController, animated: true, completion: nil) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return studentsList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellStudent", for: indexPath) // Configure the cell... let index = indexPath.row cell.textLabel?.text = studentsList[index].fullName cell.detailTextLabel?.text = String(studentsList[index].age) return cell } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in let editAlert = UIAlertController(title: "Edit Student", message: nil, preferredStyle: .alert) editAlert.addAction(UIAlertAction(title: "Save", style: .default, handler: { alert in let fullNameField = editAlert.textFields![0] as UITextField let ageField = editAlert.textFields![1] as UITextField if fullNameField.text != "", ageField.text != "" { dataBaseController.updateStudent(fullNameOld: studentsList[indexPath.row].fullName!, ageOld: Int(studentsList[indexPath.row].age), fullNameNew: fullNameField.text!, ageNew: Int(ageField.text!)!) studentsList.removeAll() for student in dataBaseController.getStudents(){ studentsList.append(student) } self.myTableView.reloadData() }else{ //display error print("error") } })) /*alert.addAction(UIAlertAction(title: "Update", style: .default, handler: { (updateAction) in //self.list[indexPath.row] = alert.textFields!.first!.text! //self.tableView.reloadRows(at: [indexPath], with: .fade) }))*/ editAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) // add text field editAlert.addTextField(configurationHandler: { (textField) -> Void in textField.text = studentsList[indexPath.row].fullName textField.textAlignment = .center }) editAlert.addTextField(configurationHandler: { (textField) -> Void in textField.text = String(studentsList[indexPath.row].age) textField.textAlignment = .center }) self.present(editAlert, animated: false) }) editAction.backgroundColor = UIColor.blue let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, indexPath) in let alert = UIAlertController(title: "Delete \(studentsList[indexPath.row].fullName!) ?", message: "", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (updateAction) in let index = indexPath.row dataBaseController.deleteStudent(fullName: studentsList[index].fullName!, age: studentsList[index].age) studentsList.remove(at: index) tableView.deleteRows(at: [indexPath], with: .fade) })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: false) }) deleteAction.backgroundColor = UIColor.red return [editAction, deleteAction] } /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source let index = indexPath.row dataBaseController.deleteStudent(fullName: studentsList[index].fullName!, age: studentsList[index].age) studentsList.remove(at: index) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
3ef98be5ca6039632af10402e5d3eb041363dcf2
Swift
ecole96/Is-It-Yacht-Rock
/IsItYacht/Song.swift
UTF-8
829
3.078125
3
[]
no_license
// // Song.swift // IsItYacht // // Created by Evan Cole on 9/15/18. // Copyright © 2018 Evan Cole. All rights reserved. // import Foundation // class for song data (optionals are only for matched songs) class Song { var title: String var artist: String var yachtski: Float? var jd: Float? var steve: Float? var hunter: Float? var dave: Float? var imageURL: String? var show: String? init(title: String,artist: String,yachtski: Float?, show: String?, jd: Float?,steve: Float?,hunter: Float?,dave: Float?, imageURL: String?) { self.title = title self.artist = artist self.yachtski = yachtski self.jd = jd self.steve = steve self.hunter = hunter self.dave = dave self.imageURL = imageURL self.show = show } }
true
90abf7ee07598f841774a1852f25b3f2b80b28f5
Swift
nawsusunyein/CurrencyExchange
/CurrencyExchange/Model/CalculatedCurrencyModel.swift
UTF-8
488
3.046875
3
[]
no_license
// // CalculatedCurrencyModel.swift // CurrencyExchange // // Created by Naw Su Su Nyein on 12/5/19. // Copyright © 2019 Naw Su Su Nyein. All rights reserved. // import Foundation class CalculatedCurrencyModel{ var type : String? var oneUnitValue : Double? var enteredUnitValue : Double? init(type:String,oneUnitValue:Double,enteredUnitValue:Double){ self.type = type self.oneUnitValue = oneUnitValue self.enteredUnitValue = enteredUnitValue } }
true
2fb881ee0c577afa1da7e58ce4e2f4f3e7ac316c
Swift
daehn/ChainedAnimation
/ChainedAnimation/AnimationProvider.swift
UTF-8
789
2.875
3
[ "MIT" ]
permissive
// // AnimationProvider.swift // ChainedAnimation // // Created by Silvan Dähn on 10/09/2016. // Copyright © 2016 Silvan Dähn. All rights reserved. // public protocol AnimationProvider { func animate(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: @escaping Animation, completion: Completion?) } struct UIViewAnimationProvider: AnimationProvider { func animate(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: @escaping Animation, completion: Completion?) { UIView.animate( withDuration: duration, delay: delay, options: options, animations: animations, completion: completion ) } }
true
5ad88f3713577d5fd6472e0c26b187ca93df9c0f
Swift
rishigoel/wheres_quito
/wheres_quito/wheres_quito/LegitLocationViewController.swift
UTF-8
1,145
2.640625
3
[]
no_license
// // LegitLocationViewController.swift // wheres_quito // // Created by Rishi Goel on 11/17/17. // Copyright © 2017 Rishi Goel. All rights reserved. // import UIKit class LegitLocationViewController: UIViewController { var locationLabel = UILabel() var location: String? var colours: Colours? override func viewDidLoad() { super.viewDidLoad() setUpView() if let location = location { locationLabel.text = location } } func setUpView() { let layer = CAGradientLayer() layer.frame = self.view.bounds if let colours = colours { layer.colors = [colours.teal.cgColor, colours.red.cgColor, colours.black.cgColor] self.view.layer.addSublayer(layer) } locationLabel.frame = CGRect(x: 0, y: self.view.bounds.height/4, width: self.view.bounds.width, height: 100) locationLabel.textAlignment = .center locationLabel.numberOfLines = 0 locationLabel.font = locationLabel.font.withSize(26.0) locationLabel.textColor = UIColor.white self.view.addSubview(locationLabel) } }
true
31f6091a55e4299f2de7fdbaab51cc030e650219
Swift
elsiden/TMS-Swift
/tms8/tms8/ViewController.swift
UTF-8
4,455
2.859375
3
[]
no_license
// // ViewController.swift // tms8 // // Created by Ivan Klishevich on 05.07.2021. // import UIKit class ViewController: UIViewController { var view1: UIView = UIView() let textField = UITextField() override func awakeFromNib() { // самый первый при создании super.awakeFromNib() print("orange awakeFromNib") } override func viewDidLoad() { // загрузилось но не показалось super.viewDidLoad() print("orange viewDidLoad") // Do any additional setup after loading the view. view.backgroundColor = UIColor.lightGray // view.backgroundColor = .red let view1 = UIView(frame: CGRect(x: 87, y: 592, width: 240, height: 128)) // let frameView1 = CGRect(x: 87, y: 592, width: 240, height: 128) // let view1 = UIView(frame: frameView1) // view1.frame = frameView1 view1.backgroundColor = .red view.addSubview(view1) // добавление на storyboard let colors: [UIColor] = [UIColor.black, UIColor.white, UIColor.red, UIColor.green, UIColor.blue] for value in 0..<colors.count { let newView = UIView(frame: CGRect(x: 50.0 * Double(value + 1), y: 70.0 * Double(value + 1), width: 50.0, height: 50.0)) newView.backgroundColor = colors[value] view.addSubview(newView) } // print(view.subviews) // элементы View (массив) let view2 = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 100, height: 50))) view2.backgroundColor = .yellow view1.addSubview(view2) let label = UILabel(frame: CGRect(origin: CGPoint(x: 300, y: 300), size: CGSize(width: 100, height: 50))) label.text = "TEXT!!!" label.textColor = UIColor.white view.addSubview(label) // ================== let textField = UITextField(frame: CGRect(x: 170.0, y: 100.0, width: 200.0, height: 44.0)) // textField.frame = CGRect(x: 170.0, y: 100.0, width: 200.0, height: 44.0) textField.backgroundColor = .white textField.placeholder = "Enter your name" view.addSubview(textField) // ================== let button = UIButton(frame: CGRect(x: 50.0, y: 600.0, width: 100.0, height: 50.0)) button.setTitle("Button", for: .normal) button.backgroundColor = UIColor(red: 200 / 255, green: 175 / 255, blue: 40 / 255, alpha: 1.0) button.addTarget(self, action: #selector(buttonTapped(_:)), for: UIControl.Event.touchUpInside) view.addSubview(button) } @objc func buttonTapped(_ sender: UIButton) { print("button was tapped and \(textField.text)") } override func viewWillAppear(_ animated: Bool) { // перед тем как показать полностью super.viewWillAppear(animated) print("orange viewWillAppear") } override func viewDidAppear(_ animated: Bool) { // когда экран показан полностью super.viewDidAppear(animated) print("orange viewDidAppear") } override func viewWillLayoutSubviews() { // когда происходит пересчет размера экрана super.viewWillLayoutSubviews() print("orange viewWillLayoutSubviews") } override func viewDidLayoutSubviews() { // когда пересчет размера экрана закончен super.viewDidLayoutSubviews() print("orange viewDidLayoutSubviews") } override func viewWillDisappear(_ animated: Bool) { // перед скрытием экрана super.viewWillDisappear(animated) print("orange viewWillDisappear") } override func viewDidDisappear(_ animated: Bool) { // когда экран скрыт super.viewDidDisappear(animated) print("orange viewDidDisappear") } deinit { print("orange deinit") } // ===== РЕДКО override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { // во время перевота экрана print("orange willTransition") } }
true
4a177623eb7f65f0bd28a8ed626e6e686ab060eb
Swift
giaset/evenlift-swift
/evenlift-swift/LFTSpotter.swift
UTF-8
2,372
2.65625
3
[]
no_license
// // LFTSpotter.swift // evenlift-swift // // Created by Gianni Settino on 2014-08-19. // Copyright (c) 2014 Milton and Parc. All rights reserved. // import UIKit class LFTSpotter: NSObject { /* Global Variables */ let url = "https://evenlift.firebaseio.com/" var firebase: Firebase var authClient: FirebaseSimpleLogin let facebookAppId = "420007321469839" /* Singleton */ class var sharedInstance: LFTSpotter { struct Static { static let instance: LFTSpotter = LFTSpotter() } return Static.instance } override init() { firebase = Firebase(url: url) authClient = FirebaseSimpleLogin(ref: firebase) super.init() } func makeSureUserIsLoggedIn(#completion: () -> ()) { // Log user in if he isn't already authClient.checkAuthStatusWithBlock({ (error: NSError!, user: FAUser!) in if (error != nil) { // there was an error self.showAlertWithTitle("Error", message: error.description) } else if (user == nil) { // user is not logged in self.loginWithCompletion({ user in completion() }) } else { // user is logged in completion() } }) } func loginWithCompletion(completion: (FAUser!) -> ()) { authClient.loginToFacebookAppWithId(facebookAppId, permissions: nil, audience: ACFacebookAudienceOnlyMe, withCompletionBlock:{ (error: NSError!, user: FAUser!) in if (error != nil) { // there was an error self.showAlertWithTitle("Error", message: error.description) } else { // login successful completion(user) } }) } func showAlertWithTitle(title: String, message: String) { // Support for UIAlertViews, which are deprecated starting in iOS8 var alert = UIAlertView() alert.title = title alert.message = message alert.addButtonWithTitle("Ok") alert.show() } /* User ID */ func userId() -> String? { return NSUserDefaults.standardUserDefaults().stringForKey("uid") } }
true
82a9eb37c4a2082b43912570f1f8a580af85b6dd
Swift
NAKAMURAAAAAAAAAA/ToDoApp2
/ToDoApp2/ThirdViewController.swift
UTF-8
1,501
2.5625
3
[]
no_license
// // ThirdViewController.swift // ToDoApp2 // // Created by Kan Nakamura on 2019/01/18. // Copyright © 2019 Kan Nakamura. All rights reserved. // import UIKit class ThirdViewController: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view todos = loadTodos() ?? [TodoKobetsunonakami]() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) todos = loadTodos() ?? [TodoKobetsunonakami]() tableView.reloadData() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } extension ThirdViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return todos.filter{ $0.done }.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DoneCell") as! donecellTableViewCell cell.donelabel?.text = todos.filter{ $0.done }[indexPath.row].todotext return cell } }
true
e96cd1c6fa6477ae4b3e706668630361cb317126
Swift
aposnov/elementsWeather
/elementsWeather/Extensions/UIImageView.swift
UTF-8
1,647
2.875
3
[]
no_license
// // UIImageView.swift // elementsWeather // // Created by Andrey Posnov on 02.08.2020. // Copyright © 2020 Andrey Posnov. All rights reserved. // import UIKit let imageCache = NSCache<NSString, UIImage>() extension UIImageView { public func imageFromURL(urlString: String) { let activityIndicator = UIActivityIndicatorView(style: .gray) activityIndicator.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height) activityIndicator.startAnimating() if self.image == nil{ self.addSubview(activityIndicator) } // check if the image is already in the cache if let imageToCache = imageCache.object(forKey: urlString as NSString) { self.image = imageToCache activityIndicator.removeFromSuperview() return } URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in if error != nil { print(error ?? "No Error") return } DispatchQueue.main.async(execute: { () -> Void in if let image = UIImage(data: data!) { // add image to cache imageCache.setObject(image, forKey: urlString as NSString) activityIndicator.removeFromSuperview() self.image = image } else { activityIndicator.removeFromSuperview() self.image = UIImage(named: "nopicture") } }) }).resume() } }
true
e2c9a933355d9cb81ce5ae1ee85b6aeddd430143
Swift
guilmoios/BeBop
/BeBop/Global/Classes/NetworkManager.swift
UTF-8
2,977
2.6875
3
[ "Apache-2.0" ]
permissive
// // NetworkManager.swift // BeBop // // Created by Guilherme Mogames on 10/4/17. // Copyright © 2017 Mogames. All rights reserved. // import UIKit import Alamofire import KRProgressHUD struct API { struct Endpoints { public static let search = "https://news.bandsintown.com/searchArtists?search=%@" public static let artist = "https://rest.bandsintown.com/artists/%@?app_id=bebop" public static let events = "https://rest.bandsintown.com/artists/%@/events?app_id=bebop" } } typealias CompletionBlock = (NSError?) -> Void var completionBlock: CompletionBlock? class NetworkManager: NSObject { open static var shared = NetworkManager() private let configuration: URLSessionConfiguration? private let sessionManager: Alamofire.SessionManager? override init() { configuration = URLSessionConfiguration.background(withIdentifier: "com.mogames.bebop") sessionManager = Alamofire.SessionManager(configuration: configuration!) super.init() } func request(_ url: String, parameters: [String: Any], showLoading: Bool? = true, completionHandler: @escaping (_ response: Any?) -> ()) { if showLoading! { DispatchQueue.main.async { KRProgressHUD.show() } } var tempURL = url if let encodedURL = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { tempURL = encodedURL } print("request: \(tempURL)") sessionManager?.request(tempURL, method: .get, parameters: parameters, encoding: parameters.count > 0 ? JSONEncoding.default : URLEncoding.default, headers: nil).responseJSON { (response) in KRProgressHUD.dismiss() if let _ = response.error { self.handleError() completionHandler(nil) return } if let result = response.result.value { debugPrint(result) if let res = result as? [String: Any] { if let err = res["message"] as? String { self.handleError(err) completionHandler(nil) return } } completionHandler(result) } } } func handleError(_ errorMessage: String = "An error has occured, please try again", action: CompletionBlock? = nil) { let alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (alertAction) in if action != nil { action!(nil) } })) if let vc = UIApplication.shared.delegate?.window??.rootViewController { vc.present(alert, animated: true, completion: nil) } } }
true
940f96ef0a9adace7a3019f2b8895654a6d189cf
Swift
ShunMitsuoka/Shopping_Stock_List
/Shopping_Stock_List/Shopping_Stock_List/View/Cell/MemoCell.swift
UTF-8
2,333
2.515625
3
[]
no_license
// // MemoCell.swift // Shopping_Stock_List // // Created by 光岡駿 on 2019/08/19. // Copyright © 2019 光岡駿. All rights reserved. // import UIKit class MemoCell: UITableViewCell,UITextViewDelegate{ override func awakeFromNib() { super.awakeFromNib() // Initialization code } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .default, reuseIdentifier: reuseIdentifier) //cell自身のサイズ let navi = MyUINavigationController() let tab = MyUITabBarController() let tableViewHeight = ViewProperties.mainBoundSize.height - navi.navigationHeight() - tab.tabBarHeight() let textFieldHeight = tableViewHeight - ViewProperties.cellHeight*7 self.frame = CGRect(x: 0, y: 0, width: ViewProperties.mainBoundSize.width, height: textFieldHeight) textView.delegate = self //textViewの設定 textView.frame = self.frame textView.backgroundColor = UIColor(red: 225/255, green: 200/255, blue: 168/255, alpha: 1) textView.font = UIFont.systemFont(ofSize: 20) textView.isEditable = true //完了ボタンの作成 let toolbar_Done = ViewProperties.setToolbar_Done(view:self, action: #selector(done_Date)) textView.inputAccessoryView = toolbar_Done self.addSubview(textView) //Cell設定 self.selectionStyle = UITableViewCell.SelectionStyle.none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let textView = UITextView() // textFieldのdoneボタンの動き @objc func done_Date() { textView.endEditing(true) } func textViewDidEndEditing(_ textView: UITextView) { textView.endEditing(true) setSelected(false, animated: false) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // func textViewDidBeginEditing(_ textView: UITextView) { // } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { setSelected(true, animated: false) return true } }
true
686e0a1b6c5500315912c294d37ca492267c90a7
Swift
mayanring/concentration
/Concentration/ViewController.swift
UTF-8
3,047
2.640625
3
[]
no_license
import UIKit class ViewController: UIViewController { lazy var game = Concentration(numberOfPairsOfCards: (cardButtons.count + 1) / 2, numberOfThemes: emojiThemes.count) @IBOutlet weak var moveCountLabel: UILabel! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet var cardButtons: [UIButton]! @IBAction func touchResetButton(_ sender: UIButton) { game.reset() updateViewFromModel() } // var emojiChoices = ["🎃", "👻", "🧟‍♀️", "🧛🏻‍♂️", "👽", "🧟‍♂️", "🦇", "🍫"] var emojiChoices = [String]() @IBAction func touchCard(_ sender: UIButton) { if let cardNumber = cardButtons.index(of: sender) { game.chooseCard(at: cardNumber) updateViewFromModel() } } func updateViewFromModel() { for index in cardButtons.indices { let button = cardButtons[index] let card = game.cards[index] if card.isFaceUp { button.setTitle(emoji(for: card), for: .normal) button.backgroundColor = #colorLiteral(red: 0.6666666865, green: 0.6666666865, blue: 0.6666666865, alpha: 1) } else { button.setTitle("", for: .normal) button.backgroundColor = card.isMatched ? #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0) : #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1) } } scoreLabel.text = "Score: \(game.score)" moveCountLabel.text = "Moves: \(game.flipCount)" } var emojiThemes = Dictionary<Int,[String]>() var emoji = Dictionary<Int,String>() func emoji(for card: Card) -> String { if emoji[card.identifier] == nil, emojiChoices.count > 0 { let randomIndex = Int(arc4random_uniform(UInt32(emojiChoices.count))) emoji[card.identifier] = emojiChoices.remove(at: randomIndex) } return emoji[card.identifier] ?? "?" } func flipCard(withEmoji emoji: String, on button: UIButton) { if button.currentTitle == emoji { button.setTitle("", for: .normal) button.backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1) } else { button.setTitle(emoji, for: .normal) button.backgroundColor = #colorLiteral(red: 0.6666666865, green: 0.6666666865, blue: 0.6666666865, alpha: 1) } } override func viewDidLoad() { emojiThemes[0] = ["🎃", "👻", "🧟‍♀️", "🧛🏻‍♂️", "👽", "🧟‍♂️", "🦇", "🍫"] emojiThemes[1] = ["🦓", "🦒", "🦔", "🦕", "🐀", "🐊", "🐇", "🐆"] emojiThemes[2] = ["🤾‍♀️", "🏄‍♀️", "🚵‍♀️", "🤽‍♀️", "⛹️‍♀️", "🤾‍♀️", "🏊‍♀️", "🚣‍♀️"] emojiChoices = emojiThemes[game.themeIndex]! } }
true
d1f7bc22854cb186e4e2edc2e702f5ebbe118b8c
Swift
jarrettc124/pv
/pozivibes/NetworkUtil.swift
UTF-8
13,528
2.53125
3
[]
no_license
// // NetworkUtil.swift // SwiftProj // // Created by Jarrett Chen on 12/21/15. // Copyright © 2015 Pixel and Processor. All rights reserved. // import Foundation class NetworkUtil{ static let backendVersion = "1.0" static let cloudinary_url = "cloudinary://761295191157382:QnNUKYvRi0RnmSABPrp0IlzOEf0@pixel-and-processor" static let NetworkErrorStatusCodeKey = "NetworkErrorStatusCodeKey" static let NetworkErrorDomain = "NetworkErrorDomain" static let NetworkErrorMessageKey = "NetworkErrorMessageKey" static let NETWORK_GENERIC_ERROR_CODE = 1400 static let NETWORK_FORBIDDEN_ERROR_CODE = 1403 static let NETWORK_NOT_FOUND_ERROR_CODE = 404 static let NETWORK_REJECT_ERROR_CODE = 1401 static let NETWORK_NOT_AUTHORIZED_ERROR_CODE = 401 static let NETWORK_VALIDATION_ERROR_CODE = 1422 static let NETWORK_SERVER_ERROR_CODE = 1500 static let NETWORK_SUCCESS_CODE = 200 static let NETWORK_UNAUTHORIZED = 401 static let NETWORK_FACEBOOK_REJECT = 500 static let NETWORK_NO_INTERNET = -1004 //Properties class var serverHost:String { #if DEBUG return "localhost" #else return "pozivibes-test.herokuapp.com" #endif } class var serverPort:String { #if DEBUG return "5000" #else return "443" #endif } class var serverIsSecure:Bool{ #if DEBUG return false #else return true #endif } class func serverURLWithPath(path:String) -> NSURL{ if(NetworkUtil.serverIsSecure){ return NSURL(string: "https://\(NetworkUtil.serverHost):\(NetworkUtil.serverPort)/v\(backendVersion)/\(path)")! }else{ return NSURL(string: "http://\(NetworkUtil.serverHost):\(NetworkUtil.serverPort)/v\(backendVersion)/\(path)")! } } class var serverURL:NSURL{ if(NetworkUtil.serverIsSecure){ return NSURL(string: "https://\(NetworkUtil.serverHost):\(NetworkUtil.serverPort)/v\(backendVersion)")! }else{ return NSURL(string: "http://\(NetworkUtil.serverHost):\(NetworkUtil.serverPort)/v\(backendVersion)")! } } class func getRoute(route:String, method:String, refresh:Bool, dataHandler:((error: NSError?, data:NSData?)->Void)){ let serverURL:NSURL = NetworkUtil.serverURLWithPath(route) print("Server URL: \(serverURL)") let session = NSURLSession.sharedSession() let request = NSMutableURLRequest(URL: serverURL) if(refresh){ request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData } request.HTTPMethod = method let task = session.dataTaskWithRequest(request, completionHandler: NetworkUtil.processNSDataWithCompletionHandler(dataHandler)) task.resume() } class func getRoute(route:String, method:String, dataHandler:(error:NSError?,data:NSData?)->Void){ getRoute(route, method: method, refresh: false, dataHandler: dataHandler) } class func getRoute(route:String, dataHandler:(error:NSError?,data:NSData?)->Void){ getRoute(route, method: "GET", dataHandler: dataHandler) } class func getRoute(route:String,refresh:Bool, dataHandler:(error:NSError?,data:NSData?)->Void){ getRoute(route, method: "GET", refresh: refresh, dataHandler: dataHandler) } class func getRoute(route:String, JSONResultHandler:(error:NSError?,result:AnyObject?)->Void){ getRoute(route, dataHandler: NetworkUtil.processJSONWithCompletionHandler(JSONResultHandler)) } class func getRoute(route:String, refresh:Bool, JSONResultHandler:(error:NSError?,result:AnyObject?)->Void){ getRoute(route, refresh: refresh, dataHandler: NetworkUtil.processJSONWithCompletionHandler(JSONResultHandler)) } class func getRoute(route:String, method:String, JSONResultHandler:(error:NSError?,result:AnyObject?)->Void){ getRoute(route, method: method, dataHandler: NetworkUtil.processJSONWithCompletionHandler(JSONResultHandler)) } class func getRoute(route:String, method:String, refresh:Bool, JSONResultHandler:(error:NSError?,result:AnyObject?)->Void){ getRoute(route, method: method, refresh: refresh, dataHandler: NetworkUtil.processJSONWithCompletionHandler(JSONResultHandler)) } class func getRoute(route:String, method:String, params:Dictionary<String,AnyObject>, dataHandler:(error:NSError?,data:NSData?)->Void){ let routeString = NetworkUtil.routeString(route, params: params) getRoute(routeString, method: method, dataHandler: dataHandler) } class func getRoute(route:String, params:Dictionary<String,AnyObject>, dataHandler:(error:NSError?,data:NSData?)->Void){ let routeString = NetworkUtil.routeString(route, params: params) getRoute(routeString, dataHandler: dataHandler) } class func getRoute(route:String, refresh:Bool, params:Dictionary<String,AnyObject>, dataHandler:(error:NSError?,data:NSData?)->Void){ let routeString = NetworkUtil.routeString(route, params: params) getRoute(routeString, refresh: refresh, dataHandler: dataHandler) } class func getRoute(route:String, params:Dictionary<String,AnyObject>?, JSONResultHandler:(error:NSError?,result:AnyObject?)->Void){ if let param = params{ let routeString = NetworkUtil.routeString(route, params: param) getRoute(routeString, JSONResultHandler: JSONResultHandler) }else{ getRoute(route, JSONResultHandler: JSONResultHandler) } } class func getRoute(route:String, refresh:Bool, params:Dictionary<String,AnyObject>, JSONResultHandler:(error:NSError?,result:AnyObject?)->Void){ let routeString = NetworkUtil.routeString(route, params: params) getRoute(routeString, refresh:refresh, JSONResultHandler: JSONResultHandler) } class func getRoute(route:String, method:String, refresh:Bool, params:Dictionary<String,AnyObject>, JSONResultHandler:(error:NSError?,result:AnyObject?)->Void){ let routeString = NetworkUtil.routeString(route, params: params) getRoute(routeString, method:method, refresh:refresh, JSONResultHandler: JSONResultHandler) } class func postToRoute(route:String, data:NSData?, completionHandler:(error:NSError?,data:NSData?)->Void){ let serverURL:NSURL = NetworkUtil.serverURLWithPath(route) print("Server URL: \(serverURL)") let session = NSURLSession.sharedSession() let request = NSMutableURLRequest(URL: serverURL) request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData request.HTTPMethod = "POST" if(data != nil){ request.HTTPBody=data } let task = session.dataTaskWithRequest(request, completionHandler: NetworkUtil.processNSDataWithCompletionHandler(completionHandler)) task.resume() } class func postToRoute(route:String?, params:Dictionary<String,AnyObject>?, data:NSData?, completionHandler:(error:NSError?,data:NSData?)->Void){ let newRouteString = NetworkUtil.routeString(route!, params: params!) NetworkUtil.postToRoute(newRouteString, data: data, completionHandler: completionHandler) } class func postToRoute(route:String,params:Dictionary<String,AnyObject>?,json:AnyObject?,completionHandler:(NSError?,AnyObject?)->Void){ guard let json = json else{ NetworkUtil.postToRoute(route, params: params, data: nil, completionHandler: NetworkUtil.processJSONWithCompletionHandler(completionHandler)) return } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { do { let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: []) let serverURL = NetworkUtil.serverURLWithPath(route) print("Server URL: \(serverURL)") let request = NSMutableURLRequest(URL: serverURL) request.HTTPMethod="POST" request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("\(jsonData.length)", forHTTPHeaderField: "Content-Length") request.HTTPBody=jsonData let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request, completionHandler: NetworkUtil.processNSDataWithCompletionHandler(NetworkUtil.processJSONWithCompletionHandler(completionHandler))) task.resume() } catch let JSONError as NSError{ dispatch_async(dispatch_get_main_queue()) { completionHandler(JSONError,nil) } } } } class func routeString(route:String, params:Dictionary<String,AnyObject>)->String{ var first = true var routeString:String = "\(route)?" for (paramKey,paramObject) in params{ if(!first){ routeString+="&" } routeString += "\(paramKey)=\(paramObject)" first=false } return routeString } class func processJSONWithCompletionHandler(completionHandler:((NSError?,AnyObject?)->Void)?)->(NSError?,NSData?)->Void{ func returnFunc(error:NSError?,data:NSData?)->Void{ if (data == nil){ if let handler = completionHandler{ dispatch_async(dispatch_get_main_queue()) { handler(error,nil) } } return } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { do { let result = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) if let handler = completionHandler{ var parsedError:NSError? if(error != nil){ var userDict:Dictionary = error!.userInfo let result = result as! [String:AnyObject] var statusCode:Int?=nil if var statusCode = result["statusCode"] as? Int{ if(statusCode != NetworkUtil.NETWORK_SUCCESS_CODE){ statusCode = statusCode+1000 } }else{ statusCode = error!.code } userDict[NetworkUtil.NetworkErrorStatusCodeKey] = statusCode! if let resultError = result["result"]!["error"]{ userDict[NetworkUtil.NetworkErrorMessageKey] = resultError } parsedError = NSError(domain: NetworkUtil.NetworkErrorDomain, code: statusCode!, userInfo: userDict) }else{ parsedError = error; } dispatch_async(dispatch_get_main_queue()){ handler(parsedError,result) } } } catch let JSONError as NSError{ if let handler = completionHandler{ dispatch_async(dispatch_get_main_queue()) { handler(JSONError,nil) } } } } } return returnFunc } class func processNSDataWithCompletionHandler(completionHandler:((NSError?,NSData?)->Void)?)->(NSData?,NSURLResponse?,NSError?)->Void{ func returnFunc(data:NSData?,response:NSURLResponse?,error:NSError?)->Void{ if let responseError = error{ if let handler = completionHandler{ handler(responseError,data) } return } let statusCode = (response as? NSHTTPURLResponse)!.statusCode if(statusCode != 200){ let error = NSError(domain: NetworkErrorDomain, code: statusCode, userInfo: [NetworkErrorStatusCodeKey:statusCode]) if let handler = completionHandler{ handler(error,data) } return } if let completionHandler = completionHandler{ completionHandler(nil,data) } } return returnFunc } }
true
8f659be518fb18ebef7bbe0693874c2abedcabbb
Swift
saggit/billion-wallet-ios
/BillionWallet/BuyPickerVM.swift
UTF-8
1,355
3
3
[ "MIT" ]
permissive
// // BuyPickerVM.swift // BillionWallet // // Created by Evolution Group Ltd on 15/03/2018. // Copyright © 2018 Evolution Group Ltd. All rights reserved. // import Foundation import UIKit protocol BuyPickerOutputDelegate: class { func didSelectPaymentMethod(_ method: PaymentMethod) } protocol BuyPickerVMDelegate: class { func selectMethodAtIndex(_ index: Int) } class BuyPickerVM { let selectedMethod: PaymentMethod? let paymentMethods: [PaymentMethod] weak var delegate: BuyPickerVMDelegate? weak var output: BuyPickerOutputDelegate? init(method: PaymentMethod?, methods: [String]?, paymentMethodsFactory: PaymentMethodFactory, output: BuyPickerOutputDelegate?) { self.output = output self.selectedMethod = method let all = paymentMethodsFactory.getPaymentMethods() if let methods = methods { self.paymentMethods = all.filter { methods.contains($0.symbol) } } else { self.paymentMethods = all } } func selectRow(at index: Int) { output?.didSelectPaymentMethod(paymentMethods[index]) } func selectMethodIfNeeded() { guard let selected = selectedMethod, let index = paymentMethods.index(of: selected) else { return } delegate?.selectMethodAtIndex(index) } }
true
a58ea0301984b0a1993cb1a1930ca3e038605b26
Swift
KrakenDev/Delight
/Sources/Delight/Containers/AnimationContainer.swift
UTF-8
1,025
2.875
3
[ "MIT" ]
permissive
/** * Representation of animation blocks that can contain property updates. Since animations are * inherently keyframe data sources (they are aware of timings and such), this protocol inherits * from KeyframeDataSource. */ public protocol AnimationContainer { var timing: KeyframeTiming { get } var isExecuting: Bool { get } /** * This adds a keyframe to the list of keyframes to run when commitAnimations() * is called. The default implementation converts the keyframe into an object that implements * the Animation protocol. */ func addAnimation<T: Keyframe>(for keyframe: T?, using animationFromRelatedKeyframes: @escaping AnimationExecution<T>) /** * Animations are nestable so this provides a plug for the receiver to execute the * animations block and inherit timing curves from the container passed in. */ func nest(inside container: AnimationContainer?) func executeAnimations() } extension AnimationContainer { func executeAnimations() {} }
true
f68d7dc0f0e0d710379b8250879c7fc317222766
Swift
nbnitin/CollectionView
/CollectionViewCompositionalLayout/BubbleViewCollectionView/BubbleViewCollectionView/CustomCollectionViewCell.swift
UTF-8
1,324
2.859375
3
[]
no_license
// // CustomCollectionViewCell.swift // BubbleViewCollectionView // // Created by Nitin Bhatia on 20/04/23. // import UIKit class CustomCollectionViewCell: UICollectionViewCell { @IBOutlet weak var lblTitle: UILabel! let deSelectedColor = UIColor(red: 0.961, green: 0.961, blue: 0.961, alpha: 1) let IneligibleColor = UIColor(red: 0.733, green: 0.733, blue: 0.733, alpha: 1) var isEligible : Bool? { didSet { if !(isEligible ?? false) { layer.borderColor = IneligibleColor.cgColor backgroundColor = .gray lblTitle.textColor = IneligibleColor } else { layer.borderColor = UIColor.red.cgColor backgroundColor = .black lblTitle.textColor = IneligibleColor } } } override var isSelected: Bool { didSet { if (self.isEligible ?? false) && isSelected { layer.borderColor = isSelected ? UIColor.red.cgColor : deSelectedColor.cgColor backgroundColor = isSelected ? UIColor.red : deSelectedColor } } } func config(isEligible: Bool, isSelected: Bool) { self.isEligible = isEligible self.isSelected = isSelected } }
true
2cb8065b995218af73d7c43f871add7a80bece6b
Swift
Wtclrsnd/pfood
/Main Project/NetworkLayer/NetworkModels/GetUserInfoResponse.swift
UTF-8
1,067
2.84375
3
[]
no_license
// // GetUserInfoResponse.swift // Main Project // // Created by Тимур Бакланов on 21.03.2020. // Copyright © 2020 Тимур Бакланов. All rights reserved. // import Foundation struct GetUserInfoResponse { let place: Int let placeM: Int let point: String let pointM: String let pointInTeam: String } extension GetUserInfoResponse: Decodable { private enum ApiResponseCodingKeys: String, CodingKey { case place = "place" case placeM = "place_m" case point = "point" case pointM = "point_m" case pointInTeam = "point_inteam" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: ApiResponseCodingKeys.self) place = try container.decode(Int.self, forKey: .place) placeM = try container.decode(Int.self, forKey: .placeM) point = try container.decode(String.self, forKey: .point) pointM = try container.decode(String.self, forKey: .pointM) pointInTeam = try container.decode(String.self, forKey: .pointInTeam) } }
true
4ffb2d1359702976b52856ad4f927716880e6567
Swift
couri-app/couri
/Couri/Couri/Restaurant Picker/RestaurantDisplay.swift
UTF-8
5,131
2.71875
3
[]
no_license
// // RestaurantDisplay.swift // Couri // // Created by David Chen on 6/23/19. // Copyright © 2019 Couri. All rights reserved. // import Foundation import UIKit class RestaurantDisplay: UITableViewCell { var restaurant: Restaurant! { didSet { restaurantImage.image = restaurant.imageName restaurantName.text = restaurant.restaurantName categoryDescription.text = restaurant.categoryDescription restaurantDescription.text = restaurant.description courierLabel.text = "\(String(restaurant.courierCount)) Couriers at \(restaurant.restaurantName)" } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() setupGradientLayer() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let restaurantImage: UIImageView = { let imageView = UIImageView() imageView.layer.cornerRadius = 5 imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFill return imageView }() let restaurantName: UILabel = { let label = UILabel() label.font = UIFont(name: "AvenirNext-Bold", size: 25) label.textColor = UIColor.white label.layer.shadowColor = UIColor.black.cgColor label.layer.shadowOffset = CGSize(width: 0, height: 0) label.layer.shadowOpacity = 0.5 label.layer.shadowRadius = 5 return label }() let restaurantDescription: UILabel = { let label = UILabel() label.font = UIFont(name: "AvenirNext-Regular", size: 16) label.numberOfLines = 0 return label }() let categoryDescription: UILabel = { let label = UILabel() label.font = UIFont(name: "AvenirNext-Medium", size: 16) label.textColor = UIColor.white label.numberOfLines = 0 return label }() let courierLabel: UILabel = { let label = UILabel() label.font = UIFont(name: "AvenirNext-Demibold", size: 16) return label }() let gradientView: UIView = { let view = UIView() return view }() func setupGradientLayer() { let gradientLayer = CAGradientLayer() gradientLayer.colors = [UIColor.clear.cgColor, UIColor.black.withAlphaComponent(0.5).cgColor] gradientLayer.locations = [0, 1] gradientView.layer.addSublayer(gradientLayer) gradientLayer.frame = CGRect(x: 0, y: 0, width: 500, height: 100) } func setupViews() { addSubview(restaurantImage) addSubview(restaurantName) addSubview(restaurantDescription) addSubview(categoryDescription) addSubview(courierLabel) restaurantImage.addSubview(gradientView) restaurantImage.translatesAutoresizingMaskIntoConstraints = false restaurantName.translatesAutoresizingMaskIntoConstraints = false restaurantDescription.translatesAutoresizingMaskIntoConstraints = false categoryDescription.translatesAutoresizingMaskIntoConstraints = false courierLabel.translatesAutoresizingMaskIntoConstraints = false gradientView.translatesAutoresizingMaskIntoConstraints = false addConstraints([ restaurantImage.leftAnchor.constraint(equalTo: leftAnchor), restaurantImage.rightAnchor.constraint(equalTo: rightAnchor), restaurantImage.heightAnchor.constraint(equalToConstant: 200), restaurantImage.topAnchor.constraint(equalTo: topAnchor, constant: 20), restaurantName.bottomAnchor.constraint(equalTo: categoryDescription.topAnchor), restaurantName.leadingAnchor.constraint(equalTo: restaurantImage.leadingAnchor, constant: 10), categoryDescription.leadingAnchor.constraint(equalTo: restaurantName.leadingAnchor), categoryDescription.bottomAnchor.constraint(equalTo: restaurantImage.bottomAnchor, constant: -10), categoryDescription.rightAnchor.constraint(equalTo: rightAnchor), courierLabel.topAnchor.constraint(equalTo: restaurantImage.bottomAnchor, constant: 10), courierLabel.leadingAnchor.constraint(equalTo: restaurantImage.leadingAnchor), restaurantDescription.topAnchor.constraint(equalTo: courierLabel.bottomAnchor, constant: 5), restaurantDescription.leadingAnchor.constraint(equalTo: restaurantImage.leadingAnchor), restaurantDescription.rightAnchor.constraint(equalTo: rightAnchor), gradientView.leftAnchor.constraint(equalTo: leftAnchor), gradientView.rightAnchor.constraint(equalTo: rightAnchor), gradientView.topAnchor.constraint(equalTo: restaurantName.topAnchor, constant: -5), gradientView.bottomAnchor.constraint(equalTo: restaurantImage.bottomAnchor), ]) } }
true
47b3a16924eadd414c698ed0a1ae49c554a06332
Swift
petercerhan/ToDo
/ToDo/CoreDataStack.swift
UTF-8
1,611
2.828125
3
[]
no_license
// // CoreDataStack.swift // ToDo // // Created by Peter Cerhan on 6/7/17. // Copyright © 2017 Peter Cerhan. All rights reserved. // import Foundation import CoreData struct CoreDataStack { private let model: NSManagedObjectModel internal let coordinator: NSPersistentStoreCoordinator private let modelURL: URL internal let dbURL: URL let context: NSManagedObjectContext // MARK: - Assembly init?(modelName: String) { guard let modelURL = Bundle.main.url(forResource: modelName, withExtension: "momd"), let model = NSManagedObjectModel(contentsOf: modelURL) else { return nil } self.modelURL = modelURL self.model = model coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = coordinator let fm = FileManager.default guard let docUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil } self.dbURL = docUrl.appendingPathComponent("model.sqlite") do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: dbURL, options: nil) } catch { fatalError("Error while configuring core data stack") } } // MARK: - Utilities func save() { do { try context.save() } catch { } } }
true
6ebe3f86319bb971d444336a0dcca5d7c289534b
Swift
xzjxylophone/RXSwiftDemo
/RXSwiftDemo/RXSwiftDemo/Controller/Third/Kingfisher/Protocol/RXTestProtocol.swift
UTF-8
1,200
2.53125
3
[ "MIT" ]
permissive
// // RXTestProtocol.swift // RXSwiftDemo // // Created by Rush.D.Xzj on 2018/8/27.你 // Copyright © 2018 TAL. All rights reserved. // import Foundation public protocol RXTestProtocol { var value: String { get } var valueImpByExtension: String { get } var valueImpByExtensionAndObject: String { get } func test() func testImpByExtension() func testImpByExtensionAndObject() } public extension RXTestProtocol { // 在protocol的extension中,函数需要有实现 func testInExtension() { NSLog("testInExtension, value:%@", self.value) NSLog("testInExtension, valueImpByExtension:%@", self.valueImpByExtension) NSLog("testInExtension, valueImpByExtensionAndObject:%@", self.valueImpByExtensionAndObject) } var valueImpByExtension: String { return "valueImpByExtension" } var valueImpByExtensionAndObject: String { return "valueImpByExtensionAndObject" } func testImpByExtension() { NSLog("testImpByExtension:%@", self.valueImpByExtension) } func testImpByExtensionAndObject() { NSLog("testImpByExtensionAndObject:%@", self.valueImpByExtensionAndObject) } }
true
d0947210ac2391a930293c6604799f29eb0c735c
Swift
RamaRai/App-CityAPI-and-Coredata
/Mobile WeatherApp SwiftAssignment2/CitySearchTVC.swift
UTF-8
5,492
2.921875
3
[]
no_license
// // CitySearchTVC.swift // Mobile WeatherApp SwiftAssignment2 // // Created by user152991 on 5/13/19. // Copyright © 2019 RamaRai. All rights reserved. // import UIKit import CoreData // TVC has TC delegates by default and search delegate and downloader delegate class CitySearchTVC : UITableViewController,UISearchBarDelegate,downloaderDelegate { // creating the array of cities from the data got from downloader //each time data is got the table is refreshed func downlaoderDidFinishWithCitiesArray(array: NSArray) { cityList = array as! [String] tableView.reloadData() } var cityList = [String]() var strcity = [String]() var myDownloader = downloader() var mypointerToPersistentContainer :NSPersistentContainer? // Loading initial view override func viewDidLoad() { super.viewDidLoad() myDownloader.delegate = self } // MARK: - Table view data source // Number of sections override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } //Number fo rows is equal to number objects in array override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cityList.count } //Filling each row of table with object from array override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) // cell.textLabel?.text = cityList[indexPath.row] // Breatking the array object atring into sub strings seperated by , let strcity = cityList[indexPath.row].components(separatedBy: ",") //Display City name as title of TV cell cell.textLabel?.text = strcity[0] // Display Province and Country as detail of TV cell cell.detailTextLabel?.text = strcity[1]+"' "+strcity[2] return cell } // Searching for cities from Cities API func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.count > 2 { //If city name has spaces it must be replaced by %20 format in url //as url CANNOT have space var mytext = searchText mytext = mytext.replacingOccurrences(of: " ", with: "%20") //Get list of cities matching with the search text in search bar myDownloader.getCities(city: mytext) } } lazy var myAppdelegate = UIApplication.shared.delegate as! AppDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let newcity = NSEntityDescription.insertNewObject(forEntityName: "Cities", into: myAppdelegate.persistentContainer.viewContext) as! Cities // Breatking the array object atring into sub strings seperated by , let strcity = cityList[indexPath.row].components(separatedBy: ",") //Display City name as title of TV cell newcity.cityName = strcity[0] newcity.country = strcity[2] myAppdelegate.saveContext() // Creating a alert popup window to let user know the city is added let alert = UIAlertController.init(title: "City Added to the favourites", message: "", preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: "ok", style: .default, handler: { (action) in self.navigationController?.popViewController(animated: true) })) present(alert, animated: true,completion: nil) } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
true
e73a2a6f9d5e0d406f101515083e0f363d5f7ffc
Swift
plvz/Bulats_practice_IOS
/Bulats_practice/GapFillingViewController.swift
UTF-8
3,317
2.515625
3
[]
no_license
// // GapFillingViewController.swift // Bulats_practice // // Created by Admin on 18/12/2017. // Copyright © 2017 utt.fr. All rights reserved. // import UIKit import SQLite class GapFillingViewController: UIViewController { var db: Connection! let sentencessTable = Table("sentences") let id = Expression<Int>("id") let type = Expression<String>("type") let sentence = Expression<String>("sentence") let position = Expression<Int>("position") let paragraph = Expression<Int>("exercice") let answersTable = Table("answers") let idAnswer = Expression<Int>("id") let fk_sentence = Expression<Int>("fk_sentence") let answer = Expression<String>("answer") let valid = Expression<String>("valid") var arrayOfAnswers:[String] = [] var scrollView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() do { self.db = try Connection("/Users/admin/Documents/Xcode-applications/Project/Bulats_practice/Bulats.db") } catch{ print(error) } scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height - 100)) scrollView.contentSize = CGSize(width: self.view.frame.size.width, height: 700) print("gap filling ") listSentence() // Do any additional setup after loading the view. } func listSentence() { var yposition = 20 do { let sentences = try self.db.prepare(self.sentencessTable.filter(self.type == "Best Word")) let sampleTextField = UITextField(frame: CGRect(x: 230, y: yposition, width: 100, height: 70)) //let sentences = self.sentencessTable.filter(self.type == "Right word") for sentence in sentences{ let id = sentence[self.id] let position = Int(sentence[self.position]) let sentence = sentence[self.sentence] print("ID :") print(id) let answers = try self.db.prepare(self.answersTable.filter(self.fk_sentence == id)) for answer in answers { print("answer----------------------") arrayOfAnswers.append(answer[self.answer]) } } } catch { print(error) } self.view.addSubview(scrollView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
674572c1e147f617b1357764bf2f20a2a3fb3784
Swift
cahz25/MatchingPairing
/MatchingPairsGame/CoreLayer/CoreLayer/Interactors/Base/Interactor.swift
UTF-8
538
2.65625
3
[]
no_license
// // Interactor.swift // CoreLayer // // Created by Cesar Hurtado on 7/12/19. // Copyright © 2019 cahz. All rights reserved. // import Foundation protocol InteractorProtocol { associatedtype P //associatedtype R func execute(params: P) } public class InteractorAsync<Params>: InteractorProtocol { typealias P = Params //typealias R = Response public init() { } public func execute(params: Params) -> () { return buildUseCase(params: params) } public func buildUseCase(params: Params) {} }
true
ff872df2d71f5bfb150ba77ea50b846f4000930f
Swift
serhii-londar/SwiftTwitch
/Sources/SwiftTwitch/Classes/Results/Clips/ClipData.swift
UTF-8
3,722
3.03125
3
[ "MIT" ]
permissive
// // ClipData.swift // SwiftTwitch // // Created by Christopher Perkins on 12/29/18. // import Foundation import Marshal /// `ClipData` is a class that encapsulates all of the information of a single returned clip from /// the returned array of Clip data from the New Twitch API's `Clips` methods. public struct ClipData: Unmarshaling { /// `broadcasterId` specifies the ID of the user from whose stream the clip was taken from. public let broadcasterId: String /// `broadcasterName` specifies the name of the user from whose stream the clip was taken from. public let broadcasterName: String /// `creationDate` specifies when the clip was created. public let creationDate: Date /// `creatorId` specifies the ID of the user from who created the clip. /// /// - Note: This shares **no relationship** with the broadcaster from whose stream the clip was /// from. See `broadcasterId` for that property instead. public let creatorId: String /// `creatorName` specifies the name of the user who created the clip. /// /// - Note: This shares **no relationship** with the broadcaster from whose stream the clip was /// from. See `broadcasterName` for that property instead. public let creatorName: String /// `embedURL` specifies the URL for which you can embed this clip into your application. public let embedURL: URL /// `gameId` specifies the ID of the game from which the clip was taken from. public let gameId: String /// `clipId` specifies the ID of the clip. public let clipId: String /// `language` specifies the language of the stream when the clip was created. public let language: String /// `thumbnailURL` specifies the URL of the clip thumbnail. public let thumbnailURL: URL /// `title` specifies the title of the clip. public let title: String /// `clipURL` specifies the URL where the clip can be viewed. /// /// - Note: This is **not** the same as the url to embed the clip. public let clipURL: URL /// `videoId` specifies the ID of the stream/video from which this clip was taken from. public let videoId: String /// `viewCount` specifies the amount of views this clip has. public let viewCount: Int /// Initializes a `ClipData` object from the input `MarshaledObject`. This will throw if there /// is missing data from the input `MarshaledObject`. /// /// - Parameter object: The object to initialize a `ClipData` piece from /// - Throws: If data is missing that was expected to be non-`nil`. public init(object: MarshaledObject) throws { broadcasterId = try object.value(for: Twitch.WebRequestKeys.broadcasterId) broadcasterName = try object.value(for: Twitch.WebRequestKeys.broadcasterName) creationDate = try object.value(for: Twitch.WebRequestKeys.createdAt) creatorId = try object.value(for: Twitch.WebRequestKeys.creatorId) creatorName = try object.value(for: Twitch.WebRequestKeys.creatorName) embedURL = try object.value(for: Twitch.WebRequestKeys.embedURL) gameId = try object.value(for: Twitch.WebRequestKeys.gameId) clipId = try object.value(for: Twitch.WebRequestKeys.id) language = try object.value(for: Twitch.WebRequestKeys.language) thumbnailURL = try object.value(for: Twitch.WebRequestKeys.thumbnailURL) title = try object.value(for: Twitch.WebRequestKeys.title) clipURL = try object.value(for: Twitch.WebRequestKeys.url) videoId = try object.value(for: Twitch.WebRequestKeys.videoId) viewCount = try object.value(for: Twitch.WebRequestKeys.viewCount) } }
true
6e4fee39d20ef71d54b188f2c845728c6b11412b
Swift
dapirra/iPhone_Memory_Game
/DavidPirragliaMemoryGame/Node.swift
UTF-8
417
3.0625
3
[]
no_license
// // Node.swift // DavidPirragliaMemoryGame // // Created by David Pirraglia on 12/17/18. // import Foundation struct Node { private var symbol: String private var match: Bool init(_ symbol: String, _ match: Bool = false) { self.symbol = symbol self.match = match } func getSymbol() -> String { return symbol } func isMatch() -> Bool { return match } }
true
f7e0f7a669cdc6e2468ee706deceab4b8d876029
Swift
loyihsu/fun-with-leetcode-in-swift
/Solutions/02 - Medium/0002. Add Two Numbers.swift
UTF-8
1,163
3.359375
3
[]
no_license
// Problem: https://leetcode.com/problems/add-two-numbers/ class Solution { func attach(_ node: ListNode?, to list: inout ListNode?) { guard var start = list else { return } while let next = start.next { start = next } start.next = node } func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { var temp1: ListNode? = l1 var temp2: ListNode? = l2 var carry = 0, newValue = 0 var answer: ListNode? while temp1 != nil || temp2 != nil || carry > 0 { newValue = carry carry = 0 if let value = temp1?.val { newValue += value } if let value = temp2?.val { newValue += value } carry = newValue >= 10 ? 1 : 0 newValue = carry != 0 ? newValue - 10 : newValue let newNode = ListNode(newValue) if answer == nil { answer = newNode } else { attach(newNode, to: &answer) } if let t = temp1 { temp1 = t.next } if let t = temp2 { temp2 = t.next } } return answer } }
true
6b504395926bd11f4af35ae65457fab249db3472
Swift
Multinerd-Forks/Swift-WTCoreGraphicsExtensions
/WTCoreGraphicsExtensions/Classes/WTCoreGraphicsExtensionsError.swift
UTF-8
2,532
2.71875
3
[ "MIT" ]
permissive
/* WTCoreGraphicsExtensionsError.swift WTCoreGraphicsExtensions Created by Wagner Truppel on 2016.12.03. The MIT License (MIT) Copyright (c) 2016 Wagner Truppel. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. When crediting me (Wagner Truppel) for this work, please use one of the following two suggested formats: Uses "WTCoreGraphicsExtensions" by Wagner Truppel https://github.com/wltrup or WTCoreGraphicsExtensions by Wagner Truppel https://github.com/wltrup */ /// An enumeration describing the possible errors that can be thrown when /// using functions from the extended `CGPoint` and `CGVector` APIs provided /// by **WTCoreGraphicsExtensions**. /// /// - **negativeTolerance**: /// Signifies that the function throwing the error expected /// a non-negative `tolerance` value but was provided with /// a negative one. /// /// - **notNormalizable**: /// Signifies that the attempted function could not be performed /// because the `CGVector` instance on which it would operate is /// not normalizable (ie, is the zero vector). /// /// - **negativeMagnitude**: /// Signifies that the attempted function expected a non-negative /// value for the `magnitude` argument but was passed a negative one. /// /// - **divisionByZero**: /// Signifies that an attempt was performed to divide a value by zero. public enum WTCoreGraphicsExtensionsError: Error { case negativeTolerance case negativeMagnitude case notNormalizable case divisionByZero }
true
fb1625741512f0e0e8b8e905a5b70841136f2b36
Swift
jotape26/PokeFinder
/PokeFinder/Models/LoginModel.swift
UTF-8
2,010
2.828125
3
[]
no_license
// // LoginModel.swift // PokeFinder // // Created by João Leite on 04/02/21. // import Foundation import RealmSwift class LoginModel: Object { var email : String = "" @objc dynamic var password : String = "" func login(success: @escaping()->(), failure: @escaping()->()) { guard let url = URL(string: "https://reqres.in/api/users?page=1") else { return } let urlRequest = URLRequest(url: url) let dataTask = URLSession.shared.dataTask(with: urlRequest, completionHandler: { (data, response, error) in if let err = error { print("Erro na requisicao: \(err.localizedDescription)") return } if let data = data { do { let jsonData = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String : Any] if let users = jsonData?["data"] as? [[String : Any]] { if users.contains(where: { ($0["email"] as? String) ?? "" == self.email }) { success() return } } } catch let exception { print(exception.localizedDescription) } } failure() }) dataTask.resume() } class func loadUser() -> LoginModel? { let uiRealm = try? Realm() return uiRealm?.objects(LoginModel.self).first } func save(email: String, password: String) { if let realm = try? Realm() { realm.beginWrite() self.password = password self.email = email if realm.objects(LoginModel.self).first == nil { realm.add(self) } try? realm.commitWrite() } } }
true
d2a69932d9f914ae313b0ad29797de8524553188
Swift
johnwongapi/APIClientKit
/Source/Request/BaseRequest.swift
UTF-8
1,498
2.734375
3
[ "MIT" ]
permissive
// // BaseRequest.swift // APIClient // // Created by John Wong on 27/11/2017. // Copyright © 2017 John Wong. All rights reserved. // import Foundation public protocol BaseRequest: class { var domain: String { get } var path: String { get } var url: String { get } var method: HTTPMethod { get } var encoding: APIEncoding { get } var header: [String:String] { get } func configHeader() -> [String:String] var parameters: [String: Any] { get } func configParameters() -> [String: Any] var callBackQueue: DispatchQueue { get } var timeoutInterval: TimeInterval { get } } public extension BaseRequest { var url: String { if self.path.isEmpty { return self.domain } var domain = self.domain var path = self.path if domain.last == "/" { domain.removeLast() } if path.first == "/" { path.removeFirst() } return "\(domain)/\(path)" } var header: [String:String] { return [:] } func configHeader() -> [String: String] { return self.header } var parameters: [String: Any] { return [:] } func configParameters() -> [String: Any] { return self.parameters } var callBackQueue: DispatchQueue { return APIClient.default.callbackQueue } var timeoutInterval: TimeInterval { return 30 } }
true
acc177214ea85af1ec2e6f2fceeb0ea9c7b1f827
Swift
LIFX/AudioKit
/AudioKit/Common/Nodes/Mixing/Automation/Fader/AKFader.swift
UTF-8
11,235
2.953125
3
[ "MIT" ]
permissive
// // AKFader.swift // AudioKit // // Created by Aurelius Prochazka and Ryan Francesconi, revision history on Github. // Copyright © 2019 AudioKit. All rights reserved. // /// Stereo Fader. Similar to AKBooster but with the addition of /// Automation support. open class AKFader: AKNode, AKToggleable, AKComponent, AKInput, AKAutomatable { public typealias AKAudioUnitType = AKFaderAudioUnit /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(effect: "fder") public static var gainRange: ClosedRange<Double> = (0 ... 4) // MARK: - Properties private var internalAU: AKAudioUnitType? private var _parameterAutomation: AKParameterAutomation? public var parameterAutomation: AKParameterAutomation? { return self._parameterAutomation } fileprivate var leftGainParameter: AUParameter? fileprivate var rightGainParameter: AUParameter? fileprivate var taperParameter: AUParameter? fileprivate var skewParameter: AUParameter? fileprivate var offsetParameter: AUParameter? fileprivate var flipStereoParameter: AUParameter? fileprivate var mixToMonoParameter: AUParameter? /// Amplification Factor, from 0 ... 4 @objc open dynamic var gain: Double = 1 { willSet { // ensure that the parameters aren't nil, // if they are we're using this class directly inline as an AKNode if internalAU?.isSetUp == true { leftGainParameter?.value = AUValue(newValue) rightGainParameter?.value = AUValue(newValue) return } // this means it's direct inline internalAU?.setParameterImmediately(.leftGain, value: newValue) internalAU?.setParameterImmediately(.rightGain, value: newValue) } } /// Left Channel Amplification Factor @objc open dynamic var leftGain: Double = 1 { willSet { if internalAU?.isSetUp == true { leftGainParameter?.value = AUValue(newValue) return } internalAU?.setParameterImmediately(.leftGain, value: newValue) } } /// Right Channel Amplification Factor @objc open dynamic var rightGain: Double = 1 { willSet { if internalAU?.isSetUp == true { rightGainParameter?.value = AUValue(newValue) return } internalAU?.setParameterImmediately(.rightGain, value: newValue) } } /// Amplification Factor in db @objc open dynamic var dB: Double { set { self.gain = pow(10.0, newValue / 20.0) } get { return 20.0 * log10(self.gain) } } /// Taper is a positive number where 1=Linear and the 0->1 and 1 and up represent curves on each side of linearity @objc open dynamic var taper: Double = 1 { willSet { if internalAU?.isSetUp == true { taperParameter?.value = AUValue(newValue) return } internalAU?.setParameterImmediately(.taper, value: newValue) } } /// Skew ranges from zero to one where zero is easing In and 1 is easing Out. default 0. @objc open dynamic var skew: Double = 0 { willSet { if internalAU?.isSetUp == true { skewParameter?.value = AUValue(newValue) return } internalAU?.setParameterImmediately(.skew, value: newValue) } } /// Offset allows you to start a ramp somewhere in the middle of it. default 0. @objc open dynamic var offset: Double = 0 { willSet { if internalAU?.isSetUp == true { offsetParameter?.value = AUValue(newValue) return } internalAU?.setParameterImmediately(.offset, value: newValue) } } /// Flip left and right signal @objc open dynamic var flipStereo: Bool = false { willSet { if internalAU?.isSetUp == true { flipStereoParameter?.value = AUValue(newValue ? 1.0 : 0.0) return } internalAU?.setParameterImmediately(.flipStereo, value: newValue ? 1.0 : 0.0) } } /// Make the output on left and right both be the same combination of incoming left and mixed equally @objc open dynamic var mixToMono: Bool = false { willSet { if internalAU?.isSetUp == true { mixToMonoParameter?.value = AUValue(newValue ? 1.0 : 0.0) return } internalAU?.setParameterImmediately(.mixToMono, value: newValue ? 1.0 : 0.0) } } /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted: Bool { return self.internalAU?.isPlaying ?? false } // MARK: - Initialization /// Initialize this fader node /// /// - Parameters: /// - input: AKNode whose output will be amplified /// - gain: Amplification factor (Default: 1, Minimum: 0) /// @objc public init(_ input: AKNode? = nil, gain: Double = 1, taper: Double = 1, skew: Double = 0, offset: Double = 0) { self.leftGain = gain self.rightGain = gain self.taper = taper self.skew = skew self.offset = offset _Self.register() super.init() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in guard let strongSelf = self else { AKLog("Error: self is nil") return } strongSelf.avAudioUnit = avAudioUnit strongSelf.avAudioNode = avAudioUnit strongSelf.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType input?.connect(to: strongSelf) } guard let tree = internalAU?.parameterTree else { AKLog("Parameter Tree Failed") return } self.leftGainParameter = tree["leftGain"] self.rightGainParameter = tree["rightGain"] self.taperParameter = tree["taper"] self.skewParameter = tree["skew"] self.offsetParameter = tree["offset"] self.flipStereoParameter = tree["flipStereo"] self.mixToMonoParameter = tree["mixToMono"] self.internalAU?.setParameterImmediately(.leftGain, value: gain) self.internalAU?.setParameterImmediately(.rightGain, value: gain) self.internalAU?.setParameterImmediately(.taper, value: taper) self.internalAU?.setParameterImmediately(.skew, value: skew) self.internalAU?.setParameterImmediately(.offset, value: offset) self.internalAU?.setParameterImmediately(.flipStereo, value: flipStereo ? 1.0 : 0.0) self.internalAU?.setParameterImmediately(.mixToMono, value: mixToMono ? 1.0 : 0.0) if let internalAU = internalAU, let avAudioUnit = avAudioUnit { self._parameterAutomation = AKParameterAutomation(internalAU, avAudioUnit: avAudioUnit) } } open override func detach() { super.detach() self._parameterAutomation = nil } @objc deinit { AKLog("* { AKFader }") } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing @objc open func start() { self.internalAU?.shouldBypassEffect = false // self.internalAU?.start() // shouldn't be necessary now } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { self.internalAU?.shouldBypassEffect = true // self.internalAU?.stop() // shouldn't be necessary now } // MARK: - AKAutomatable public func startAutomation(at audioTime: AVAudioTime?, duration: AVAudioTime?) { self.parameterAutomation?.start(at: audioTime, duration: duration) } public func stopAutomation() { self.parameterAutomation?.stop() } /// Convenience function for adding a pair of points for both left and right addresses public func addAutomationPoint(value: Double, at sampleTime: AUEventSampleTime, anchorTime: AUEventSampleTime, rampDuration: AUAudioFrameCount = 0, taper taperValue: Double? = nil, skew skewValue: Double? = nil, offset offsetValue: AUAudioFrameCount? = nil) { guard let leftAddress = leftGainParameter?.address, let rightAddress = rightGainParameter?.address else { AKLog("Param addresses aren't valid") return } // if a taper value is passed in, also add a point with its address to trigger at the same time if let taperValue = taperValue, let taperAddress = taperParameter?.address { self.parameterAutomation?.addPoint(taperAddress, value: AUValue(taperValue), sampleTime: sampleTime, anchorTime: anchorTime, rampDuration: rampDuration) } // if a skew value is passed in, also add a point with its address to trigger at the same time if let skewValue = skewValue, let skewAddress = skewParameter?.address { self.parameterAutomation?.addPoint(skewAddress, value: AUValue(skewValue), sampleTime: sampleTime, anchorTime: anchorTime, rampDuration: rampDuration) } // if an offset value is passed in, also add a point with its address to trigger at the same time if let offsetValue = offsetValue, let offsetAddress = offsetParameter?.address { self.parameterAutomation?.addPoint(offsetAddress, value: AUValue(offsetValue), sampleTime: sampleTime, anchorTime: anchorTime, rampDuration: rampDuration) } self.parameterAutomation?.addPoint(leftAddress, value: AUValue(value), sampleTime: sampleTime, anchorTime: anchorTime, rampDuration: rampDuration) self.parameterAutomation?.addPoint(rightAddress, value: AUValue(value), sampleTime: sampleTime, anchorTime: anchorTime, rampDuration: rampDuration) } }
true
7b8dc4a9db5109656a6fac2b122ebb3501d8e913
Swift
rbirdman/PersonalProjects
/Mastermind/Mastermind/HumanPlayer.swift
UTF-8
1,348
3.4375
3
[]
no_license
// // HumanPlayer.swift // Mastermind // // Created by Ryan Bird on 12/7/14. // Copyright (c) 2014 Ryan Bird. All rights reserved. // import Foundation class HumanPlayer: Player { init() { } func readLine() -> String { var fh = NSFileHandle.fileHandleWithStandardInput() var str = NSString(data: fh.availableData, encoding: NSUTF8StringEncoding) var str_val = String(str!) // remove endline character return str_val.substringToIndex(str_val.endIndex.predecessor()) // } } func lineToColorSequence(line:String) -> GameBoard.ColorSequence { var colors = line.componentsSeparatedByString(" ") var sequence = GameBoard.ColorSequence() for color in colors { var piece = GameBoard.Piece.stringToPiece(color) sequence.sequence.append(piece) } return sequence } func getSecretSequence(sequenceLength:Int) -> GameBoard.ColorSequence { print("What is the secret sequence? ") var input = readLine() return lineToColorSequence(input) } func getGuess(sequenceLength:Int) -> GameBoard.ColorSequence { print("What is your guess? ") var input = readLine() return lineToColorSequence(input) // return GameBoard.ColorSequence(pieces:GameBoard.Piece.Blue, GameBoard.Piece.Red, GameBoard.Piece.Green, GameBoard.Piece.Yellow) } func guessResult(correctPlacement:Int, incorrectPlacement:Int) { } }
true
07e46bc1fb5301beaaa93bfe1af3aca156792f8c
Swift
CheshirskijCat/otus-swiftui-coursework
/hw_15/hw_15/view/FilmView.swift
UTF-8
1,702
2.828125
3
[]
no_license
// // FilmView.swift // hw_11 // // Created by Dmitry Dementyev on 20.04.2020. // Copyright © 2020 Dmitry Dementyev. All rights reserved. // import Foundation import SwiftUI struct FilmView: View { @EnvironmentObject private (set) var content: FilmViewModel var body: some View { VStack{ HStack{ Text("Title") .frame(width: 100, alignment: .trailing) Text(content.title) .frame(width: 200, alignment: .leading) } HStack{ Text("Director") .frame(width: 100, alignment: .trailing) Text(content.director) .frame(width: 200, alignment: .leading) } HStack{ Text("Producer") .frame(width: 100, alignment: .trailing) Text(content.producer) .frame(width: 200, alignment: .leading) } HStack{ Text("Release date") .frame(width: 100, alignment: .trailing) Text(content.releaseDate) .frame(width: 200, alignment: .leading) } HStack{ Text("Score") .frame(width: 100, alignment: .trailing) Text(content.rtScore) .frame(width: 200, alignment: .leading) } HStack{ Text("Description") .frame(width: 100, alignment: .trailing) Text(content.filmDescription) .frame(width: 200) .lineLimit(10) } } } }
true
54f635cec7b2bd2362b4f9d83f730781d6dad1c9
Swift
nhatduy129/ios-core
/Project/42.TransitionAnimationAdvance/42.TransitionAnimationAdvance/Controllers/PresentationController.swift
UTF-8
3,473
2.671875
3
[]
no_license
// // PresentationController.swift // 42.TransitionAnimationAdvance // // Created by Duy Nguyen on 26/3/20. // Copyright © 2020 Duy Nguyen. All rights reserved. // import UIKit class BasePresentedVC: UIViewController, UIViewControllerTransitioningDelegate { var widthPresentedPercent: Float { return 0.8 } var heightPresentedPercent: Float { return 0.5 } required init?(coder: NSCoder) { super.init(coder: coder) self.modalPresentationStyle = .custom self.transitioningDelegate = self } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // Add round coner self.view.layer.masksToBounds = true self.view.layer.cornerRadius = 10 } // MARK: - UIViewControllerTransitioningDelegate func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { return PresentationController(presented: presented, presenting: presenting, widthPercent: self.widthPresentedPercent, heightPercent: self.heightPresentedPercent) } } fileprivate class PresentationController : UIPresentationController { private var widthPercent: Float = 1 private var heightPercent: Float = 1 private override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { super.init(presentedViewController: presentedViewController, presenting: presentingViewController) } convenience init(presented: UIViewController, presenting: UIViewController?, widthPercent: Float, heightPercent: Float) { self.init(presentedViewController: presented, presenting: presenting) self.widthPercent = widthPercent self.heightPercent = heightPercent } override func presentationTransitionWillBegin() { guard let viewToAnimate = self.containerView else { return } viewToAnimate.clipsToBounds = true viewToAnimate.transform = CGAffineTransform(scaleX: 0, y: 0) self.presentedViewController.transitionCoordinator?.animate(alongsideTransition: {_ in viewToAnimate.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: nil) } override func presentationTransitionDidEnd(_ completed: Bool) { UIView.animate(withDuration: 0.15, animations: {[unowned self] in self.presentingViewController.view.superview?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5) }) } override func dismissalTransitionWillBegin() { guard let viewToAnimate = self.containerView else { return } self.presentedViewController.transitionCoordinator?.animate(alongsideTransition: {_ in viewToAnimate.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) // If put 0, it does not work }, completion: nil) } override var frameOfPresentedViewInContainerView: CGRect { guard let containerView = containerView else { return .zero } return CGRect(x: containerView.bounds.width * CGFloat(1 - self.widthPercent) / 2, y: containerView.bounds.height * CGFloat(1 - self.heightPercent) / 2, width: containerView.bounds.width * CGFloat(self.widthPercent), height: containerView.bounds.height * CGFloat(self.heightPercent)) } }
true
9dab7ff311ba3f9ab903e92d3be220ac82a4ef10
Swift
omochi/WeaselRoll
/Sources/WeaselRoll/Store/StoreProtocol.swift
UTF-8
363
3.109375
3
[ "MIT" ]
permissive
public protocol StoreProtocol { associatedtype Value func load() throws -> Value func store(_ value: Value) throws } extension StoreProtocol { @discardableResult public func modify(_ f: (inout Value) throws -> Void) throws -> Value { var value = try load() try f(&value) try store(value) return value } }
true
cb64c031c09a6820fa612ee48718725daf3ed6b4
Swift
risa-nonogaki/Fridge-Checker
/Fridge/NewRecipeIngredientsViewController.swift
UTF-8
5,722
2.515625
3
[]
no_license
// // NewRecipeIngredientsViewController.swift // Fridge // // Created by Lisa Nonogaki on 2020/10/11. // Copyright © 2020 Lisa Nonogaki. All rights reserved. // import UIKit import NCMB class NewRecipeIngredientsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate, ingredientsDelegate { var ingredientsArray = [String]() var quantityArray = [String]() var unitArray = [String]() @IBOutlet var ingredientsTableView: UITableView! @IBOutlet var numberOfPeopleTextField: UITextField! @IBOutlet var nextPageButton: UIButton! override func viewDidLoad() { super.viewDidLoad() ingredientsTableView.dataSource = self ingredientsTableView.delegate = self numberOfPeopleTextField.delegate = self ingredientsTableView.tableFooterView = UIView() ingredientsTableView.rowHeight = 50 numberOfPeopleTextField.keyboardType = .decimalPad // カスタムセルの宣言 let nib = UINib(nibName: "IngredientsTableViewCell", bundle: Bundle.main) ingredientsTableView.register(nib, forCellReuseIdentifier: "IngredientsCell") } override func viewWillAppear(_ animated: Bool) { let ud = UserDefaults.standard if ud.bool(forKey: "newRecipe") == true { if ud.bool(forKey: "makingRecipe2") == false { ingredientsArray.removeAll() //作ってる最中って伝えるもの ud.set(true, forKey: "makingRecipe2") } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return ingredientsArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "IngredientsCell") as! IngredientsTableViewCell cell.ingredientsTextField.text = ingredientsArray[indexPath.row] cell.quantityTextField.text = quantityArray[indexPath.row] cell.unitTextField.text = unitArray[indexPath.row] cell.delegate = self cell.tag = indexPath.row return cell } func textFieldDidEndEditing(_ textField: UITextField) { confirmContent() } func didEditIngredientsTextField(tableViewCell: UITableViewCell, textField: UITextField){ ingredientsArray[tableViewCell.tag] = textField.text! //print(ingredientsArray) } func didEditQuantityTextField(tableViewCell: UITableViewCell, textField: UITextField) { quantityArray[tableViewCell.tag] = textField.text! //print(quantityArray) } func didEditUnitTextField(tableViewCell: UITableViewCell, textField: UITextField) { unitArray[tableViewCell.tag] = textField.text! //print(unitArray) } func deleteIngredientsCellButton(tableViewCell: UITableViewCell, button: UIButton) { ingredientsArray.remove(at: tableViewCell.tag) unitArray.remove(at: tableViewCell.tag) quantityArray.remove(at: tableViewCell.tag) print(unitArray) print(quantityArray) ingredientsTableView.reloadData() } func confirmContent() { if ingredientsArray.count > 0 || numberOfPeopleTextField.text != nil { nextPageButton.isHidden = false } else { nextPageButton.isHidden = true } } @IBAction func tapScreen(_ sender: Any) { self.view.endEditing(true) } //材料cellの追加 @IBAction func addIngredients() { let alertController = UIAlertController(title: "材料追加", message: "材料名を入力してください", preferredStyle: .alert) let addAction = UIAlertAction(title: "追加", style: .default) { (action) in // newItemsの配列(辞書型)に追加する self.ingredientsArray.append((alertController.textFields?.first?.text)!) // 配列をcellの数に揃える self.quantityArray.append("") self.unitArray.append("") // print(self.ingredientsArray) print(self.quantityArray) print(self.unitArray) self.ingredientsTableView.reloadData() self.confirmContent() } let cancelAction = UIAlertAction(title: "キャンセル", style: .cancel) { (action) in alertController.dismiss(animated: true, completion: nil) } alertController.addAction(addAction) alertController.addAction(cancelAction) // textFieldをalertControllerに追加する alertController.addTextField { (textField) in textField.placeholder = "材料名" } self.present(alertController, animated: true, completion: nil) } @IBAction func nextPage() { // userdefaultsに今ある情報を全て保存して画面遷移する //材料の配列・単位の配列・量の配列・何人分か let ud = UserDefaults.standard ud.set(numberOfPeopleTextField.text, forKey: "numberOfPeople") ud.set(ingredientsArray, forKey: "ingredientsArray") ud.set(quantityArray, forKey: "quantityArray") ud.set(unitArray, forKey: "unitArray") self.performSegue(withIdentifier: "toHowTo", sender: nil) } }
true
85c8a7ff6ca8e26899fda1ad852e30dc01412cea
Swift
Zipz-App/zipz-sdk-ios
/ZipzSDK/API Bridge/APIManager.swift
UTF-8
2,404
2.53125
3
[]
no_license
// // APIManager.swift // Zipz Framework // // Created by Mirko Trkulja on 25/04/2020. // Copyright © 2020 Aware. All rights reserved. // import Foundation import UIKit import CoreTelephony public enum TapSource: String { case organic = "organic" case notification = "notification" case deeplink = "deeplink" } class APIManager { // MARK: - Static // Set environment endpoint and version static let productionBase: String = "https://api.zipz.app/sdk/" static let developmentBase: String = "https://api.zipz.dev/sdk/" static let verison: String = "v1" static let environment: NetworkEnvironment = .development // MARK: - Static Computed Properties static var id: String = { guard let id = APIManager.getProperty(for: "APP_ID") else { fatalError("Insert APP_ID string property into Info.plist") } return id }() static var secret: String = { guard let secret = APIManager.getProperty(for: "APP_SECRET") else { fatalError("Insert APP_SECRET string property into Info.plist") } return secret }() static var device: String = { return UIDevice().type.rawValue }() static var sdkVersion: Int = { return 1 }() static var system: String = { return UIDevice.current.systemVersion }() static var carrier: String = { let networkInfo = CTTelephonyNetworkInfo() if let carriers = networkInfo.serviceSubscriberCellularProviders { for (key, value) in carriers { if let carrier = value.carrierName { return carrier } } } return "Unknown Carrier" }() static var bearer: String = { guard let token = APIToken.read()?.token else { return "" } return "Bearer \(token)" }() // MARK: - Private Init private init(){} // MARK: - Private Static private static func getProperty(for key: String) -> String? { guard let plist = Bundle.main.infoDictionary else { fatalError("FATAL ERROR: Info.plist not found!") } guard let value: String = plist[key] as? String else { return nil } return value } }
true
b3f8f04e5fa37c3ef9111914bb0ee121c5b85d6e
Swift
cerezo074/Swift-DataStructures
/Samples/Problem Solving.playground/Sources/String+Substring.swift
UTF-8
613
3.453125
3
[]
no_license
import Foundation public extension String { func substring(from leftPosition: Int, to rightPosition: Int) -> String? { guard rightPosition <= count - 1, rightPosition > leftPosition, leftPosition >= 0 else { return nil } let leftIndex = index(startIndex, offsetBy: leftPosition) let rightOffset = (count - rightPosition) * -1 let rightIndex = index(endIndex, offsetBy: rightOffset) guard leftIndex < rightIndex else { return nil } return String(self[leftIndex...rightIndex]) } }
true
543c48eafb85535ec3c20ac471f5753988658a52
Swift
ezefranca/TBLCategories
/Swift Extensions/UIImage+TBL.swift
UTF-8
1,678
2.84375
3
[ "MIT" ]
permissive
import UIKit extension UIImage { func imageWithColor(color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let context = UIGraphicsGetCurrentContext()! CGContextTranslateCTM(context, 0, self.size.height) CGContextScaleCTM(context, 1.0, -1.0); CGContextSetBlendMode(context, .Normal) let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect CGContextClipToMask(context, rect, self.CGImage) color.setFill() CGContextFillRect(context, rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage UIGraphicsEndImageContext() return newImage } class func imageWithText(text: String, textAttributes: [String: AnyObject]) -> UIImage { let size = text.sizeWithAttributes(textAttributes) UIGraphicsBeginImageContext(size) text.drawInRect(CGRect(origin: CGPointZero, size: size), withAttributes: textAttributes) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } class func imageWithText(text: String, font: UIFont, color: UIColor? = UIColor.darkTextColor()) -> UIImage { var attributes = [String : AnyObject]() attributes[NSFontAttributeName] = font attributes[NSForegroundColorAttributeName] = color return imageWithText(text, textAttributes: attributes) } class func imageWithText(text: String, fontSize: CGFloat, color: UIColor? = nil) -> UIImage { return imageWithText(text, font: UIFont.systemFontOfSize(fontSize), color: color) } }
true
2fa701265b119ae28db33ad0a9a2a1d837dfb635
Swift
kongzichixiangjiao/GATransitionAnimation
/CoreAnimation/vc/TileLayerViewController.swift
UTF-8
1,365
2.859375
3
[]
no_license
// // TileLayerViewController.swift // GATransitionAnimation // // Created by houjianan on 2017/3/26. // Copyright © 2017年 houjianan. All rights reserved. // import UIKit class TileLayerViewController: UIViewController { lazy var scrollView: UIScrollView = { let s = UIScrollView(frame: self.view.bounds) s.backgroundColor = UIColor.orange self.view.addSubview(s) return s }() override func viewDidLoad() { super.viewDidLoad() let tileLayer = CATiledLayer() tileLayer.frame = CGRect(x: 0, y: 0, width: 500, height: 500) tileLayer.delegate = self CATiledLayer.fadeDuration() self.scrollView.layer.addSublayer(tileLayer) self.scrollView.contentSize = tileLayer.frame.size tileLayer.setNeedsDisplay() } deinit { print("TileLayerViewController deinit") } } extension TileLayerViewController: CALayerDelegate { func draw(_ layer: CALayer, in ctx: CGContext) { // 所以请小心谨慎地确保你在这个方法中实现的绘制代码是线程安全的 UIGraphicsPushContext(ctx) let bounds = ctx.boundingBoxOfClipPath let image = UIImage(named: "02.png") image?.draw(in: bounds) UIGraphicsPopContext() } }
true
825d87c1872131b5c7e14e9798ffa9186438ade6
Swift
Ja7423/DrawView
/CustomView/CustomDrawView.swift
UTF-8
7,786
2.578125
3
[]
no_license
// // CustomDrawView.swift // CustomView // // Created by 何家瑋 on 2017/4/10. // Copyright © 2017年 何家瑋. All rights reserved. // import UIKit import CoreGraphics protocol CustomDrawViewDelegate { func getTotalPath(customDrawView : CustomDrawView) -> ([DrawPath]) func addPathRecord(customDrawView : CustomDrawView, moveRecord : DrawPath) func updatePathRecordWhenMoving(customDrawView : CustomDrawView, eachMovingPoint : [AnyObject]) } class CustomDrawView: UIView { var lineColor = UIColor.black var drawWidth : CGFloat = 5.0 var delegate : CustomDrawViewDelegate? var currentDrawMode = drawMode.line private var lastTouchPoint : CGPoint = CGPoint(x: 0.0, y: 0.0) private var drawImageView : UIImageView = UIImageView() private var eachMoveRecord : [AnyObject]? //MARK: //MARK: init override init(frame: CGRect) { super.init(frame: frame) drawImageView.frame = frame drawImageView.backgroundColor = UIColor.white self.frame = frame self.addSubview(drawImageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: //MARK: public func currentImage() -> UIImage? { if drawImageView.image != nil { return drawImageView.image } return nil } //MARK: // MARK: touch event func detectPanGestrue(panGesture : UIPanGestureRecognizer) { let touchPoint = panGesture.location(in: panGesture.view) switch panGesture.state { case .began: lastTouchPoint = touchPoint if eachMoveRecord == nil { eachMoveRecord = [AnyObject]() } switch currentDrawMode { case .line: eachMoveRecord?.append(lastTouchPoint as AnyObject) // add first touch point default: break } // append new array let drawPath = DrawPath() drawPath.lineColor = lineColor drawPath.drawWidth = drawWidth drawPath.moveRecord = eachMoveRecord! delegate?.addPathRecord(customDrawView: self, moveRecord: drawPath) case .changed: switch currentDrawMode { case .line: lastTouchPoint = touchPoint eachMoveRecord?.append(lastTouchPoint as AnyObject) case .circle: // circle only record last path let path = pathForDrawCircle(start: lastTouchPoint, toPoint: touchPoint) eachMoveRecord?.removeAll() eachMoveRecord?.append(path) case .rectAngle: // rectangle only record last path let path = pathForRectAngle(start: lastTouchPoint, toPoint: touchPoint) eachMoveRecord?.removeAll() eachMoveRecord?.append(path) } if eachMoveRecord != nil { delegate?.updatePathRecordWhenMoving(customDrawView: self, eachMovingPoint: eachMoveRecord!) } setNeedsDisplay() // update view case .ended: eachMoveRecord = nil default: break } } //MARK: //MARK: draw override func draw(_ rect: CGRect) { // Drawing code var isFirstPoint = true var previousPoint : CGPoint? var totalPath = [DrawPath]() totalPath = (delegate?.getTotalPath(customDrawView: self)) ?? [DrawPath]() UIGraphicsBeginImageContext(drawImageView.frame.size) for drawPath in totalPath { lineColor = drawPath.lineColor lineColor.set() drawWidth = drawPath.drawWidth if let points = drawPath.moveRecord as? [CGPoint] { for point in points { if isFirstPoint { isFirstPoint = false } else { pathForDrawLine(move: previousPoint!, toPoint: point).stroke() } previousPoint = point } isFirstPoint = true } else if let paths = drawPath.moveRecord as? [UIBezierPath] { for path in paths { path.stroke() } } } drawImageView.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } private func pathForDrawLine(move fromPoint : CGPoint, toPoint : CGPoint) ->UIBezierPath { let path = UIBezierPath() path.move(to: fromPoint) path.addLine(to: toPoint) path.lineWidth = drawWidth return path } private func pathForDrawCircle(start firstTouchPoint : CGPoint, toPoint : CGPoint) ->UIBezierPath { let path = UIBezierPath() let dx = toPoint.x - firstTouchPoint.x let dy = toPoint.y - firstTouchPoint.y let distance = sqrtf(Float(dx * dx + dy * dy)) path.addArc(withCenter: firstTouchPoint, radius: CGFloat(distance), startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true) path.lineWidth = drawWidth return path } private func pathForRectAngle(start firstTouchPoint : CGPoint, toPoint : CGPoint) ->UIBezierPath { let width = toPoint.x - firstTouchPoint.x let height = toPoint.y - firstTouchPoint.y let path = UIBezierPath(rect: CGRect(x: firstTouchPoint.x, y: firstTouchPoint.y, width: width, height: height)) path.lineWidth = drawWidth return path } }
true
16fff1874b12886152eb488057a6b33bb5a3b163
Swift
AdrianoAntoniev/BibliaSagrada
/BibliaSagrada/Supporting Files/Extensions.swift
UTF-8
227
2.609375
3
[]
no_license
// // File.swift // BibliaSagrada // // Created by Adriano Rodrigues Vieira on 28/02/21. // import Foundation // MARK: - Extension for int - convert to string extension Int { func toString() -> String { return "\(self)" } }
true
8884c555038b3a96b0b54272cd1a6a362867ae77
Swift
IvanGast/Basketball-Teams-Swift
/BasketballTeams/Cells/PlayerTableViewCell.swift
UTF-8
684
2.734375
3
[]
no_license
// // PlayerTableViewCell.swift // BasketballTeams // // Created by Ivan on 05/07/2019. // Copyright © 2019 Ivan. All rights reserved. // import UIKit class PlayerTableViewCell: UITableViewCell { @IBOutlet weak var playerImage: UIImageView! @IBOutlet weak var playerLabel: UILabel! func setup(_ image: UIImage, _ name: String, _ position: String, _ id: String) { playerImage.image = image playerImage.layer.cornerRadius = playerImage.frame.height/2 if position == "" { playerLabel.text = name } else { playerLabel.text = name + ", " + position } accessibilityIdentifier = id } }
true
3c6dfe50dfd6c70d99209a739d2284535cb43a1e
Swift
eslamhamam22/247IOS
/TwentyfourSeven/Data/Model/PlacePhoto.swift
UTF-8
672
2.765625
3
[]
no_license
// // PlacePhoto.swift // TwentyfourSeven // // Created by Salma on 8/15/19. // Copyright © 2019 Objects. All rights reserved. // import Foundation import Gloss class PlacePhoto: NSObject, Glossy{ var photo_reference : String? override init() { photo_reference = "" } init(photo_reference : String?) { self.photo_reference = photo_reference } required init?(json : JSON){ photo_reference = Decoder.decode(key: "photo_reference")(json) } func toJSON() -> JSON? { return jsonify([ Encoder.encode(key: "photo_reference")(self.photo_reference) ]) } }
true
96725679a541e0b7b8c52a970366a88d6043f192
Swift
Taboo-Game/Taboo-IOS
/Taboo-Game/Test.swift
UTF-8
280
2.6875
3
[]
no_license
// // Test.swift // Taboo-Game // // Created by Furkan Kaan Ugsuz on 20/01/2021. // import Foundation var testArray : [Test]? class Test { var test1 : String init(test1: String) { self.test1 = test1 } } func addTest() { testArray?.append(Test(test1: "yeay")) }
true
c28ca220fa1a89c867f8c47ae25a6ad0d9299de2
Swift
ComandoLando/swift-fhir
/sources/Models/EligibilityRequest.swift
UTF-8
12,925
2.53125
3
[ "Apache-2.0" ]
permissive
// // EligibilityRequest.swift // SwiftFHIR // // Generated from FHIR 1.4.0.8139 (http://hl7.org/fhir/StructureDefinition/EligibilityRequest) on 2016-08-17. // 2016, SMART Health IT. // import Foundation /** * Eligibility request. * * This resource provides the insurance eligibility details from the insurer regarding a specified coverage and * optionally some class of service. */ open class EligibilityRequest: DomainResource { override open class var resourceType: String { get { return "EligibilityRequest" } } /// Benefit Category. public var benefitCategory: Coding? /// Benefit SubCategory. public var benefitSubCategory: Coding? /// Business agreement. public var businessArrangement: String? /// Insurance or medical plan. public var coverageIdentifier: Identifier? /// Insurance or medical plan. public var coverageReference: Reference? /// Creation date. public var created: DateTime? /// Author. public var entererIdentifier: Identifier? /// Author. public var entererReference: Reference? /// Servicing Facility. public var facilityIdentifier: Identifier? /// Servicing Facility. public var facilityReference: Reference? /// Business Identifier. public var identifier: [Identifier]? /// Responsible organization. public var organizationIdentifier: Identifier? /// Responsible organization. public var organizationReference: Reference? /// Original version. public var originalRuleset: Coding? /// The subject of the Products and Services. public var patientIdentifier: Identifier? /// The subject of the Products and Services. public var patientReference: Reference? /// Desired processing priority. public var priority: Coding? /// Responsible practitioner. public var providerIdentifier: Identifier? /// Responsible practitioner. public var providerReference: Reference? /// Resource version. public var ruleset: Coding? /// Estimated date or dates of Service. public var servicedDate: FHIRDate? /// Estimated date or dates of Service. public var servicedPeriod: Period? /// Insurer. public var targetIdentifier: Identifier? /// Insurer. public var targetReference: Reference? /** Initialize with a JSON object. */ public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) { super.init(json: json, owner: owner) } override open func populate(fromJSON json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? { var errors = super.populate(fromJSON: json, presentKeys: &presentKeys) ?? [FHIRJSONError]() if let js = json { if let exist = js["benefitCategory"] { presentKeys.insert("benefitCategory") if let val = exist as? FHIRJSON { self.benefitCategory = Coding(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "benefitCategory", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["benefitSubCategory"] { presentKeys.insert("benefitSubCategory") if let val = exist as? FHIRJSON { self.benefitSubCategory = Coding(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "benefitSubCategory", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["businessArrangement"] { presentKeys.insert("businessArrangement") if let val = exist as? String { self.businessArrangement = val } else { errors.append(FHIRJSONError(key: "businessArrangement", wants: String.self, has: type(of: exist))) } } if let exist = js["coverageIdentifier"] { presentKeys.insert("coverageIdentifier") if let val = exist as? FHIRJSON { self.coverageIdentifier = Identifier(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "coverageIdentifier", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["coverageReference"] { presentKeys.insert("coverageReference") if let val = exist as? FHIRJSON { self.coverageReference = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "coverageReference", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["created"] { presentKeys.insert("created") if let val = exist as? String { self.created = DateTime(string: val) } else { errors.append(FHIRJSONError(key: "created", wants: String.self, has: type(of: exist))) } } if let exist = js["entererIdentifier"] { presentKeys.insert("entererIdentifier") if let val = exist as? FHIRJSON { self.entererIdentifier = Identifier(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "entererIdentifier", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["entererReference"] { presentKeys.insert("entererReference") if let val = exist as? FHIRJSON { self.entererReference = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "entererReference", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["facilityIdentifier"] { presentKeys.insert("facilityIdentifier") if let val = exist as? FHIRJSON { self.facilityIdentifier = Identifier(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "facilityIdentifier", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["facilityReference"] { presentKeys.insert("facilityReference") if let val = exist as? FHIRJSON { self.facilityReference = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "facilityReference", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["identifier"] { presentKeys.insert("identifier") if let val = exist as? [FHIRJSON] { self.identifier = Identifier.instantiate(fromArray: val, owner: self) as? [Identifier] } else { errors.append(FHIRJSONError(key: "identifier", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["organizationIdentifier"] { presentKeys.insert("organizationIdentifier") if let val = exist as? FHIRJSON { self.organizationIdentifier = Identifier(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "organizationIdentifier", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["organizationReference"] { presentKeys.insert("organizationReference") if let val = exist as? FHIRJSON { self.organizationReference = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "organizationReference", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["originalRuleset"] { presentKeys.insert("originalRuleset") if let val = exist as? FHIRJSON { self.originalRuleset = Coding(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "originalRuleset", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["patientIdentifier"] { presentKeys.insert("patientIdentifier") if let val = exist as? FHIRJSON { self.patientIdentifier = Identifier(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "patientIdentifier", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["patientReference"] { presentKeys.insert("patientReference") if let val = exist as? FHIRJSON { self.patientReference = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "patientReference", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["priority"] { presentKeys.insert("priority") if let val = exist as? FHIRJSON { self.priority = Coding(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "priority", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["providerIdentifier"] { presentKeys.insert("providerIdentifier") if let val = exist as? FHIRJSON { self.providerIdentifier = Identifier(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "providerIdentifier", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["providerReference"] { presentKeys.insert("providerReference") if let val = exist as? FHIRJSON { self.providerReference = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "providerReference", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["ruleset"] { presentKeys.insert("ruleset") if let val = exist as? FHIRJSON { self.ruleset = Coding(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "ruleset", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["servicedDate"] { presentKeys.insert("servicedDate") if let val = exist as? String { self.servicedDate = FHIRDate(string: val) } else { errors.append(FHIRJSONError(key: "servicedDate", wants: String.self, has: type(of: exist))) } } if let exist = js["servicedPeriod"] { presentKeys.insert("servicedPeriod") if let val = exist as? FHIRJSON { self.servicedPeriod = Period(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "servicedPeriod", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["targetIdentifier"] { presentKeys.insert("targetIdentifier") if let val = exist as? FHIRJSON { self.targetIdentifier = Identifier(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "targetIdentifier", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["targetReference"] { presentKeys.insert("targetReference") if let val = exist as? FHIRJSON { self.targetReference = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "targetReference", wants: FHIRJSON.self, has: type(of: exist))) } } } return errors.isEmpty ? nil : errors } override open func asJSON() -> FHIRJSON { var json = super.asJSON() if let benefitCategory = self.benefitCategory { json["benefitCategory"] = benefitCategory.asJSON() } if let benefitSubCategory = self.benefitSubCategory { json["benefitSubCategory"] = benefitSubCategory.asJSON() } if let businessArrangement = self.businessArrangement { json["businessArrangement"] = businessArrangement.asJSON() } if let coverageIdentifier = self.coverageIdentifier { json["coverageIdentifier"] = coverageIdentifier.asJSON() } if let coverageReference = self.coverageReference { json["coverageReference"] = coverageReference.asJSON() } if let created = self.created { json["created"] = created.asJSON() } if let entererIdentifier = self.entererIdentifier { json["entererIdentifier"] = entererIdentifier.asJSON() } if let entererReference = self.entererReference { json["entererReference"] = entererReference.asJSON() } if let facilityIdentifier = self.facilityIdentifier { json["facilityIdentifier"] = facilityIdentifier.asJSON() } if let facilityReference = self.facilityReference { json["facilityReference"] = facilityReference.asJSON() } if let identifier = self.identifier { json["identifier"] = identifier.map() { $0.asJSON() } } if let organizationIdentifier = self.organizationIdentifier { json["organizationIdentifier"] = organizationIdentifier.asJSON() } if let organizationReference = self.organizationReference { json["organizationReference"] = organizationReference.asJSON() } if let originalRuleset = self.originalRuleset { json["originalRuleset"] = originalRuleset.asJSON() } if let patientIdentifier = self.patientIdentifier { json["patientIdentifier"] = patientIdentifier.asJSON() } if let patientReference = self.patientReference { json["patientReference"] = patientReference.asJSON() } if let priority = self.priority { json["priority"] = priority.asJSON() } if let providerIdentifier = self.providerIdentifier { json["providerIdentifier"] = providerIdentifier.asJSON() } if let providerReference = self.providerReference { json["providerReference"] = providerReference.asJSON() } if let ruleset = self.ruleset { json["ruleset"] = ruleset.asJSON() } if let servicedDate = self.servicedDate { json["servicedDate"] = servicedDate.asJSON() } if let servicedPeriod = self.servicedPeriod { json["servicedPeriod"] = servicedPeriod.asJSON() } if let targetIdentifier = self.targetIdentifier { json["targetIdentifier"] = targetIdentifier.asJSON() } if let targetReference = self.targetReference { json["targetReference"] = targetReference.asJSON() } return json } }
true
147bf22966d77878fff80895c7f4c03159af5258
Swift
khou22/Gesture-Driven-Animations-iOS
/GestureDrivenAnimations/GestureDrivenAnimations/Extensions.swift
UTF-8
1,082
3.171875
3
[]
no_license
// // Extensions.swift // GestureDrivenAnimations // // Created by Breathometer on 7/5/16. // Copyright © 2016 KevinHou. All rights reserved. // import Foundation import UIKit extension UIColor { public convenience init?(hexString: String) { let r, g, b, a: CGFloat var hexColor = hexString if hexString.hasPrefix("#") { hexColor.remove(at: hexString.startIndex) if hexColor.characters.count == 6 { let scanner = Scanner(string: hexColor) var hexNumber: UInt64 = 0 if scanner.scanHexInt64(&hexNumber) { r = CGFloat((hexNumber & 0xff0000) >> 24) / 255 g = CGFloat((hexNumber & 0x00ff00) >> 16) / 255 b = CGFloat((hexNumber & 0x0000ff) >> 8) / 255 a = CGFloat(1.0) self.init(red: r, green: g, blue: b, alpha: a) return } } } return nil } }
true
ec73bf576c2214c8aadb8a064f0d07e704c8eb7d
Swift
lightspeedretail/FHIRModels
/Sources/FMCore/FHIRParserError.swift
UTF-8
3,587
2.859375
3
[ "Apache-2.0" ]
permissive
// // FHIRParserError.swift // HealthSoftware // // Copyright 2020 Apple Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation public struct FHIRParserErrorPosition: CustomStringConvertible { public let string: String public let location: Int public init(string: String, location: Int) { self.string = string self.location = location } public var description: String { return "[\(location)] in “\(string)”" } } // MARK: - FHIRParserErrorPosition extension FHIRParserErrorPosition: Equatable { public static func ==(lhs: FHIRParserErrorPosition, rhs: FHIRParserErrorPosition) -> Bool { if lhs.string != rhs.string { return false } if lhs.location != rhs.location { return false } return true } } // MARK: - FHIRDateParserError public enum FHIRDateParserError: LocalizedError { case invalidSeparator(FHIRParserErrorPosition) case invalidYear(FHIRParserErrorPosition) case invalidMonth(FHIRParserErrorPosition) case invalidDay(FHIRParserErrorPosition) case invalidHour(FHIRParserErrorPosition) case invalidMinute(FHIRParserErrorPosition) case invalidSecond(FHIRParserErrorPosition) case invalidTimeZonePrefix(FHIRParserErrorPosition) case invalidTimeZoneHour(FHIRParserErrorPosition) case invalidTimeZoneMinute(FHIRParserErrorPosition) case additionalCharacters(FHIRParserErrorPosition) public var errorDescription: String? { switch self { case .invalidSeparator(let position): return "Invalid separator at \(position)" case .invalidYear(let position): return "Invalid year at \(position)" case .invalidMonth(let position): return "Invalid month at \(position)" case .invalidDay(let position): return "Invalid day at \(position)" case .invalidHour(let position): return "Invalid hour at \(position)" case .invalidMinute(let position): return "Invalid minute at \(position)" case .invalidSecond(let position): return "Invalid second at \(position)" case .invalidTimeZonePrefix(let position): return "Invalid time zone prefix at \(position)" case .invalidTimeZoneHour(let position): return "Invalid time zone hour at \(position)" case .invalidTimeZoneMinute(let position): return "Invalid time zone minute at \(position)" case .additionalCharacters(let position): return "Unexpected characters after \(position)" } } public var errorPosition: FHIRParserErrorPosition { switch self { case .invalidSeparator(let position): return position case .invalidYear(let position): return position case .invalidMonth(let position): return position case .invalidDay(let position): return position case .invalidHour(let position): return position case .invalidMinute(let position): return position case .invalidSecond(let position): return position case .invalidTimeZonePrefix(let position): return position case .invalidTimeZoneHour(let position): return position case .invalidTimeZoneMinute(let position): return position case .additionalCharacters(let position): return position } } }
true
3dfb1b7662e5b23e7020ba6ad9d736bb5a20414b
Swift
jkrusnik/Apodini
/Sources/Apodini/Semantic Model Builder/Relationship/RelationshipCandidate.swift
UTF-8
8,166
3
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
// // Created by Andreas Bauer on 23.01.21. // enum RelationshipType: Hashable, CustomStringConvertible, CustomDebugStringConvertible { /// All relationships from the destination are inherited (including the self relationship). /// This requires that the `RelationshipSourceCandidate` contains resolvers /// for all path parameters of the relationship destination. case inheritance /// A reference describes a special case of Relationship where properties /// of the returned data is REPLACED by the relationship (e.g. a link in the REST exporter). /// This type requires that the `RelationshipSourceCandidate` contains resolvers /// for all path parameters of the relationship destination. case reference(name: String) /// A link is any kind of Relationship. It doesn't enforce any path parameters to be resolved /// (although it can be resolved if wanted). case link(name: String) var description: String { switch self { case .inheritance: return "inheritance" case .reference: return "reference" case .link: return "link" } } var debugDescription: String { switch self { case .inheritance: return "inheritance" case let .reference(name): return #"reference(name: "\#(name)")"# case let .link(name): return #"link(name: "\#(name)")"# } } var checkResolvers: Bool { if case .link = self { return false } return true } func hash(into hasher: inout Hasher) { description.hash(into: &hasher) } static func == (lhs: RelationshipType, rhs: RelationshipType) -> Bool { switch (lhs, rhs) { case (.inheritance, .inheritance), (.reference, .reference), (.link, .link): return true default: return false } } } /// Defines a relationship source candidate, either a resolved `RelationshipSourceCandidate` or unresolved `PartialRelationshipSourceCandidate` protocol SomeRelationshipSourceCandidate: CustomDebugStringConvertible { var type: RelationshipType { get } var destinationType: Any.Type { get } var reference: EndpointReference { get } var resolvers: [AnyPathParameterResolver] { get } /// Returns a resolved version of the candidate representation func ensureResolved(using builder: RelationshipBuilder) -> RelationshipSourceCandidate } /// Represents a candidate for a `EndpointRelationship` create using type information /// (either completely automatically or by type hints from the user) struct RelationshipSourceCandidate: SomeRelationshipSourceCandidate { var debugDescription: String { "RelationshipCandidate(\(type.debugDescription), targeting: \(destinationType), resolvers: \(resolvers.count))" } /// Defines the type of `RelationshipSourceCandidate`. See `RelationshipType`. /// For `.reference` type this implicitly defines the name of the relationship. let type: RelationshipType /// Defines the type of the destination in the `TypeIndex` let destinationType: Any.Type /// Defines the reference to the source let reference: EndpointReference let resolvers: [AnyPathParameterResolver] /// Initializes a `RelationshipSourceCandidate` with type of inheritance. init(destinationType: Any.Type, reference: EndpointReference, resolvers: [AnyPathParameterResolver]) { self.type = .inheritance self.destinationType = destinationType self.reference = reference self.resolvers = resolvers } fileprivate init(from partialCandidate: PartialRelationshipSourceCandidate, reference: EndpointReference, using builder: RelationshipBuilder) { self.type = partialCandidate.type self.destinationType = partialCandidate.destinationType self.reference = reference var parameterResolvers: [AnyPathParameterResolver] if case .inheritance = type { parameterResolvers = reference.absolutePath.listPathParameters().resolvers() } else { // We take all resolver used for inheritance into account in order for this to work // the `TypeIndex.resolve` steps MUST parse inheritance candidates FIRST. parameterResolvers = builder.selfRelationshipResolvers(for: reference) } // inserting manually defined resolvers BEFORE the "automatically" derived path parameter resolvers // to avoid conflicting resolvers (e.g. path parameter resolving the same parameter as property resolver) parameterResolvers.insert(contentsOf: partialCandidate.resolvers, at: 0) self.resolvers = parameterResolvers } func ensureResolved(using builder: RelationshipBuilder) -> RelationshipSourceCandidate { self } } /// A `RelationshipSourceCandidate` but without the scope of the `Endpoint` /// meaning still missing the `EndpointReference` and missing any `PathParameterResolver` in the `resolvers`. struct PartialRelationshipSourceCandidate: SomeRelationshipSourceCandidate { var debugDescription: String { "PartialRelationshipSourceCandidate(\(type.debugDescription), targeting: \(destinationType), resolvers: \(resolvers.count))" } /// Defines the type of `PartialRelationshipSourceCandidate`. See `RelationshipType`. /// For `.reference` type this implicitly defines the name of the relationship. let type: RelationshipType /// Defines the type of the destination in the `TypeIndex` let destinationType: Any.Type let resolvers: [AnyPathParameterResolver] /// Defines the reference to the source var reference: EndpointReference { guard let reference = storedReference else { fatalError("Tried accessing reference of PartialRelationshipSourceCandidate which wasn't linked to an Endpoint yet!") } return reference } var storedReference: EndpointReference? /// Initializes a `RelationshipSourceCandidate` with type of inheritance. init(destinationType: Any.Type, resolvers: [AnyPathParameterResolver]) { self.type = .inheritance self.destinationType = destinationType self.resolvers = resolvers } /// Initializes a `RelationshipSourceCandidate` with type of reference. init(reference name: String, destinationType: Any.Type, resolvers: [AnyPathParameterResolver]) { self.type = .reference(name: name) self.destinationType = destinationType self.resolvers = resolvers } /// Initializes a `RelationshipSourceCandidate` with type of reference. init(link name: String, destinationType: Any.Type, resolvers: [AnyPathParameterResolver] = []) { self.type = .link(name: name) self.destinationType = destinationType self.resolvers = resolvers } mutating func link(to endpoint: _AnyEndpoint) { storedReference = endpoint.reference } func ensureResolved(using builder: RelationshipBuilder) -> RelationshipSourceCandidate { RelationshipSourceCandidate(from: self, reference: reference, using: builder) } } extension Array where Element == PartialRelationshipSourceCandidate { func linked(to endpoint: _AnyEndpoint) -> [PartialRelationshipSourceCandidate] { map { var candidate = $0 candidate.link(to: endpoint) return candidate } } } extension Array where Element == RelationshipSourceCandidate { /// Index the `RelationshipSourceCandidate` array by the `EndpointReference` stored in `reference`. func referenceIndexed() -> CollectedRelationshipCandidates { var candidates: CollectedRelationshipCandidates = [:] for sourceCandidate in self { var collectedCandidates = candidates[sourceCandidate.reference, default: []] collectedCandidates.append(sourceCandidate) candidates[sourceCandidate.reference] = collectedCandidates } return candidates } }
true
908f11c202d1d7744ba38b7ec99cd4ec1b439c90
Swift
ekandemir/SwiftPractices
/timer/timer/ViewController.swift
UTF-8
800
2.65625
3
[]
no_license
// // ViewController.swift // timer // // Created by Developing on 7.08.2017. // Copyright © 2017 erdinckandemir. All rights reserved. // import UIKit class ViewController: UIViewController { var timer = Timer() var isonme = true @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(change), userInfo: nil, repeats: true) } @objc func change(_ sender: Any){ if isonme { imageView.image = UIImage(named: "onme.jpg") isonme = !isonme }else{ imageView.image = UIImage(named: "onyou.jpg") isonme = !isonme } } }
true
fb153175e583cff8431be0686b2752b2a4878ca6
Swift
kirualex/ColourLoveSwift
/ColourLoveSwift/Classes/Extensions/UIColor+Extensions.swift
UTF-8
1,763
3.078125
3
[]
no_license
// // UIColor+Extensions.swift // ColourLoveSwift // // Created by Alexis Creuzot on 17/11/2015. // Copyright © 2015 alexiscreuzot. All rights reserved. // extension UIColor { convenience init(hex: String) { let hex = hex.stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet) var int = UInt32() NSScanner(string: hex).scanHexInt(&int) let a, r, g, b: UInt32 switch hex.characters.count { case 3: // RGB (12-bit) (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: (a, r, g, b) = (1, 1, 1, 0) } self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255) } func inverseColor() -> UIColor { var r: CGFloat = 0.0 var g: CGFloat = 0.0 var b: CGFloat = 0.0 var a: CGFloat = 0.0 if self.getRed(&r, green: &g, blue: &b, alpha: &a) { return UIColor(red: 1.0-r, green: 1.0 - g, blue: 1.0 - b, alpha: a) } return self } func contrastColor() -> UIColor { let components = CGColorGetComponents(self.CGColor) let rBright = components[0] * 299 let gBright = components[1] * 587 let bBright = components[2] * 114 let brightness = (rBright + gBright + bBright) / 1000 if brightness < 0.5 { return UIColor.whiteColor() } else { return UIColor.blackColor() } } }
true
5024ea777e27b1eeb447b412d192e9612abd9253
Swift
adavalli123/Test
/Test/Items.swift
UTF-8
880
3.15625
3
[]
no_license
// // Items.swift // Test // // Created by Srikanth Adavalli on 5/16/16. // Copyright © 2016 Srikanth Adavalli. All rights reserved. // import UIKit class Items: Equatable { var productName: String var productPrice: String var productImage: UIImage var prodFullImage: UIImage var prodColor: String init(productName: String, productPrice: String, productImage: UIImage, prodFullImage: UIImage, prodColor: String) { self.productName = productName self.productPrice = productPrice self.productImage = productImage self.prodFullImage = prodFullImage self.prodColor = prodColor } } func ==(lhs: Items, rhs: Items) -> Bool { guard lhs.productName == rhs.productName && lhs.productPrice == rhs.productPrice && lhs.productImage == rhs.productImage && lhs.prodColor == rhs.prodColor else { return false } return true }
true
ce3937d5e14c9a31d0d83fd0d5f7de197af13148
Swift
HarryHoo23/Bright-Mroute
/Bright-Mroute-Iteration 2/Mroute/DashBoardViewController.swift
UTF-8
9,011
2.609375
3
[]
no_license
// // DashBoardViewController.swift // Mroute // // Created by Zhongheng Hu on 30/3/19. // Copyright © 2019 Zhongheng Hu. All rights reserved. // This is the class that when user load the application, initial page for user to navigate. import UIKit import Firebase // import firebase source code. import MapKit class DashBoardViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { var locationManager: CLLocationManager = CLLocationManager() var ref: DatabaseReference! //reference of firebase database var handle: DatabaseHandle! // handle of the firebase database var finalFacility = [Facility]() // create the array of facility, saved as object. var prones = [ProneZone]() // create the array of pronezone, saved as object. var hookTurn = [HookTurn]() // create the array of hookturn, saved as object. var quizArray = [Question]() var parking = [ParkingLot]() @IBAction func roadAssistanceButton(_ sender: Any) { // let phoneNumber = "1800105211" // if let phoneURL = URL(string: "tel://\(phoneNumber)"){ // UIApplication.shared.open(phoneURL, options: [:], completionHandler: nil) // } print("Tap") } override func viewDidLoad() { super.viewDidLoad() addFacility() addProneZone() addHookTurn() addQuestion() addParkingLot() // let addButton = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(tapButton)) //self.navigationItem.rightBarButtonItem = addButton // let user to allow location authorization. //self.viewDidLoad() self.locationManager.requestAlwaysAuthorization() self.locationManager.requestWhenInUseAuthorization() } // add facility data into facility arraylist. func addFacility(){ var newFacility = [Facility]() let ref2 = Database.database().reference().child("Facility") // retrieve data from firebase, the data source named "Facility" ref2.observe(.value , with: { snapshot in if snapshot.childrenCount > 0 || snapshot.childrenCount == 0 { for data in snapshot.children.allObjects as! [DataSnapshot]{ let object = data.value as? [String: AnyObject] let name = object?["Address"] as! String let long = object?["Longitude"] as! Double let lat = object?["Latitude"] as! Double let type = object?["Asset Type"] as! String let theFacility = Facility(name: name, type: type, longitude: long, latitude: lat) // create a new object, saved all attributes as init. newFacility.append(theFacility) } } self.finalFacility = newFacility }) } // similar to addFacility(), add hook turn data. func addHookTurn(){ var hook = [HookTurn]() let ref2 = Database.database().reference().child("HookTurn") ref2.observe(.value , with: { snapshot in if snapshot.childrenCount > 0 || snapshot.childrenCount == 0 { for data in snapshot.children.allObjects as! [DataSnapshot]{ let object = data.value as? [String: AnyObject] let name = object?["Name_Of_Roads"] as! String let long = object?["Lng"] as! Double let lat = object?["Lat"] as! Double let hookTurnInCBD = HookTurn(name: name, longitude: long, latitude: lat) hook.append(hookTurnInCBD) } } self.hookTurn = hook }) } // similar to addFacility(), add pronezone data. func addProneZone(){ var proneZone = [ProneZone]() let ref2 = Database.database().reference().child("ProneZone") ref2.observe(.value , with: { snapshot in if snapshot.childrenCount > 0 || snapshot.childrenCount == 0 { for data in snapshot.children.allObjects as! [DataSnapshot]{ let object = data.value as? [String: AnyObject] let name = object?["ROAD_GEOMETRY"] as! String let long = object?["LONGITUDE"] as! Double let lat = object?["LATITUDE"] as! Double let speed = object?["SPEED_ZONE"] as! String let critical = object?["Critical Level"] as! String let frequency = object?["Frequency"] as! Int let prone1 = ProneZone(title: name, longtitude: long, latitude: lat, speed: speed, critical: critical, frequency: frequency) proneZone.append(prone1) } } self.prones = proneZone }) } func addQuestion(){ var newQuiz = [Question]() var correctAnswer: Int = 0 let ref2 = Database.database().reference().child("Quiz") ref2.observe(.value , with: { snapshot in if snapshot.childrenCount > 0 || snapshot.childrenCount == 0 { for data in snapshot.children.allObjects as! [DataSnapshot]{ let object = data.value as? [String: AnyObject] let question = object?["Question"] as! String let choiceA = object?["Option A"] as! String let choiceB = object?["Option B"] as! String let choiceC = object?["Option C"] as! String let choiceD = object?["Option D"] as! String let answer = object?["Answer"] as! String let number = object?["No"] as! Int let description = object?["Description"] as! String switch answer { case "A" : correctAnswer = 0 case "B": correctAnswer = 1 case "C": correctAnswer = 2 case "D": correctAnswer = 3 default: break } let quiz = Question(questionText: question, choiceA: "A. " + choiceA, choiceB: "B. " + choiceB, choiceC: "C. " + choiceC, choiceD: "D. " + choiceD, answer: correctAnswer, qNumber: number, qDescription: description) newQuiz.append(quiz) } } self.quizArray = newQuiz //print(self.quizArray.count) }) } //This function is going to add the parkinglot information func addParkingLot(){ var parks = [ParkingLot]() let ref2 = Database.database().reference().child("ParkingLot") ref2.observe(.value , with: { snapshot in if snapshot.childrenCount > 0 || snapshot.childrenCount == 0 { for data in snapshot.children.allObjects as! [DataSnapshot]{ let object = data.value as? [String: AnyObject] let long = object?["lon"] as! Double let lat = object?["lat"] as! Double let bayId = object?["Bay_id"] as! Int64 let timeDuration = object?["TimeDuration"] as! Int let parkingDuration = object?["Parking_Duration"] as! String let payment = object?["Pay_Type"] as! String let streetId = object?["st_marker_id"] as! String let time = object?["Time"] as! String let status = object?["status"] as! String let days = object?["Days"] as! String let parkingLot = ParkingLot(longitude: long, latitude: lat, bayID: bayId, timeduration: timeDuration, duration: parkingDuration, payType: payment, streetID: streetId, parkTime: time, status: status, days: days) parks.append(parkingLot) } } self.parking = parks }) } //pass data from dashborad to two different controllers. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.destination is MapViewController{ let mc = segue.destination as? MapViewController mc?.proneZ = self.prones mc?.hookTurn = self.hookTurn } if segue.destination is AccessibleSpotsViewController{ let ac = segue.destination as? AccessibleSpotsViewController ac?.facility = self.finalFacility } if segue.destination is RulesViewController{ let rc = segue.destination as? RulesViewController rc?.questions = self.quizArray } if segue.destination is ParkingLotViewController{ let pc = segue.destination as? ParkingLotViewController pc?.parking = self.parking } } }
true
e09d71d3d910ba0e5a9f74ca5a2b2958db675f41
Swift
hutattedonmyarm/AOC2019
/11/11/main.swift
UTF-8
4,972
3.296875
3
[]
no_license
import Foundation public typealias Row = [Paint] public typealias Grid = [Row] public struct Point: Hashable { let column: Int let row: Int } public enum Direction { case up case right case down case left } public enum Paint: CustomStringConvertible { case black case white func toInt() -> Int { switch self { case .black: return 0 case .white: return 1 } } init?(output: Int) { if output == 0 { self = .black } else if output == 1 { self = .white } else { return nil } } public var description: String { switch self { case .black: return " " case .white: return "#" } } } public struct InfinityGrid: CustomStringConvertible { private var currentPosition: Point public private(set) var visited: [Point: Paint] private static let defaultColor = Paint.black public init(startColor: Paint) { self.currentPosition = Point(column: 0, row: 0) self.visited = [Point: Paint]() self.visited[currentPosition] = startColor } public init() { self.init(startColor: InfinityGrid.defaultColor) } mutating func moveRight() -> Paint { currentPosition = Point(column: self.currentPosition.column+1, row: self.currentPosition.row) return detect() } mutating func moveDown() -> Paint { currentPosition = Point(column: self.currentPosition.column, row: self.currentPosition.row+1) return detect() } mutating func moveLeft() -> Paint { currentPosition = Point(column: self.currentPosition.column-1, row: self.currentPosition.row) return detect() } mutating func moveUp() -> Paint { currentPosition = Point(column: self.currentPosition.column, row: self.currentPosition.row-1) return detect() } mutating func detect() -> Paint { if let paint = visited[currentPosition] { return paint } else { self.visited[currentPosition] = InfinityGrid.defaultColor return InfinityGrid.defaultColor } } mutating func paint(withColor color: Paint) { self.visited[currentPosition] = color } public var description: String { let maxCol = visited.max { $0.key.column < $1.key.column }!.key.column let minCol = visited.min { $0.key.column < $1.key.column }!.key.column let maxRow = visited.max { $0.key.row < $1.key.row }!.key.row let minRow = visited.min { $0.key.row < $1.key.row }!.key.row var str = "" for col in minCol...maxCol { for row in (minRow...maxRow).reversed() { let point = Point(column: col, row: row) var color = Paint.black if let painted = visited[point] { color = painted } str += color.description } str += "\n" } return str } } func go(input: String) { let memory = IOProgram.parse(program: input) var panels = InfinityGrid() var direction = Direction.up let input = { panels.detect().toInt() } var shouldPaint = true let output: (Int) -> Void = { if shouldPaint { panels.paint(withColor: Paint(output: $0)!) } else { switch direction { case .down where $0 == 0: direction = .right _ = panels.moveRight() case .down where $0 == 1: direction = .left _ = panels.moveLeft() case .left where $0 == 0: direction = .down _ = panels.moveDown() case .left where $0 == 1: direction = .up _ = panels.moveUp() case .up where $0 == 0: direction = .left _ = panels.moveLeft() case .up where $0 == 1: direction = .right _ = panels.moveRight() case .right where $0 == 0: direction = .up _ = panels.moveUp() case .right where $0 == 1: direction = .down _ = panels.moveDown() default: fatalError("Unknown output") } } shouldPaint = !shouldPaint } let robot = IOProgram(program: memory, input: input, output: output) robot.run() print(panels.visited.count) panels = InfinityGrid(startColor: .white) let robot2 = IOProgram(program: memory, input: input, output: output) robot2.run() print(panels) } guard let fileContents = try? String(contentsOfFile: "input.txt") else { fatalError("Cannot open input file") } go(input: fileContents)
true
95ec50998fb4f7060151c9b29ef8c5a7c0b7f73c
Swift
aship/dq3_ios
/DQ3/Constants/Positions/AliahanTownHouse.swift
UTF-8
740
2.734375
3
[ "MIT" ]
permissive
// // AliahanTownHouse.swift // DQ3 // // Created by aship on 2021/01/12. // // 母の初期位置 let AliahanTownHouseMotherPositionX = 4 let AliahanTownHouseMotherPositionY = 5 // 母がオープニングでさあ行きましょうと待機してる座標 let AliahanTownHouseMotherWaitingPositionX = 8 let AliahanTownHouseMotherWaitingPositionY = 2 // 勇者がオープニングで母にさあ行きましょうと言われる座標 let AliahanTownHouseMotherCallPositionX = 7 // 階段 let AliahanTownHouseStairsPositionX = 9 let AliahanTownHouseStairsPositionY = 2 // 勇者のじいちゃん let AliahanTownHouseOldManPositionX = 7 let AliahanTownHouseOldManPositionY = 5 let AliahanTownHouseOldManDirection: Direction = .up
true
17047c780323310297a4f7fd626e3a670c781f63
Swift
nonobjc/PushNotificationsApp
/PushApp/PayloadModification/NotificationService.swift
UTF-8
2,780
2.75
3
[]
no_license
// // NotificationService.swift // PayloadModification // // Created by Alexander on 19/02/2019. // Copyright © 2019 Alexander. All rights reserved. // import UserNotifications class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let bestAttemptContent = bestAttemptContent { // Modify the notification content bestAttemptContent.title = ROT228.shared.decrypt(bestAttemptContent.title) bestAttemptContent.body = ROT228.shared.decrypt(bestAttemptContent.body) if let urlPath = request.content.userInfo["media-url"] as? String, let url = URL(string: ROT228.shared.decrypt(urlPath)) { let destination = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(url.lastPathComponent) do { let data = try Data(contentsOf: url) try data.write(to: destination) let attachment = try UNNotificationAttachment(identifier: "", url: destination) bestAttemptContent.attachments = [attachment] } catch { } } if let badgeValue = bestAttemptContent.badge as? Int { switch badgeValue { case 0: UserDefaults.extensions.badge = 0 bestAttemptContent.badge = 0 default: let current = UserDefaults.extensions.badge let new = current + 1 UserDefaults.extensions.badge = new bestAttemptContent.badge = NSNumber(value: new) } } contentHandler(bestAttemptContent) } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } }
true
c76bdcb0eaaeafef9b7965e6aa68484bd1f11cf3
Swift
tienan-git/bukuma-ios
/Bukuma_ios_swift/UIImage+Extension.swift
UTF-8
5,643
2.921875
3
[]
no_license
// // UIImage+Extension.swift // Bukuma_ios_swift // // Created by Hiroshi Chiba on 2016/04/11. // Copyright © 2016年 Hiroshi Chiba. All rights reserved. // import Foundation import CoreGraphics private struct SizeReletaion { private enum Element { case Height case Width } private let longerSide: (value: CGFloat, element: Element) private let shoterSide: (value: CGFloat, element: Element) init(size: CGSize, scale: CGFloat) { longerSide = size.width > size.height ? (size.width * scale, .Width) : (size.height * scale, .Height) shoterSide = size.width > size.height ? (size.height * scale, .Height) : (size.width * scale, .Width) } func centerTrimRect() -> CGRect { let delta = (longerSide.value - shoterSide.value) / 2 let x = longerSide.element == .Height ? 0 : delta let y = longerSide.element == .Width ? 0 : delta return CGRect(x: x, y: y, width: shoterSide.value, height: shoterSide.value) } func relativeCenterTrimRect(targetSize: CGSize) -> CGRect { let delta = -(longerSide.value - shoterSide.value) / 2 let x = longerSide.element == .Height ? 0 : delta let y = longerSide.element == .Width ? 0 : delta let width = longerSide.element == .Width ? longerSide.value : shoterSide.value let height = longerSide.element == .Height ? longerSide.value : shoterSide.value let scale = shoterSide.element == .Height ? targetSize.height / height : targetSize.width / width return CGRect( x: x * scale, y: y * scale, width: width * scale, height: height * scale ) } } public extension UIImage { public func resizeImageFromImageSize(_ size: CGSize) ->UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, 0) self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resizedImage } public class func imageWithColor(_ color: UIColor, size: CGSize) ->UIImage? { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContext(rect.size) guard let context = UIGraphicsGetCurrentContext() else { return nil } context.setFillColor(color.cgColor) context.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } public class func imageWithColor(_ color: UIColor, _ cornerRadius: CGFloat, size: CGSize) ->UIImage? { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContext(rect.size) guard let context = UIGraphicsGetCurrentContext() else { return nil } context.setFillColor(color.cgColor) context.fill(rect) let bezierPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius) bezierPath.fill() let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func roundedCenterTrimImage(cornerRadius: CGFloat, targetSize: CGSize) -> UIImage? { let sizeRelation = SizeReletaion(size: size, scale: scale) guard let newImage = trimmedImage(rect: sizeRelation.centerTrimRect()) else { return nil } let scaledSize = CGSize(width: targetSize.width * scale, height: targetSize.height * scale) UIGraphicsBeginImageContext(scaledSize) let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: scaledSize.width, height: scaledSize.height), cornerRadius: cornerRadius) let imageView = UIImageView(image: newImage) imageView.frame = CGRect(x: 0, y: 0, width: scaledSize.width, height: scaledSize.height) imageView.layer.masksToBounds = true let maskLayer = CAShapeLayer() maskLayer.path = path.cgPath imageView.layer.mask = maskLayer guard let context = UIGraphicsGetCurrentContext() else { return nil } imageView.layer.render(in: context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func trimmedImage(rect: CGRect) -> UIImage? { guard let cgImage = self.cgImage!.cropping(to: rect) else { return nil } return UIImage(cgImage: cgImage) } public class func imageWithColor(_ color: UIColor) ->UIImage? { return self.imageWithColor(color, size: CGSize(width: 1.0, height: 1.0)) } public func imageAddingImage(_ image: UIImage, offset: CGPoint) ->UIImage? { var size: CGSize = self.size let scale: CGFloat = self.scale size.width *= scale size.height *= scale UIGraphicsBeginImageContext(size) self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) image.draw(in: CGRect(x: scale * offset.x, y: scale * offset.y, width: image.size.width * scale, height: image.size.height * scale)) guard let context = UIGraphicsGetCurrentContext() else { return nil } guard let bitmapContext = context.makeImage() else { return nil } let destImage = UIImage(cgImage: bitmapContext, scale: image.scale, orientation: .up) UIGraphicsEndImageContext() return destImage } }
true
23d39b891b1795f5e637e6d856f5f4d1ef2fdc51
Swift
cotsog/BricBrac
/BricBrac/BricBrac.swift
UTF-8
2,266
3.359375
3
[ "MIT" ]
permissive
// // BricBrac.swift // BricBrac // // Created by Marc Prud'hommeaux on 7/18/15. // Copyright © 2015 io.glimpse. All rights reserved. // /// A BricBrac is a user-defined type that can serialize/deserialize to/from some Bric /// In addition to conforming to Bricable and Bracable, it also provides Equatable and Hashable implementations /// and the ability to perform a deep copy with `bricbrac()`; note that standard primitives like String and Bool /// conform to both Bricable and Bracable but not to BricBrac because we don't want to conflict with their own /// Equatable and Hashable implementations public protocol BricBrac: Bricable, Bracable, Equatable, Hashable { // /// Perform semantic validation of the BricBrac; this could verify requirements that // /// cannot be addressed by the type system, such as string and array length requirements // func validate() throws } public extension BricBrac { /// A Bricable hash value is just the hash of its Bric var hashValue: Int { return bric().hashValue } /// Returns a deep copy of this instance func bricbrac() throws -> Self { return try Self.brac(self.bric()) } // /// The default validation method does nothing // func validate() { } } /// Bricable conformance means that you can compare two instances by comparing their serialized forms /// Note that this only comes from adopting `BricBrac`, and is not conferred by merely adopting `Bricable` and `Bracable`, /// because some types may want to be bricable and bracable but have their own equality logic public func == <J1: BricBrac, J2: BricBrac>(j1: J1, j2: J2) -> Bool { return j1.bric() == j2.bric() } /// A BricBrac that only bracs elements that do not conform to the underlying type /// Useful for handling "not" elements of the JSON Schema spec public struct NotBrac<T: Bricable where T: Bracable> : BricBrac, NilLiteralConvertible { public init() { } public init(nilLiteral: ()) { } /// this type does not bric to anything public func bric() -> Bric { return .Nul } public static func brac(bric: Bric) throws -> NotBrac { do { try T.brac(bric) } catch { return NotBrac() } throw BracError.ShouldNotBracError(type: T.self, path: []) } }
true
d0293ad1a6e6097e60673c8ad910965a2225bc9d
Swift
jep9816/PrimaMateria
/PrimaMateria/Source/Features/Help/SUIHelpBalloonView.swift
UTF-8
3,684
2.515625
3
[]
no_license
// // SUIHelpBalloon.swift // PrimaMateria // // Created by Jerry Porter on 6/17/21. // Copyright ©2023 Jerry Porter. All rights reserved. // import SwiftUI struct SUIHelpBalloonViewConfig { static let preferredContentSize = CGSize(width: 500, height: 400) } struct SUIHelpBalloonView: View { @EnvironmentObject var environment: SUIHelpBallonEnvironment @ObservedObject var webViewStateModel: SUIWebViewStateModel = SUIWebViewStateModel() var body: some View { NavigationView { ZStack { SUILoadingView(isShowing: .constant(webViewStateModel.loading)) { //loading logic taken from https://stackoverflow.com/a/56496896/9838937 //Add onNavigationAction if callback needed SUIWebView(url: URL(fileURLWithPath: environment.elementTipPath), webViewStateModel: self.webViewStateModel) .frame(width: SUIHelpBalloonViewConfig.preferredContentSize.width - 2, height: SUIHelpBalloonViewConfig.preferredContentSize.height - 38).offset(x: 0, y: 0) .background(Color(XTRColorFactory.helpBackgroundColor)) } .background(Color(XTRColorFactory.helpBackgroundColor)) .navigationBarTitle(Text(webViewStateModel.pageTitle), displayMode: .inline) .navigationBarItems( leading: // swiftlint:disable multiple_closures_with_trailing_closure Button(action: { self.webViewStateModel.goBack.toggle() }) { Label("Left Arrow", systemImage: "arrowtriangle.left.fill") .labelStyle(IconOnlyLabelStyle()) .frame(width: SUIWebViewConfig.barButtonSize.width, height: SUIWebViewConfig.barButtonSize.height, alignment: .leading) } .opacity(!webViewStateModel.canGoBack ? 0: 1) .disabled(!webViewStateModel.canGoBack) .aspectRatio(contentMode: .fill) .font(XTRFontFactory.boldSystem26), trailing: // swiftlint:disable multiple_closures_with_trailing_closure Button(action: { self.webViewStateModel.goForward.toggle() }) { Label("Right Arrow", systemImage: "arrowtriangle.right.fill") .labelStyle(IconOnlyLabelStyle()) .frame(width: SUIWebViewConfig.barButtonSize.width, height: SUIWebViewConfig.barButtonSize.height, alignment: .trailing) } .opacity(!webViewStateModel.canGoForward ? 0: 1) .disabled(!webViewStateModel.canGoForward) .aspectRatio(contentMode: .fill) .font(XTRFontFactory.boldSystem26) ) .frame(width: SUIHelpBalloonViewConfig.preferredContentSize.width - 2, height: SUIHelpBalloonViewConfig.preferredContentSize.height - 2).offset(x: 0, y: 0) } .background(Color(XTRColorFactory.helpBackgroundColor)) } } } struct SUIHelpBalloon_Previews: PreviewProvider { static var previews: some View { SUIHelpBalloonView().environmentObject(SUIHelpBallonEnvironment()) .previewLayout(.fixed(width: SUIHelpBalloonViewConfig.preferredContentSize.width, height: SUIHelpBalloonViewConfig.preferredContentSize.height)) } }
true
1f782503e973a4c2cd8db5635befb0ff001b017a
Swift
CameronRivera/Pursuit-Core-iOS-Functions-Lab-One
/Pursuit-Core-iOS-Functions-Lab-One/Pursuit-Core-iOS-Functions-Lab-One/functionsQuestions.swift
UTF-8
3,640
4.4375
4
[]
no_license
import Foundation // Question One // Write a function that takes in a Double and returns that number times two func double(_ num: Double) -> Double { return num * 2 } // Question Two // Write a function that takes in two Doubles and returns the smaller number func min(_ numOne: Double, _ numTwo: Double) -> Double { if numOne > numTwo { return numTwo } else { return numOne } } // Question Three // Write a function that takes in an array of Doubles and returns the smallest Double func smallestValue(in arr: [Double]) -> Double { var smallestDouble: Double = -1 if !arr.isEmpty { smallestDouble = arr[0] } for a in arr{ if a <= smallestDouble{ smallestDouble = a } } return smallestDouble } // Question Four // Write a function that counts how many characters in a String match a specific character. func occurrances(of char: Character, in str: String) -> Int { var timesCharMatched = 0 for s in str{ if s == char{ timesCharMatched += 1 } } return timesCharMatched } // Question Five // Write a function called removeNils that takes an array of optional Ints and returns an array with them unwrapped with any nil values removed. func removeNils(from arr: [Int?]) -> [Int] { var intArray: [Int] = [] for a in arr{ if let notNil = a{ intArray.append(notNil) } } return intArray } // Question Six // Write a function that takes a String as input and returns a dictionary that maps each character to its number of occurrences func frequencyDictionary(of str: String) -> [Character: Int] { var charOccurrence: [Character:Int] = [:] for s in str{ charOccurrence.updateValue(0,forKey:s) } for s in str{ charOccurrence.updateValue((charOccurrence[s] ?? 0) + 1,forKey: s) } return charOccurrence } // Question Seven // Write a function that returns all of the unique Characters in a String. func uniqueCharacters(in str: String) -> [Character] { var charSet: Set<Character> = [] var charSetDoubles: Set<Character> = [] var uniqueCharacters: [Character] = [] var setTuple: (Bool,Character) for s in str{ setTuple = charSet.insert(s) if !setTuple.0{ charSetDoubles.insert(setTuple.1) } } for s in str{ if !charSetDoubles.contains(s) { uniqueCharacters.append(s) } } return uniqueCharacters } // Question Eight // Write a function that checks if a String is a palindrome (the same backwards and forwards). // Bonus: Do not use the built in .reverse() or .reversed() methods. Ignore whitespaces, capitalization, and punctuation. func isPalindrome(str: String) -> Bool { var reversedString = "" var isAPalindrome = true let tempString = str var trimmedString: String = "" var offSet = 0 var currentIndex: String.Index = trimmedString.index(trimmedString.startIndex,offsetBy:offSet) for char in tempString{ if (char.isPunctuation || char.isWhitespace) { continue } trimmedString += String(char) } for s in trimmedString{ reversedString = String(s) + reversedString } for char in reversedString{ if(char.lowercased() != trimmedString[currentIndex].lowercased()){ isAPalindrome = false } offSet += 1 currentIndex = trimmedString.index(trimmedString.startIndex,offsetBy:offSet) } return isAPalindrome }
true
8518ddf7895aaba302928b91c67a45160d3feee6
Swift
gwcDominate/Dominate
/FinalProject2/PopUp12ViewController.swift
UTF-8
2,046
2.8125
3
[]
no_license
// // PopUp12ViewController.swift // FinalProject2 // // Created by GWC Student on 8/23/17. // Copyright © 2017 GWC Student. All rights reserved. // import UIKit class PopUp12ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var trophy: UIImageView! var array3 = [String]() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black.withAlphaComponent(0.5) array3 = ["Create a club with your friends (it can be a simple as a book club)","Watch a movie from a different genre","Go to a bowling alley and challenge someone to a game"] trophy.isHidden = true } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell12 = tableView.dequeueReusableCell(withIdentifier: "cell12")! as UITableViewCell cell12.textLabel?.text = array3[indexPath.row] cell12.textLabel?.numberOfLines=0; return cell12 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } let checkmark = 3 var amtCheckmark = 0 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCellAccessoryType.checkmark{ tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none amtCheckmark -= 1 } else { tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark amtCheckmark += 1 } if amtCheckmark == 3{ trophy.isHidden = false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func closePopUp12(_ sender: Any) { self.view.removeFromSuperview() } }
true
aa2e6efc9dfeec98a97bcf5fc3a8c5d01341a3a9
Swift
vadim-chistiakov/Stories
/Stories/PresentationLayer/Views/StoryProgressBar/ViewModels/BaseStoryProgressBarViewModel.swift
UTF-8
1,430
2.5625
3
[ "MIT" ]
permissive
// // BaseStoryProgressBarViewModel.swift // Stories // // Created by Чистяков Вадим Евгеньевич on 25/05/2019. // Copyright © 2019 ChistProduction. All rights reserved. // final class BaseStoryProgressBarViewModel: StoryProgressBarViewModel { var pagesCount: Int var viewModels: [StoryPageProgressViewModel] = [] weak var delegate: StoryProgressBarViewModelDelegate? init(pagesCount: Int) { self.pagesCount = pagesCount generateViewModels() } func start(forIndex index: Int) { viewModels[index].action.value = .start } func pause(forIndex index: Int) { viewModels[index].action.value = .pause } func resume(forIndex index: Int) { viewModels[index].action.value = .resume } func stop(forIndex index: Int) { viewModels[index].action.value = .stop } func reset(forIndex index: Int) { viewModels[index - 1].action.value = .reset viewModels[index].action.value = .reset } func generateViewModels() { viewModels.removeAll() for _ in 0..<pagesCount { viewModels.append(StoryPageProgressViewModel(delegate: self)) } } } extension BaseStoryProgressBarViewModel: StoryPageProgressViewModelDelegate { func storyPageProgressViewModelDidFinishAnimation(_ viewModel: StoryPageProgressViewModel) { delegate?.storyProgressBarViewModelDidFinishAnimation(self) } }
true
7a1ddf1fc3606478074a6d9ce54487b2a680857d
Swift
tangmac0323/FairAppIOS
/FairAppIOS/View/MainView/StoreView/Header/StoreHeaderView.swift
UTF-8
1,073
2.859375
3
[]
no_license
// // StoreHeaderView.swift // FairAppIOS // // Created by Mengtao Tang on 9/9/20. // Copyright © 2020 Mo's Company. All rights reserved. // import Foundation import SwiftUI struct StoreHeaderView: View { @Binding var isNavBarHidden: Bool @State var rating: Int @State var title: String @State var description: String { didSet { print(self.description) } } var body: some View { Section(header:Text("")) { // title Text("\(self.title)") // poster Image(systemName: "photo") .resizable() .frame(height: 200) // rating RatingStar(rating: $rating) // review NavigationLink(destination: ReviewView(isNavBarHidden: self.$isNavBarHidden)) { Text("Review") } //.buttonStyle(PlainButtonStyle()) // description TextField("", text: self.$description) } } }
true
848b79e32f1991a4b4d90727222cfc2dd6c3e913
Swift
Adubedat/Piscine-Swift
/D06/D06/UIShapeView.swift
UTF-8
1,464
3.015625
3
[]
no_license
// // UIShapeView.swift // D06 // // Created by Arthur DUBEDAT on 4/3/18. // Copyright © 2018 Arthur DUBEDAT. All rights reserved. // import Foundation import UIKit class UIShapeView : UIView { let width = CGFloat(100) let height = CGFloat(100) let isCircle : Bool? private func setupForm() { if isCircle! { self.layer.cornerRadius = self.frame.size.width/2 } } private func setupColor() { switch Int(arc4random_uniform(6)) { case 0: self.backgroundColor = UIColor.blue case 1: self.backgroundColor = UIColor.red case 2: self.backgroundColor = UIColor.green case 3: self.backgroundColor = UIColor.brown case 4: self.backgroundColor = UIColor.purple default: self.backgroundColor = UIColor.orange } } init(x: CGFloat, y: CGFloat) { isCircle = Int(arc4random_uniform(2)) == 0 let rect = CGRect(x: x - (width / 2.0), y: y - (height / 2.0), width: width, height: height) super.init(frame: rect) setupForm() setupColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var collisionBoundsType: UIDynamicItemCollisionBoundsType { if isCircle! { return .ellipse } return .rectangle } }
true
0a7e8c9f242e0aade2b3f6e8a806fec83f0b884c
Swift
SanfordWilson/message
/Dummy Messager/MessageFactory.swift
UTF-8
1,067
2.875
3
[]
no_license
// // MessageFactory.swift // Dummy Messager // // Created by Sanford Wilson on 8/16/17. // Copyright © 2017 Sanford Wilson. All rights reserved. // import CoreData import UIKit class MessageFactory { static func makeMessage(withText text: String?, onChat chat: Chat, time: NSDate, isSender: Bool = false) -> Message { let delegate = UIApplication.shared.delegate as! AppDelegate let context = delegate.persistentContainer.viewContext let message = NSEntityDescription.insertNewObject(forEntityName: "Message", into: context) as! Message message.text = text message.time = time as Date message.chat = chat message.isSender = isSender if !(chat.lastMessage != nil) || time.compare(chat.lastMessage!.time! as Date) == .orderedDescending { chat.lastMessage = message } do { try context.save() } catch let err { print(err) } return message } }
true
17c03ef1568e20e77c08e5eba31cc5bbcc4e2c25
Swift
ozhadaie/UNIT_Factory
/swift-piscine/d01/ex02/Deck.swift
UTF-8
469
2.5625
3
[]
no_license
import Foundation class Deck : NSObject { static let allSpades : [Card] = Value.allValues.map({Card(c:Color.spade, v:$0)}) static let allDiamonds : [Card] = Value.allValues.map({Card(c:Color.diamond, v:$0)}) static let allClubs : [Card] = Value.allValues.map({Card(c:Color.club, v:$0)}) static let allHearts : [Card] = Value.allValues.map({Card(c:Color.heart, v:$0)}) static let allCards : [Card] = allSpades + allClubs + allHearts + allDiamonds }
true
ba3c82126f0cf878f37ee13dd4e8935238c82dd0
Swift
identity2/music-training
/MusicTraining/Tuner Metronome/TMNote.swift
UTF-8
1,201
3.46875
3
[]
no_license
import Foundation enum Accidental: Int { case natural = 0 case sharp = 1 case flat = 2 } class TMNote: Equatable { enum Accidental: Int { case natural = 0, sharp, flat } enum Name: Int { case a = 0, b, c, d, e, f, g } static let all: [TMNote] = [ TMNote(.c, .natural), TMNote(.c, .sharp), TMNote(.d, .natural), TMNote(.e, .flat), TMNote(.e, .natural), TMNote(.f, .natural), TMNote(.f, .sharp), TMNote(.g, .natural), TMNote(.a, .flat), TMNote(.a, .natural), TMNote(.b, .flat), TMNote(.b, .natural) ] var note: Name var accidental: Accidental var frequency: Double { let index = TMNote.all.firstIndex(of: self)! - TMNote.all.firstIndex(of: TMNote(.a, .natural))! return 440.0 * pow(2.0, Double(index) / 12.0) } init(_ note: Name, _ accidental: Accidental) { self.note = note self.accidental = accidental } static func ==(lhs: TMNote, rhs: TMNote) -> Bool { return lhs.note == rhs.note && lhs.accidental == rhs.accidental } static func !=(lhs: TMNote, rhs: TMNote) -> Bool { return !(lhs == rhs) } }
true
f45b7efb899c70fe63858c0c6bfce124acd1895b
Swift
crumpf/advent-of-code
/2022/Swift/Advent of Code/Common/Stack.swift
UTF-8
643
3.40625
3
[]
no_license
// // Stack.swift // AdventUnitTests // // Created by Christopher Rumpf on 12/16/22. // struct Stack<Element> { private var stack: [Element] = [] var isEmpty: Bool { stack.isEmpty } var count: Int { stack.count } // Add an element to the top of the stack. mutating func push(_ element: Element) { stack.append(element) } // Remove an element from the top of the stack and return it. mutating func pop() -> Element? { stack.isEmpty ? nil : stack.removeLast() } // Peek at the topmost element without removing it. func peek() -> Element? { stack.last } }
true
c26d8b4828bc36f2307b9c950001b3e7dc8d78bd
Swift
NAVEENRAJ3692/Xerviceus
/XServices/Managers/ThemeManager.swift
UTF-8
886
2.65625
3
[]
no_license
// // ThemeManager.swift // XServices // // Created by K Saravana Kumar on 26/08/19. // Copyright © 2019 Securenext. All rights reserved. // import UIKit class ThemeManager { static let sharedInstance = ThemeManager() fileprivate let gradientButtonColors = ["#4F86A6","#51B683", "#51B683"] fileprivate let gradientButtonColorsDisabled = ["#8C97A0","#B4C1BC", "#B4C1BC"] var gradientButtonTheme:Theme { return themeFrom(gradientButtonColors) } var gradientButtonDisabledTheme:Theme{ return themeFrom(gradientButtonColorsDisabled) } fileprivate func themeFrom(_ colors: [String]) -> Theme { let theme = Theme() theme.primaryColor = UIColor(named: colors[0]) theme.secondaryColor = UIColor(named: colors[1]) theme.imageOverlayColor = UIColor(named: colors[2]) return theme } }
true
ddb84f98d1532d9d56628655dc28dee0799a739d
Swift
yicongli/RestaurantApp
/RestaurantBrowser/RestaurantBrowser/AppDelegate.swift
UTF-8
1,339
2.53125
3
[ "MIT" ]
permissive
// // AppDelegate.swift // RestaurantBrowser // // Created by Yicong Li on 10/5/19. // Copyright © 2019 Yicong Li. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { /// The main window let window = UIWindow() /// the manager for handling location service let locationService = LocationServices() /// get the UI from story borad let storyBoard = UIStoryboard(name: "Main", bundle: nil) func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // check the service status first and show different views switch locationService.status { case .notDetermined, .restricted, .denied: // if there is no access to the location service, then show the location enqury view let locationViewControllor = storyBoard.instantiateViewController(withIdentifier: "LocationViewController") as? LocationViewController locationViewControllor?.locationService = locationService window.rootViewController = locationViewControllor default: assertionFailure() } // show the main window window.makeKeyAndVisible() return true } }
true
905f5192abb43e90601871e941c08a781c765308
Swift
unc-dan/FollowHub
/Model/Follower.swift
UTF-8
427
2.8125
3
[]
no_license
// // Follower.swift // FollowHub // // Created by Dan T on 16/04/2020. // Copyright © 2020 Dan T. All rights reserved. // import Foundation struct Follower: Codable, Hashable { var login: String var avatarUrl: String //if we want specific variable to be hashed rather than everything in Follower (slight optimisation) func hash(into hasher: inout Hasher) { hasher.combine(login) } }
true
2d82f291dee70ea04572e52c88e25c85f64c5583
Swift
Finb/Bark
/Common/Moya/BarkTargetType.swift
UTF-8
3,460
2.59375
3
[ "MIT" ]
permissive
// // BarkTargetType.swift // Bark // // Created by huangfeng on 2018/6/25. // Copyright © 2018 Fin. All rights reserved. // import Moya import RxSwift import UIKit // 保存全局Providers private var retainProviders: [String: Any] = [:] protocol BarkTargetType: TargetType { var parameters: [String: Any]? { get } } extension BarkTargetType { var headers: [String: String]? { return nil } var baseURL: URL { return URL(string: ServerManager.shared.currentServer.address)! } var method: Moya.Method { return .get } var parameterEncoding: ParameterEncoding { return URLEncoding.default } var sampleData: Data { return Data() } var task: Task { return requestTaskWithParameters } var requestTaskWithParameters: Task { // 默认参数 var defaultParameters: [String: Any] = [:] // 协议参数 if let parameters = self.parameters { for (key, value) in parameters { defaultParameters[key] = value } } return Task.requestParameters(parameters: defaultParameters, encoding: parameterEncoding) } /// 实现此协议的类,将自动获得用该类实例化的 provider 对象 static var provider: RxSwift.Reactive<MoyaProvider<Self>> { let key = "\(Self.self)" if let provider = retainProviders[key] as? RxSwift.Reactive<MoyaProvider<Self>> { return provider } let provider = Self.weakProvider retainProviders[key] = provider return provider } /// 不被全局持有的 Provider ,使用时,需要持有它,否则将立即释放,请求随即终止 static var weakProvider: RxSwift.Reactive<MoyaProvider<Self>> { var plugins: [PluginType] = [] #if DEBUG plugins.append(LogPlugin()) #endif let provider = MoyaProvider<Self>(plugins: plugins) return provider.rx } } public extension RxSwift.Reactive where Base: MoyaProviderType { func request(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> Observable<Response> { return Single.create { [weak base] single in let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: nil) { result in switch result { case let .success(response): single(.success(response)) case let .failure(error): single(.failure(error)) } } return Disposables.create { cancellableToken?.cancel() } }.asObservable() } } private class LogPlugin: PluginType { func willSend(_ request: RequestType, target: TargetType) { print("\n-------------------\n准备请求: \(target.path)") print("请求方式: \(target.method.rawValue)") if let params = (target as? BarkTargetType)?.parameters { print(params) } print("\n") } func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) { print("\n-------------------\n请求结束: \(target.path)") if let data = try? result.get().data, let resutl = String(data: data, encoding: String.Encoding.utf8) { print("请求结果: \(resutl)") } print("\n") } }
true
4365ce9f25708c68eff5adae7604b588de6af473
Swift
vladimirkofman/TableTie
/TableTie/AnyRow.swift
UTF-8
1,240
3.109375
3
[ "MIT" ]
permissive
// // AnyRow.swift // TableTie // // Created by Vladimir Kofman on 21/04/2017. // Copyright © 2017 Vladimir Kofman. All rights reserved. // import UIKit /** Acts as an abstract protocol for all row items to be displayed. All row items should conform to this protocol through Row. */ public protocol AnyRow { /// reuseIdentifier to use when dequeing reusable cell var reuseIdentifier: String { get } /// Row Height var rowHeight: CGFloat { get } /// Called when the row is selected func didSelectRow(of tableView: UITableView, at indexPath: IndexPath) /// "Private" method, don't override. Implemented in Row func _dequeueCell(tableView: UITableView) -> UITableViewCell /// "Private" method, don't override. Implemented in Row func _configure(cell: UITableViewCell) } /// Default implementations of AnyRow protocol public extension AnyRow { /// Using class name as reuseIdentifier var reuseIdentifier: String { return String(describing: type(of: self)) } /// Default row height var rowHeight: CGFloat { return UITableView.automaticDimension } /// Do nothing by default func didSelectRow(of tableView: UITableView, at indexPath: IndexPath) {} }
true
a5fd4cc2f8feaa75b2182682cea9dd74fd5ee94c
Swift
sakthivelbala/movieDatabase
/MovieDB/MovieDB/view/movieCell/movieCellExtension.swift
UTF-8
2,725
2.625
3
[]
no_license
// // movieCellExtension.swift // MovieDB // // Created by Sakthivel Balakrishnan on 08/08/19. // Copyright © 2019 Sakthivel Balakrishnan. All rights reserved. // import UIKit extension movieCell{ func setUpMovieImage() { addSubview(backdropImage) NSLayoutConstraint.activate([ backdropImage.topAnchor.constraint(equalTo: topAnchor), backdropImage.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.8), backdropImage.widthAnchor.constraint(equalTo: widthAnchor) ]) } func setUpRatingText() { circularProgressView.addSubview(ratingText) NSLayoutConstraint.activate([ ratingText.leftAnchor.constraint(equalTo: circularProgressView.leftAnchor), ratingText.rightAnchor.constraint(equalTo: circularProgressView.rightAnchor), ratingText.topAnchor.constraint(equalTo: circularProgressView.topAnchor), ratingText.bottomAnchor.constraint(equalTo: circularProgressView.bottomAnchor) ]) } func setUpCircularProgressView() { addSubview(circularProgressView) NSLayoutConstraint.activate([ circularProgressView.leftAnchor.constraint(equalTo: leftAnchor), circularProgressView.topAnchor.constraint(equalTo: backdropImage.bottomAnchor), circularProgressView.bottomAnchor.constraint(equalTo: bottomAnchor), circularProgressView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.15) ]) setUpCircularProgressBar() setUpRatingText() } func setUpCircularProgressBar(){ circularProgressView.layoutIfNeeded() let circularPath=UIBezierPath(arcCenter: CGPoint(x: circularProgressView.bounds.width/2, y: circularProgressView.bounds.height/2), radius: circularProgressView.bounds.width/2*0.8, startAngle: 0, endAngle: 2*CGFloat.pi, clockwise: true).cgPath progressCircle.path=circularPath progressCircle.lineWidth=circularProgressView.frame.height/15 circularProgressView.layer.addSublayer(progressCircle) } func setupTextStackView(){ titleDateStackView.addArrangedSubview(movieTitle) titleDateStackView.addArrangedSubview(movieDate) addSubview(titleDateStackView) NSLayoutConstraint.activate([ titleDateStackView.topAnchor.constraint(equalTo: backdropImage.bottomAnchor,constant: frame.height/40), titleDateStackView.bottomAnchor.constraint(equalTo: bottomAnchor,constant: -frame.height/30), titleDateStackView.leftAnchor.constraint(equalTo: circularProgressView.rightAnchor), titleDateStackView.rightAnchor.constraint(equalTo: rightAnchor) ]) } }
true
a08a71dc78bfb2bd6e821f8facc149b65768b8aa
Swift
pseudomuto/CircuitBreaker
/Pod/Classes/OpenState.swift
UTF-8
1,117
2.59375
3
[ "MIT" ]
permissive
// // OpenState.swift // Pods // // Created by David Muto on 2016-02-02. // // class OpenState: BaseState { private var timer: NSTimer? private(set) var scheduled: Bool = false private(set) var resetTimeout: NSTimeInterval init(_ breakerSwitch: Switch, invoker: Invoker, resetTimeout: NSTimeInterval) { self.resetTimeout = resetTimeout super.init(breakerSwitch, invoker: invoker) } override func type() -> StateType { return .Open } override func activate() { synchronized { self.timer = NSTimer.scheduledTimerWithTimeInterval( self.resetTimeout, target: self, selector: Selector("halfOpen:"), userInfo: nil, repeats: false ) self.scheduled = true } } override func onSuccess() { } override func onError() { } override func invoke<T>(block: () throws -> T) throws -> T { throw Error.OpenCircuit } @objc func halfOpen(timer: NSTimer) { timer.invalidate() synchronized { self.scheduled = false self.breakerSwitch.attempt(self) } } }
true
e7022aebd56524faa9e5533bc6696f20138904f2
Swift
jakebromberg/Deft
/RIVTester_3_0.swift
UTF-8
4,561
3.359375
3
[ "MIT" ]
permissive
/** # Public Interface ## Adding Test(s) `addTest(description: String, failureMessage: String, _: () -> Bool)` `faddTest(description: String, failureMessage: String, _: () -> Bool)` `xaddTest(description: String, failureMessage: String, _: () -> Bool)` ## Executing Test(s) `executeTests(autoPrintTests: Bool = true)` # Output Notation "." : Test succeeded "F" : Test failed ">" : Test marked as pending */ public class RIVTester { private struct RIVTest { let description : String let executable : () -> Bool let expectedBehavior : String let pending : Bool let focused : Bool } private var tests = [RIVTest]() private var hasFocusedTest = false // MARK: Public public init() {} /** Adds a test. - Parameter description: The description to output if the test is executed. - Parameter expectedBehavior: The message to output if the test is executed and fails. - Parameter block: The block to determine if the test succeeds or fails. */ public func addTest(description: String, expectedBehavior: String, _ executable: @escaping () -> Bool) { tests.append(RIVTest(description: description, executable: executable, expectedBehavior: expectedBehavior, pending: false, focused: false)) } /** Adds a focused test. - Important: If one or more focused tests are added, all non-focused tests will be treated as pending. - Parameter description: The description to output if the test is executed. - Parameter expectedBehavior: The message to output if the test is executed and fails. - Parameter block: The block to determine if the test succeeds or fails. */ public func faddTest(description: String, expectedBehavior: String, _ executable: @escaping () -> Bool) { hasFocusedTest = true tests.append(RIVTest(description: description, executable: executable, expectedBehavior: expectedBehavior, pending: false, focused: true)) } /** Adds a pending test. - Warning: Pending tests will not be executed. - Note: This has the same function signature as its counterparts for ease of use. - Parameter description: The description to output if the test is executed. - Parameter expectedBehavior: The message to output if the test is executed and fails. - Parameter block: The block to determine if the test succeeds or fails. */ public func xaddTest(description: String, expectedBehavior: String, _ executable: @escaping () -> Bool) { tests.append(RIVTest(description: description, executable: executable, expectedBehavior: expectedBehavior, pending: true, focused: false)) } /** Executes the tests. - Parameter autoPrintTests: Specify if the resulting output should be printed. Defaults to true - Returns: The resulting output `String` that will/would be printed, specified by `autoPrintTests`. */ public func executeTests(autoPrintTests shouldPrint: Bool = true) -> String { let result = processTests() if shouldPrint { print(result) } return result } // MARK: Private private func processTests() -> String { var result = "" var succeeded = 0 var pending = 0 for (index, test) in tests.enumerated() { result += testOutput(test: test, number: index + 1, succeeded: &succeeded, pending: &pending) } return result + endLine(totalCount: self.tests.count, succeeded: succeeded, pending: pending) } private func endLine(totalCount: Int, succeeded: Int, pending: Int) -> String { return "\nExecuted \(tests.count) test(s) | \(succeeded) succeeded | \(tests.count - succeeded - pending) failed | \(pending) pending" } private func testOutput(test: RIVTest, number: Int, succeeded : inout Int , pending : inout Int) -> String { let isPending = test.pending || (hasFocusedTest && !test.focused) if isPending { pending += 1 return "> Test \(number): \(test.description)\n" } else if test.executable() { succeeded += 1 return ". Test \(number): \(test.description)\n" } else { return "F Test \(number): \(test.description) -> \(test.expectedBehavior)\n" } } }
true
435277f9de6b8e1a6d30488c4af04cf1c7cc6d38
Swift
rikusouda/Riko
/Riko/Util/UserDefaultsUtil.swift
UTF-8
570
2.5625
3
[]
no_license
// // UserDefaultsUtil.swift // Riko // // Created by katsuya on 2017/03/04. // Copyright © 2017年 Yoshitaka Kazue. All rights reserved. // import Foundation class UserDefaultsUtil { static let rikoNameKey = "uc_riko_name_key" static let userDefaults = UserDefaults.standard static var rikoName: String { get { let result = userDefaults.string(forKey: rikoNameKey) ?? "" return result } set(msg) { userDefaults.set(msg, forKey: rikoNameKey) userDefaults.synchronize() } } }
true
be51847c316edfd6a8d7c0830603408f00d9ffb8
Swift
vahids/swiftui_tutorial
/SwiftUITutorials/Models/Product.swift
UTF-8
1,488
3.515625
4
[]
no_license
// // Product.swift // SwiftUITutorials // // Created by Vahid Sayad on 7/17/21. // import Foundation struct Product: Identifiable { let id: Int let name: String let price: Double let color: String let width: Double let height: Double let image: String var roundedPrice: String { return String(format: "%.2f", price) } var size: String { return String(format: "%.1f x %.1f", width, height) } } extension Product { static func all() -> [Product] { return [ Product(id: 1, name: "Classic", price: 800, color: "#2333bb", width: 800, height: 450, image: "classic"), Product(id: 2, name: "Face Off", price: 1200, color: "#ffeebb", width: 1000, height: 500, image: "face-off"), Product(id: 3, name: "Garden", price: 350, color: "#e3e3e3", width: 400, height: 200, image: "garden"), Product(id: 4, name: "Pirsok", price: 400, color: "#3eff55", width: 600, height: 100, image: "pirsok"), Product(id: 5, name: "Dalan", price: 700, color: "#ff33bb", width: 700, height: 400, image: "dalan"), Product(id: 6, name: "Garden", price: 350, color: "#e3e3e3", width: 400, height: 200, image: "garden"), Product(id: 7, name: "Pirsok", price: 400, color: "#3eff55", width: 600, height: 100, image: "pirsok"), Product(id: 8, name: "Dalan", price: 700, color: "#ff33bb", width: 700, height: 400, image: "dalan") ] } }
true
7b2125da906ddb607d6f5ff975322e9ac3843164
Swift
borjaIgartua/Places
/Places/Places/Code/Modules/Places/PlacesInteractor.swift
UTF-8
1,359
2.875
3
[ "MIT" ]
permissive
// // PlacesInteractor.swift // Places // // Created by Borja Igartua Pastor on 8/6/17. // Copyright © 2017 Borja Igartua Pastor. All rights reserved. // import UIKit import CoreData import CoreLocation class PlacesInteractor { let locationManager = LocationManager() weak var delegate: PlaceInteractorDelegate? var places = [Place]() func retrivePlaces() { places.removeAll() if let appDelegate = UIApplication.shared.delegate as? AppDelegate { let managedContext = appDelegate.persistentContainer.viewContext let fetchRequest = Place.placeFetchRequest() if let retrievedPlaces = try? managedContext.fetch(fetchRequest) { self.places.append(contentsOf: retrievedPlaces) } self.delegate?.didUpdatePlaces(self.places) } } func startUpdatingLocation() { self.locationManager.startUpdatingLocation { [weak delegate = self.delegate] locations in self.locationManager.stopUpdatingLocation() delegate?.didUpdateLocation!(location: locations[0]) } } } @objc protocol PlaceInteractorDelegate: class { func didUpdatePlaces(_ places: [Place]?) @objc optional func didUpdateLocation(location: CLLocation) }
true