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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
cb71b9d9a9bc91a05293f93ea5b0d7ee74def43b
|
Swift
|
jiyangwang/swift-playground-collections
|
/Graphing.playground/Sources/PlaygroundInternal/LinePlotDrawable.swift
|
UTF-8
| 9,288
| 2.84375
| 3
|
[] |
no_license
|
//
// LineChartLayer.swift
// Charts
//
import UIKit
private let FunctionSampleInternalInPoints = 1.0
internal class LinePlotDrawable: ChartDrawable {
var dataProvider: LineData?
var symbol: Symbol? = Symbol()
var lineStyle = LineStyle.none
var lineWidth: CGFloat = 2.0
private func drawSymbolsAtPoints(points: [(Double, Double)], inChartView chartView: ChartView, inContext context: CGContext) {
guard let symbol = symbol else { return }
for point in points {
let screenPoint = chartView.convertPointToScreen(modelPoint: CGPoint(x: point.0, y: point.1))
symbol.draw(atCenterPoint: CGPoint(x: screenPoint.x, y: screenPoint.y), fillColor: color.uiColor, usingContext: context)
}
}
// MARK: - ChartDrawable conformance -
var color = Color.blue
var label: String?
func draw(withChartView chartView: ChartView, context: CGContext) {
guard let dataProvider = dataProvider else { return }
let modelPoints = dataProvider.data(forBounds: chartView.axisBounds, chartView: chartView)
let screenPoints = modelPoints.map { modelPoint -> CGPoint in
return chartView.convertPointToScreen(modelPoint: CGPoint(x: modelPoint.0, y: modelPoint.1))
}
if lineStyle != .none {
for (index, point) in screenPoints.enumerated() {
if (index == 0) {
context.move(to: point)
} else {
context.addLine(to: point)
}
}
switch lineStyle {
case .dashed:
context.setLineDash(phase: 0, lengths: [6, 10])
case .dotted:
context.setLineDash(phase: 0, lengths: [1, 6])
default:
break
}
context.setStrokeColor(color.cgColor)
context.setLineJoin(.round)
context.setLineWidth(lineWidth)
context.strokePath()
}
drawSymbolsAtPoints(points: modelPoints, inChartView: chartView, inContext: context)
}
func boundsOfData(inChartView chartView: ChartView) -> Bounds {
guard let dataProvider = dataProvider else { return Bounds.infinite }
return dataProvider.boundsOfData(chartView: chartView)
}
func values(inScreenRect rect: CGRect, inChartView chartView: ChartView) -> [ChartValue] {
guard let dataProvider = dataProvider else { return [] }
let minPoint = chartView.convertPointFromScreen(screenPoint: CGPoint(x: rect.minX, y: rect.maxY))
let maxPoint = chartView.convertPointFromScreen(screenPoint: CGPoint(x: rect.maxX, y: rect.minY))
let bounds = Bounds(minX: Double(minPoint.x), maxX: Double(maxPoint.x), minY: Double(minPoint.y), maxY: Double(maxPoint.y))
let includeInterpolatedValues = dataProvider.providesInterpolatedData && lineStyle.isConnected
return dataProvider.data(withinBounds: bounds, chartView: chartView, includeInterpolatedValues: includeInterpolatedValues).map { data in
let screenPoint = chartView.convertPointToScreen(modelPoint: CGPoint(x: data.1.0, y: data.1.1))
let index = data.0
let value = data.1
let isInterpolated = includeInterpolatedValues && index == nil
return ChartValue(chartDrawable: self, index: index, value: value, interpolated: isInterpolated, screenPoint: screenPoint)
}
}
}
internal protocol LineData: CustomPlaygroundQuickLookable {
var providesInterpolatedData: Bool { get }
func boundsOfData(chartView: ChartView) -> Bounds
func data(forBounds bounds: Bounds, chartView: ChartView) -> [(Double, Double)]
func data(withinBounds bounds: Bounds, chartView: ChartView, includeInterpolatedValues: Bool) -> [(Int?, (Double, Double))]
}
internal class DiscreteLineData: LineData {
fileprivate let xyData: XYData
init(xyData: XYData) {
self.xyData = xyData
}
var providesInterpolatedData: Bool {
return true
}
func boundsOfData(chartView: ChartView) -> Bounds {
guard xyData.count > 0 else { return Bounds.infinite }
let xData = xyData.xData
let yData = xyData.yData
return Bounds(minX: xData.min()!, maxX: xData.max()!, minY: yData.min()!, maxY: yData.max()!)
}
func data(forBounds bounds: Bounds, chartView: ChartView) -> [(Double, Double)] {
return xyData.xyData
}
func data(withinBounds bounds: Bounds, chartView: ChartView, includeInterpolatedValues: Bool) -> [(Int?, (Double, Double))] {
let xyData = self.xyData.xyData
var dataWithinBounds = [(Int?, (Double, Double))]()
if xyData.count == 0 {
return dataWithinBounds
}
for (index, data) in xyData.enumerated() {
if bounds.contains(data: data) {
dataWithinBounds.append((index, data))
}
}
if includeInterpolatedValues && dataWithinBounds.count == 0 {
for (index, data) in xyData.enumerated() {
if data.0 > bounds.midX {
if index == 0 {
break
}
guard let interpolatedValue = interpolatedValueBetween(a: xyData[index - 1], b: data, time: Double(bounds.midX)) else {
break
}
if bounds.contains(data: interpolatedValue) {
// We can only have at most 1 interpolated value and it cannot have an index.
dataWithinBounds.append((nil, interpolatedValue))
break
}
}
}
}
return dataWithinBounds
}
private func interpolatedValueBetween(a: (Double, Double), b: (Double, Double), time: Double) -> (Double, Double)? {
let interpolationWidth = (b.0 - a.0)
let interpolationHeight = (b.1 - a.1)
let interpolationTime = (time - a.0) / interpolationWidth
if interpolationTime < 0 || interpolationTime > 1 {
return nil
}
return (a.0 + (interpolationWidth * interpolationTime), a.1 + (interpolationHeight * interpolationTime))
}
}
extension DiscreteLineData: CustomPlaygroundQuickLookable {
internal var customPlaygroundQuickLook: PlaygroundQuickLook {
get {
let numPoints = xyData.count
let suffix = numPoints == 1 ? "point" : "points"
return .text("\(numPoints) \(suffix)")
}
}
}
internal class FunctionLineData: LineData {
fileprivate let function: (Double) -> Double
init(function: @escaping (Double) -> Double) {
self.function = function
}
var providesInterpolatedData: Bool {
return false
}
/// For function data, use the current chart's x bounds, and then sample the data to determine the y bounds.
func boundsOfData(chartView: ChartView) -> Bounds {
// grab the data for the current chart bounds.
var bounds = chartView.axisBounds
let boundedData = data(forBounds: bounds, chartView: chartView)
guard boundedData.count > 0 else { return Bounds.infinite }
// grab the y points for the data.
let yData = boundedData.map { $0.1 }
// update the x bounds to indicate that the data is unbounded.
bounds.minX = .infinity
bounds.maxX = .infinity
// udpate the bounds match the y data min and max values.
bounds.minY = yData.min()!
bounds.maxY = yData.max()!
return bounds
}
func data(forBounds bounds: Bounds, chartView: ChartView) -> [(Double, Double)] {
let axisBounds = chartView.axisBounds
let screenZeroAsModel = chartView.convertPointFromScreen(screenPoint: CGPoint.zero).x
let screenStrideOffsetAsModel = chartView.convertPointFromScreen(screenPoint: CGPoint(x: FunctionSampleInternalInPoints, y: 0.0)).x
let modelStride = Double(screenStrideOffsetAsModel - screenZeroAsModel)
var data = [(Double, Double)]()
for x in stride(from: axisBounds.minX, through: axisBounds.maxX, by: modelStride) {
data.append((x, function(x)))
}
// make sure we always go to the end.
data.append(axisBounds.maxX, function(axisBounds.maxX))
return data
}
func data(withinBounds bounds: Bounds, chartView: ChartView, includeInterpolatedValues: Bool) -> [(Int?, (Double, Double))] {
let data = (bounds.midX, function(bounds.midX))
if bounds.contains(data: data) {
return [(nil, data)] // Function data won't ever have an index.
}
return []
}
}
extension FunctionLineData: CustomPlaygroundQuickLookable {
internal var customPlaygroundQuickLook: PlaygroundQuickLook {
get {
return .text(String(describing: function))
}
}
}
| true
|
1ac693e8c9d97283ecec32e1d23054f78747bbce
|
Swift
|
paulsurette71/Shot-On-Goal
|
/myShotTracker/GoalieDetailsAttributedString.swift
|
UTF-8
| 2,216
| 2.828125
| 3
|
[] |
no_license
|
//
// GoalieDetailsAttributedString.swift
// Shot On Goal
//
// Created by Surette, Paul on 2017-10-24.
// Copyright © 2017 Surette, Paul. All rights reserved.
//
import Foundation
import UIKit
class GoalieDetailsAttributedString {
let fontColour:UIColor = .darkGray
func goalieDetailInformation(number: String, firstName:String, lastName: String) -> NSAttributedString {
let firstNameAttributedString = NSMutableAttributedString(string: firstName)
firstNameAttributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.thin), range: NSMakeRange(0, firstNameAttributedString.length))
let lastNameAttributedString = NSMutableAttributedString(string: lastName)
lastNameAttributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.heavy), range: NSMakeRange(0, lastNameAttributedString.length))
let combination = NSMutableAttributedString()
let spaceAttributedString = NSMutableAttributedString(string: " ")
let poundAttributedString = NSMutableAttributedString(string: "#")
poundAttributedString.addAttribute(NSAttributedString.Key.font,value: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.thin),range: NSMakeRange(0, poundAttributedString.length))
poundAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: fontColour, range: NSMakeRange(0, poundAttributedString.length))
let numberAttributedString = NSMutableAttributedString(string: number)
numberAttributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.thin), range: NSMakeRange(0, numberAttributedString.length))
//Connor Surette | #1
combination.append(firstNameAttributedString)
combination.append(spaceAttributedString)
combination.append(lastNameAttributedString)
combination.append(spaceAttributedString)
combination.append(poundAttributedString)
combination.append(numberAttributedString)
return combination
}
}
| true
|
a51db48579b905c41379b8516eab7437ccd5de56
|
Swift
|
Lanhaoo/UIModule
|
/UIModule/Classes/Tools/Regex.swift
|
UTF-8
| 2,390
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// Regex.swift
// RedEvelope
//
// Created by 陈政宏 on 2018/9/14.
// Copyright © 2018年 陈政宏. All rights reserved.
//
import Foundation
//手机
let IDCardTW = Regex("^[a-zA-Z][0-9]{9}$")
let IDCardMC = Regex("^[1|5|7][0-9]{6}\\(?[0-9A-Z]\\)?$")
let IDCardHK = Regex("^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$")
let MobileRegex = Regex("^1[3-9][0-9]\\d{8}$")
///18位身份证号码
let IDCard18 = Regex("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])$")
///15位身份证号码
let IDCard15 = Regex("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$")
//电子邮件
let EmailRegex = Regex("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")
//中文
let ChineseRegex = Regex("[\\u4e00-\\u9fa5]")
//验证是否是6位纯数字
let PasswordNumSix = Regex("^\\d{6}$")
//密码(以字母开头,长度在6~18之间,只能包含字母、数字和下划线)/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/
let PasswordRegex = Regex("^(?=.*[a-zA-Z])(?=.*\\d)(?=.*[~!@#$%^&*()_+`\\-={}:\";'<>?,./]).{8,}$")
//密码正则 8-16位,数字、字母、标点符号
let PasswRegex = Regex("(?!.*\\s)(?!^[\\u4e00-\\u9fa5]+$)(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^.{6,18}$")
//强密码(必须包含大小写字母和数字的组合,不能使用特殊字符,长度在8-18之间)
let StrongPasswordRegex = Regex("^[a-zA-Z0-9]{8,18}$")
let S = Regex("^[a-zA-Z0-9_,.?]{8,18}$")//Regex("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,18}$")
//邮编
let PostCodeRegex = Regex("[1-9]\\d{5}(?!\\d)")
//用户名 只能由数字、26个英文字母或下划线组成的字符串:
let UserNameRegex = Regex("^[a-zA-z][a-zA-Z0-9_]{2,9}$")
//座机号码
let PhoneRegex = Regex("\\d{2,5}-\\d{7,8}")
public class Regex {
private let internalExpression:NSRegularExpression?
private let pattern:String
init(_ pattern:String) {
self.pattern = pattern
self.internalExpression = try? NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
}
public func match(_ input:String) -> Bool {
guard let internalExpression = self.internalExpression else { return false }
let matches = internalExpression.matches(in: input, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, input.count))
return matches.count > 0
}
}
| true
|
98e96a391a58fee830a1b9ebd12159d7be9bb935
|
Swift
|
klemenkosir/SwiftExtensions
|
/SwiftExtensions/SwiftExtensions/UILabelExtension.swift
|
UTF-8
| 820
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// UILabelExtension.swift
// SwiftExtensions
//
// Created by Klemen Kosir on 17. 12. 16.
// Copyright © 2016 Klemen Kosir. All rights reserved.
//
import UIKit
public extension UILabel {
@IBInspectable var isVertical: Bool {
get {
return self.isVertical
}
set {
self.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_2))
}
}
func setText(html: String) {
if let htmlData = html.data(using: String.Encoding.unicode) {
do {
self.attributedText = try NSAttributedString(data: htmlData,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
} catch let e as NSError {
print("Couldn't parse \(html): \(e.localizedDescription)")
}
}
}
}
| true
|
6120b6aa43ad070ce9dbcfb7c33377ef167b5ded
|
Swift
|
isurs93/Algorithm_Swift
|
/Algorithm_Swift/Programmers/skillCheck/openChat.swift
|
UTF-8
| 1,372
| 3.265625
| 3
|
[] |
no_license
|
//
// openChat.swift
// Algorithm_Swift
//
// Created by 박성주 on 2020/07/11.
// Copyright © 2020 박성주. All rights reserved.
//
import Foundation
class openChat{
func solution(_ record:[String]) -> [String]{
var userData : [String : String] = [:]
let logData = record
var result = [String]()
for str in logData{
let data = str.components(separatedBy: " ")
let command = data[0]
let userId = data[1]
var nickName = ""
if data.count == 3 {
nickName = data[2]
}
if command == "Enter"{
userData.updateValue(nickName, forKey: userId)
result.append("\(userId)님이 들어왔습니다.")
}
else if command == "Change" {
userData.updateValue(nickName, forKey: userId)
}
else if command == "Leave" {
result.append("\(userId)님이 나갔습니다.")
}
}
for index in 0..<result.count{
for (key, value) in userData {
if result[index].contains(key) {
result[index] = result[index].replacingOccurrences(of: key, with: value)
}
}
}
return result
}
}
| true
|
baea0dc6e2161b1ebadc0bcf6ae0f371143646dd
|
Swift
|
notdetninja47/DB_CourseWork
|
/JewelryTrader/ProductFilter.swift
|
UTF-8
| 1,926
| 2.6875
| 3
|
[] |
no_license
|
//
// ProductFilter.swift
// JewelryTrader
//
// Created by Daniel Slupskiy on 28.11.16.
// Copyright © 2016 Daniel Slupskiy. All rights reserved.
//
import Foundation
import CoreData
class ProductFilter {
var sortKey = "name"
var nameSearch: String?
var minPrice: Float?
var maxPrice: Float?
var onlyAvailable = true
var metalType:MetalType?
var productType:ProductType?
var color: Color?
var fetchRequest:NSFetchRequest{
let result = NSFetchRequest(entityName: "Product")
let sortDescriptor = NSSortDescriptor(key: sortKey, ascending: true)
result.sortDescriptors = [sortDescriptor]
var predicates = [NSPredicate]()
if let minPrice = minPrice {
predicates.append(NSPredicate(format: "price > \(minPrice)"))
}
if let maxPrice = maxPrice {
predicates.append(NSPredicate(format: "price < \(maxPrice)"))
}
if onlyAvailable {
predicates.append(NSPredicate(format: "sale = nil"))
}
if let metal = metalType {
predicates.append(NSPredicate(format: "%K == %@", "metalType", metal))
}
if let type = productType {
predicates.append(NSPredicate(format: "%K == %@", "type", type))
}
if let color = color {
predicates.append(NSPredicate(format: "%K == %@", "color", color))
}
let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
result.predicate = compoundPredicate
return result
}
var fetchedResultsController:NSFetchedResultsController {
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataManager.instance.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultsController
}
}
| true
|
44134c1c9272545e020adf7b37140fcd405d8d89
|
Swift
|
Jopses/Hotel
|
/Hotel/Services/Network/Api/HotelApi.swift
|
UTF-8
| 858
| 2.765625
| 3
|
[] |
no_license
|
import Moya
import UIKit
enum HotelApi {
case getHotels(path: String)
case getHotelById(_ id: Int)
}
// MARK: - Moya setup
extension HotelApi: TargetType {
var baseURL: URL {
guard let url = URL(string: AppDefaults.apiUrl) else {
fatalError("Failed to provide api base url")
}
return url
}
var path: String {
switch self {
case let .getHotels(path):
return "/\(path).json"
case let .getHotelById(id):
return "/\(id).json"
}
}
var method: Moya.Method {
return .get
}
var task: Task {
return .requestPlain
}
var sampleData: Data {
return Data()
}
var validationType: ValidationType {
return .successCodes
}
var headers: [String: String]? {
return nil
}
}
| true
|
5d5d2922ab2380c309f03bdfe7895a5451c18481
|
Swift
|
AnitaMax/calculator
|
/calculter/ViewController.swift
|
UTF-8
| 6,451
| 2.59375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// calculter
//
// Created by Apple44 on 19/3/18.
// Copyright © 2019年 zhy. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var main: UILabel!
@IBOutlet weak var describ: UILabel!
@IBOutlet weak var sin: UIButton!
@IBOutlet weak var tan: UIButton!
@IBOutlet weak var cos: UIButton!
var haspoint = false
var isopt = false
var hasleft = false
var isResult = false
var isNaN = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.main.text = "0"
self.describ.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func clear(_ sender: UIButton) {
self.describ.text = ""
self.main.text = "0"
self.haspoint = false
self.isopt = false
self.hasleft = false
self.isNaN = false
self.brain.clearDecscibsion()
//恢复变大的结果
main.font = UIFont.systemFont(ofSize: 28)
}
var curValue:Double{
get{
return Double(self.main.text!)!
}
set{
self.main.text = String(newValue)
}
}
@IBAction func numbers(_ sender: UIButton) {
//恢复变大的结果
main.font = UIFont.systemFont(ofSize: 28)
//处理当前显示为上一次的处理结果的场景
if isResult {
main.text = "0"
haspoint=false
}
isResult = false
//处理当前显示不合法的场景
isNaN = false
switch sender.currentTitle! {
case ".":
if self.haspoint == true {
return
}
if self.main.text == ""{
self.main.text = self.main.text! + "0"
}
self.main.text = self.main.text! + sender.currentTitle!
self.isopt = false
self.haspoint = true
case "0","1","2","3","4","5","6","7","8","9":
if main.text == "0"{
if sender.currentTitle == "0"{
return
}
self.main.text?.removeAll()
}
self.main.text = self.main.text! + sender.currentTitle!
self.isopt = false
default:
return
}
}
@IBAction func last(_ sender: UIButton) {
main.text = String(lastequal)
isResult = true
}
@IBAction func back(_ sender: UIButton) {
//结果不许回退
if isResult {
return
}
let pretext:String? = self.main.text
let len=pretext?.characters.count
//回退时如果是小数点就重置小数点flag
if pretext?.substring(from: (pretext?.index((pretext?.endIndex)!, offsetBy: -1))!) == "."{
self.haspoint = false
}
//回退
if len! >= 1 {
self.main.text = self.main.text?.substring(to: (pretext?.index((pretext?.endIndex)!, offsetBy: -1))!)
}
if len == 1{
self.main.text = "0"
}
}
var brain = calculatorBrain()
let magicWord : Dictionary<String,String>=[
"520":"520 i love you",
"4.1":"4.1 your festival",
"521":"521 fffffffffffff",
]
@IBAction func one_opts(_ sender: UIButton) {
//结果变大
if sender.currentTitle == "="{
main.font = UIFont.systemFont(ofSize: 50)
}
else{
//恢复变大的结果
main.font = UIFont.systemFont(ofSize: 28)
}
//魔术词的计算
for word in magicWord.keys{
if magicWord[word] == self.main.text{
self.main.text = word
}
}
//当结果不合法时禁止继续计算
if self.isNaN == true {
self.brain.clearDecscibsion()
return
}
//开始计算
brain.setOperand(self.curValue)
brain.performOpt(sender.currentTitle!)
if let res=brain.result {
//处理不合法结果
if res.isNaN || res.isInfinite {
self.main.text = "超出范围或不合法"
isNaN = true
}
// 处理整数的小数点问题 520.0 ->520 和 结果的小数点
else if String(res).substring(from: String(res).index(String(res).endIndex, offsetBy: -2)) == ".0" {
self.main.text=String(res).substring(to: String(res).index(String(res).endIndex, offsetBy: -2))
self.haspoint=false
}
else{
self.curValue = res
self.haspoint=true
}
//魔力词显示
for word in magicWord.keys {
if word == main.text {
self.main.text = magicWord[word]
}
}
}
describ.text = brain.descirbsion!
isResult = true
}
@IBAction func changTriFunc(_ sender: UIButton) {
if sin.currentTitle == "sin"{
sin.setTitle("sin-¹", for: UIControlState.normal)
cos.setTitle("cos-¹", for: UIControlState.normal)
tan.setTitle("tan-¹", for: UIControlState.normal)
}
else{
sin.setTitle("sin", for: UIControlState.normal)
cos.setTitle("cos", for: UIControlState.normal)
tan.setTitle("tan", for: UIControlState.normal)
}
}
@IBOutlet weak var line1: UIStackView!
@IBOutlet weak var line2: UIStackView!
@IBOutlet weak var x: UIButton!
@IBOutlet weak var genhao: UIButton!
@IBOutlet weak var daoshu: UIButton!
@IBOutlet weak var pai: UIButton!
@IBOutlet weak var e: UIButton!
@IBAction func turn(_ sender: UIButton) {
let super_opt :[UIView ] = [line1,line2,x,genhao,daoshu,pai,e]
if line1.isHidden == false {
for each in super_opt {
each .isHidden = true
}
}
else{
for each in super_opt {
each .isHidden = false
}
}
}
}
| true
|
041448667cebcc9c38084ed8d09b142750d8abca
|
Swift
|
maschall/adventofcode
|
/2016/1/code.swift
|
UTF-8
| 2,958
| 3.59375
| 4
|
[] |
no_license
|
#!/usr/bin/env xcrun --sdk macosx swift
enum Turn : String {
case Left = "L"
case Right = "R"
var spinValue: Int {
switch self {
case .Left: return -1
case .Right: return 1
}
}
static func fromMove(_ move: String) -> Turn {
let turnValue = String(move.characters.prefix(1))
return Turn(rawValue: turnValue)!
}
}
enum Direction : Int {
case North = 0, East, South, West
var scaleX: Int {
switch self {
case .East: return 1
case .West: return -1
default: return 0
}
}
var scaleY: Int {
switch self {
case .North: return 1
case .South: return -1
default: return 0
}
}
mutating func turn(_ move: String) {
self = Direction(rawValue: (self.rawValue + Turn.fromMove(move).spinValue + 4) % 4)!
}
}
struct Point {
let x, y : Int
init(_ x: Int, _ y: Int) {
self.x = x
self.y = y
}
func move(distance: Int, direction: Direction) -> Point {
let nextX = x + distance * direction.scaleX
let nextY = y + distance * direction.scaleY
return Point(nextX, nextY)
}
var distanceToOrigin : Int {
return abs(self.x) + abs(self.y)
}
}
struct Line {
let pointA, pointB : Point
init(_ a: Point, _ b : Point) {
self.pointA = a
self.pointB = b
}
func intersects(_ line : Line) -> Bool {
let intersectsX = (self.pointA.x < line.pointB.x && self.pointB.x > line.pointA.x)
let intersectsY = (self.pointA.y < line.pointB.y && self.pointB.y > line.pointA.y)
return intersectsX && intersectsY
}
func intersection(_ line : Line) -> Point? {
if self.intersects(line) {
let x = self.pointA.x - self.pointB.x == 0 ? self.pointA.x : line.pointA.x
let y = self.pointA.y - self.pointB.y == 0 ? self.pointA.y : line.pointA.y
return Point(x,y)
} else {
return nil
}
}
}
var locations = [Point]()
var point = Point(0, 0)
locations.append(point)
var currentDirection = Direction.North
for move in CommandLine.arguments.dropFirst(1) {
currentDirection.turn(move)
var distance = String(move.characters.dropFirst(1))
if (distance.hasSuffix(",")) {
distance = String(distance.characters.dropLast(1))
}
point = point.move(distance: Int(distance)!, direction: currentDirection)
locations.append(point)
}
print("distance to origin: \(point.distanceToOrigin)")
var lines = [Line]()
var previousPoint = locations[0]
for nextPoint in locations.dropFirst(1) {
lines.append(Line(previousPoint,nextPoint))
previousPoint = nextPoint
}
var intersection : Point?
for (index, lineA) in lines.enumerated() {
for lineB in lines.dropFirst(index+1) {
intersection = lineA.intersection(lineB)
if intersection != nil {
break
}
}
if intersection != nil {
break
}
}
if intersection != nil {
print("first intersection: \(intersection!.distanceToOrigin)")
} else {
print("never intersects")
}
| true
|
f113a049cfd9c7bf487bb0d0adb43ba53faaec1a
|
Swift
|
caleberi/swift-tutorial-guide
|
/examples/19_lesson.swift
|
UTF-8
| 147
| 3.546875
| 4
|
[
"MIT"
] |
permissive
|
// Tenary Operator & Return Keyword
var isBiggerThanFive : (Int) ->Bool = {number in
let result = number>5 ? true : false
return result
}
| true
|
cbdee124c3c7ac00de130039ae5f70cb39085777
|
Swift
|
veader/advent_of_code
|
/2016/day22/solution.swift
|
UTF-8
| 5,618
| 2.90625
| 3
|
[] |
no_license
|
#!/usr/bin/env swift
import Foundation
// ----------------------------------------------------------------------------
struct GridNode {
let x: Int
let y: Int
let size: Int
let used: Int
let available: Int
let usedPercentage: Int
init?(_ input: String) {
// http://rubular.com/r/zJQc1T7ckJ
let nodeRegex = "^\\/dev\\/grid\\/node-x(\\d+)-y(\\d+)\\s+(\\d+)T\\s+(\\d+)T\\s+(\\d+)T\\s+(\\d+)%"
guard let matches = input.matches(regex: nodeRegex) else { return nil }
guard let match = matches.first else { return nil }
// 0 1 2 3 4 5
// format: /dev/grid/node-x0-y0 90T 69T 21T 76%
x = Int.init(match.captures[0])!
y = Int.init(match.captures[1])!
size = Int.init(match.captures[2])!
used = Int.init(match.captures[3])!
available = Int.init(match.captures[4])!
usedPercentage = Int.init(match.captures[5])!
}
func willFit(within node: GridNode) -> Bool {
// we are A, node is B...
// Node A is **not** empty (its `Used` is not zero).
guard used > 0 else { return false }
// Nodes A and B are **not the same** node.
guard !(x == node.x && y == node.y) else { return false }
// The data on node A (its `Used`) **would fit** on node B (its `Avail`).
return used <= node.available
}
}
extension GridNode: CustomDebugStringConvertible {
var debugDescription: String {
return "GridNode(\(x),\(y) S:\(size)T U:\(used)T A:\(available)T)"
}
}
// ----------------------------------------------------------------------------
struct Grid {
let maxX: Int
let maxY: Int
var nodes: [GridNode]
init(_ input: [String]) {
nodes = input.flatMap { GridNode($0) }
let maxXNode: GridNode! = nodes.max { a, b in a.x < b.x }
maxX = maxXNode.x
let maxYNode: GridNode! = nodes.max { a, b in a.y < b.y }
maxY = maxYNode.y
}
func node(x: Int, y: Int) -> GridNode? {
return nodes.first(where: { $0.x == x && $0.y == y})
}
func viablePairs() -> [[GridNode]] {
var pairs = [[GridNode]]()
nodes.forEach { nodeA in
nodes.forEach { nodeB in
if nodeA.willFit(within: nodeB) {
// print("Node \(nodeA) will fit into Node \(nodeB)")
pairs.append([nodeA, nodeB])
}
}
}
return pairs
}
}
extension Grid: CustomDebugStringConvertible {
var debugDescription: String {
var desc = "Grid(maxX:\(maxX), maxY:\(maxY) nodes:\(nodes.count))\n"
let rows = (0...maxY).map { y in
return (0...maxX).flatMap { x in
guard let node = self.node(x: x, y: y) else { return nil }
return "\(node.usedPercentage)".padding(toLength: 3, withPad: " ", startingAt:0)
}.joined(separator: "| ")
}.joined(separator: "\n")
// pad to 3
desc += "\(rows)"
return desc
}
}
// ----------------------------------------------------------------------------
extension String {
struct RegexMatch : CustomDebugStringConvertible {
let match: String
let captures: [String]
let range: NSRange
var debugDescription: String {
return "RegexMatch( match: '\(match)', captures: [\(captures)], range: \(range) )"
}
init(string: String, regexMatch: NSTextCheckingResult) {
var theCaptures: [String] = (0..<regexMatch.numberOfRanges).flatMap { index in
let range = regexMatch.rangeAt(index)
if let _ = range.toRange() {
return (string as NSString).substring(with: range)
} else {
return nil
}
}
match = theCaptures.removeFirst() // the 0 index is the whole string that matches
captures = theCaptures
range = regexMatch.range
}
}
func matches(regex: String) -> [RegexMatch]? {
do {
let regex = try NSRegularExpression(pattern: regex, options: .caseInsensitive)
let wholeThing = NSMakeRange(0, characters.count)
let regexMatches = regex.matches(in: self, options: .withoutAnchoringBounds, range: wholeThing)
guard let _ = regexMatches.first else { return nil }
return regexMatches.flatMap { m in
return RegexMatch.init(string: self, regexMatch: m)
}
} catch {
return nil
}
}
}
// ----------------------------------------------------------------------------
// returns the lines out of the input file
func readInputData() -> [String] {
guard let currentDir = ProcessInfo.processInfo.environment["PWD"] else {
print("No current directory.")
return []
}
let inputPath = "\(currentDir)/input.txt"
do {
let data = try String(contentsOfFile: inputPath, encoding: .utf8)
let lines = data.components(separatedBy: "\n")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty }
return lines
} catch {
return []
}
}
// ----------------------------------------------------------------------------
// MARK: - "MAIN()"
let lines = readInputData()
var grid = Grid(lines)
print(grid)
print("Found \(grid.nodes.count) nodes")
// var pairs = grid.viablePairs()
// print("Found \(pairs.count) valid pairs")
| true
|
798971607a01579fbfa9dc6e918d3d7760686225
|
Swift
|
DeanChung13/DCWheelPickerView
|
/DCWheelPickerViewDemo/DCWheelPickerView/DCWheelContainer.swift
|
UTF-8
| 7,047
| 2.828125
| 3
|
[
"LicenseRef-scancode-other-permissive",
"MIT"
] |
permissive
|
//
// DCWheelContainer.swift
// DCWheelPickerViewDemo
//
// Created by DeanChung on 2018/8/16.
// Copyright © 2018 DeanChung. All rights reserved.
//
import UIKit
enum WheelContainerStyle {
case outside, inside
}
class DCWheelContainerView: UIView {
let sectorColor1 = UIColor(rgbHex: 0x59636F).cgColor
let sectorColor2 = UIColor(rgbHex: 0x90A6BC).cgColor
let sectorSelectedColor = UIColor(rgbHex: 0x55BFE7).cgColor
private let numberOfSectors = 10
private var borderWidth: CGFloat = 4.0
private var selectedIndex: Int = 0
private var maxNumber: Int = 0
private var style: WheelContainerStyle
private var sectorLayers: [CAShapeLayer] = []
private var prepareChangeToSector: DCWheelSector?
private var radius: CGFloat {
return (frame.size.width - borderWidth) / 2.0
}
// MARK: lazy properties
private lazy var sectors: [DCWheelSector] = {
var sectors: [DCWheelSector] = []
sectors.reserveCapacity(numberOfSectors)
return sectors
}()
private lazy var fanWidth: CGFloat = {
return CGFloat.pi * 2 / CGFloat(numberOfSectors)
}()
// MARK: initializer
init(frame: CGRect, style: WheelContainerStyle = .outside) {
self.style = style
super.init(frame: frame)
backgroundColor = UIColor.clear
isUserInteractionEnabled = false
buildSectors()
drawWheel()
setupBorder()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func buildSectors() {
var mid = CGFloat.pi
for i in 0 ..< numberOfSectors {
let sector = DCWheelSector(index: i, fanWidth: fanWidth)
mid += fanWidth
sectors.append(sector)
}
}
private func drawWheel() {
doWithAllSectors(action: drawShape)
doWithAllSectors(action: addTextLabel)
}
private func updateSelectedSectorBackgroundColor(index newSelectedIndex: Int) {
let oldSelectedSectorLayer = sectorLayers[selectedIndex]
fillColor(layer: oldSelectedSectorLayer, index: selectedIndex)
let newSelectedSectorLayer = sectorLayers[newSelectedIndex]
newSelectedSectorLayer.fillColor = sectorSelectedColor
selectedIndex = newSelectedIndex
}
private func doWithAllSectors(action: (DCWheelSector) -> Void) {
for sector in sectors {
action(sector)
}
}
private func drawShape(with sector: DCWheelSector) {
let sectorLayer = CAShapeLayer()
let path = UIBezierPath()
path.move(to: centerPoint)
path.addArc(withCenter: centerPoint,
radius: radius,
startAngle: CGFloat(sector.arcStartAngle),
endAngle: CGFloat(sector.arcEndAngle),
clockwise: true)
path.close()
sectorLayer.path = path.cgPath
fillColor(layer: sectorLayer, index: sector.index)
sectorLayers.append(sectorLayer)
layer.addSublayer(sectorLayer)
}
private func fillColor(layer: CAShapeLayer, index: Int) {
let color1 = (style == .outside) ? sectorColor1 : sectorColor2
let color2 = (style == .outside) ? sectorColor2 : sectorColor1
layer.fillColor = (index % 2 == 0) ? color1 : color2
}
private func addTextLabel(with sector: DCWheelSector) {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: radius, height: radius))
label.font = UIFont.boldSystemFont(ofSize: 26)
label.backgroundColor = UIColor.clear
label.textColor = UIColor.white
label.textAlignment = .center
label.text = "\(sector.index)"
label.layer.anchorPoint = CGPoint(x: 0.5, y: labelAnchorPointY())
label.layer.position = centerPoint
label.transform = CGAffineTransform.identity
.rotated(by: sector.labelAngle)
addSubview(label)
}
private func labelAnchorPointY() -> CGFloat {
return (style == .outside) ? 1.37 : 1.3
}
private func setupBorder() {
let borderLayer = CAShapeLayer()
let path = UIBezierPath(ovalIn: bounds.insetBy(dx: borderWidth, dy: borderWidth))
borderLayer.path = path.cgPath
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.strokeColor = UIColor.white.cgColor
borderLayer.lineWidth = borderWidth
borderLayer.shadowColor = UIColor.darkGray.cgColor
borderLayer.shadowOffset = CGSize(width: 2.0, height: 2.0)
borderLayer.shadowOpacity = 0.8
layer.addSublayer(borderLayer)
}
private func detectCurrentSector() -> DCWheelSector {
let currentSectorRadians = rotatedSectorRadians()
return detectSector(sectorRadians: currentSectorRadians) ?? sectors.first!
}
private func detectSector(sectorRadians: CGFloat) -> DCWheelSector? {
return sectors.filter {
var result = false
var minValue = $0.minValue
var maxValue = $0.maxValue
if maxValue < minValue {
if sectorRadians < 0 {
minValue = -CGFloat.pi - ($0.midValue - $0.minValue)
} else {
maxValue = CGFloat.pi + ($0.midValue - $0.minValue)
}
}
result = sectorRadians > minValue && sectorRadians < maxValue
return result
}.last
}
private func rotatedRadians() -> CGFloat {
return CGFloat(atan2f(Float(transform.b), Float(transform.a)))
}
private func rotatedSectorRadians() -> CGFloat {
return sectorDifferenceRadians(from: rotatedRadians())
}
private func sectorDifferenceRadians(from radians: CGFloat) -> CGFloat {
let result: CGFloat
if radians >= 0 {
result = radians - CGFloat.pi
} else {
result = radians + CGFloat.pi
}
return result
}
func detectIndex(gestureTrack: DCWheelGestureTrack? = nil) -> Int {
guard let tracker = gestureTrack else {
return detectPanIndex()
}
if tracker.isTapped {
return detectTapIndex(point: tracker.endPolarPoint)
} else {
return detectPanIndex()
}
}
private func detectPanIndex() -> Int {
let sector = detectCurrentSector()
let result = sector.index
prepareChangeToSector = sector
return result
}
private func detectTapIndex(point: DCPolarPoint) -> Int {
var totalRadians = point.radians + rotatedRadians()
if totalRadians > CGFloat.pi {
totalRadians = -2*CGFloat.pi + totalRadians
}
if totalRadians < -CGFloat.pi {
totalRadians = 2*CGFloat.pi + totalRadians
}
guard let sector = detectSector(sectorRadians: totalRadians) else {
print("Unknown radians: \(totalRadians)")
return -99
}
let result = sector.index
prepareChangeToSector = sector
return result
}
func alignmentToNewSector() {
guard let sector = prepareChangeToSector else { return }
let sectorDifferenceValue = sectorDifferenceRadians(from: sector.midValue)
UIView.animate(withDuration: 0.5,
delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5,
options: [.curveEaseOut], animations: {
self.transform = CGAffineTransform.identity.rotated(by: sectorDifferenceValue)
}, completion: nil)
prepareChangeToSector = nil
updateSelectedSectorBackgroundColor(index: sector.index)
}
}
| true
|
0ba96e7e23a6edc6034810bec8d7be52be0360bc
|
Swift
|
NekoFluff/Devil-s-Agenda
|
/DevilsAgenda/TableViewCells/SwitchTableViewCell.swift
|
UTF-8
| 1,129
| 2.8125
| 3
|
[] |
no_license
|
//
// LabelTableViewCell.swift
// DevilsAgenda
//
// Created by Alexander Nou on 10/7/17.
// Copyright © 2017 Team PlanIt. All rights reserved.
//
import UIKit
protocol SwitchTableViewCellDelegate {
func switchCell(cell: UITableViewCell, isNowOn isOn: Bool);
}
class SwitchTableViewCell: UITableViewCell {
@IBOutlet weak var title: UILabel!
@IBOutlet weak var cellSwitch: UISwitch!
var delegate : SwitchTableViewCellDelegate?
var editingDisabled = false {
didSet {
self.cellSwitch.isEnabled = !editingDisabled
}
}
@IBAction func switchChanged(_ sender: UISwitch) {
self.delegate?.switchCell(cell: self, isNowOn: sender.isOn)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configure(title: String, isOn: Bool) {
self.title.text = title
self.cellSwitch.isOn = isOn
}
}
| true
|
63bc4a56001f4893d180cfb0b0397163e8e0e248
|
Swift
|
kylietramle/Practice-Problems
|
/BinarySearch.playground/Contents.swift
|
UTF-8
| 912
| 4.03125
| 4
|
[] |
no_license
|
// binary search
import Foundation
let array = [1,4,5,7,9,13,16,18,20,23,25,27]
func binarySearch(searchValue: Int, array: [Int]) -> Bool {
var leftIndex = 0
var rightIndex = array.count - 1
while leftIndex <= rightIndex {
let middleIndex = (leftIndex + rightIndex)/2
let middleValue = array[middleIndex]
print("middle index is \(middleIndex); middle number is \(middleValue); leftIndex is \(leftIndex); rightIndex is \(rightIndex); for [\(array[leftIndex]), \(array[rightIndex])]")
if searchValue == middleValue {
return true
}
if searchValue < middleValue {
rightIndex = middleIndex - 1
}
if searchValue > middleValue {
leftIndex = middleIndex + 1
}
}
return false
}
print (binarySearch(searchValue: 27, array: array))
| true
|
247a07011d4e03a785079674bfe7301e74043104
|
Swift
|
carlosypunto/PendulaTone
|
/PendulaTone/ViewController.swift
|
UTF-8
| 1,321
| 2.6875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// PendulaTone
//
// Created by Simon Gladman on 13/01/2015.
// Copyright (c) 2015 Simon Gladman. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
var pendula = [Pendulum]()
let notes = [261.6, 277.2, 293.7, 311.1, 329.6, 349.2, 370.0, 392.0, 415.3, 440.0, 466.2, 493.9]
override func viewDidLoad()
{
super.viewDidLoad()
view.backgroundColor = UIColor.lightGrayColor()
for (idx, noteFrequency): (Int, Double) in notes.enumerate()
{
let i = idx + 5
let pendulumDuration = (15 / Float(i))
let pendulumLength = (21 - i) * 25
let pendulum = Pendulum(pendulumDuration: pendulumDuration , pendulumLength: pendulumLength, noteFrequency: noteFrequency)
pendula.append(pendulum)
view.addSubview(pendulum)
}
}
override func viewDidLayoutSubviews()
{
for (_, pendulum): (Int, Pendulum) in pendula.enumerate()
{
pendulum.frame = CGRect(x: view.frame.width / 2, y: 20, width: 0, height: 0)
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
b9c4dc7041ca33f7e2e8f581c5cd5cb89fca32f3
|
Swift
|
VincentGeranium/Swift-Study
|
/2020-03-17-EnumerationExample-2.playground/Contents.swift
|
UTF-8
| 617
| 3.75
| 4
|
[] |
no_license
|
import UIKit
enum School: String {
case primary = "유치원"
case elemantary = "초등학교"
case middle = "중학교"
case high = "고등학교"
case college = "대학"
case university = "대학교"
case graduate = "대학원"
}
let highestEducationLevel: School = School.university
print("저의 최종학력은 \(highestEducationLevel.rawValue) 졸업입니다.")
enum WeekDays: Character {
case mon = "월", tue = "화", wed = "수", thu = "목", fri = "금", sat = "토", sun = "일"
}
let today: WeekDays = WeekDays.tue
print("오늘은 \(today.rawValue)요일입니다.")
| true
|
68ca328a6a37bc2c932b7e713176ec72ca549514
|
Swift
|
ProfessorManhattan/Mist
|
/Mist/Helpers/Downloader.swift
|
UTF-8
| 2,389
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
//
// Downloader.swift
// Mist
//
// Created by Nindi Gill on 11/3/21.
//
import Foundation
struct Downloader {
static func download(_ product: Product, settings: Settings) throws {
let semaphore: DispatchSemaphore = DispatchSemaphore(value: 0)
let temporaryURL: URL = URL(fileURLWithPath: settings.temporaryDirectory(for: product))
let urls: [String] = [product.distribution] + product.packages.map { $0.url }.sorted { $0 < $1 }
PrettyPrint.printHeader("DOWNLOAD")
for (index, url) in urls.enumerated() {
guard let source: URL = URL(string: url) else {
throw MistError.invalidURL(url: url)
}
let current: Int = index + 1
let currentString: String = "\(current < 10 && product.totalFiles >= 10 ? "0" : "")\(current)"
PrettyPrint.print("Downloading file \(currentString) of \(product.totalFiles) - \(source.lastPathComponent)...")
let task: URLSessionDownloadTask = URLSession.shared.downloadTask(with: source) { url, response, error in
if let error: Error = error {
PrettyPrint.print(prefix: "└─", error.localizedDescription)
exit(1)
}
guard let response: HTTPURLResponse = response as? HTTPURLResponse else {
PrettyPrint.print(prefix: "└─", "There was an error retrieving \(source.lastPathComponent)")
exit(1)
}
guard response.statusCode == 200 else {
PrettyPrint.print(prefix: "└─", "Invalid HTTP status code: \(response.statusCode)")
exit(1)
}
guard let location: URL = url else {
PrettyPrint.print(prefix: "└─", "Invalid temporary URL")
exit(1)
}
let destination: URL = temporaryURL.appendingPathComponent(source.lastPathComponent)
do {
try FileManager.default.moveItem(at: location, to: destination)
semaphore.signal()
} catch {
PrettyPrint.print(prefix: "└─", error.localizedDescription)
exit(1)
}
}
task.resume()
semaphore.wait()
}
}
}
| true
|
7d75d1f262f193f9b5ebafc8574d6ddb71dbf29a
|
Swift
|
sagardhake9790/Gutenberg
|
/Gutenberg/CommonFiles/Fonts/Font.swift
|
UTF-8
| 791
| 2.5625
| 3
|
[] |
no_license
|
//
// Font.swift
// Gutenberg
//
// Created by Sagar Dhake on 10/01/21.
//
import UIKit
public struct Font {
static let heading1Style = UIFont(name: "Montserrat-SemiBold", size: 32)
static let heading2Style = UIFont(name: "Montserrat-SemiBold", size: 24)
static let semiBoldLargeFontStyle = UIFont(name: "Montserrat-SemiBold", size: 20)
static let regularLargeFontStyle = UIFont(name: "Montserrat-Regular", size: 20)
static let semiBoldMediumFontStyle = UIFont(name: "Montserrat-SemiBold", size: 16)
static let regularMediumFontStyle = UIFont(name: "Montserrat-Regular", size: 16)
static let semiBoldSmallFontStyle = UIFont(name: "Montserrat-SemiBold", size: 12)
static let regularSmallFontStyle = UIFont(name: "Montserrat-Regular", size: 12)
}
| true
|
3537d788b6cd3f85c73f65713516809ddaa22878
|
Swift
|
fweissi/WatchDogsSignup
|
/Sources/App/Middleware/MemberMiddleware.swift
|
UTF-8
| 5,087
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
import Vapor
import HTTP
import Foundation
import VaporPostgreSQL
final class MemberMiddleware: Middleware {
let drop: Droplet?
init(drop: Droplet) {
self.drop = drop
}
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
var errorStatus: Status = .forbidden
var errorMessage = "You are not allowed to perform this task in a browser."
if request.uri.host.contains("update") {
print("Update")
}
if request.accept.prefers("html") {
let url = URL(string: request.uri.path)
if let lastComponent = url?.lastPathComponent {
if lastComponent.contains("css") || lastComponent.contains("js") || lastComponent.contains("gif") {
return try next.respond(to: request)
}
else {
do {
var response = try next.respond(to: request)
if url!.absoluteString.contains("members") {
let components = url!.path.components(separatedBy: "/")
let count = components.count
let lastComponent = components[count - 2]
switch lastComponent {
case "", "members":
if let drop = drop,
let bodyBytes = response.body.bytes {
do {
let parameters = try JSON(bytes: bodyBytes)
let myResponse = try drop.view.make("manage", ["page": "member", "members": parameters]).makeResponse()
return myResponse
}
catch {
print("Error")
}
}
default:
response = Response(redirect: "/members")
}
}
else if url!.absoluteString.contains("teachers") {
let components = url!.path.components(separatedBy: "/")
let count = components.count
let lastComponent = components[count - 2]
switch lastComponent {
case "", "teachers":
if let drop = drop,
let bodyBytes = response.body.bytes {
do {
let parameters = try JSON(bytes: bodyBytes)
let myResponse = try drop.view.make("teacher", ["page": "teacher", "teachers": parameters]).makeResponse()
return myResponse
}
catch {
print(error.localizedDescription)
errorStatus = .expectationFailed
errorMessage = "The page cannot be rendered due to a parsing error."
throw Abort.custom(status: errorStatus, message: errorMessage)
}
}
case "show":
if let drop = drop,
let bodyBytes = response.body.bytes {
do {
let parameter = try JSON(bytes: bodyBytes)
let parameters = try Teacher.all().makeJSON()
let myResponse = try drop.view.make("teacher", ["page": "teacher", "teachers": parameters, "teacher": parameter]).makeResponse()
return myResponse
}
catch {
errorStatus = .expectationFailed
errorMessage = "The page cannot be rendered due to a parsing error."
throw Abort.custom(status: errorStatus, message: errorMessage)
}
}
default:
return Response(redirect: "/teachers")
}
}
}
catch {
throw Abort.custom(status: errorStatus, message: errorMessage)
}
}
}
}
return try next.respond(to: request)
}
}
| true
|
2aa0f1415fe5c8489cab2afc0d2fbcfb03260aeb
|
Swift
|
envelore/speechPartsRecognizerClient
|
/Speech Recognizer/Document/DocumentController.swift
|
UTF-8
| 3,381
| 2.78125
| 3
|
[] |
no_license
|
import Models
import UIKit
import SpeechNetwork
import Foundation
final class DocumentViewController: UIViewController, DocumentViewInput {
// MARK: - Properties
private var document: Document?
private var contentView = DocumentView()
private var networkService = RecognitionNetworkService()
// MARK: - UIViewController lifecycle
override func loadView() {
view = contentView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
document?.open { [weak self] success in
if success {
self?.setData(data: self?.document)
} else {
print("Error: document opening failed")
self?.dismissDocumentViewController()
}
}
}
// MARK: - DocumentViewInput
func setData(data document: Document?) {
self.document = document
setUpView()
}
// MARK: - Private
private func setUpView() {
if let text = document?.userText {
contentView.setViewData(text: NSAttributedString(string: text), needReload: true)
}
contentView.onClose = { [weak self] in
self?.dismissDocumentViewController()
}
contentView.onDidScroll = { [weak self] range, string in
if let string = string,
let words = self?.detectWordsIn(string: string) {
let request = TextRecognitionRequest(words: words)
self?.networkService.recognize(request: request) { result in
self?.process(range: range, result: result)
}
}
}
}
private func dismissDocumentViewController() {
dismiss(animated: true) {
self.document?.close(completionHandler: nil)
}
}
private func process(range: NSRange, result: RecognitionApiResponse) {
if result.result.isError,
let message = result.result.errorMessage {
showError(error: message)
return
}
guard let previousText = document?.userText,
let range = previousText.rangeFromNSRange(nsRange: range),
let speechParts = result.result.speechParts else { return }
let attributedString = NSMutableAttributedString(string: previousText)
var index = 0
previousText.enumerateSubstrings(in: range, options: .byWords) { (substring, _, range, _) -> () in
if substring != nil, index < speechParts.count {
let color: UIColor
switch speechParts[index] {
case .noun:
color = .blue
case .verb:
color = .red
case .adjective:
color = .magenta
default:
color = .black
}
attributedString.setAttributes([.foregroundColor: color], range: range.nsRange(in: previousText))
index += 1
}
}
contentView.setViewData(text: attributedString, needReload: false)
}
private func detectWordsIn(string: String) -> [String] {
return string.words()
}
private func showError(error: String) {
contentView.showError(text: error)
}
}
| true
|
5df334ed38ec3f00538ee2d0c9992e23e8b1dd9a
|
Swift
|
lostbearlabs/LogLlama
|
/Script/DetectDuplicatesCommand.swift
|
UTF-8
| 1,684
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
/**
Processes log lines looking for duplicates and produces a summary by adding ersatz log lines at the top of the list.
When looking for matches, we replace phrases of the form "=value" and phrases the look like digits with placeholders, so that similar lines will match even if their details differ.
*/
class DetectDuplicatesCommand : ScriptCommand {
var callback : ScriptCallback
var threshold : Int
init(callback: ScriptCallback, threshold: Int) {
self.callback = callback
self.threshold = threshold
}
func validate() -> Bool {
true
}
func changesData() -> Bool {
false
}
func run(logLines: inout [LogLine], runState: inout RunState) -> Bool {
var counts : [String: Int] = [:]
self.callback.scriptUpdate(text: "Looking for lines that occur more that \(self.threshold) times")
for line in logLines {
let x = line.getAnonymousString()
if counts.contains(where: {$0.key == x}) {
counts[x] = counts[x]! + 1
} else {
counts[x] = 1
}
}
var repeated : [String] = []
for( text, count ) in counts {
if count > self.threshold {
self.callback.scriptUpdate(text: "... found \(count) lines like: \(text)")
let newLine = LogLine(text: "[\(count) LINES LIKE THIS] \(text)", lineNumber: 0)
logLines.insert(newLine, at:0)
repeated.append(text)
}
}
// TODO: also filter them??
return true
}
}
| true
|
693f73e5e6cf8d74a020f4b0babaf8b1e9037e42
|
Swift
|
Harry-TS/trees
|
/src/ios/trees/DatasetsViewController.swift
|
UTF-8
| 3,178
| 2.59375
| 3
|
[] |
no_license
|
import UIKit
class DatasetsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
self.tableView.reloadData()
self.updateCurrentDataset()
}
override func viewDidLoad()
{
super.viewDidLoad()
Dataset.didLoad.add(tag: self)
{
dataset in
self.updateCurrentDataset()
}
LocationService.instance.geocodeDatasetChanged.add(tag: self)
{
dataset in
for indexPath in self.tableView!.indexPathsForVisibleRows!
{
let cell = self.tableView.cellForRow(at:indexPath) as! DatasetTableViewCell
let cellDataset = Dataset.all[indexPath.row]
cell.locationView.isHidden = (dataset == nil || cellDataset !== LocationService.instance.geocodeDataset)
}
}
}
////////////////////////////////////////
@IBOutlet weak var tableView: UITableView!
////////////////////////////////////////
private func updateCurrentDataset()
{
if let dataset = Dataset.current
{
let index = Dataset.all.firstIndex(where: { dataset === $0 })!
self.tableView.selectRow(at: IndexPath(row: index, section: 0), animated: false, scrollPosition: .none)
}
else
{
if let index = self.tableView.indexPathForSelectedRow
{
self.tableView.deselectRow(at: index, animated: true)
}
}
}
////////////////////////////////////////
// UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return Dataset.all.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier:"cell_id") as! DatasetTableViewCell
let dataset = Dataset.all[indexPath.row]
cell.titleLabel.text = "\(dataset.name), \(dataset.administrativeArea)"
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
let formattedNumber = numberFormatter.string(from: NSNumber(value: dataset.numberOfSites))!
cell.subtitleLabel.text = "\(formattedNumber) trees"
cell.locationView.isHidden = (dataset !== LocationService.instance.geocodeDataset)
cell.checkView.isHidden = (dataset !== Dataset.current)
return cell
}
////////////////////////////////////////
// UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
Dataset.all[indexPath.row].load()
let cell = self.tableView.cellForRow(at:indexPath) as! DatasetTableViewCell
cell.checkView.isHidden = false
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)
{
let cell = self.tableView.cellForRow(at:indexPath) as! DatasetTableViewCell
cell.checkView.isHidden = true
}
}
| true
|
4c9212eece3f691ec40969f62d0a6988c3661526
|
Swift
|
kzzou/zhihu
|
/知乎日报/Sections/ThemeSection.swift
|
UTF-8
| 503
| 2.5625
| 3
|
[] |
no_license
|
//
// ThemeSection.swift
// 知乎日报
//
// Created by 邹凯章 on 2017/7/6.
// Copyright © 2017年 邹凯章. All rights reserved.
//
import Foundation
import RxDataSources
struct ThemeSection {
var items: [ThemeModel]
}
extension ThemeSection: SectionModelType {
typealias Item = ThemeModel
var identity: String {
return ""
}
init(original: ThemeSection, items: [Item]) {
self = original
self.items = items
}
}
| true
|
4f52c5271c8e882111f2bb2f9e2c022d9ae37c80
|
Swift
|
dpelovski/retro-calculator
|
/RetroCalculator/RetroCalculator/ViewController.swift
|
UTF-8
| 11,593
| 3.09375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// RetroCalculator
//
// Created by Damian Pelovski on 1/13/17.
// Copyright © 2017 Damian Pelovski. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var outputLbl: UILabel!
@IBOutlet weak var stackHex: UIStackView!
var btnSound: AVAudioPlayer!
// currentOperation starts with empty
var currentOperation = Operation.Empty
var runningNumber = ""
var leftValStr = ""
var rightValStr = ""
var result = ""
//Enum for the different kinds of operations
enum Operation: String {
case Divide = "/"
case Multiply = "*"
case Subtract = "-"
case Add = "+"
case Empty = "Empty"
}
override func viewDidLoad() {
super.viewDidLoad()
//path is the path to the resource btn.wav
let path = Bundle.main.path(forResource: "btn", ofType: "wav")
// iOS works with URL's so we create a URL from a string path
let soundURL = URL(fileURLWithPath: path!)
do {
//AVAudioPlayer is a player created from a URL
try btnSound = AVAudioPlayer(contentsOf: soundURL)
//preparing the btnSound to play
btnSound.prepareToPlay()
}
catch let err as NSError {
//if any error occurs we would print it to the console so we can see the error message
print(err.debugDescription)
}
outputLbl.text = "0"
typeLabel.text = "DEC"
}
// IBAction linked to the 9 numbers
@IBAction func numberPressed(sender: UIButton) {
//when a number is pressed from 1-9 we play a sound
playSound()
//we use sender.tag, because we used the tag attribute for every button from 1 ot 9 in the storyboard. We then append the content of the tag to the runningNumber
if sender.tag == 21 {
runningNumber += "A"
}
else if sender.tag == 22 {
runningNumber += "B"
}
else if sender.tag == 23 {
runningNumber += "C"
}
else if sender.tag == 24 {
runningNumber += "D"
}
else if sender.tag == 25 {
runningNumber += "E"
}
else if sender.tag == 26 {
runningNumber += "F"
}
else{
runningNumber += "\(sender.tag)"
}
//we append the running number to the label that we are using
outputLbl.text = runningNumber
}
@IBAction func onClearPressed(sender: AnyObject) {
playSound()
outputLbl.text = "0"
runningNumber = ""
leftValStr = ""
rightValStr = ""
result = ""
currentOperation = Operation.Empty
}
@IBAction func onDividePressed(sender: AnyObject) {
processOperation(operation: .Divide, inSystem: typeLabel.text!)
}
@IBAction func onMultiplyPressed(sender: AnyObject) {
processOperation(operation: .Multiply, inSystem: typeLabel.text!)
}
@IBAction func onSubtractPressed(sender: AnyObject) {
processOperation(operation: .Subtract, inSystem: typeLabel.text!)
}
@IBAction func onAddPress(sender: AnyObject) {
processOperation(operation: .Add, inSystem: typeLabel.text!)
}
@IBAction func onEqualPress(sender: AnyObject) {
processOperation(operation: currentOperation, inSystem: typeLabel.text!)
}
func playSound() {
//stop the button from playing the sound if it is currently playing it
if btnSound.isPlaying {
btnSound.stop()
}
btnSound.play()
}
func processOperation(operation: Operation, inSystem: String) {
playSound()
switch inSystem {
case "BIN":
calculateBin(operation: operation)
break
case "OCT":
calculateOct(operation: operation)
break
case "DEC":
calculateDecimal(operation: operation)
break
case "HEX":
calculateHex(operation: operation)
break
default:
break
}
}
func calculateOct(operation: Operation) {
if currentOperation != Operation.Empty {
//The user selected an operator,but then selected another operator without first entering a number
if runningNumber != "" {
rightValStr = runningNumber
runningNumber = ""
let leftSideVal = Int(leftValStr, radix: 8)!
let rightSideVal = Int(leftValStr, radix: 8)!
if currentOperation == Operation.Multiply {
result = "\(leftSideVal * rightSideVal)"
} else if currentOperation == Operation.Divide {
result = "\(leftSideVal / rightSideVal)"
} else if currentOperation == Operation.Subtract {
result = "\(leftSideVal - rightSideVal)"
} else if currentOperation == Operation.Add {
result = "\(leftSideVal + rightSideVal)"
}
leftValStr = result
outputLbl.text = result
}
currentOperation = operation
} else {
//This is the first time an operator has been pressed
leftValStr = runningNumber
runningNumber = ""
currentOperation = operation
}
}
func calculateHex(operation: Operation) {
if currentOperation != Operation.Empty {
//The user selected an operator,but then selected another operator without first entering a number
if runningNumber != "" {
rightValStr = runningNumber
runningNumber = ""
let leftSideVal = Int(leftValStr, radix: 16)!
let rightSideVal = Int(leftValStr, radix: 16)!
if currentOperation == Operation.Multiply {
result = "\(leftSideVal * rightSideVal)"
} else if currentOperation == Operation.Divide {
result = "\(leftSideVal / rightSideVal)"
} else if currentOperation == Operation.Subtract {
result = "\(leftSideVal - rightSideVal)"
} else if currentOperation == Operation.Add {
result = "\(leftSideVal + rightSideVal)"
}
leftValStr = result
outputLbl.text = result
}
currentOperation = operation
} else {
//This is the first time an operator has been pressed
leftValStr = runningNumber
runningNumber = ""
currentOperation = operation
}
}
func calculateBin(operation: Operation) {
if currentOperation != Operation.Empty {
//The user selected an operator,but then selected another operator without first entering a number
if runningNumber != "" {
rightValStr = runningNumber
runningNumber = ""
let leftSideVal = Int(leftValStr, radix: 2)!
let rightSideVal = Int(leftValStr, radix: 2)!
if currentOperation == Operation.Multiply {
result = "\(leftSideVal * rightSideVal)"
} else if currentOperation == Operation.Divide {
result = "\(leftSideVal / rightSideVal)"
} else if currentOperation == Operation.Subtract {
result = "\(leftSideVal - rightSideVal)"
} else if currentOperation == Operation.Add {
result = "\(leftSideVal + rightSideVal)"
}
leftValStr = result
outputLbl.text = result
}
currentOperation = operation
} else {
//This is the first time an operator has been pressed
leftValStr = runningNumber
runningNumber = ""
currentOperation = operation
}
}
func calculateDecimal(operation: Operation) {
if currentOperation != Operation.Empty {
//The user selected an operator,but then selected another operator without first entering a number
if runningNumber != "" {
rightValStr = runningNumber
runningNumber = ""
if currentOperation == Operation.Multiply {
result = "\(Double(leftValStr)! * Double(rightValStr)!)"
} else if currentOperation == Operation.Divide {
result = "\(Double(leftValStr)! / Double(rightValStr)!)"
} else if currentOperation == Operation.Subtract {
result = "\(Double(leftValStr)! - Double(rightValStr)!)"
} else if currentOperation == Operation.Add {
result = "\(Double(leftValStr)! + Double(rightValStr)!)"
}
leftValStr = result
outputLbl.text = result
}
currentOperation = operation
} else {
//This is the first time an operator has been pressed
leftValStr = runningNumber
runningNumber = ""
currentOperation = operation
}
}
func restartAfterChoosingType() {
outputLbl.text = "0"
runningNumber = ""
leftValStr = ""
rightValStr = ""
result = ""
currentOperation = Operation.Empty
}
@IBAction func binPressed(_ sender: Any) {
playSound()
typeLabel.text = "BIN"
restartAfterChoosingType()
stackHex.isHidden = true
}
@IBAction func hexPressed(_ sender: Any) {
playSound()
typeLabel.text = "HEX"
restartAfterChoosingType()
stackHex.isHidden = false
}
@IBAction func decPressed(_ sender: Any) {
playSound()
typeLabel.text = "DEC"
restartAfterChoosingType()
stackHex.isHidden = true
}
@IBAction func octPressed(_ sender: Any) {
playSound()
typeLabel.text = "OCT"
restartAfterChoosingType()
stackHex.isHidden = true
}
@IBAction func transform(_ sender: Any) {
// let regexHex = try! NSRegularExpression(pattern: "^[a-fA-F0-9]+$", options: [])
if outputLbl.text != "0" {
switch typeLabel.text! {
case "BIN":
outputLbl.text! = String(Int(result)!, radix: 2)
case "OCT":
outputLbl.text! = String(Int(result)!, radix: 8)
case "HEX":
if let number = Int(outputLbl.text!) {
if number != 1 {
outputLbl.text! = String(Int(result)!, radix: 16)
}
}
default:
break
}
}
}
}
| true
|
5f3b49a2bf14086f4b323e04f9afba6bcc1d40fd
|
Swift
|
KemiAirewele/SuperpositionIVProject
|
/SuperpositionIV/NetworkingService.swift
|
UTF-8
| 4,412
| 2.953125
| 3
|
[] |
no_license
|
//
// NetworkingService.swift
// SuperpositionIV
//
// Created by Kemi Airewele on 2/29/20.
// Copyright © 2020 Kemi Airewele. All rights reserved.
//
import Foundation
import Firebase
import FirebaseAuth
import FirebaseStorage
import FirebaseDatabase
import UIKit
struct NetworkingService {
var databaseRef: DatabaseReference! {
return Database.database().reference()
}
var storageRef: StorageReference {
return Storage.storage().reference()
}
// 3 -- Saving the User Info in the Database
fileprivate func saveInfo(_ user: User!, name: String, password: String, skinType: Int) {
// Create our user dictionary info\
let userInfo = ["email": user.email!, "name": name, "uid": user.uid, "skinType": skinType] as [String : Any]
// Create User Reference
let userRef = databaseRef.child("users").child(user.uid)
//Save the user Info in the Database
userRef.setValue(userInfo)
signIn(user.email!, password: password)
}
// 4 -- Sign In
func signIn(_ email: String, password: String){
Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
if error == nil {
if let user = user {
print("\(user.user.displayName) has signed in!")
}
} else {
print(error!.localizedDescription)
}
})
}
// 2 -- Set User Info
fileprivate func setUserInfo(_ user: User!, name: String, password: String, skinType: Int){
let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = name
changeRequest?.commitChanges(completion: { (error) in
if error == nil {
self.saveInfo(user, name: name, password: password, skinType: skinType)
} else{
print(error!.localizedDescription)
}
})
}
// 1-- We Create the User
func signUp(_ email: String, name: String, password: String, skinType: Int) {
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
if error == nil {
self.setUserInfo(user?.user, name: name, password: password, skinType: skinType)
} else {
print(error!.localizedDescription)
}
})
}
// Reset Password
func resetPassword(_ email: String){
Auth.auth().sendPasswordReset(withEmail: email, completion: { (error) in
if error == nil {
print("An email with information on how to reset your password has been sent to you. Thank You")
} else {
print(error!.localizedDescription)
}
})
}
func updateEmail(_ email: String, oldEmail: String, password: String){
let user = Auth.auth().currentUser
var credential: AuthCredential
// Prompt the user to re-provide their sign-in credentials
credential = EmailAuthProvider.credential(withEmail: oldEmail, password: password)
user?.reauthenticate(with: credential, completion: { (authResult, error) in
if let error = error {
// An error happened.
print(error.localizedDescription)
} else {
// User re-authenticated.
Auth.auth().currentUser?.updateEmail(to: email, completion: { (error) in
if error == nil {
print("Email has been updated")
} else {
print(error!.localizedDescription)
}
})
}
})
}
func signOut(){
do{
try Auth.auth().signOut();
defaults.set(false, forKey:"LoggedIn")
defaults.removeObject(forKey: "userEmail")
defaults.synchronize()
} catch let logoutError {
print(logoutError)
}
}
}
| true
|
c9ae6628419f8288d49048dd6d376d7454ff94ba
|
Swift
|
croanlabs/ios-futurities
|
/Consensus Clubs/Scenes/ShowPoll/ShowPollPresenter.swift
|
UTF-8
| 1,433
| 2.875
| 3
|
[] |
no_license
|
//
// ShowProductPresenter.swift
// Consensus Clubs
//
// Created by Ger O'Sullivan on 2018-05-18.
// Copyright © 2018 Consensus Clubs. All rights reserved.
//
import UIKit
import CompanyCore
struct ShowPollPresenter: ShowPollPresentable {
private weak var viewController: ShowPollDisplayable?
private let currencyFormatter: NumberFormatter
init(viewController: ShowPollDisplayable?) {
self.viewController = viewController
self.currencyFormatter = NumberFormatter()
self.currencyFormatter.numberStyle = .currency
}
}
extension ShowPollPresenter {
func presentFetchedPoll(for response: ShowPollModels.Response) {
let viewModel = ShowPollModels.ViewModel(
id: response.poll.id,
name: response.poll.name,
content: response.poll.content,
price: currencyFormatter.string(from: NSNumber(value: Float(response.poll.priceCents) / 100))
?? "\(response.poll.priceCents / 100)"
)
viewController?.displayFetchedPoll(with: viewModel)
}
func presentFetchedPoll(error: DataError) {
// Handle and parse error
let viewModel = AppModels.Error(
title: "Poll Error", // TODO: Localize
message: "There was an error retrieving the poll: \(error)" // TODO: Localize
)
viewController?.display(error: viewModel)
}
}
| true
|
592ea2906d47b79da0eed0737c7dd0c11fa95e9a
|
Swift
|
Bill-Haku/AlarmOfiOS
|
/ASimpleAlarm/ASimpleAlarm/AddAlarmView.swift
|
UTF-8
| 4,971
| 2.84375
| 3
|
[] |
no_license
|
//
// AddAlarmView.swift
// ASimpleAlarm
//
// Created by YZH on 2021/1/16.
//
import SwiftUI
import AVFoundation
struct AddAlarmView: View {
@ObservedObject var globalContent: GlobalContent
// @State private var setDate = Date()
// @State private var isOn = false
var body: some View {
NavigationView {
VStack {
DatePicker("Please enter a time", selection: $globalContent.setDate, displayedComponents: .hourAndMinute)
.labelsHidden()
.datePickerStyle(WheelDatePickerStyle())
/* Toggle("",isOn:$isOn)
.offset(x:-50)
*/
Button {
self.globalContent.registerLocal()
//registerLocal()
} label: {
Text("Confirmation of receipt of notification")
}
Spacer()
}
.navigationBarTitle(Text("Setting"), displayMode: .inline)
.navigationBarItems(trailing: Button(action: {
self.globalContent.addAlarm()
self.globalContent.scheduleLocal()
//scheduleLocal()
self.checkWhetherEqual()
print(globalContent.alarmLabelArray)
}) {
Text("Save")
})
}
}
func checkWhetherEqual() {
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
print("Timer fired!")
print("1")
let now = Date()
let nowDateComponents = Calendar.current.dateComponents([.hour, .minute], from: now)
let nowDateHour = nowDateComponents.hour ?? 0
let nowDateMinute = nowDateComponents.minute ?? 0
let nowDateString = "\(nowDateHour) : \(nowDateMinute)"
print("nowDateString: \(nowDateString)")
if globalContent.alarmLabelArray.count != 0 {
if nowDateString == globalContent.alarmLabelArray[0] {
print("time is now!!!!!!!")
playAudio()
timer.invalidate()
}
}
}
}
func playAudio() {
var music: AVAudioPlayer!
let path = Bundle.main.path(forResource: "mc", ofType: "mp3")!
let url = URL(fileURLWithPath: path)
do {
print("music is here")
music = try AVAudioPlayer(contentsOf: url)
music?.play()
} catch {
// couldn't load file :(
}
}
func registerLocal() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Yay!")
} else {
print("D'oh")
}
}
}
func scheduleLocal() {
registerCategories()
let center = UNUserNotificationCenter.current()
// not required, but useful for testing!
center.removeAllPendingNotificationRequests()
let content = UNMutableNotificationContent()
content.title = "Late wake up call"
content.body = "The early bird catches the worm, but the second mouse gets the cheese."
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "fizzbuzz"]
//content.sound = UNNotificationSound(named: UNNotificationSoundName("mc.mp3"))
content.sound = UNNotificationSound.criticalSoundNamed(UNNotificationSoundName(rawValue: "MusicTest.m4a"))
//content.sound = UNNotificationSound.default
//var dateComponents = DateComponents()
let components = Calendar.current.dateComponents([.hour, .minute], from: globalContent.setDate)
let hour = components.hour ?? 0
let minute = components.minute ?? 0
//dateComponents.hour = 10
//dateComponents.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}
func registerCategories() {
let center = UNUserNotificationCenter.current()
//center.delegate = self
let show = UNNotificationAction(identifier: "show", title: "Tell me more…", options: .foreground)
let category = UNNotificationCategory(identifier: "alarm", actions: [show], intentIdentifiers: [])
center.setNotificationCategories([category])
}
}
struct AddAlarmView_Previews: PreviewProvider {
static var previews: some View {
AddAlarmView(globalContent: GlobalContent())
}
}
| true
|
81df18a322432c01d687010d562a6e3b8f964284
|
Swift
|
ozankit/iOSProjects
|
/DemoProject/EXPANDABLETABLEVIEW/DownStateButton.swift
|
UTF-8
| 1,457
| 2.78125
| 3
|
[] |
no_license
|
//
// Redio.swift
// EXPANDABLETABLEVIEW
//
// Created by LaNet on 8/3/16.
// Copyright © 2016 LaNet. All rights reserved.
//
import UIKit
class DownStateButton: UIButton {
let uncheckedImage = UIImage(named: "Unchecked-Checkbox")! as UIImage
let checkedImage = UIImage(named: "Checked-Checkbox")! as UIImage
var myAlternateButton:Array<DownStateButton>?
var downStateImage:String? = "Checked-Checkbox"
{
didSet{
if downStateImage != nil {
self.setImage(UIImage(named: downStateImage!), forState: UIControlState.Selected)
}
}
}
func unselectAlternateButtons(){
if myAlternateButton != nil {
self.selected = true
for aButton:DownStateButton in myAlternateButton! {
aButton.selected = false
}
}else{
toggleButton()
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
unselectAlternateButtons()
super.touchesBegan(touches as! Set<UITouch>, withEvent: event)
}
func toggleButton(){
if self.selected==false{
self.selected = true
}else {
self.selected = false
}
}
}
| true
|
775949684cc864adf484338d4759a8811ceda133
|
Swift
|
tyrionchiang/DrumMachine
|
/DrumMachine/SettingViewController.swift
|
UTF-8
| 2,568
| 2.515625
| 3
|
[] |
no_license
|
//
// SettingViewController.swift
// DrumMachine
//
// Created by Chiang Chuan on 2016/6/14.
// Copyright © 2016年 Chiang Chuan. All rights reserved.
//
import UIKit
class SettingViewController: UIViewController {
var soundEngine : SoundEngine?
var metronomeEngine : MetronomeEngine?
@IBOutlet var volumeSlider: [UISlider]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
syncVolumeSliderSet()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if stopPlayByRecording{
metronomeEngine?.startPlay()
stopPlayByRecording = false
}
}
func syncVolumeSliderSet(){
if let engine = soundEngine{
for slider in volumeSlider{
slider.value = engine.channelVolumes[slider.tag]
}
}
}
@IBAction func volumeSliderHasBeenChanged(_ sender: UISlider) {
if let engine = soundEngine{
engine.channelVolumes[sender.tag] = sender.value
soundEngine?.channelVolumes = engine.channelVolumes
}
}
override var prefersStatusBarHidden : Bool {
return true
}
@IBAction func unwindForSettingSegue(_ unwindSegue: UIStoryboardSegue) {
}
var stopPlayByRecording: Bool = false
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier{
switch identifier {
case "recordingController0":
(segue.destination as? RecordingViewController)?.channelNumber = 4
(segue.destination as? RecordingViewController)?.soundEngine = soundEngine
if let engine = metronomeEngine{
if engine.isPlaying(){
metronomeEngine?.stopPlay()
stopPlayByRecording = true
}
}
case "recordingController1":
(segue.destination as? RecordingViewController)?.channelNumber = 5
(segue.destination as? RecordingViewController)?.soundEngine = soundEngine
if let engine = metronomeEngine{
if engine.isPlaying(){
metronomeEngine?.stopPlay()
stopPlayByRecording = true
}
}
default:
break;
}
}
}
}
| true
|
34ae4e77a8cda2138f714e98a45542a21035a543
|
Swift
|
Summerly/Record
|
/Record/NewRecordViewController.swift
|
UTF-8
| 1,905
| 2.703125
| 3
|
[] |
no_license
|
//
// newRecordViewController.swift
// Record
//
// Created by xiyuexin on 15/11/19.
// Copyright © 2015年 xiyuexin. All rights reserved.
//
import UIKit
class NewRecordViewController: UIViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var priceTextField: UITextField!
@IBOutlet weak var numberTextField: UITextField!
@IBOutlet weak var timeDatePicker: UIDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func saveButtonPressed(sender: UIButton) {
let time = timeDatePicker.date
if nameTextField.text!.isEmpty {
self.emptyWarning("Name should not be empty")
}
if priceTextField.text!.isEmpty {
self.emptyWarning("Price should not be empty")
}
if numberTextField.text!.isEmpty {
self.emptyWarning("Number should not be empty")
}
if !nameTextField.text!.isEmpty && !priceTextField.text!.isEmpty && !numberTextField.text!.isEmpty {
let record = Record(name: nameTextField.text!, price: priceTextField.text!,
number: Int(numberTextField.text!)!, time: "\(time)")
RecordManager().saveRecord(record)
if let navigationController = self.navigationController {
navigationController.popViewControllerAnimated(true)
}
}
}
private func emptyWarning(message: String) {
let alert = UIAlertController(title: "", message: message, preferredStyle: .Alert)
let action = UIAlertAction(title: "I know", style: .Default, handler: nil)
alert.addAction(action)
presentViewController(alert, animated: true, completion: nil)
}
}
| true
|
df5a127b2635754255eceeab0e98696c0e551d2c
|
Swift
|
ChalAlex/meteo_app
|
/meteo_app/ViewControllers/Master/MainViewController.swift
|
UTF-8
| 2,633
| 2.5625
| 3
|
[] |
no_license
|
//
// MainViewController.swift
// meteo_app
//
// Created by Alexandre Jegouic on 10/12/2019.
// Copyright © 2019 Alexandre Jegouic. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
private var interactor: MainInteractor = DefaultMainInteractor()
fileprivate var model: MainViewModel = MainViewModel.initialized
/// Use to pass identifier of clicked cell
private var dataId: String = ""
@IBOutlet fileprivate var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
updateView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
interactor.start(delegate: self)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
interactor.stop()
}
public func updateView() {
self.title = model.title
tableView.reloadData()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let controller = segue.destination as? DetailViewController else { return }
controller.setWeatherDataId(self.dataId)
}
}
extension MainViewController: MainDelegate {
func update(_ model: MainViewModel) {
self.model = model
updateView()
}
func launchSegue(_ identifier: String, dataId: String) {
self.dataId = dataId
self.performSegue(withIdentifier: identifier, sender: self)
}
func showAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Retry", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
extension MainViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.cells.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for: indexPath)
cell.textLabel?.text = model.cells[indexPath.row].title
cell.detailTextLabel?.text = model.cells[indexPath.row].subtitle
return cell
}
}
extension MainViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
interactor.rowSelected(at: indexPath.row)
}
}
| true
|
e2a03a760e6ec5e2b0b560471af47a1c0eb39d8c
|
Swift
|
arbel91/Clendar
|
/ClendarWidget/Widget/Date Info/DateInfoWidget.swift
|
UTF-8
| 1,146
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// DateInfoWidget.swift
// DateInfoWidget
//
// Created by Vinh Nguyen on 10/31/20.
// Copyright © 2020 Vinh Nguyen. All rights reserved.
//
import SwiftUI
import WidgetKit
/*
Reference
+ https://developer.apple.com/design/human-interface-guidelines/ios/system-capabilities/widgets
+ https://developer.apple.com/documentation/widgetkit/creating-a-widget-extension
+ https://wwdcbysundell.com/2020/getting-started-with-widgetkit/
+ https://github.com/pawello2222/WidgetExamples
*/
struct DateInfoWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(
kind: Constants.WidgetKind.dateInfoWidget.rawValue,
provider: DateInfoWidgetTimelineProvider()) { entry in
DateInfoWidgetEntryView(entry: entry)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(WidgetBackgroundView())
}
.configurationDisplayName(NSLocalizedString("Date Info Widget", comment: ""))
.description(NSLocalizedString("Check calendar at a glance", comment: ""))
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}
| true
|
ef027eb358e2f8e020a93f73aa861bbcf7a23394
|
Swift
|
JiachenRen/Kelvin
|
/Kelvin/System/Syntax/Tokenizer.swift
|
UTF-8
| 902
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
//
// Tokenizer.swift
// Kelvin
//
// Created by Jiachen Ren on 10/1/19.
// Copyright © 2019 Jiachen Ren. All rights reserved.
//
import Foundation
public typealias Token = Character
public class Tokenizer {
/// A unicode scalar value that would never interfere with input
/// In this case, the scalar value (and the ones after)
/// does not have any unicode counterparts
private static var scalar = 60000
/// Reset the scalar
fileprivate static func reset() {
scalar = 60000
}
/// Generate next available encoding from a unique scalar.
public static func next() -> Token {
// Assign a unique code to the operation consisting of
// an unused unicode
let encoding = Character(UnicodeScalar(scalar)!)
// Increment the scalar so that each operator is unique.
scalar += 1
return encoding
}
}
| true
|
748fab7840c9ba8f54c0f90b5e36c60ed19ad514
|
Swift
|
kwdx/LeetCode-Practise
|
/Swift/707.设计链表.swift
|
UTF-8
| 3,350
| 3.71875
| 4
|
[] |
no_license
|
/*
* @lc app=leetcode.cn id=707 lang=swift
*
* [707] 设计链表
*/
// @lc code=start
class MyLinkedList {
private class Node {
let value: Int
var prev: Node?
var next: Node?
init(value: Int, prev: Node? = nil, next: Node? = nil) {
self.value = value
self.prev = prev
self.next = next
}
}
private var size = 0
private var head = Node(value: 0)
private var tail = Node(value: 0)
init() {
head.next = tail
tail.prev = head
}
func get(_ index: Int) -> Int {
guard (0..<size).contains(index) else { return -1 }
var node: Node?
if index + 1 < size - index {
node = head;
for _ in 0...index {
node = node?.next
}
} else {
node = tail
for _ in 0..<(size - index) {
node = node?.prev
}
}
return node?.value ?? -1
}
func addAtHead(_ val: Int) {
addAtIndex(0, val)
}
func addAtTail(_ val: Int) {
addAtIndex(size, val)
}
func addAtIndex(_ index: Int, _ val: Int) {
guard index <= size else { return }
if (index > size) {
return;
}
var index = max(0, index)
var prev: Node?
var succ: Node?
if index < size - index {
prev = head
for _ in 0..<index {
prev = prev?.next
}
succ = prev?.next
} else {
succ = tail
for _ in 0..<(size - index) {
succ = succ?.prev
}
prev = succ?.prev
}
size += 1
let node = Node(value: val)
node.prev = prev;
node.next = succ
prev?.next = node
succ?.prev = node
}
func deleteAtIndex(_ index: Int) {
guard (0..<size).contains(index) else { return }
var prev: Node?
var succ: Node?
if index < size - index {
prev = head
for _ in 0..<index {
prev = prev?.next
}
succ = prev?.next?.next
} else {
succ = tail
for _ in 0..<(size - index - 1) {
succ = succ?.prev
}
prev = succ?.prev?.prev
}
size -= 1
prev?.next = succ
succ?.prev = prev
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* let obj = MyLinkedList()
* let ret_1: Int = obj.get(index)
* obj.addAtHead(val)
* obj.addAtTail(val)
* obj.addAtIndex(index, val)
* obj.deleteAtIndex(index)
*/
// @lc code=end
func main() {
/**
MyLinkedList linkedList = new MyLinkedList();
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1,2); //链表变为1-> 2-> 3
linkedList.get(1); //返回2
linkedList.deleteAtIndex(1); //现在链表是1-> 3
linkedList.get(1); //返回3
*/
let linkedList = MyLinkedList()
linkedList.addAtHead(1)
linkedList.addAtTail(3)
linkedList.addAtIndex(1, 2)
assert(2 == linkedList.get(1))
linkedList.deleteAtIndex(1)
assert(3 == linkedList.get(1))
}
| true
|
6eee32089901ba3b02d14024a120dfa6ee684706
|
Swift
|
Yrocky/LearnSwiftUI
|
/DoSwiftUI/DoSwiftUI/Helper/Tree/TreeNode.swift
|
UTF-8
| 298
| 2.671875
| 3
|
[] |
no_license
|
//
// TreeNode.swift
// DoSwiftUI
//
// Created by rocky on 2021/1/21.
//
import Foundation
struct TreeNode<A> {
var value: A
var children: [TreeNode<A>] = []
init(_ value: A, children: [TreeNode<A>] = []) {
self.value = value
self.children = children
}
}
| true
|
5be11898d43ede81728d86cd0675ff8eaf5d1b5e
|
Swift
|
JJamiie/Jibjib-IOSApplication
|
/Jibjib/Jibjib/PaddingLabel.swift
|
UTF-8
| 885
| 2.796875
| 3
|
[] |
no_license
|
//
// PaddingLabel.swift
// Jibjib
//
// Created by JJamie Rashata on 5/14/2559 BE.
// Copyright © 2559 Chulalongkorn University. All rights reserved.
//
import UIKit
class PaddingLabel: UILabel {
let topInset = CGFloat(15.0), bottomInset = CGFloat(15.0), leftInset = CGFloat(20.0), rightInset = CGFloat(20.0)
override func drawTextInRect(rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
intrinsicSuperViewContentSize.height += topInset + bottomInset
intrinsicSuperViewContentSize.width += leftInset + rightInset
return intrinsicSuperViewContentSize
}
}
| true
|
8bcbe65472fa9f504f5b0a5e04da7b0298327fc6
|
Swift
|
mike-politowicz/SampleCode
|
/SampleCode/ContactService.swift
|
UTF-8
| 2,361
| 2.953125
| 3
|
[] |
no_license
|
import Contacts
class ContactService {
static func requestContactPermission(completionHandler: @escaping (Bool) -> ()) {
let contactStore = CNContactStore()
contactStore.requestAccess(for: .contacts) { (isGranted, error) in
if let error = error {
print("ERROR: \(error.localizedDescription)")
}
completionHandler(isGranted)
}
}
static func localContactsWithEmailOrPhone() -> [Contact] {
let contactStore = CNContactStore()
let keysToFetch = [
CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactEmailAddressesKey,
CNContactPhoneNumbersKey] as! [CNKeyDescriptor]
var allContainers: [CNContainer] = []
do {
allContainers = try contactStore.containers(matching: nil)
} catch {
print("Error fetching containers")
}
var results: [Contact] = []
for container in allContainers {
let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier)
do {
let containerResults = try contactStore.unifiedContacts(matching: fetchPredicate,
keysToFetch: keysToFetch)
containerResults.forEach({ (contact) -> Void in
guard (contact.emailAddresses.count > 0) || (contact.phoneNumbers.count > 0) else {
return
}
let newContact = Contact(firstName: contact.givenName,
lastName: contact.familyName,
fullName: CNContactFormatter.string(from: contact, style: .fullName) ??
contact.givenName + " " + contact.familyName,
emailAddress: contact.emailAddresses.first?.value as String?,
phoneNumber: contact.phoneNumbers.first?.value.stringValue as String?)
results.append(newContact)
})
} catch {
print("Error fetching results for container")
}
}
return results
}
}
| true
|
b9c132bcd80c98ebf523af8a7a4695142a93c467
|
Swift
|
Beaver/BeaverSample
|
/Module/Core/Core/MovieCardState.swift
|
UTF-8
| 1,201
| 3.359375
| 3
|
[] |
no_license
|
import Beaver
public struct MovieCardState: Beaver.State {
public var error: String?
public var currentScreen: CurrentScreen = .none
public var title: String? {
switch currentScreen {
case .main(_, let title):
return title.uppercased()
default:
return nil
}
}
public init() {
}
}
extension MovieCardState {
/// Represents the currently shown screen
public enum CurrentScreen {
case none
case main(id: Int, title: String)
}
}
extension MovieCardState {
public static func ==(lhs: MovieCardState, rhs: MovieCardState) -> Bool {
return lhs.error == rhs.error &&
lhs.currentScreen == rhs.currentScreen
}
}
extension MovieCardState.CurrentScreen: Equatable {
public static func ==(lhs: MovieCardState.CurrentScreen, rhs: MovieCardState.CurrentScreen) -> Bool {
switch (lhs, rhs) {
case (.none, .none):
return true
case (.main(let leftId, let leftTitle), .main(let rightId, let rightTitle)):
return leftId == rightId && leftTitle == rightTitle
default:
return false
}
}
}
| true
|
9a53c4c90f3b3c6a6dc8df8cef0cb94bfd592d43
|
Swift
|
cresouls/source_code_swift
|
/Extension/UIScrollView+ScrollToView.swift
|
UTF-8
| 937
| 2.625
| 3
|
[] |
no_license
|
//
// UIScrollView+ScrollToView.swift
// JoboyService
//
// Created by Sreejith Ajithkumar on 09/07/19.
// Copyright © 2019 Sreejith Ajithkumar. All rights reserved.
//
import UIKit
extension UIScrollView {
func scrollToView(view:UIView, animated: Bool) {
if let origin = view.superview {
let childStartPoint = origin.convert(view.frame.origin, to: self)
self.scrollRectToVisible(CGRect(x: childStartPoint.x, y: 0, width: view.frame.width, height: view.frame.height), animated: animated)
}
}
func scrollToTop(animated: Bool) {
let topOffset = CGPoint(x: 0, y: -contentInset.top)
setContentOffset(topOffset, animated: animated)
}
func scrollToBottom() {
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom)
if(bottomOffset.y > 0) {
setContentOffset(bottomOffset, animated: true)
}
}
}
| true
|
046a2f3357ac356a3edbbd1cc50f280a23733981
|
Swift
|
oseval/datahub_swift
|
/Classes/Data.swift
|
UTF-8
| 2,301
| 2.75
| 3
|
[] |
no_license
|
protocol DHDataGen {
var genClock: Any { get }
}
protocol DHData: DHDataGen {
associatedtype D
associatedtype C
var data: D { get }
var clock: C { get }
}
extension DHData {
var genClock: Any { get { return self.clock } }
}
protocol DHAtLeastOnceDataGen {
var genPreviousClock: Any { get }
var isSolid: Bool { get }
}
protocol DHAtLeastOnceData: DHData {
var previousClock: C { get }
}
extension DHAtLeastOnceData {
var genPreviousClock: Any { get { return self.previousClock } }
var isSolid: Bool { get { return true } }
}
protocol DHDataOpsGen {
var kind: String { get }
var genGt: (Any, Any) -> Bool { get }
var genZero: DHDataGen { get }
}
extension DHDataOpsGen {
func liftEntity<EG: DHEntityGen, D: DHData>(_ entityGen: EG, _ data: D) -> D? {
return type(of: data) == type(of: self.genZero) ? data : nil
}
}
protocol DHDataOps: DHDataOpsGen {
associatedtype Dt: DHData
var gt: (Dt.C, Dt.C) -> Bool { get }
var zero: Dt { get }
func combine(_ a: Dt, _ b: Dt) -> Dt
func diffFromClock(_ a: Dt, _ from: Dt.C) -> Dt
func nextClock(_ current: Dt.C) -> Dt.C
func getRelations(_ data: Dt) -> (Set<DHEntityGenH>, Set<DHEntityGenH>)
// var matchData: (DHDataGen) -> Dt?
}
extension DHDataOps {
var genGt: (Any, Any) -> Bool { get { return {
let a = $0 as! Self.Dt.C
let b = $1 as! Self.Dt.C
return self.gt(a, b)
} } }
var genZero: DHDataGen { get { return self.zero } }
var zero: Dt { get { return self.zero } }
func combine(_ a: Self.Dt, _ b: Self.Dt) -> Self.Dt {
return gt(a.clock, b.clock) ? a : b
}
func diffFromClock(_ a: Dt, _ from: Self.Dt.C) -> Self.Dt {
return gt(a.clock, from) ? a : self.zero
}
func getRelations(_ data: Self.Dt) -> (Set<DHEntityGenH>, Set<DHEntityGenH>) {
return (Set(), Set())
}
}
struct M : DHAtLeastOnceData {
typealias C = Int
typealias D = String
let data: String
let clock: Int
let previousClock: Int
let isSolid: Bool = true
}
struct ClockInt<C> {
let cur: C
let start: C
}
// ai alo eff
//
//a + prevId
//
//c + + + order
//
//i + + + id
| true
|
2631d5787c12990b22204b12f74d8e3b852bbaa5
|
Swift
|
ahershailesh/FindIt
|
/FindIt/PreviewImageViewController.swift
|
UTF-8
| 2,036
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// PreviewImageControllerViewController.swift
// FindIt
//
// Created by Shailesh Aher on 3/6/18.
// Copyright © 2018 Shailesh Aher. All rights reserved.
//
import UIKit
protocol PreviewImageProtocol {
func imageLikeButtonTapped(model: PreviewModel, selection: Bool)
func imageShared(model: PreviewModel)
}
class PreviewImageViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var notifier : PreviewImageProtocol?
var model : PreviewModel?
var selection : Bool = false {
didSet {
setupToolBar()
}
}
convenience init() {
self.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
setupToolBar()
imageView.image = model?.image
}
private func setupToolBar() {
navigationController?.setToolbarHidden(false, animated: true)
let imageName = selection ? "ic_check_circle_white_36pt" : "ic_check_white_36pt"
let likeButton = UIBarButtonItem(image: UIImage(named: imageName), style: .plain, target: self, action: #selector(likeButtonTapped))
let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let share = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareButtonTapped))
setToolbarItems([likeButton, spacer, share], animated: true)
}
@objc func likeButtonTapped() {
selection = !selection
notifier?.imageLikeButtonTapped(model: model!, selection: selection)
}
@objc func shareButtonTapped() {
let activityController = UIActivityViewController(activityItems: [model?.image!], applicationActivities: nil)
activityController.completionWithItemsHandler = { [weak self] (_,completed,_, _) in
if completed {
self?.notifier?.imageShared(model: self!.model!)
}
}
present(activityController, animated: true, completion: nil)
}
}
| true
|
3298ec5d2bfb74b89058965f47a6aa5d2a2c704a
|
Swift
|
huyunf/PriceCalc
|
/PriceCaculator/ViewController.swift
|
UTF-8
| 7,257
| 2.546875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// PriceCaculator
//
// Created by Yunfeng Hu on 3/13/16.
// Copyright © 2016 Yunfeng Hu. All rights reserved.
//
import UIKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l <= r
default:
return !(rhs < lhs)
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class ViewController: UIViewController {
// text
@IBOutlet weak var originalPriceText: UITextField!
@IBOutlet weak var discountText: UITextField!
@IBOutlet weak var taxText: UITextField!
@IBOutlet weak var purchaseFeeText: UITextField!
@IBOutlet weak var weightText: UITextField!
@IBOutlet weak var shippingFeeText: UITextField!
@IBOutlet weak var shippingFeeTotalText: UITextField!
@IBOutlet weak var exchangeRateText: UITextField!
@IBOutlet weak var packagePriceText: UITextField!
// label
@IBOutlet weak var atpDollarLable: UILabel!
@IBOutlet weak var qpDollarLable: UILabel!
@IBOutlet weak var profitDollarLable: UILabel!
//@IBOutlet weak var atpRMBLable: UILabel!
@IBOutlet weak var qpRMBLable: UILabel!
@IBOutlet weak var profitRMBLable: UILabel!
@IBOutlet weak var InsuranceDollarLable: UILabel!
@IBOutlet weak var InsuranceRMBLable: UILabel!
@IBOutlet weak var messageLable: UILabel!
// deal with keyboard when enter number
@IBAction func CloseKeyBoard(_ sender: AnyObject) {
originalPriceText.resignFirstResponder()
discountText.resignFirstResponder()
taxText.resignFirstResponder()
purchaseFeeText.resignFirstResponder()
weightText.resignFirstResponder()
shippingFeeText.resignFirstResponder()
shippingFeeTotalText.resignFirstResponder()
exchangeRateText.resignFirstResponder()
packagePriceText.resignFirstResponder()
}
@IBAction func keyBoardDone(_ sender: UITextField) {
originalPriceText.resignFirstResponder()
discountText.resignFirstResponder()
taxText.resignFirstResponder()
purchaseFeeText.resignFirstResponder()
weightText.resignFirstResponder()
shippingFeeText.resignFirstResponder()
shippingFeeTotalText.resignFirstResponder()
exchangeRateText.resignFirstResponder()
packagePriceText.resignFirstResponder()
}
// calculate button
@IBAction func calculateButton(_ sender: UIButton) {
var originalPrice: Float!
var discount: Float!
var tax: Float!
var purchaseFee: Float!
var weight: Float!
var unitShippingFee: Float!
var ShippingFee: Float!
var exchangeRate: Float!
var PackagePrice: Float!
var afterTaxPrice: Float!
var InsuranceFeeDollar: Float!
var InsuranceFeeRMB: Float!
var quotePriceDollar: Float!
var profitDollar: Float!
var quotePriceRMB: Float!
var profitRMB: Float!
if(Float(originalPriceText.text!)<=0){
messageLable.text = "Enter Correct Price!"
return
}else if(Float(discountText.text!)<0 || Float(discountText.text!)>100){
messageLable.text = "Enter Correct Discount!"
return
}else if(Float(taxText.text!)<0 || Float(taxText.text!)>100){
messageLable.text = "Enter Correct Tax Rate!"
return
}else if(Float(purchaseFeeText.text!)<0 || Float(purchaseFeeText.text!)>100){
messageLable.text = "Enter Correct Purchase Rate!"
return
}else if(Float(weightText.text!)==0){
messageLable.text = "Enter Correct Weight!"
return
}else if(Float(shippingFeeText.text!)<0){
messageLable.text = "Enter Correct Unit Shipping Fee ($/lb)!"
return
}else if(Float(exchangeRateText.text!)<=0){
messageLable.text = "Enter Correct Exchange Rate!"
return
}else if(Float(packagePriceText.text!)<0){
messageLable.text = "Enter Correct Package price!"
return
}else{
messageLable.text = "Message: "
originalPrice = Float(originalPriceText.text!)
}
//print("original price = \(originalPrice)")
originalPrice = Float(originalPriceText.text!)
discount = Float(discountText.text!)
tax = Float(taxText.text!)
purchaseFee = Float(purchaseFeeText.text!)
weight = Float(weightText.text!)
unitShippingFee = Float(shippingFeeText.text!)
exchangeRate = Float(exchangeRateText.text!)
PackagePrice = Float(packagePriceText.text!)
print("originalPrice=\(originalPrice), discout=\(discount), tax=\(tax), purchaseFee=\(purchaseFee), weithg=\(weight), unitShippingFee=\(unitShippingFee), exchangeRate=\(exchangeRateText), PackagePrice=\(PackagePrice)")
afterTaxPrice = (originalPrice*(100-discount)/100)*(1+tax/100)
atpDollarLable.text = String(afterTaxPrice)
InsuranceFeeDollar = afterTaxPrice*0.03
InsuranceDollarLable.text = String(InsuranceFeeDollar)
InsuranceFeeRMB = InsuranceFeeDollar * exchangeRate
InsuranceRMBLable.text = String(InsuranceFeeRMB)
profitDollar = afterTaxPrice * purchaseFee/100
profitDollarLable.text = String(profitDollar)
profitRMB = profitDollar*exchangeRate
profitRMBLable.text = String(profitRMB)
ShippingFee = weight * unitShippingFee
shippingFeeTotalText.text = String(ShippingFee)
quotePriceDollar = afterTaxPrice*(1+purchaseFee/100) + ShippingFee + PackagePrice + InsuranceFeeDollar
qpDollarLable.text = String(quotePriceDollar)
quotePriceRMB = quotePriceDollar * exchangeRate
qpRMBLable.text = String(quotePriceRMB)
}
@IBAction func resetButton(_ sender: UIButton) {
atpDollarLable.text = String(0.0)
profitDollarLable.text = String(0.0)
profitRMBLable.text = String(0.0)
shippingFeeTotalText.text = String(0.0)
qpDollarLable.text = String(0.0)
qpRMBLable.text = String(0.0)
InsuranceDollarLable.text = String(0.0)
InsuranceRMBLable.text = String(0.0)
originalPriceText.text = String(0.0)
}
}
| true
|
c579aeb95e1e80efeb84416b3df9274622e4a26c
|
Swift
|
cwoloszynski/etcetera
|
/Sources/Etcetera/ImageCache.swift
|
UTF-8
| 49,145
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
//
// ImageCache.swift
// Etcetera
//
// Copyright © 2018 Nice Boy LLC. All rights reserved.
//
#if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
/// An image cache that balances high-performance features with straightforward
/// usage and sensible defaults.
///
/// - Note: This file is embarassingly long, but it's purposeful. Each file in
/// Etcetera is meant to be self-contained, ready to be dropped into your
/// project all by itself. That's also why this file has some duplicated bits of
/// utility code found elsewhere in Etcetera.
///
/// - Warning: This class currently only supports iOS. I have vague plans to
/// have it support macOS and watchOS, too, but that's not guaranteed.
public class ImageCache {
// MARK: Shared Instance
/// The shared instance. You're not obligated to use this.
public static let shared = ImageCache()
// MARK: Public Properties
/// The default directory where ImageCache stores files on disk.
public static var defaultDirectory: URL {
return FileManager.default.caches.subdirectory(named: "Images")
}
/// Disk storage will be automatically trimmed to this byte limit (by
/// trimming the least-recently accessed items first). Trimming will occur
/// whenever the app enters the background.
public var byteLimitForFileStorage: Bytes = .fromMegabytes(500) {
didSet { trimStaleFiles() }
}
/// Your app can provide something stronger than "\(url.hashValue)" if you
/// will encounter images with very long file URLs that could collide with
/// one another. The value returned from this function is used to form the
/// filename for cached images (since URLs could be longer than the max
/// allowed file name length). Letting your app inject this functionality
/// eliminates an awkward dependency on a stronger hashing algorithm.
public var uniqueFilenameFromUrl: (URL) -> String
/// When `true` this will empty the in-memory cache when the app enters the
/// background. This can help reduce the likelihood that your app will be
/// terminated in order to reclaim memory for foregrounded applications.
/// Defaults to `false`.
public var shouldRemoveAllImagesFromMemoryWhenAppEntersBackground: Bool {
get { return memoryCache.shouldRemoveAllObjectsWhenAppEntersBackground }
set { memoryCache.shouldRemoveAllObjectsWhenAppEntersBackground = newValue }
}
// MARK: Private Properties
private let directory: URL
private let urlSession: URLSession
private let formattingTaskRegistry = TaskRegistry<ImageKey, Image?>()
private let downloadTaskRegistry = TaskRegistry<URL, DownloadResult?>()
private let memoryCache = MemoryCache<ImageKey, Image>()
private let formattingQueue: OperationQueue
private let workQueue: OperationQueue
private var observers = [NSObjectProtocol]()
// MARK: Init / Deinit
/// Designated initializer.
///
/// - parameter directory: The desired directory. This must not be a system-
/// managed directory (like /Caches), but it can be a subdirectory thereof.
public init(directory: URL = ImageCache.defaultDirectory) {
self.uniqueFilenameFromUrl = { return "\($0.hashValue)" }
self.directory = directory
self.urlSession = {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 15
config.timeoutIntervalForResource = 90
return URLSession(configuration: config)
}()
self.formattingQueue = {
let q = OperationQueue()
q.qualityOfService = .userInitiated
return q
}()
self.workQueue = {
let q = OperationQueue()
q.qualityOfService = .userInitiated
return q
}()
FileManager.default.createDirectory(at: directory)
registerObservers()
}
deinit {
observers.forEach {
NotificationCenter.default.removeObserver($0)
}
}
// MARK: Public Methods
/// Retrieves an image from the specified URL, formatted to the requested
/// format.
///
/// If the formatted image already exists in memory, it will be returned
/// synchronously. If not, ImageCache will look for the cached formatted
/// image on disk. If that is not found, ImageCache will look for the cached
/// original image on disk, format it, save the formatted image to disk, and
/// return the formatted image. If all of the above turn up empty, the
/// original file will be downloaded from the url and saved to disk, then
/// the formatted image will be generated and saved to disk, then the
/// formatted image will be cached in memory, and then finally the formatted
/// image will be returned to the caller via the completion handler. If any
/// of the above steps fail, the completion block will be called with `nil`.
///
/// Concurrent requests for the same resource are combined into the smallest
/// possible number of active tasks. Requests for different image formats
/// based on the same original image will lead to a single download task for
/// the original file. Requests for the same image format will lead to a
/// single image formatting task. The same result is distributed to all
/// requests in the order in which they were requested.
///
/// - parameter url: The HTTP URL at which the original image is found.
///
/// - parameter format: The desired image format for the completion result.
///
/// - parameter completion: A completion handler called when the image is
/// available in the desired format, or if the request failed. The
/// completion handler will always be performed on the main queue.
///
/// - returns: A callback mode indicating whether the completion handler was
/// executed synchronously before the return, or will be executed
/// asynchronously at some point in the future. When asynchronous, the
/// cancellation block associated value of the `.async` mode can be used to
/// cancel the request for this image. Cancelling a request will not cancel
/// any other in-flight requests. If the cancelled request was the only
/// remaining request awaiting the result of a downloading or formatting
/// task, then the unneeded task will be cancelled and any in-progress work
/// will be abandoned.
@discardableResult
public func image(from url: URL, format: Format = .original, completion: @escaping (Image?) -> Void) -> CallbackMode {
#if os(iOS)
let task = _BackgroundTask.start()
let completion: (Image?) -> Void = {
completion($0)
task?.end()
}
#endif
let key = ImageKey(url: url, format: format)
if let image = memoryCache[key] {
completion(image)
return .sync
}
// Use a deferred value for `formattingRequestId` so that we can capture
// a future reference to the formatting request ID. This will allow us
// to cancel the request whether it's in the downloading or formatting
// step at the time the user executes the cancellation block. The same
// approach applies to the download request.
let formattingRequestId = DeferredValue<UUID>()
let downloadRequestId = DeferredValue<UUID>()
checkForFormattedImage(from: url, key: key) { [weak self] cachedImage in
guard let this = self else { completion(nil); return }
if let image = cachedImage {
this.memoryCache[key] = image
completion(image)
} else {
downloadRequestId.value = this.downloadFile(from: url) { [weak this] downloadResult in
guard let this = this else { completion(nil); return }
guard let downloadResult = downloadResult else { completion(nil); return }
// `this.formatImage` is asynchronous, but returns a request ID
// synchronously which can be used to cancel the formatting request.
formattingRequestId.value = this.formatImage(
key: key,
result: downloadResult,
format: format,
completion: completion
)
}
}
}
return .async(cancellation: { [weak self] in
#if os(iOS)
defer { task?.end() }
#endif
guard let this = self else { return }
if let id = formattingRequestId.value {
this.formattingTaskRegistry.cancelRequest(withId: id)
}
if let id = downloadRequestId.value {
this.downloadTaskRegistry.cancelRequest(withId: id)
}
})
}
/// Removes all the cached images from the in-memory cache only. Files on
/// disk will not be removed.
public func removeAllImagesFromMemory() {
memoryCache.removeAll()
}
/// Removes and recreates the directory containing all cached image files.
/// Images cached in-memory will not be removed.
public func removeAllFilesFromDisk() {
_ = try? FileManager.default.removeItem(at: directory)
FileManager.default.createDirectory(at: directory)
}
/// Convenience function for storing user-provided images in memory.
///
/// - parameter image: The image to be added. ImageCache will not apply any
/// formatting to this image.
///
/// - parameter key: A developer-provided key uniquely identifying this image.
public func add(userProvidedImage image: Image, toInMemoryCacheUsingKey key: String) {
guard let actualKey = self.actualKey(forUserProvidedKey: key) else { return }
memoryCache[actualKey] = image
}
/// Convenience function for retrieving user-provided images in memory.
///
/// - parameter key: The developer-provided key used when adding the image.
///
/// - returns: Returns the image, if found in the in-memory cache, else it
/// will return `nil`.
public func userProvidedImage(forKey key: String) -> Image? {
guard let actualKey = self.actualKey(forUserProvidedKey: key) else { return nil }
return memoryCache[actualKey]
}
// MARK: Private Methods
/// Returns the underlying ImageKey used for a user-provided key.
private func actualKey(forUserProvidedKey key: String) -> ImageKey? {
guard let encoded = key.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { return nil}
guard let url = URL(string: "imagecache://\(encoded)") else { return nil}
return ImageKey(url: url, format: .original)
}
/// Adds a request for formatting a downloaded image. If this request is the
/// first for this format, it will create a task for that format. Otherwise
/// it will be appended to the existing task. Upon completion of the task,
/// the formatted image will be inserted into the in-memory cache.
///
/// If an image in the requested format already exists on disk, then the
/// the request(s) will be fulfilled with that existing image.
///
/// - parameter key: The key to use when caching the image.
///
/// - parameter result: The result of a previous download phase. Contains
/// either a previously-downloaded image, a local URL to a freshly-
/// downloaded image file.
///
/// - parameter format: The requested image format.
///
/// - parameter completion: A block performed on the main queue when the
/// requested is fulfilled, or when the underlying task fails for one reason
/// or another.
///
/// - returns: Returns an ID for the request. This ID can be used to later
/// cancel the request if needed.
private func formatImage(key: ImageKey, result: DownloadResult, format: Format, completion: @escaping (Image?) -> Void) -> UUID {
return formattingTaskRegistry.addRequest(
taskId: key,
workQueue: workQueue,
taskExecution: { [weak self] finish in
guard let this = self else { finish(nil); return }
let destination = this.fileUrl(forFormattedImageWithKey: key)
if let image = FileManager.default.image(fromFileAt: destination) {
finish(image)
} else {
this.formattingQueue.addOperation {
let image = format.image(from: result)
if let image = image {
FileManager.default.save(image, to: destination)
}
finish(image)
}
}
},
taskCancellation: { [weak self] in
self?.formattingQueue.cancelAllOperations()
},
taskCompletion: { [weak self] result in
result.map{ self?.memoryCache[key] = $0 }
},
requestCompletion: completion
)
}
/// Adds a request for downloading an image.
///
/// If the original image is found already on disk, then the image will be
/// instantiated from the data on disk. Otherwise, the image will be
/// downloaded and moved to the expected location on disk, and the resulting
/// file URL will be returned to the caller via the completion block.
///
/// - parameter url: The HTTP URL at which the original image is found.
///
/// - parameter completion: A block performed on the main queue when the
/// image file is found, or if the request fails.
///
/// - returns: Returns an ID for the request. This ID can be used to later
/// cancel the request if needed.
private func downloadFile(from url: URL, completion: @escaping (DownloadResult?) -> Void) -> UUID {
let destination = fileUrl(forOriginalImageFrom: url)
let taskValue = DeferredValue<URLSessionDownloadTask>()
return downloadTaskRegistry.addRequest(
taskId: url,
workQueue: workQueue,
taskExecution: { finish in
if FileManager.default.fileExists(at: destination), let image = Image.fromFile(at: destination) {
finish(.previous(image))
} else {
taskValue.value = self.urlSession.downloadTask(with: url) { (temp, _, _) in
if let temp = temp, FileManager.default.moveFile(from: temp, to: destination) {
finish(.fresh(destination))
} else {
finish(nil)
}
}
taskValue.value?.resume()
}
},
taskCancellation: { taskValue.value?.cancel() },
taskCompletion: { _ in },
requestCompletion: completion
)
}
/// Checks if an existing image of a given format already exists on disk.
///
/// - parameter url: The HTTP URL at which the original image is found.
///
/// - parameter key: The key used when caching the formatted image.
///
/// - parameter completion: A block performed with the result, called upon
/// the main queue. If found, the image is decompressed on a background
/// queue to avoid doing so on the main queue.
private func checkForFormattedImage(from url: URL, key: ImageKey, completion: @escaping (Image?) -> Void) {
deferred(on: workQueue) {
let image: Image? = {
let destination = self.fileUrl(forFormattedImageWithKey: key)
guard let data = try? Data(contentsOf: destination) else { return nil }
guard let image = Image(data: data) else { return nil }
return ImageDrawing.decompress(image)
}()
onMain {
completion(image)
}
}
}
private func fileUrl(forOriginalImageFrom url: URL) -> URL {
let filename = uniqueFilenameFromUrl(url)
return directory.appendingPathComponent(filename, isDirectory: false)
}
private func fileUrl(forFormattedImageWithKey key: ImageKey) -> URL {
let filename = uniqueFilenameFromUrl(key.url) + key.filenameSuffix
return directory.appendingPathComponent(filename, isDirectory: false)
}
private func registerObservers() {
#if os(iOS)
observers.append(NotificationCenter.default.addObserver(
forName: UIApplication.didEnterBackgroundNotification,
object: nil,
queue: .main,
using: { [weak self] _ in
self?.trimStaleFiles()
}))
#endif
}
private func trimStaleFiles() {
#if os(iOS)
let task = _BackgroundTask.start()
#endif
DispatchQueue.global().async {
FileManager.default.removeFilesByDate(
inDirectory: self.directory,
untilWithinByteLimit: self.byteLimitForFileStorage
)
#if os(iOS)
task?.end()
#endif
}
}
}
//------------------------------------------------------------------------------
// MARK: - Typealiases
//------------------------------------------------------------------------------
extension ImageCache {
// MARK: Typealiases (All)
public typealias Bytes = UInt
// MARK: Typealiases (iOS)
#if os(iOS)
public typealias Image = UIImage
public typealias Color = UIColor
#endif
// MARK: Typealiases (macOS)
#if os(OSX)
public typealias Image = NSImage
public typealias Color = NSColor
#endif
}
private typealias Image = ImageCache.Image
private typealias Color = ImageCache.Color
//------------------------------------------------------------------------------
// MARK: - Bytes (Convenience)
//------------------------------------------------------------------------------
extension ImageCache.Bytes {
public static func fromMegabytes(_ number: UInt) -> UInt {
return number * 1_000_000
}
}
//------------------------------------------------------------------------------
// MARK: - CallbackMode
//------------------------------------------------------------------------------
extension ImageCache {
/// The manner in which a completion handler is (or will be) executed.
///
/// Indicates whether a completion handler was executed synchronously before
/// the return, or will be executed asynchronously at some point in the
/// future. When asynchronous, the cancellation block associated value of
/// the `.async` mode can be used to cancel the pending request.
public enum CallbackMode {
/// The completion handler was performed synchronously, before the
/// method returned.
case sync
/// The completion handler will be performed asynchronously, sometime
/// after the method returned.
///
/// - parameter cancellation: A block which the caller can use to cancel
/// the in-flight request.
case async(cancellation: () -> Void)
}
}
//------------------------------------------------------------------------------
// MARK: - Format
//------------------------------------------------------------------------------
extension ImageCache {
/// Describes the format options to be used when processing a source image.
public enum Format: Hashable {
// MARK: Typealiases
/// Use `0` to default to the system-determined default.
public typealias ContentScale = CGFloat
// MARK: Formats
/// Do not modify the source image in any way.
case original
/// Scale the source image, with a variety of options.
///
/// - parameter size: The desired output size, in points.
///
/// - parameter mode: The manner in which the image will be scaled
/// relative to the desired output size.
///
/// - parameter bleed: The number of points, relative to `size`, that
/// the image should be scaled beyond the desired output size.
/// Generally, you should provide a value of `0` since this isn't a
/// commonly-used feature. However, you might want to use a value larger
/// than `0` if the source image has known artifacts (like, say, a one-
/// pixel border around some podcast artwork) which can be corrected by
/// drawing the image slightly larger than the output size, thus
/// cropping the border from the result.
///
/// - parameter opaque: If `false`, opacity in the source image will be
/// preserved. If `true`, any opacity in the source image will be
/// blended into the default (black) bitmap content.
///
/// - parameter cornerRadius: If this value is greater than `0`, the
/// image will be drawn with the corners rounded by an equivalent number
/// of points (relative to `size`). A value of `0` or less will disable
/// this feature.
///
/// - parameter border: If non-nil, the resulting image will include the
/// requested border drawn around the perimeter of the image.
///
/// - parameter contentScale: The number of pixels per point, which is
/// used to reckon the output image size relative to the requested
/// `size`. Pass `0` to use the native defaults for the current device.
case scaled(size: CGSize, mode: ContentMode, bleed: CGFloat, opaque: Bool, cornerRadius: CGFloat, border: Border?, contentScale: ContentScale)
/// Scale the source image and crop it to an elliptical shape. The
/// resulting image will have transparent contents in the corners.
///
/// - parameter size: The desired output size, in points.
///
/// - parameter border: If non-nil, the resulting image will include the
/// requested border drawn around the perimeter of the image.
///
/// - parameter contentScale: The number of pixels per point, which is
/// used to reckon the output image size relative to the requested
/// `size`. Pass `0` to use the native defaults for the current device.
case round(size: CGSize, border: Border?, contentScale: ContentScale)
/// Draw the source image using a developer-supplied formatting block.
///
/// - parameter editKey: A key uniquely identifying the formatting
/// strategy used by `block`. This key is **not** specific to any
/// particular image, but is instead common to all images drawn with
/// this format. ImageCache will combine the edit key with other unique
/// parameters when caching an image drawn with a custom format.
///
/// - parameter block: A developer-supplied formatting block which
/// accepts the unmodified source image as input and returns a formatted
/// image. The developer does not need to cache the returned image.
/// ImageCache will cache the result in the same manner as images drawn
/// using the other formats.
case custom(editKey: String, block: (ImageCache.Image) -> ImageCache.Image)
public func hash(into hasher: inout Hasher) {
switch self {
case .original:
hasher.combine(".original")
case let .scaled(size, mode, bleed, opaque, cornerRadius, border, contentScale):
hasher.combine(".scaled")
hasher.combine(size.width)
hasher.combine(size.height)
hasher.combine(mode)
hasher.combine(bleed)
hasher.combine(opaque)
hasher.combine(cornerRadius)
hasher.combine(border)
hasher.combine(contentScale)
case let .round(size, border, contentScale):
hasher.combine(".round")
hasher.combine(size.width)
hasher.combine(size.height)
hasher.combine(border)
hasher.combine(contentScale)
case .custom(let key, _):
hasher.combine(".original")
hasher.combine(key)
}
}
public static func ==(lhs: Format, rhs: Format) -> Bool {
switch (lhs, rhs) {
case (.original, .original):
return true
case let (.scaled(ls, lm, lbl, lo, lc, lb, lcs), .scaled(rs, rm, rbl, ro, rc, rb, rcs)):
return ls == rs && lm == rm && lbl == rbl && lo == ro && lc == rc && lb == rb && lcs == rcs
case let (.round(ls, lb, lc), .round(rs, rb, rc)):
return ls == rs && lb == rb && lc == rc
case let (.custom(left, _), .custom(right, _)):
return left == right
default:
return false
}
}
fileprivate func image(from result: DownloadResult) -> Image? {
switch result {
case .fresh(let url):
guard let image = Image.fromFile(at: url) else { return nil }
return ImageDrawing.draw(image, format: self)
case .previous(let image):
return ImageDrawing.draw(image, format: self)
}
}
}
}
//------------------------------------------------------------------------------
// MARK: - ContentMode
//------------------------------------------------------------------------------
extension ImageCache.Format {
/// Platform-agnostic analogue to UIView.ContentMode
public enum ContentMode {
/// Contents scaled to fill with fixed aspect ratio. Some portion of
/// the content may be clipped.
case scaleAspectFill
/// Contents scaled to fit with fixed aspect ratio. The remainder of
/// the resulting image area will be either transparent or black,
/// depending upon the requested `opaque` value.
case scaleAspectFit
}
}
//------------------------------------------------------------------------------
// MARK: - Border
//------------------------------------------------------------------------------
extension ImageCache.Format {
/// Border styles you can use when drawing a scaled or round image format.
public enum Border: Hashable {
case hairline(ImageCache.Color)
public func hash(into hasher: inout Hasher) {
switch self {
case .hairline(let color):
hasher.combine(".hairline")
hasher.combine(color)
}
}
public static func ==(lhs: Border, rhs: Border) -> Bool {
switch (lhs, rhs) {
case let (.hairline(left), .hairline(right)): return left == right
}
}
#if os(iOS)
fileprivate func draw(around path: UIBezierPath) {
guard let context = UIGraphicsGetCurrentContext() else { return }
switch self {
case .hairline(let color):
context.setStrokeColor(color.cgColor)
let perceivedWidth: CGFloat = 1.0 // In the units of the context!
let actualWidth = perceivedWidth * 2.0 // Half'll be cropped
context.setLineWidth(actualWidth) // it's centered
context.addPath(path.cgPath)
context.strokePath()
}
}
#endif
}
}
//------------------------------------------------------------------------------
// MARK: - ImageDrawing
//------------------------------------------------------------------------------
/// Utility for drawing an image according to a specified format.
///
/// - Note: This is public since it may be useful outside this file.
public enum /*scope*/ ImageDrawing {
// MARK: Common
/// Draws `image` using the specified format.
///
/// - returns: Returns the formatted image.
public static func draw(_ image: ImageCache.Image, format: ImageCache.Format) -> ImageCache.Image {
switch format {
case .original:
return decompress(image)
case let .scaled(size, mode, bleed, opaque, cornerRadius, border, contentScale):
return draw(image, at: size, using: mode, bleed: bleed, opaque: opaque, cornerRadius: cornerRadius, border: border, contentScale: contentScale)
case let .round(size, border, contentScale):
return draw(image, clippedByOvalOfSize: size, border: border, contentScale: contentScale)
case .custom(_, let block):
return block(image)
}
}
// MARK: macOS
#if os(OSX)
fileprivate static func decompress(_ image: Image) -> Image {
// Not yet implemented.
return image
}
private static func draw(_ image: Image, at targetSize: CGSize, using mode: ImageCache.Format.ContentMode, opaque: Bool, cornerRadius: CGFloat, border: ImageBorder?, contentScale: CGFloat) -> Image {
// Not yet implemented.
return image
}
private static func draw(_ image: Image, clippedByOvalOfSize targetSize: CGSize, border: ImageCache.Format.Border?, contentScale: CGFloat) -> Image {
// Not yet implemented.
return image
}
#endif
// MARK: iOS
#if os(iOS)
fileprivate static func decompress(_ image: Image) -> Image {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1)) // Size doesn't matter.
defer { UIGraphicsEndImageContext() }
image.draw(at: CGPoint.zero)
return image
}
private static func draw(_ image: Image, at targetSize: CGSize, using mode: ImageCache.Format.ContentMode, bleed: CGFloat, opaque: Bool, cornerRadius: CGFloat, border: ImageCache.Format.Border?, contentScale: CGFloat) -> Image {
guard !image.size.equalTo(.zero) else { return image }
guard !targetSize.equalTo(.zero) else { return image }
switch mode {
case .scaleAspectFill, .scaleAspectFit:
var scaledSize: CGSize
if mode == .scaleAspectFit {
scaledSize = image.sizeThatFits(targetSize)
} else {
scaledSize = image.sizeThatFills(targetSize)
}
if bleed != 0 {
scaledSize.width += bleed * 2
scaledSize.height += bleed * 2
}
let x = (targetSize.width - scaledSize.width) / 2.0
let y = (targetSize.height - scaledSize.height) / 2.0
let drawingRect = CGRect(x: x, y: y, width: scaledSize.width, height: scaledSize.height)
UIGraphicsBeginImageContextWithOptions(targetSize, opaque, contentScale)
defer { UIGraphicsEndImageContext() }
if cornerRadius > 0 || border != nil {
let clipRect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)
let bezPath = UIBezierPath(roundedRect: clipRect, cornerRadius: cornerRadius)
bezPath.addClip()
image.draw(in: drawingRect)
border?.draw(around: bezPath)
} else {
image.draw(in: drawingRect)
}
return UIGraphicsGetImageFromCurrentImageContext() ?? image
}
}
private static func draw(_ image: Image, clippedByOvalOfSize targetSize: CGSize, border: ImageCache.Format.Border?, contentScale: CGFloat) -> Image {
guard !image.size.equalTo(.zero) else { return image }
guard !targetSize.equalTo(.zero) else { return image }
let scaledSize = image.sizeThatFills(targetSize)
let x = (targetSize.width - scaledSize.width) / 2.0
let y = (targetSize.height - scaledSize.height) / 2.0
let drawingRect = CGRect(x: x, y: y, width: scaledSize.width, height: scaledSize.height)
let clipRect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)
UIGraphicsBeginImageContextWithOptions(targetSize, false, 0)
defer { UIGraphicsEndImageContext() }
let bezPath = UIBezierPath(ovalIn: clipRect)
bezPath.addClip()
image.draw(in: drawingRect)
border?.draw(around: bezPath)
return UIGraphicsGetImageFromCurrentImageContext() ?? image
}
#endif
}
//------------------------------------------------------------------------------
// MARK: - ImageKey
//------------------------------------------------------------------------------
/// Uniquely identifies a particular format of an image from a particular URL.
private class ImageKey: Hashable {
/// The HTTP URL to the original image from which the cached image was derived.
let url: URL
/// The format used when processing the cached image.
let format: ImageCache.Format
init(url: URL, format: ImageCache.Format) {
self.url = url
self.format = format
}
func hash(into hasher: inout Hasher) {
hasher.combine(url)
hasher.combine(format)
}
var filenameSuffix: String {
switch format {
case .original:
return "_original"
case let .scaled(size, mode, bleed, opaque, radius, border, contentScale):
let base = "_scaled_\(Int(size.width))_\(Int(size.height))_\(mode)_\(Int(bleed))_\(opaque)_\(Int(radius))_\(Int(contentScale))"
if let border = border, case .hairline(let color) = border {
return base + "_hairline(\(color))"
} else {
return base + "_nil"
}
case let .round(size, border, contentScale):
let base = "_round_\(Int(size.width))_\(Int(size.height))"
if let border = border, case .hairline(let color) = border {
return base + "_hairline(\(color))" + "_\(Int(contentScale))"
} else {
return base + "_nil"
}
case let .custom(key, _):
return "_custom_\(key)"
}
}
static func ==(lhs: ImageKey, rhs: ImageKey) -> Bool {
return lhs.url == rhs.url && lhs.format == rhs.format
}
}
//------------------------------------------------------------------------------
// MARK: - DownloadResult
//------------------------------------------------------------------------------
/// Communicates to `ImageCache` whether the result of a download operation was
/// that a new file was freshly downloaded, or whether a previously-downloaded
/// file was able to be used.
private enum DownloadResult {
/// A fresh file was downloaded and is available locally at a file URL.
case fresh(URL)
/// A previously-downloaded image was already available on disk.
case previous(Image)
}
//------------------------------------------------------------------------------
// MARK: - MemoryCache
//------------------------------------------------------------------------------
private class MemoryCache<Key: Hashable, Value> {
var shouldRemoveAllObjectsWhenAppEntersBackground = false
private var items = _ProtectedDictionary<Key, Value>()
private var observers = [NSObjectProtocol]()
subscript(key: Key) -> Value? {
get { return items[key] }
set { items[key] = newValue }
}
subscript(filter: (Key) -> Bool) -> [Key: Value] {
get {
return items.access {
$0.filter{ filter($0.key) }
}
}
}
init() {
#if os(iOS)
observers.append(NotificationCenter.default.addObserver(
forName: UIApplication.didReceiveMemoryWarningNotification,
object: nil,
queue: .main,
using: { [weak self] _ in
self?.removeAll()
}))
observers.append(NotificationCenter.default.addObserver(
forName: UIApplication.didEnterBackgroundNotification,
object: nil,
queue: .main,
using: { [weak self] _ in
guard let this = self else { return }
if this.shouldRemoveAllObjectsWhenAppEntersBackground {
this.removeAll()
}
}))
#endif
}
deinit {
observers.forEach(NotificationCenter.default.removeObserver)
}
func removeAll() {
items.access{ $0.removeAll() }
}
}
//------------------------------------------------------------------------------
// MARK: - DeferredValue
//------------------------------------------------------------------------------
private class DeferredValue<T> {
var value: T?
}
//------------------------------------------------------------------------------
// MARK: - TaskRegistry
//------------------------------------------------------------------------------
private class TaskRegistry<TaskID: Hashable, Result> {
typealias RequestID = UUID
typealias Finish = (Result) -> Void
typealias TaskType = Task<TaskID, Result>
typealias RequestType = Request<Result>
private var protectedTasks = _Protected<[TaskID: TaskType]>([:])
func addRequest(taskId: TaskID, workQueue: OperationQueue, taskExecution: @escaping (@escaping Finish) -> Void, taskCancellation: @escaping () -> Void, taskCompletion: @escaping TaskType.Completion, requestCompletion: @escaping RequestType.Completion) -> RequestID {
let request = RequestType(completion: requestCompletion)
protectedTasks.access { tasks in
if var task = tasks[taskId] {
task.requests[request.id] = request
tasks[taskId] = task
} else {
var task = Task<TaskID, Result>(
id: taskId,
cancellation: taskCancellation,
completion: taskCompletion
)
task.requests[request.id] = request
tasks[taskId] = task
let finish: Finish = { [weak self] result in
onMain{ self?.finishTask(withId: taskId, result: result) }
}
// `deferred(on:block:)` will dispatch to next main runloop then
// from there dispatch to a global queue, ensuring that the
// completion block cannot be executed before this method returns.
deferred(on: workQueue){ taskExecution(finish) }
}
}
return request.id
}
func cancelRequest(withId id: RequestID) {
let taskCancellation: TaskType.Cancellation? = protectedTasks.access { tasks in
guard var (_, task) = tasks.first(where:{ $0.value.requests[id] != nil }) else { return nil }
task.requests[id] = nil
let shouldCancelTask = task.requests.isEmpty
if shouldCancelTask {
tasks[task.id] = nil
return task.cancellation
} else {
tasks[task.id] = task
return nil
}
}
taskCancellation?()
}
private func finishTask(withId id: TaskID, result: Result) {
let (taskCompletion, requestCompletions): (TaskType.Completion?, [RequestType.Completion]?) = protectedTasks.access { tasks in
let task = tasks[id]
tasks[id] = nil
return (task?.completion, task?.requests.values.map{ $0.completion })
}
// Per my standard habit, completion handlers are always performed on
// the main queue.
if let completion = taskCompletion {
onMain { completion(result) }
}
if let completions = requestCompletions {
onMain {
completions.forEach{ $0(result) }
}
}
}
}
//------------------------------------------------------------------------------
// MARK: - Task
//------------------------------------------------------------------------------
private struct Task<TaskID: Hashable, Result> {
typealias Cancellation = () -> Void
typealias Completion = (Result) -> Void
var requests = [UUID: Request<Result>]()
let id: TaskID
let cancellation: Cancellation
let completion: Completion
init(id: TaskID, cancellation: @escaping Cancellation, completion: @escaping Completion) {
self.id = id
self.cancellation = cancellation
self.completion = completion
}
}
//------------------------------------------------------------------------------
// MARK: - Request
//------------------------------------------------------------------------------
private struct Request<Result> {
typealias Completion = (Result) -> Void
let id = UUID()
let completion: Completion
}
//------------------------------------------------------------------------------
// MARK: - _BackgroundTask
//------------------------------------------------------------------------------
#if os(iOS)
private class _BackgroundTask {
private var taskId: UIBackgroundTaskIdentifier = .invalid
static func start() -> _BackgroundTask? {
let task = _BackgroundTask()
let successful = task.startWithExpirationHandler(handler: nil)
return (successful) ? task : nil
}
func startWithExpirationHandler(handler: (() -> Void)?) -> Bool {
self.taskId = UIApplication.shared.beginBackgroundTask {
if let safeHandler = handler { safeHandler() }
self.end()
}
return (self.taskId != .invalid)
}
func end() {
guard self.taskId != .invalid else { return }
let taskId = self.taskId
self.taskId = .invalid
UIApplication.shared.endBackgroundTask(taskId)
}
}
#endif
//------------------------------------------------------------------------------
// MARK: - URL (Convenience)
//------------------------------------------------------------------------------
extension URL {
fileprivate func subdirectory(named name: String) -> URL {
return appendingPathComponent(name, isDirectory: true)
}
}
//------------------------------------------------------------------------------
// MARK: - FileManager (Convenience)
//------------------------------------------------------------------------------
extension FileManager {
fileprivate var caches: URL {
#if os(iOS)
return urls(for: .cachesDirectory, in: .userDomainMask).first!
#elseif os(OSX)
let library = urls(for: .libraryDirectory, in: .userDomainMask).first!
return library.appendingPathComponent("Caches", isDirectory: true)
#endif
}
fileprivate func createDirectory(at url: URL) {
do {
try createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
} catch {
assertionFailure("Unable to create directory at \(url). Error: \(error)")
}
}
fileprivate func fileExists(at url: URL) -> Bool {
return fileExists(atPath: url.path)
}
fileprivate func moveFile(from: URL, to: URL) -> Bool {
if fileExists(atPath: to.path) {
return didntThrow{ _ = try replaceItemAt(to, withItemAt: from) }
} else {
return didntThrow{ _ = try moveItem(at: from, to: to) }
}
}
fileprivate func image(fromFileAt url: URL) -> Image? {
if let data = try? Data(contentsOf: url) {
return Image(data: data)
} else {
return nil
}
}
fileprivate func save(_ image: Image, to url: URL) {
#if os(iOS)
guard let data = image.pngData() else { return }
#elseif os(OSX)
guard let data = image.tiffRepresentation else { return }
#endif
do {
if fileExists(at: url) {
try removeItem(at: url)
}
try data.write(to: url, options: .atomic)
} catch {}
}
fileprivate func removeFilesByDate(inDirectory directory: URL, untilWithinByteLimit limit: UInt) {
struct Item {
let url: NSURL
let fileSize: UInt
let dateModified: Date
}
let keys: [URLResourceKey] = [.fileSizeKey, .contentModificationDateKey]
guard let urls = try? contentsOfDirectory(
at: directory,
includingPropertiesForKeys: keys,
options: .skipsHiddenFiles
) else { return }
let items: [Item] = (urls as [NSURL])
.compactMap { url -> Item? in
guard let values = try? url.resourceValues(forKeys: keys) else { return nil }
return Item(
url: url,
fileSize: (values[.fileSizeKey] as? NSNumber)?.uintValue ?? 0,
dateModified: (values[.contentModificationDateKey] as? Date) ?? Date.distantPast
)
}
.sorted{ $0.dateModified < $1.dateModified }
var total = items.map{ $0.fileSize }.reduce(0, +)
var toDelete = [Item]()
for (_, item) in items.enumerated() {
guard total > limit else { break }
total -= item.fileSize
toDelete.append(item)
}
toDelete.forEach {
_ = try? self.removeItem(at: $0.url as URL)
}
}
}
//------------------------------------------------------------------------------
// MARK: - Image (Convenience)
//------------------------------------------------------------------------------
extension Image {
#if os(iOS)
fileprivate static func fromFile(at url: URL) -> Image? {
guard let data = try? Data(contentsOf: url) else { return nil }
return Image(data: data)
}
#endif
fileprivate func sizeThatFills(_ other: CGSize) -> CGSize {
guard !size.equalTo(.zero) else { return other }
let h = size.height
let w = size.width
let heightRatio = other.height / h
let widthRatio = other.width / w
if heightRatio > widthRatio {
return CGSize(width: w * heightRatio, height: h * heightRatio)
} else {
return CGSize(width: w * widthRatio, height: h * widthRatio)
}
}
fileprivate func sizeThatFits(_ other: CGSize) -> CGSize {
guard !size.equalTo(.zero) else { return other }
let h = size.height
let w = size.width
let heightRatio = other.height / h
let widthRatio = other.width / w
if heightRatio > widthRatio {
return CGSize(width: w * widthRatio, height: h * widthRatio)
} else {
return CGSize(width: w * heightRatio, height: h * heightRatio)
}
}
}
//------------------------------------------------------------------------------
// MARK: - GCD (Convenience)
//------------------------------------------------------------------------------
private func onMain(_ block: @escaping () -> Void) {
DispatchQueue.main.async{ block() }
}
private func deferred(on queue: OperationQueue, block: @escaping () -> Void) {
onMain{ queue.addOperation(block) }
}
private func didntThrow(_ block: () throws -> Void) -> Bool {
do{ try block(); return true } catch { return false }
}
//------------------------------------------------------------------------------
// MARK: - Locking
//------------------------------------------------------------------------------
private final class _Lock {
private var lock = os_unfair_lock()
func locked<T>(_ block: () throws -> T) rethrows -> T {
os_unfair_lock_lock(&lock)
defer { os_unfair_lock_unlock(&lock) }
return try block()
}
}
private final class _Protected<T> {
private let lock = _Lock()
private var value: T
fileprivate init(_ value: T) {
self.value = value
}
fileprivate func access<Return>(_ block: (inout T) throws -> Return) rethrows -> Return {
return try lock.locked {
try block(&value)
}
}
}
private final class _ProtectedDictionary<Key: Hashable, Value> {
fileprivate typealias Contents = [Key: Value]
private let protected: _Protected<Contents>
fileprivate init(_ contents: Contents = [:]) {
self.protected = _Protected(contents)
}
fileprivate subscript(key: Key) -> Value? {
get { return protected.access{ $0[key] } }
set { protected.access{ $0[key] = newValue } }
}
fileprivate func access<Return>(_ block: (inout Contents) throws -> Return) rethrows -> Return {
return try protected.access(block)
}
}
| true
|
5f580323806110c364fc23747f27e14a2ceb1093
|
Swift
|
francodvelasco/SimulVac
|
/UserModules/Vaccines.playgroundmodule/Sources/VaccineDetailedView.swift
|
UTF-8
| 5,338
| 2.71875
| 3
|
[] |
no_license
|
import SwiftUI
import Resources
public struct VaccineDetailedView: View {
@Binding var showView: Bool
let vaccine: VaccineInformation
public init(showView: Binding<Bool>, vaccine: VaccineInformation) {
self._showView = showView
self.vaccine = vaccine
}
public var body: some View {
VStack(alignment: .leading, spacing: 1) {
Spacer()
.frame(height: 10)
HStack {
Spacer()
VaccineView(vaccine: vaccine)
Spacer()
}
Spacer()
.frame(height: 10)
Text("Efficacy Rates")
.font(.system(.title2, design: .rounded))
.fontWeight(.medium)
.padding(.leading)
HStack {
VStack(alignment: .leading) {
Text("Against Mild Cases")
.lineLimit(1)
.fixedSize(horizontal: false, vertical: true)
Spacer().frame(height: 15)
Text("\(Int(vaccine.mildEfficacyRate))%")
.font(.largeTitle)
}
.font(.title2)
.padding(8)
.fixedSize(horizontal: false, vertical: true)
.background(Color.backgroundColor)
.cornerRadius(8)
VStack(alignment: .leading) {
Text("Against Severe Cases")
.lineLimit(1)
.fixedSize(horizontal: false, vertical: true)
Spacer().frame(height: 15)
Text("\(Int(vaccine.severeEfficacyRate))%")
.font(.largeTitle)
}
.font(.title2)
.padding(8)
.fixedSize(horizontal: false, vertical: true)
.background(Color.backgroundColor)
.cornerRadius(8)
VStack(alignment: .leading) {
Text("Against Death")
.lineLimit(1)
.fixedSize(horizontal: false, vertical: true)
Spacer().frame(height: 15)
Text("\(Int(vaccine.deathEfficacyRate))%")
.font(.largeTitle)
}
.font(.title2)
.padding(8)
.fixedSize(horizontal: false, vertical: true)
.background(Color.backgroundColor)
.cornerRadius(8)
}
.padding(.horizontal)
Spacer()
.frame(height: 10)
Text("More about \(vaccine.manufacturer)'s vaccine")
.font(.system(.title2, design: .rounded))
.fontWeight(.medium)
.padding(.leading)
VStack(alignment: .leading) {
if let WHOurl = URL(string: vaccine.WHOInfo) {
Link(destination: WHOurl) {
HStack {
Spacer()
Text("World Health Organization (WHO)")
Spacer()
}
.padding(8)
.foregroundColor(Color.white)
.background(Color.blue)
.cornerRadius(8)
}
}
if let CDCurl = URL(string: vaccine.CDCInfo) {
Link(destination: CDCurl) {
HStack {
Spacer()
Text("US Center for Disease Control (CDC)")
Spacer()
}
.padding(8)
.foregroundColor(Color.white)
.background(Color.blue)
.cornerRadius(8)
}
}
if let FDAurl = URL(string: vaccine.FDAInfo) {
Link(destination: FDAurl) {
HStack {
Spacer()
Text("US Food and Drug Administration (FDA)")
Spacer()
}
.padding(8)
.foregroundColor(Color.white)
.background(Color.blue)
.cornerRadius(8)
}
}
}
.padding(.horizontal)
HStack {
Spacer()
Button(action: {
self.showView = false
}) {
HStack {
Text("Go Back")
.fontWeight(.semibold)
Image(systemName: "arrow.uturn.left")
}
.padding()
.foregroundColor(Color.white)
.background(Color.red)
.cornerRadius(8)
}
Spacer()
}
.padding(.vertical)
}
.foregroundColor(Color.black)
.background(Color.white)
.frame(width: 500)
.cornerRadius(8)
}
}
| true
|
b527e52e37852c97a36364bce3efa758ec8e618b
|
Swift
|
HunterKane/On-The-Map
|
/On The Map/Table/AddLocationController.swift
|
UTF-8
| 3,650
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// AddLocationController.swift
// On The Map
//
// Created by Hunter Sparrow on 4/19/18.
// Copyright © 2018 Hunter Sparrow. All rights reserved.
//
import UIKit
import CoreLocation
class AddLocationController: UIViewController {
//MARK: Properties
@IBOutlet var locationTextField: UITextField!
@IBOutlet var websiteTextField: UITextField!
@IBOutlet var findLocationButton: UIButton!
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
locationTextField.delegate = self
websiteTextField.delegate = self
keyboardYLimit.buttonY = (findLocationButton?.frame.origin.y)! + self.view.frame.origin.y / self.view.frame.origin.y
}
//Keyboard
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
subscribeToKeyboardNotification()
}
//Keyboard
override func viewWillDisappear(_ animated: Bool) {
unsubscribeToKeyboardNotifications()
}
// Actions
@IBAction func userDidTapView(_ sender: Any) {
resignIfFirstResponder(locationTextField)
resignIfFirstResponder(websiteTextField)
}
@IBAction func findLocationButtonPressed(_ sender: Any) {
if locationTextField.text!.isEmpty ||
websiteTextField.text!.isEmpty {
self.showAlert(text:"Location or Website Empty.")
}
else {
view.showBlurLoader()
getCoordinatesForAddress(address: locationTextField.text!, vc: self, { (result, error) in
DispatchQueue.main.async {
if let error = error {
self.showAlert(text: error.localizedDescription)
}
else if let result = result,
let location = result.location,
let name = result.name,
let country = result.country {
self.navigateToLocationPreview(location: location, name: name, country: country)
}
self.view.removeBlurLoader()
}
})
}
}
private func navigateToLocationPreview (location: CLLocation, name: String, country: String) {
if let navController = navigationController {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "AddLocationMapController") as! AddLocationMapController
vc.userLocationUpdate = AddLocationMapController.UserLocationUpdate(
userLocation: location,
userAddress: getCompleteAddressString(name: name, country: country),
userMediaUrl: websiteTextField.text!,
userName: getCompleteUserName())
navController.pushViewController(vc, animated: true)
}
}
private func getCompleteAddressString (name: String, country: String) ->String {
var completeAddress = ""
if name != "" {
completeAddress = name
}
if country != "" {
completeAddress += ", " + country
}
return completeAddress
}
private func getCompleteUserName () -> String {
if let firstName = StudentModel.sharedInstance.userLocation?.firstName,
let lastName = StudentModel.sharedInstance.userLocation?.lastName {
return firstName + ", " + lastName
}
else {
return "Unknown name"
}
}
}
| true
|
aaa9bcad139c0d6549777e2a86c1fade6ad6aefa
|
Swift
|
k-kohey/SimpleCoordinatorPattern
|
/SimpleCoordinatorPattern/ViewController/ViewController.swift
|
UTF-8
| 766
| 2.71875
| 3
|
[] |
no_license
|
//
// HomeViewController.swift
// SimpleCoordinatorPattern
//
// Created by kawaguchi kohei on 2019/02/10.
// Copyright © 2019年 kawaguchi kohei. All rights reserved.
//
import UIKit
final class ViewController: UIViewController {
struct Callback {
var detailPage: () -> ()
}
var transitionCallback: Callback?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .gray
let button = UIButton(frame: CGRect(x: 150, y: 300, width: 300, height: 300))
button.backgroundColor = .blue
button.addTarget(self, action: #selector(didTappedButton), for: .touchUpInside)
view.addSubview(button)
}
@objc private func didTappedButton() {
transitionCallback?.detailPage()
}
}
| true
|
7471a08f86741aa30659ffaef39354b56c23fb75
|
Swift
|
PaulineNS/Reciplease
|
/RecipleaseApp/App/Recipe/RecipesViewController.swift
|
UTF-8
| 1,752
| 2.5625
| 3
|
[] |
no_license
|
//
// RecipesViewController.swift
// Reciplease
//
// Created by Pauline Nomballais on 08/11/2019.
// Copyright © 2019 PaulineNomballais. All rights reserved.
//
import UIKit
final class RecipesViewController: UIViewController {
// MARK: - Outlets
@IBOutlet private weak var recipesTableView: UITableView! {
didSet {
recipesTableView.tableFooterView = UIView()
}
}
// MARK: - Public Properties
var viewModel: RecipesViewModel!
// MARK: - Private Properties
private lazy var source: RecipesDataSource = RecipesDataSource()
// MARK: - View life cycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
recipesTableView.delegate = source
recipesTableView.dataSource = source
viewModel.start()
recipesTableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
bind(to: source)
bind(to: viewModel)
let nibName = UINib(nibName: "RecipeTableViewCell",
bundle: nil)
recipesTableView.register(nibName,
forCellReuseIdentifier: "recipeCell")
updateTheNavigationBar(navBarItem: navigationItem)
}
// MARK: - Bindings
private func bind(to source: RecipesDataSource) {
source.selectedRecipe = viewModel.didSelectRecipe
}
private func bind(to viewModel: RecipesViewModel) {
viewModel.recipes = { [weak self] recipes in
self?.source.updateCell(with: recipes)
self?.recipesTableView.reloadData()
}
}
func didRemoveARecipeFromFavorites() {
viewModel.getFavoritesRecipes()
}
}
| true
|
acb9b9ab0afa8efa7ee60d1fc275b0d229838b23
|
Swift
|
n8chur/Listable
|
/Internal Pods/EnglishDictionary/Sources/EnglishDictionary.swift
|
UTF-8
| 1,989
| 3.15625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// EnglishDictionary.swift
// CheckoutApplet
//
// Created by Kyle Van Essen on 6/25/19.
//
import UIKit
class BundleFinder : NSObject {}
public class EnglishDictionary
{
public static let dictionary : EnglishDictionary = EnglishDictionary()
public let wordsByLetter : [Letter]
public let allWords : [Word]
public init()
{
let main = Bundle(for: EnglishDictionary.self)
let bundle = Bundle(url: main.url(forResource: "EnglishDictionaryResources", withExtension: "bundle")!)!
let stream = InputStream(url: bundle.url(forResource: "dictionary", withExtension: "json")!)!
defer { stream.close() }
stream.open()
let json = try! JSONSerialization.jsonObject(with: stream, options: []) as! [String:String]
var letters = [String:Letter]()
var words = [Word]()
for (word, description) in json
{
let firstCharacter = String(word.first!)
let word = Word(word: word, description: description)
let letter = letters[firstCharacter, default: Letter(letter: firstCharacter)]
letter.words.append(word)
words.append(word)
letters[firstCharacter] = letter
}
self.wordsByLetter = letters.values.sorted { $0.letter < $1.letter }
self.wordsByLetter.forEach { $0.sort() }
self.allWords = words.sorted { $0.word < $1.word }
}
public class Letter
{
public let letter : String
public var words : [Word] = []
init(letter : String)
{
self.letter = letter
}
fileprivate func sort()
{
self.words.sort {
$0.word < $1.word
}
}
}
public struct Word : Equatable
{
public let word : String
public let description : String
}
}
| true
|
2301e393e5ed7371bac6080a051e3a8c1dba631f
|
Swift
|
yungfan/SwiftUI-learning
|
/SwiftUI 3.0/Modifier14-badge/Modifier14-badge/ContentView.swift
|
UTF-8
| 878
| 2.703125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// Modifier14-badge
//
// Created by 杨帆 on 2021/10/14.
//
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
Text("首页")
.tabItem {
Text("首页")
Image(systemName: "house")
}
.badge(1)
Text("消息")
.tabItem {
Text("消息")
Image(systemName: "message")
}
.badge("new")
Text("通讯录")
.tabItem {
Text("通讯录")
Image(systemName: "person")
}
.badge(Text("100"))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
3e707d5f5318adb76dfe32b23da769f541e1f413
|
Swift
|
heumn/LionShare
|
/LionShare/TabBarController.swift
|
UTF-8
| 369
| 2.546875
| 3
|
[] |
no_license
|
import Foundation
import UIKit
class TabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
guard let vcs = self.viewControllers else { return }
// Remove tabBarItem titles and adjust icons accordingly
for vc in vcs {
vc.tabBarItem.title = nil
vc.tabBarItem.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0)
}
}
}
| true
|
4fbb324bb7e72cc554194734fe83662947d8e1f7
|
Swift
|
bryanOrtiz/fitness
|
/fitness/Models/Exercise.swift
|
UTF-8
| 889
| 2.703125
| 3
|
[] |
no_license
|
//
// Exercise.swift
// fitness
//
// Created by Bryan Ortiz on 5/9/21.
// Copyright © 2021 Ortiz. All rights reserved.
//
import Foundation
struct Exercise: Codable {
let id: Int
let name: String
let uuid: String
let description: String
let creationDate: String
let category: Int
let muscles: [Int]
let musclesSecondary: [Int]
let equipment: [Int]
let language: Int
let license: Int
let licenseAuthor: String
let variations: [Int]
enum CodingKeys: String, CodingKey {
case id
case name
case uuid
case description
case category
case muscles
case equipment
case language
case license
case variations
case creationDate = "creation_date"
case musclesSecondary = "muscles_secondary"
case licenseAuthor = "license_author"
}
}
| true
|
070d64823f98c00c4b54cd0a3046647f657b951f
|
Swift
|
bagasstb/Dice
|
/Dice/ViewController.swift
|
UTF-8
| 1,209
| 3.109375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Dice
//
// Created by bagasstb on 27/02/19.
// Copyright © 2019 xProject. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var randomDice1: Int = 0
var randomDice2: Int = 0
@IBOutlet weak var dice1: UIImageView!
@IBOutlet weak var dice2: UIImageView!
let diceArray = ["dice1", "dice2", "dice3", "dice4", "dice5", "dice6"]
override func viewDidLoad() {
super.viewDidLoad()
rollDice()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func rollPressed(_ sender: UIButton) {
rollDice()
}
func rollDice() {
randomDice1 = getRandom()
randomDice2 = getRandom()
dice1.image = getDiceImage(index: randomDice1)
dice2.image = getDiceImage(index: randomDice2)
}
func getRandom() -> Int {
return Int.random(in: 0 ... 5)
}
func getDiceImage(index: Int) -> UIImage? {
return UIImage(named: diceArray[index])
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
rollDice()
}
}
| true
|
af09bf233d6c7b49ba798baf8c14c44ae90a8893
|
Swift
|
WonderlandTeam/Ucount_iOS
|
/Ucount_iOS/Ucount_IOS/Ucount_IOS/Financial/talkViewController.swift
|
UTF-8
| 1,206
| 2.671875
| 3
|
[] |
no_license
|
//
// talkViewController.swift
// Ucount_IOS
//
// Created by 黄飘 on 2017/8/30.
// Copyright © 2017年 李一鹏. All rights reserved.
//
import UIKit
class talkViewController: UIViewController {
typealias talkCallBack = (_ words: String)->Void
var callBack: talkCallBack!
@IBOutlet weak var talkContent: UITextView!
@IBAction func cancelTapped(_ sender: UIButton) {
self.callBack("")
self.dismiss(animated: true)
}
@IBAction func pushTapped(_ sender: UIButton) {
self.callBack(talkContent.text)
self.dismiss(animated: true)
}
override func viewDidLoad() {
self.talkContent.text = "请在这里发表评论。"
self.talkContent.becomeFirstResponder()
self.talkContent.layer.borderWidth = 1
self.talkContent.layer.borderColor = UIColor.gray.cgColor
self.talkContent.layer.cornerRadius = 10
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
ffc1858c426b11fb04a71740a2552a308970ce4c
|
Swift
|
toddheasley/version
|
/Sources/Version/Version.swift
|
UTF-8
| 1,319
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
public struct Version: CustomStringConvertible {
public let major: Int
public let minor: Int
public let patch: Int
public func description(verbose: Bool) -> String {
return (patch > 0 || verbose) ? "\(major).\(minor).\(patch)" : "\(major).\(minor)"
}
public init(_ description: String? = nil) {
let components: [Int] = (description ?? "").components(separatedBy: ".").map { component in
return Int(component) ?? 0
}
major = max(components[0], 1) // Enforce minimum version 1.0
minor = (components.count > 1 && components[0] != 0) ? max(components[1], 0) : 0
patch = (components.count > 2 && components[0] != 0) ? max(components[2], 0) : 0
}
// MARK: CustomStringConvertible
public var description: String {
return description(verbose: false)
}
}
extension Version: Comparable {
// MARK: Comparable
public static func ==(x: Version, y: Version) -> Bool {
return (x.major == y.major) && (x.minor == y.minor) && (x.patch == y.patch)
}
public static func <(x: Version, y: Version) -> Bool {
return (x.major < y.major) || (x.major == y.major && x.minor < y.minor) || (x.major == y.major && x.minor == y.minor && x.patch < y.patch)
}
}
| true
|
9d50aecd62907fbd274fe5c42bda7c31409970a5
|
Swift
|
nezhitsya/Swift-30-Projects
|
/Project 15 - SlideMenu/SlideMenu/ViewController.swift
|
UTF-8
| 2,025
| 2.984375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// SlideMenu
//
// Created by 이다영 on 2021/04/13.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imageView: UIImageView!
enum vcName: String {
case first = "FirstViewController"
case second = "SecondViewController"
case third = "ThirdViewController"
}
override func viewDidLoad() {
super.viewDidLoad()
let firstVC = UIViewController(nibName: vcName.first.rawValue, bundle: nil)
let secondVC = UIViewController(nibName: vcName.second.rawValue, bundle: nil)
let thirdVC = UIViewController(nibName: vcName.third.rawValue, bundle: nil)
add(childViewController: firstVC, toParentViewController: self)
add(childViewController: secondVC, toParentViewController: self)
add(childViewController: thirdVC, toParentViewController: self)
changeX(ofView: self.imageView, xPosition: view.frame.width)
scrollView.addSubview(self.imageView)
changeX(ofView: firstVC.view, xPosition: view.frame.width * 1)
changeX(ofView: secondVC.view, xPosition: view.frame.width * 2)
changeX(ofView: thirdVC.view, xPosition: view.frame.width * 3)
scrollView.contentSize = CGSize(width: view.frame.width * 4, height: view.frame.height)
scrollView.contentOffset.x = view.frame.width
}
override var prefersStatusBarHidden: Bool {
return true
}
private func changeX(ofView view: UIView, xPosition: CGFloat) {
var frame = view.frame
frame.origin.x = xPosition
view.frame = frame
}
private func add(childViewController: UIViewController, toParentViewController parentViewController: UIViewController) {
addChild(childViewController)
scrollView.addSubview(childViewController.view)
childViewController.didMove(toParent: parentViewController)
}
}
| true
|
21de53361ab4648f76bc8b22e97a3f73486c8bda
|
Swift
|
juliand665/DomiBuriBot
|
/Sources/App/Update Handler/UpdateHandler.swift
|
UTF-8
| 2,609
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
import Vapor
import HandyOperators
struct Subscription {
/// the chat to send updates to
var chat: Chat
/// the user whose updates we're subscribed to, or nil for everyone
var username: String?
}
var subscription: Subscription?
struct UpdateHandler {
typealias Result = Future<HTTPStatus>
let request: Request
let update: Update
let message: Message
let session: Session
var chat: Chat { message.chat }
init(handling update: Update, using sessionManager: SessionManager, request: Request) throws {
self.request = request
self.update = update
try self.message = update.message ?? update.editedMessage ??? Abort(.notAcceptable)
self.session = sessionManager.session(for: message.chat)
}
func handleUpdate() throws -> Result {
if let message = update.message {
if let text = message.text {
print("got message:", text)
if text.hasPrefix("/") {
return try handleCommand(text)
} else {
return try handleGuess(text)
}
} else {
print("got non-text message")
dump(message)
return try sendMarkdownMessage("📝 All the answers can be expressed as plain text!")
}
} else if let message = update.editedMessage {
print("got edited message", message)
return try sendMarkdownMessage("😤 Editing is _cheating_!")
} else {
print("unknown update type")
dump(update)
return ok()
}
}
func sendMarkdownMessage(_ message: String) throws -> Result {
try request.client()
.sendMarkdownMessage(message, in: chat)
.map { _ in try self.updateSubscriber(forMessage: message) }
.transform(to: .ok)
}
private func updateSubscriber(forMessage message: String) throws -> Result {
guard let subscription = subscription else { return ok() }
guard false
|| subscription.username == nil
|| subscription.username == self.message.sender?.username
else { return ok() }
func quote(_ text: String) -> String {
text.components(separatedBy: "\n").map { "> \($0)" }.joined(separator: "\n")
}
let update = """
@\(self.message.sender?.username ?? "<sender without username>"):
\(quote(self.message.text ?? "<message without text>"))
reply:
\(quote(message))
"""
return try request.client()
.sendMarkdownMessage(update, in: subscription.chat)
.transform(to: .ok)
.mapIfError { _ in .ok } // ignore errors because this is secondary functionality
}
func sendFile(id: String) throws -> Result {
try request.client()
.sendDocument(id: id, in: chat)
.transform(to: .ok)
}
func ok() -> Result {
request.next().newSucceededFuture(result: .ok)
}
}
| true
|
922532d96efdd109eaa4a5825eaae4e530d938dc
|
Swift
|
pepilloguajar/bbcNews
|
/bbcNews/AppDelegate.swift
|
UTF-8
| 3,997
| 2.5625
| 3
|
[] |
no_license
|
//
// AppDelegate.swift
// bbcNews
//
// Created by JJ Montes on 13/01/2019.
// Copyright © 2019 jjmontes. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//Check Jail Break
if application.isDeviceJailbroken() {
self.showDeviceJailbrokenAlert()
}
self.window = UIWindow(frame: UIScreen.main.bounds)
self.navigationController = HomeAssembly.homePresenterNavigationController()
self.navigationController?.isNavigationBarHidden = true
self.window?.rootViewController = self.navigationController
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
self.refreshView()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
//Realiza el refresco de la pantalla, al volver de segundo plano.
private func refreshView() {
// Necesario para refrescar la infomración cuando se vuelve de segundo plano.
if let nav = window?.rootViewController {
//Si tenemos implementado en nuestra vista el protocolo, será ejecutado desde esta función.
let top = nav.navigationController?.topViewController
if let refresh = top as? BaseViewControllerRefresh {
refresh.backToBackGroundRefresh()
}
}
}
private func showDeviceJailbrokenAlert() {
let alert = UIAlertController(title: "Error!", message: "Your device is jailbroken. For security reasons this app can't be run on a jailbroken device. ", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Exit", style: UIAlertAction.Style.destructive, handler: { _ in exit(1) }))
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindow.Level.alert + 1
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alert, animated: true, completion: nil)
}
}
| true
|
0054ecc804638f6bdc87fc119cd11b3fd1d8a6dc
|
Swift
|
sandro93/Covid19Stats
|
/Covid19Stats/Covid19Stats/Core/CD19Core/Extensions/Extensions.swift
|
UTF-8
| 2,018
| 2.953125
| 3
|
[] |
no_license
|
//
// UIExtensions.swift
// Covid19Stats
//
// Created by Aleksandre Ebanoidze on 5/7/20.
// Copyright © 2020 Aleksandre Ebanoidze. All rights reserved.
//
import Foundation
import UIKit
public extension Int {
var toString : String { get { return "\(self)" } }
}
public extension String {
var toInt : Int { get { let number = NSDecimalNumber(string: self); return number == NSDecimalNumber.notANumber ? 0 : number.intValue } }
}
extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element { reduce(.zero, +) }
}
public extension NSObject {
static var stringFromClass : String { return NSStringFromClass(self) }
var stringFromClass : String { return NSStringFromClass(type(of: self)) }
static var className : String { return self.stringFromClass.components(separatedBy: ".").last! }
var className : String { return self.stringFromClass.components(separatedBy: ".").last! }
}
protocol Reusable: class {
static var reuseIdentifier: String { get }
}
extension Reusable {
static var reuseIdentifier: String { return String(describing: self) }
}
extension UITableViewCell: Reusable {
@objc func fill(with item: Any)
{
}
}
extension UIView {
class func fromNib<T: UIView>() -> T {
return Bundle(for: T.self).loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T
}
}
extension UIImageView {
func setImage(from urlString: String, placeholder: UIImage? = nil) {
guard let url = URL(string: urlString) else { return }
ImageCache.shared.imageFor(url: url) { [weak self] (result, error) in
if let result = result {
DispatchQueue.main.async() {
self?.image = result
}
}
if error != nil {
DispatchQueue.main.async() {
self?.image = placeholder
}
}
}
}
}
| true
|
7dc212c705a71ded74bbc7c22489dc93f824da53
|
Swift
|
Starman1123/ios-decal-proj3
|
/Photos/Photos/InstagramAPI.swift
|
UTF-8
| 5,007
| 2.78125
| 3
|
[] |
no_license
|
//
// InstagramAPI.Swift
// Photos
//
// Created by Gene Yoo on 11/3/15.
// Copyright © 2015 iOS DeCal. All rights reserved.
//
import Foundation
import Alamofire
class InstagramAPI {
let url1: NSURL = NSURL(string: "https://api.instagram.com/v1/media/popular?client_id=01825446a0d34fc5a7cee5ea7a4a59f7")!
let url2: NSURL = NSURL(string: "https://api.instagram.com/v1/media/search?lat=37.8716667&lng=-122.2716667&client_id=01825446a0d34fc5a7cee5ea7a4a59f7")!
static let baseURLString = "https://api.instagram.com"
static let clientID = "01825446a0d34fc5a7cee5ea7a4a59f7"
static let clientSecret = "245df10595f040908da523ab8a88b121"
static let redirectURI = "http://shanew92.com/"
static let getCodeURI = "https://api.instagram.com/oauth/authorize/?client_id=01825446a0d34fc5a7cee5ea7a4a59f7&redirect_uri=http://shanew92.com/&response_type=code"
static let searchUserURL : String = "https://api.instagram.com/v1/users/search?"
static func getRequestAccessTokenURLStringAndParams(code: String) -> (URLString: String, Params: [String: AnyObject]) {
let params = ["client_id": self.clientID, "client_secret": self.clientSecret, "grant_type": "authorization_code", "redirect_uri": self.redirectURI, "code": code]
let urlString = self.baseURLString + "/oauth/access_token"
return (urlString, params)
}
static func getCode() -> NSURLRequest {
let URLRequest = NSURLRequest(URL: NSURL(string: self.getCodeURI)!)
return URLRequest
}
func loadUsers(searchText: String, completion: (([User]) -> Void)!) {
let originalString = InstagramAPI.searchUserURL+"q="+searchText+"&client_id=01825446a0d34fc5a7cee5ea7a4a59f7"
let escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())
print(escapedString)
let task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: escapedString!)!) {
(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if error == nil {
//FIX ME
var users: [User]! = []
do {
let feedDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
// FILL ME IN, REMEMBER TO USE FORCED DOWNCASTING
if let dataList = feedDictionary["data"] as? [[String : AnyObject]] {
for dic in dataList {
let user: User = User(data: dic)
users.append(user)
}
}
// DO NOT CHANGE BELOW
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
dispatch_async(dispatch_get_main_queue()) {
completion(users)
}
}
} catch let error as NSError {
print("ERROR: \(error.localizedDescription)")
}
}
}
task.resume()
}
/* Connects with the Instagram API and pulls resources from the server. */
func loadPhotos(urlNum: Int, completion: (([Photo]) -> Void)!) {
var url: NSURL = url1
if urlNum == 1 {
url = url2
}
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {
(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if error == nil {
//FIX ME
var photos: [Photo]! = []
do {
let feedDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
// FILL ME IN, REMEMBER TO USE FORCED DOWNCASTING
if let dataList = feedDictionary["data"] as? [[String : AnyObject]] {
for dic in dataList {
let photo: Photo = Photo(data: dic)
photos.append(photo)
}
if photos.count%2 != 0 {
photos.removeLast()
}
}
// DO NOT CHANGE BELOW
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
dispatch_async(dispatch_get_main_queue()) {
completion(photos)
}
}
} catch let error as NSError {
print("ERROR: \(error.localizedDescription)")
}
}
}
task.resume()
}
}
| true
|
ed8d14bd0643e60af62e0b368cf5e890d95bdbc1
|
Swift
|
DrGrk/MyCalculator
|
/Calculator.swift
|
UTF-8
| 675
| 2.609375
| 3
|
[] |
no_license
|
//
// Calculator.swift
// MyCalculator
//
// Created by David Guichon on 2017-09-28.
// Copyright © 2017 David Guichon. All rights reserved.
//
import Foundation
import UIKit
class Calculator {
//CONSIDER MAKING THIS A SINGLETON
//CONSIDER CREATING PROTOCOLS TO CHANGE THE FUNCTION OF THE CALCULATOR
var keyPad: KeyPad!
var displayScreen: DisplayScreen!
init(vcView: UIView) {
keyPad = KeyPad.init(vcView: vcView)
displayScreen = DisplayScreen.init(vcView: vcView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
7b260f41193f2cf259f82c54b5c9b63cc6eff021
|
Swift
|
jolyot/CustomCellDefinitionWithEnum
|
/CustomCellExample/ListViewModel.swift
|
UTF-8
| 958
| 2.65625
| 3
|
[] |
no_license
|
//
// ListViewModel.swift
// CustomCellExample
//
// Created by Kazunori Takaishi on 2018/04/22.
// Copyright © 2018 Kazunori Takaishi. All rights reserved.
//
import UIKit
final class ListViewModel: NSObject {
var cellModels = [ListViewCellModel]()
func initialize() {
let customNo1 = CustomNo1TableViewCellViewModel(titleName: "カスタムセル1", cellType: ListViewCustomCellType.customNo1)
let customNo2 = CustomNo2TableViewCellViewModel(aboveTitleName: "カスタムセル2above", belowTitleName: "カスタムセル2below", cellType: ListViewCustomCellType.customNo2)
let customNo3 = CustomNo3TableViewCellViewModel(uperTitleName: "カスタムセル3uper", middleTitleName: "カスタムセル3middle", bottomTitleName: "カスタムセル3bottom", cellType: ListViewCustomCellType.customNo3)
cellModels.append(customNo1)
cellModels.append(customNo2)
cellModels.append(customNo3)
}
}
| true
|
b30193b7ecfacf0dfb06e2750a1b6872fc66e18b
|
Swift
|
pauljarysta/iOS-HideMenu
|
/HideMenu/HideMenu/Helpers.swift
|
UTF-8
| 1,060
| 2.53125
| 3
|
[] |
no_license
|
//
// Helpers.swift
// HideMenu
//
// Created by Paul on 16/10/2018.
// Copyright © 2018 Paul Jarysta. All rights reserved.
//
import UIKit
struct Device {
// iDevice detection code
static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad
static let IS_IPHONE = UIDevice.current.userInterfaceIdiom == .phone
static let IS_RETINA = UIScreen.main.scale >= 2.0
static let SCREEN_WIDTH = Int(UIScreen.main.bounds.size.width)
static let SCREEN_HEIGHT = Int(UIScreen.main.bounds.size.height)
static let SCREEN_MAX_LENGTH = Int( max(SCREEN_WIDTH, SCREEN_HEIGHT) )
static let SCREEN_MIN_LENGTH = Int( min(SCREEN_WIDTH, SCREEN_HEIGHT) )
static let IS_IPHONE_4_OR_LESS = IS_IPHONE && SCREEN_MAX_LENGTH < 568
static let IS_IPHONE_5 = IS_IPHONE && SCREEN_MAX_LENGTH == 568
static let IS_IPHONE_6 = IS_IPHONE && SCREEN_MAX_LENGTH == 667
static let IS_IPHONE_6P = IS_IPHONE && SCREEN_MAX_LENGTH == 736
static let IS_IPHONE_X = IS_IPHONE && SCREEN_MAX_LENGTH >= 812
}
| true
|
35b3a932a62d5a2953ae7238ecabe25b240a31e5
|
Swift
|
Try64/WeatherApp
|
/WeatherApp/ViewController.swift
|
UTF-8
| 1,749
| 2.65625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// WeatherApp
//
// Created by studentNumber13 on 5/12/17.
// Copyright © 2017 studentNumber13. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController , CLLocationManagerDelegate{
let manager = CLLocationManager()
var currentLocation:CLLocation?
var ansArray:[String]?
var one:String?
var two:String?
var three:String?
@IBOutlet var LabelTemperature: UILabel!
@IBOutlet var LabelWindSpeed: UILabel!
@IBOutlet var LabelHumidity: UILabel!
@IBOutlet var ShowTemperature: UILabel!
@IBOutlet var ShowWindspeed: UILabel!
@IBOutlet var ShowHumidity: UILabel!
@IBAction func buttonPressed(_ sender: Any) {
let tryObj = NetworkPortion(CoOrdinate: currentLocation!)
tryObj.getTheInfo()
// = tryObj.returnData()
//print(ansArray![0])
one? = (tryObj.me?.a)!
two? = (tryObj.me?.b)!
three? = (tryObj.me?.c)!
print((tryObj.me?.a)!)
}
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
manager.desiredAccuracy = kCLLocationAccuracyBest
//let url = URL(string: <#T##String#>)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
currentLocation = locations[0] as CLLocation
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print (error)
}
}
| true
|
60551a1162ea7aaf726e60726647ae30017d9a83
|
Swift
|
Maxelnot/Yelpy
|
/Yelp/BusinessCell.swift
|
UTF-8
| 1,444
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// BusinessCell.swift
// Yelp
//
// Created by Cong Tam Quang Hoang on 14/02/17.
// Copyright © 2017 Timothy Lee. All rights reserved.
//
import UIKit
class BusinessCell: UITableViewCell {
@IBOutlet weak var restRatings: UIImageView!
@IBOutlet weak var restDistance: UILabel!
@IBOutlet weak var restPhoto: UIImageView!
@IBOutlet weak var restName: UILabel!
@IBOutlet weak var restAddress: UILabel!
@IBOutlet weak var restTags: UILabel!
@IBOutlet weak var restReview: UILabel!
var business: Business! {
didSet {
restName.text = business.name
restName.sizeToFit()
if business.imageURL != nil {
restPhoto.setImageWith(business.imageURL!)
}
restTags.text = business.categories
restAddress.text = business.address
restReview.text = "\(business.reviewCount!) Reviews"
restRatings.setImageWith(business.ratingImageURL!)
restDistance.text = business.distance
}
}
override func layoutSubviews() {
super.layoutSubviews()
}
override func awakeFromNib() {
super.awakeFromNib()
restPhoto.layer.cornerRadius = 5
restPhoto.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| true
|
df7eacdd162582e933dac7a74d4a06141c2514e6
|
Swift
|
nguyentruongky/LogInExtensionSample_Start
|
/LogInExtensionSample_Start/DataValidationExtension.swift
|
UTF-8
| 1,071
| 2.9375
| 3
|
[] |
no_license
|
//
// DataValidationExtension.swift
// LogInExtensionSample_Start
//
// Created by Ky Nguyen on 1/14/16.
// Copyright © 2016 Ky Nguyen. All rights reserved.
//
import Foundation
import UIKit
extension ViewController : UITextFieldDelegate {
func isValidEmail(email: String) -> Bool {
let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluateWithObject(email)
}
func isValidPassword(pass: String) -> Bool {
// Check your password requirement here
return pass.characters.count > 4 ? true: false
}
func handleLogInButtonEnable() {
if (isValidEmail(emailTextField.text!) && isValidPassword(passwordTextField.text!) == true) {
enabledButton(loginButton)
}
else {
disabledButton(loginButton)
}
}
}
| true
|
e9b2bd6c68624558a528e968ebec8172101dc838
|
Swift
|
kslive/VKClient
|
/VK Client/News/Controller/NewsViewController.swift
|
UTF-8
| 3,155
| 2.875
| 3
|
[] |
no_license
|
//
// NewsViewController.swift
// VK Client
//
// Created by Eugene Kiselev on 31.08.2020.
// Copyright © 2020 Eugene Kiselev. All rights reserved.
//
import UIKit
class NewsViewController: UIViewController {
private let refreshControl = UIRefreshControl()
private let networkManager = NetworkManager()
private var nextFrom = ""
private var isLoading = false
var news = [NewsModel]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.prefetchDataSource = self
fetchRequestNews()
setupRefreshControl()
}
func setupRefreshControl() {
refreshControl.tintColor = .white
refreshControl.addTarget(self, action: #selector(reload), for: .valueChanged)
tableView.addSubview(refreshControl)
}
func fetchRequestNews(nextFrom: String = "" ,callback: (([NewsModel], String?) -> ())? = nil) {
networkManager.fetchRequestNews(startFrom: nextFrom) { [weak self] (news, nextFrom) in
self?.nextFrom = nextFrom
self?.news = news
callback?(news,nextFrom)
OperationQueue.main.addOperation {
self?.tableView.reloadData()
}
}
}
}
// MARK: ACTION
extension NewsViewController {
@objc private func reload() {
fetchRequestNews { [weak self] (news,_) in
guard let self = self else { return }
self.refreshControl.endRefreshing()
guard news.count > 0 else { return }
self.news = news + self.news
}
}
}
// MARK: TABLE VIEW DATA SOURCE
extension NewsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return news.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NewsCell", for: indexPath) as! NewsCell
let newsItem = news[indexPath.row]
cell.configure(for: newsItem)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}
// MARK: PREFETCHING
extension NewsViewController: UITableViewDataSourcePrefetching {
func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
guard let maxRow = indexPaths
.map({ $0.row })
.max()
else { return }
if maxRow > news.count - 3,
!isLoading {
isLoading = true
fetchRequestNews(nextFrom: nextFrom) { [weak self] (news,_) in
guard let self = self else { return }
self.news.append(contentsOf: news)
self.isLoading = false
}
}
}
}
| true
|
08137af8f9aeb7ba9bf1a004543a1d4f5bf190b6
|
Swift
|
ericandrewmeadows/pregnancy_stress_app
|
/Calmlee/WalkthroughViewController.swift
|
UTF-8
| 3,200
| 2.5625
| 3
|
[] |
no_license
|
//
// WalkthroughViewController.swift
// Calmlee
//
// Created by Eric Meadows on 5/26/16.
// Copyright © 2016 Calmlee. All rights reserved.
//
import UIKit
@IBDesignable class WalkthroughViewController: UIViewController {
// UI Elements
@IBOutlet weak var walkthroughQuipSection: WalkthroughQuipSection?
@IBOutlet weak var walkthroughImage: UIImageView!
@IBOutlet weak var pageProgress: UILabel!
var bandIcon: UIImage = UIImage(named: "BandIcon")!
var calmGirl: UIImage = UIImage(named: "CalmGirlFace")!
var happyGirl: UIImage = UIImage(named: "HappyGirlFace")!
var width: CGFloat = 0
var height: CGFloat = 0
var wI_w: CGFloat = 0
var wI_h: CGFloat = 0
var wI_x: CGFloat = 0
var wI_y: CGFloat = 0
// Walkthrough Quip items
var quipPage = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.width = self.view.bounds.width
self.height = self.view.bounds.height
var newFrame : CGRect = CGRectMake(0, self.height / 2, self.width, self.height / 2)
self.walkthroughQuipSection!.frame = newFrame
// newFrame = CGRectMake(0, self.height * 27 / 400, self.width, self.height * 3 / 100)
newFrame = CGRectMake(0, self.height * 44 / 100, self.width, self.height * 3 / 100)
self.pageProgress.frame = newFrame
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func goTo_nextQuip(sender: AnyObject?) {
self.quipPage += 1
self.walkthroughQuipSection!.walkthroughQuip.text = switchQuip(self.quipPage)
walkthroughImage.frame = CGRectMake(self.wI_x,
self.wI_y,
self.wI_w,
self.wI_h)
}
func switchQuip(quipNum: Int) -> String {
// Standard Layout items
self.wI_h = self.height * 9 / 100
self.wI_y = self.height * 23 / 100
// Default due to majority of images (2/3)
self.wI_w = self.wI_h * 5 / 6
self.wI_x = (self.width - self.wI_w) / 2
switch quipNum {
case 1:
walkthroughImage.image = self.bandIcon
self.wI_w = self.wI_h * 5 / 4
self.wI_x = (self.width - self.wI_w * 11 / 15) / 2
pageProgress.text = "1 of 3"
return "Detect stress in real time"
case 2:
walkthroughImage.image = self.calmGirl
pageProgress.text = "2 of 3"
return "Learn the most effective ways to manage stress for you"
case 3:
walkthroughImage.image = self.happyGirl
pageProgress.text = "3 of 3"
return "Live life with a clear mind"
case 4:
self.performSegueWithIdentifier("goto_calmleeScore", sender: nil)
return ""
default:
return "OOOOOOOOOOOOOOOOOOOOOO"
}
}
}
| true
|
f2bceb1adf0e69585a05e37ee2761fdb03d70514
|
Swift
|
ra7bi/swift-hoody-app
|
/MyHood/Post.swift
|
UTF-8
| 1,487
| 3.078125
| 3
|
[] |
no_license
|
//
// Post.swift
// MyHood
//
// Created by fahad alrahbi on 3/5/16.
// Copyright © 2016 FahadCoder. All rights reserved.
//
import Foundation
// nsobject and nscodeing for arciving
class Post:NSObject,NSCoding {
private var _imagePath: String!
private var _title:String!
private var _postDesc:String!
var imagePath:String {
return _imagePath
}
var title:String {
return _title
}
var postDesc:String {
return _postDesc
}
init(imagePath:String, title:String, postDesc:String)
{
self._imagePath = imagePath
self._title = title
self._postDesc = postDesc
}
override init() {
}
// - Mark Protocol
// We have to emplement it only , it will call automaticaly both functions
required convenience init?(coder aDecoder: NSCoder) {
self.init()
self._imagePath = aDecoder.decodeObjectForKey("imagePath") as? String
self._title = aDecoder.decodeObjectForKey("title") as? String
self._postDesc = aDecoder.decodeObjectForKey("description") as? String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self._imagePath, forKey: "imagePath")
aCoder.encodeObject(self._title, forKey: "title")
aCoder.encodeObject(self._postDesc, forKey: "description")
}
}
| true
|
946d4cd641663c7d95b8eada91edbe335389fa10
|
Swift
|
cghost182/TheAgileMonkey
|
/TheAgileMonkey/TheAgileMonkey/Modules/AlbumsView/AlbumsViewController.swift
|
UTF-8
| 2,987
| 2.5625
| 3
|
[] |
no_license
|
import Foundation
import UIKit
private struct Constants {
static let albumCellReusableIdentifier = "AlbumTableViewCell"
}
protocol AlbumsViewProtocol: class {
func refreshTable()
func showError()
}
class AlbumsViewController: UIViewController {
//MARK: - Outlets
@IBOutlet weak var albumTableView: UITableView!
@IBOutlet weak var errorLabel: UILabel!
//MARK: - Properties
var presenter: AlbumsPresenterInput?
//MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
presenter?.updateView()
showSpinner()
}
private func configureView() {
title = self.presenter?.getArtistName()
setupTableView()
setupBackButton()
setupErrorLabel(isHidden: true)
}
private func setupTableView() {
albumTableView.dataSource = self
albumTableView.delegate = self
}
private func setupBackButton() {
let backButton = UIButton(type: .custom)
backButton.setImage(#imageLiteral(resourceName: "backArrow"), for: .normal)
backButton.adjustsImageWhenHighlighted = false
backButton.addTarget(self, action: #selector(backButtonPressed), for: .touchUpInside)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
}
private func setupErrorLabel(isHidden: Bool) {
DispatchQueue.main.async {
self.errorLabel.isHidden = isHidden
}
}
@objc func backButtonPressed() {
DispatchQueue.main.async { [weak self] in
self?.navigationController?.popViewController(animated: true)
}
}
}
extension AlbumsViewController: AlbumsViewProtocol {
func refreshTable() {
DispatchQueue.main.async {
self.hideSpinner()
self.setupErrorLabel(isHidden: true)
self.albumTableView.reloadData()
}
}
func showError() {
hideSpinner()
setupErrorLabel(isHidden: false)
}
}
extension AlbumsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
presenter?.albumsArray.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = albumTableView.dequeueReusableCell(withIdentifier: Constants.albumCellReusableIdentifier, for: indexPath) as! AlbumTableViewCell
cell.configure(with: presenter?.albumsArray[indexPath.row])
return cell
}
}
extension AlbumsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let albumSelected = presenter?.albumsArray[indexPath.row]
presenter?.navigateToSongsView(with: albumSelected)
}
}
| true
|
a37d065313535ebe75dbb23cc919f56ef5e63334
|
Swift
|
ABGitRu/MVVM2
|
/MVVM2/DetailView/View/DetailViewController.swift
|
UTF-8
| 1,835
| 3.03125
| 3
|
[] |
no_license
|
//
// DetailViewController.swift
// MVVM2
//
// Created by Mac on 03.08.2021.
//
import UIKit
class DetailViewController: UIViewController {
var viewModel: DetailViewModelType? {
didSet {
guard let viewModel = viewModel else { return }
textLabel.text = viewModel.personDescription
}
}
var textLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = .zero
label.textColor = .white
label.font = UIFont(name: "Copperplate", size: 30)
return label
}()
override func loadView() {
super.loadView()
view.addSubview(textLabel)
view.backgroundColor = .red
}
override func viewDidLoad() {
super.viewDidLoad()
viewModel?.age.bind { [unowned self] in
guard let string = $0 else { return }
self.textLabel.text = string
}
delay(delay: 5) { [unowned self] in
self.viewModel?.age.value = "Let's return to persons"
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
setConstraints()
}
private func delay(delay: Double, closure: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(wallDeadline: .now() + delay) {
closure()
}
}
private func setConstraints() {
let constraints = [
textLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
textLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 5),
textLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -5)
]
NSLayoutConstraint.activate(constraints)
}
}
| true
|
5fae00af2503a46e38a8558a0033594c3e049263
|
Swift
|
Ajwinarski/Cards
|
/Shared/Sprites/Buttons/TRIWireButton.swift
|
UTF-8
| 2,911
| 2.703125
| 3
|
[] |
no_license
|
//
// TRIWireButton.swift
// Tripeak
//
// Created by CodeCaptain on 1/7/16.
// Copyright © 2016 CodeCaptain. All rights reserved.
//
import SpriteKit
class TRIWireButton: TRIBaseButton {
var action: Selector?
var border: SKShapeNode!
var label: SKLabelNode!
var icon: SKSpriteNode!
convenience init(color: SKColor, size: CGSize, title: String) {
self.init()
self.size = size
let position = CGPoint(x: 0, y: 0)
let borderSize = CGSize(width: size.width, height: size.height)
self.border = SKShapeNode(
rect: CGRect(
origin: position,
size: borderSize
),
cornerRadius: 2.0
)
self.border.lineWidth = 4.0
self.border.strokeColor = color
self.border.position = CGPoint(
x: -size.width / 2,
y: -size.height / 2
)
self.addChild(self.border)
self.label = SKLabelNode(text: title)
self.addChild(self.label)
self.label.fontSize = 24
self.label.fontName = Fonts.HelveticaNeueLight.rawValue
self.label.horizontalAlignmentMode = .Center
self.label.verticalAlignmentMode = .Center
self.updateHover(false, hover: self.hover)
}
convenience init(color: SKColor, size: CGSize, title: String, image: String) {
self.init()
self.size = size
self.icon = SKSpriteNode(imageNamed: image)
let aspectRatio = self.icon.size.width / self.icon.size.height
let newSize = size.height * 0.5
self.icon.size = CGSize(
width: newSize,
height: newSize / aspectRatio
)
self.addChild(self.icon)
let position = CGPoint(x: 0, y: 0)
let size = CGSize(width: size.width, height: size.height)
self.border = SKShapeNode(
rect: CGRect(
origin: position,
size: size
),
cornerRadius: 2.0
)
self.border.lineWidth = 4.0
self.border.strokeColor = color
self.border.lineJoin = .Round
self.border.position = CGPoint(
x: -size.width / 2,
y: -size.height / 2
)
self.addChild(self.border)
self.label = SKLabelNode(text: title)
self.addChild(self.label)
self.label.fontName = Fonts.HelveticaNeueLight.rawValue
self.label.position = CGPoint(
x: self.label.position.x,
y: -self.size.height / 2
)
self.updateHover(false, hover: self.hover)
}
override func updateHover(animated: Bool, hover: Bool) {
var alpha: CGFloat = 1.0
if !hover {
alpha = 0.25
}
if animated {
let action: SKAction = SKAction.fadeAlphaTo(alpha, duration: 0.1)
self.border.runAction(action)
self.label.runAction(action)
} else {
self.border.alpha = alpha
self.label.alpha = alpha
}
}
func updateLabelPosition() {
self.label.position = CGPoint(
x: self.label.position.x,
y: self.label.position.y - self.label.fontSize - 20
)
}
}
| true
|
97c755a42d8b949d9522a4b38a32bbe25d80459b
|
Swift
|
smd2m80/michel
|
/michel/michel/sumi/ZoomscrollView.swift
|
UTF-8
| 3,733
| 2.859375
| 3
|
[] |
no_license
|
import UIKit
import AVFoundation
class ZoomscrollView: UIView, UIScrollViewDelegate {
var scrollView: UIScrollView! = nil
var imageView: UIImageView! = nil
override init(frame: CGRect) {
super.init(frame: frame)
myInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
myInit()
}
override func layoutSubviews() {
super.layoutSubviews()
scrollView.frame = self.bounds
imageView.frame = scrollView.bounds
}
/// 初期化
func myInit() {
// ScrollViewを作成
scrollView = UIScrollView()
scrollView.minimumZoomScale = 1
scrollView.maximumZoomScale = 5
scrollView.isScrollEnabled = true
scrollView.zoomScale = 1
scrollView.contentSize = self.bounds.size
scrollView.delegate = self
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.backgroundColor = UIColor.black
self.addSubview(scrollView)
// 画像を作成
let image = UIImage(named: "3")
imageView = UIImageView(image: image)
imageView.isUserInteractionEnabled = true // 画像がタップできるようにする
imageView.contentMode = UIView.ContentMode.scaleAspectFit
scrollView.addSubview(imageView)
}
// MARK: - UIScrollViewDelegate
/// ズームしたいUIViewを返す
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
/// ズーム変更
func scrollViewDidZoom(_ scrollView: UIScrollView) {
self.updateImageCenter()
}
/// ズーム完了
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
self.updateImageCenter()
}
/// ズーム時の矩形を求める
/// - parameter scale: 拡大率
/// - parameter center: 中央の座標
/// - returns: ズーム後の表示エリア
func zoomRectForScale(scale:CGFloat, center: CGPoint) -> CGRect{
var zoomRect: CGRect = CGRect()
zoomRect.size.height = self.frame.size.height / scale
zoomRect.size.width = self.frame.size.width / scale
zoomRect.origin.x = center.x - zoomRect.size.width / 2.0
zoomRect.origin.y = center.y - zoomRect.size.height / 2.0
return zoomRect
}
/// ズーム後の画像の位置を調整する
func updateImageCenter() {
let image = imageView.image
// UIViewContentMode.ScaleAspectFit時のUIImageViewの画像サイズを求める
let frame = AVMakeRect(aspectRatio: image!.size, insideRect: imageView.bounds)
var imageSize = CGSize(width: frame.size.width, height: frame.size.height)
imageSize.width *= scrollView.zoomScale
imageSize.height *= scrollView.zoomScale
var point: CGPoint = CGPoint.zero
point.x = imageSize.width / 2
if imageSize.width < scrollView.bounds.width {
point.x += (scrollView.bounds.width - imageSize.width) / 2
}
point.y = imageSize.height / 2
if imageSize.height < scrollView.bounds.height {
point.y += (scrollView.bounds.height - imageSize.height) / 2
}
imageView.center = point
}
}
extension UIScrollView {
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.next?.touchesBegan(touches, with: event)
print("touchesBegan")
}
}
| true
|
8dc311149ba782f110852907b15062043b57a67a
|
Swift
|
bow-swift/bow
|
/Sources/Bow/Data/SetK.swift
|
UTF-8
| 2,597
| 3.671875
| 4
|
[
"Apache-2.0"
] |
permissive
|
import Foundation
/// Witness for the `SetK<A>` data type. To be used in simulated Higher Kinded Types.
public final class ForSetK {}
/// Partial application of the SetK type constructor, omitting the last type parameter.
public typealias SetKPartial = ForSetK
/// Higher Kinded Type alias to improve readability over `Kind<ForSetK, A>`.
public typealias SetKOf<A> = Kind<ForSetK, A>
/// An unordered collection of unique elements, wrapped to act as a Higher Kinded Type.
public final class SetK<A: Hashable>: SetKOf<A> {
fileprivate let set: Set<A>
/// Union of two sets.
///
/// - Parameters:
/// - lhs: Left hand side of the union.
/// - rhs: Right hand side of the union.
/// - Returns: A new set that includes all elements present in both sets.
public static func +(lhs: SetK<A>, rhs: SetK<A>) -> SetK<A> {
SetK(lhs.set.union(rhs.set))
}
/// Safe downcast.
///
/// - Parameter fa: Value in the higher-kind form.
/// - Returns: Value cast to SetK.
public static func fix(_ fa: SetKOf<A>) -> SetK<A> {
fa as! SetK<A>
}
/// Initializes a `SetK` with the elements of a `Swift.Set`.
///
/// - Parameter set: A set of elements to be wrapped in this `SetK`.
public init(_ set: Set<A>) {
self.set = set
}
/// Initializes a `SetK` from a variable number of elements.
///
/// - Parameter elements: Values to be wrapped in this `SetK`.
public init(_ elements: A...) {
self.set = Set(elements)
}
/// Extracts a `Swift.Set` from this wrapper.
public var asSet: Set<A> {
self.set
}
/// Combines this set with another using the union of the underlying `Swift.Set`s.
///
/// - Parameter y: A set
/// - Returns: A set containing the elements of the two sets.
public func combineK(_ y: SetK<A>) -> SetK<A> {
self + y
}
}
/// Safe downcast.
///
/// - Parameter fa: Value in higher-kind form.
/// - Returns: Value cast to SetK.
public postfix func ^<A>(_ fa: SetKOf<A>) -> SetK<A> {
SetK.fix(fa)
}
// MARK: Instance of Semigroup for SetK
extension SetK: Semigroup {
public func combine(_ other: SetK<A>) -> SetK<A> {
self + other
}
}
// MARK: Instance of Monoid for SetK
extension SetK: Monoid {
public static func empty() -> SetK<A> {
SetK(Set([]))
}
}
// MARK: Set extensions
public extension Set {
/// Wraps this set into a `SetK`.
///
/// - Returns: A `SetK` that contains the elements of this set.
func k() -> SetK<Element> {
SetK(self)
}
}
| true
|
8c4ed83b750a37e22ba81106738c3a3cdade5e8a
|
Swift
|
pdramoss/PokedexV2
|
/PokedexV2/PokedexV2/Extension/Int-Extension.swift
|
UTF-8
| 153
| 2.96875
| 3
|
[] |
no_license
|
//
import Foundation
extension Int {
func numberWithZeros(number: Int = 4) -> String {
return String(format: "%0\(number)d", self)
}
}
| true
|
2be81dde2301ef3d7fd4dc5afb87e15c2ed73ae9
|
Swift
|
quding0308/KDAlgorithmKit
|
/KDAlgorithmKit/Classes/DataStructure/Queue.swift
|
UTF-8
| 2,107
| 3.84375
| 4
|
[
"MIT"
] |
permissive
|
//
// Queue.swift
// KDTool
//
// Created by hour on 2018/8/7.
//
/*
Queue
A queue is a list where you can only insert new items at the back and
remove items from the front. This ensures that the first item you enqueue
is also the first item you dequeue. First come, first serve!
A queue gives you a FIFO or first-in, first-out order. The element you
inserted first is also the first one to come out again. It's only fair!
In this implementation, enqueuing is an O(1) operation, dequeuing is O(n).
*/
/*
public struct Queue<T> {
fileprivate var array = [T]()
public var isEmpty: Bool {
return array.isEmpty
}
public var count: Int {
return array.count
}
public mutating func enqueue(_ element: T) {
array.append(element)
}
public mutating func dequeue() -> T? {
if isEmpty {
return nil
} else {
return array.removeFirst()
}
}
public var front: T? {
return array.first
}
}
*/
/*
First-in first-out queue (FIFO)
New elements are added to the end of the queue. Dequeuing pulls elements from
the front of the queue.
Enqueuing and dequeuing are O(1) operations.
*/
public struct Queue<T> {
fileprivate var array = [T?]()
fileprivate var head = 0
public var count: Int {
return array.count - head
}
public var isEmpty: Bool {
return count == 0
}
public mutating func enqueue(_ element: T) {
array.append(element)
}
public mutating func dequeue() -> T? {
guard head < array.count, let element = array[head] else { return nil }
array[head] = nil
head += 1
let percentage = Double(head) / Double(array.count)
if array.count > 50 && percentage > 0.25 {
array.removeFirst(head)
head = 0
}
return element
}
public var front: T? {
if isEmpty {
return nil
} else {
return array[head]
}
}
}
| true
|
cd1d295c5454c1d708940ec3ea8878b15b346e84
|
Swift
|
winterdl/Boast
|
/Boast/views/login/AuthenticationView.swift
|
UTF-8
| 6,143
| 2.625
| 3
|
[] |
no_license
|
//
// AuthenticationView.swift
// Boast
//
// Created by David Keimig on 9/15/20.
//
import SwiftUI
import Firebase
import FirebaseAuth
import FirebaseUI
struct AuthenticationView: View {
let createUserStore: CreateUserStore = CreateUserStore()
@State var username: String = ""
@State var password: String = ""
@State var isSignUp: Bool = false
@Environment(\.colorScheme) var colorScheme: ColorScheme
@StateObject var emailState = EnhancedTextFieldState()
@StateObject var passwordState = EnhancedTextFieldState()
func getTintColor() -> Color {
if self.colorScheme == .light {
return Color(UIColor.systemBackground.darker(by: 10.0)!)
} else {
return Color(UIColor.systemBackground.lighter(by: 10.0)!)
}
}
func onUsernameComplete() {
passwordState.isActive = true
}
func onPasswordComplete() {
print(self.username)
print(self.password)
Auth.auth().signIn(withEmail: self.username, password: self.password) { (result, error) in
print(error)
}
}
var body: some View {
NavigationView {
VStack {
Text("Boast")
.font(.largeTitle)
.bold()
.padding()
ScrollView {
VStack {
EnhancedTextField(
placeholder: "Username",
text: self.$username,
enhancedTextFieldState: emailState,
onComplete: self.onUsernameComplete,
autocomplete: false,
autocaptialize: .none,
keyboardType: .emailAddress
)
.frame(minWidth: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, idealWidth: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, minHeight: 50, idealHeight: 50, maxHeight: 50, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.cornerRadius(6)
.padding([.leading, .top, .trailing])
EnhancedTextField(
placeholder: "Password",
text: self.$password,
enhancedTextFieldState: passwordState,
onComplete: self.onPasswordComplete,
autocomplete: false,
autocaptialize: .none,
keyboardType: .default,
isSecureTextEntry: true
)
.frame(minWidth: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, idealWidth: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, minHeight: 50, idealHeight: 50, maxHeight: 50, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.cornerRadius(6)
.padding()
Button(action: {
self.onPasswordComplete()
}, label: {
Text("Log in")
.bold()
.frame(minWidth: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, idealWidth: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, minHeight: 50, idealHeight: 50, maxHeight: 50, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.foregroundColor(.white)
.background(Color.accentColor)
.cornerRadius(6)
.padding([.leading, .trailing])
})
HStack {
Rectangle()
.fill(Color(UIColor.separator))
.frame(minWidth: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, idealWidth: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, minHeight: 1, idealHeight: 1, maxHeight: 1, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
Text("OR")
.font(.caption)
.bold()
.foregroundColor(Color(UIColor.separator))
Rectangle()
.fill(Color(UIColor.separator))
.frame(minWidth: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, idealWidth: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, minHeight: 1, idealHeight: 1, maxHeight: 1, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
}
.padding()
FacebookView()
.padding(.bottom)
GitHubView()
.padding(.bottom)
}
}
Spacer()
Divider()
HStack {
Text("Don't have an account?")
.font(.caption)
.foregroundColor(.secondary)
NavigationLink(
destination: SignUpView(),
isActive: self.$isSignUp,
label: {
Text("Sign Up.")
.font(.caption)
}
)
}
.padding([.top, .bottom])
}
.navigationBarHidden(true)
}
.environmentObject(createUserStore)
}
}
struct AuthenticationView_Previews: PreviewProvider {
static var previews: some View {
AuthenticationView()
}
}
| true
|
6bfd90e8a6faf64cd38bc59c1a22832e1fd8d40e
|
Swift
|
team360r/RealmCoder
|
/Tests/RealmCoderTests/ModelTests/MuppetTests.swift
|
UTF-8
| 1,920
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// MuppetTests.swift
// RealmCoderTests
//
// Created by Jay Lyerly on 10/9/19.
// Copyright © 2019 Oak City Labs. All rights reserved.
//
import RealmCoder
import RealmSwift
import XCTest
/// Test Notes:
/// MuppetTests excercises these specific aspects of the RealmCoder
/// - Updating objects identified by primary key from multiple JSON chunks
///
final class MuppetTests: XCTestCase {
var coder: RealmCoder!
override func setUp() {
super.setUp()
guard let realm = try? realmFactory() else {
XCTFail("Can't get a realm from the factory.")
return
}
coder = RealmCoder(realm: realm)
}
override func tearDown() {
coder = nil
super.tearDown()
}
func loadJson(fromFile filename: String) -> Data? {
guard let data = data(fromFile: filename) else {
XCTFail("Can't read test data from file \(filename)")
return nil
}
return data
}
func testDecodeMuppetJson() throws {
let data1 = loadJson(fromFile: "muppet_part1.json")!
let data2 = loadJson(fromFile: "muppet_part2.json")!
let muppet = try coder.decode(Muppet.self, from: data1)
XCTAssertEqual(muppet.objId, "qwerqer-xvbxvb-asdfasdfas")
XCTAssertEqual(muppet.name, "Fozzie")
XCTAssertEqual(muppet.gender, "male")
XCTAssertNil(muppet.species)
XCTAssertNil(muppet.occupation)
let muppet2 = try coder.decode(Muppet.self, from: data2)
XCTAssertEqual(muppet2.objId, "qwerqer-xvbxvb-asdfasdfas")
XCTAssertEqual(muppet2.name, "Fozzie")
XCTAssertEqual(muppet2.gender, "male")
XCTAssertEqual(muppet2.species, "bear")
XCTAssertEqual(muppet2.occupation, "comedian")
}
static var allTests = [
("testDecodeMuppetJson", testDecodeMuppetJson)
]
}
| true
|
f739e14d7031f25fef7ca6a7c214312cc1cd37b6
|
Swift
|
psharanda/AnyCoder
|
/Sources/Decoder.swift
|
UTF-8
| 27,083
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
//
// Created by Pavel Sharanda on 29.09.16.
// Copyright © 2016 Pavel Sharanda. All rights reserved.
//
import Foundation
public protocol AnyDecodable {
init?(decoder: AnyDecoder) throws
}
public protocol AnyValueDecodable {
associatedtype ValueType
init?(value: ValueType) throws
}
//MARK: - AnyDecoder
public protocol AnyDecoder {
func anyValue(forKey: String) -> Any?
}
extension Dictionary: AnyDecoder {
public func anyValue(forKey key: String) -> Any? {
if let key = key as? Key {
return self[key]
} else {
return nil
}
}
}
extension NSDictionary: AnyDecoder {
public func anyValue(forKey key: String) -> Any? {
return self[key]
}
}
extension AnyDecoder {
public func decoder(forKey key: String) throws -> AnyDecoder {
if let value = anyValue(forKey: key) {
return try castValue(value) { $0 }
} else {
throw DecoderErrorType.missing.error
}
}
public func decoder(forKey key: String, throwIfMissing: Bool = false) throws -> AnyDecoder? {
if let value = anyValue(forKey: key) {
return try doActionHandlingNull(value: value) {
return try castValue(value) { $0 }
}
} else {
if throwIfMissing {
throw DecoderErrorType.missing.error
} else {
return nil
}
}
}
public func decode<T: AnyDecodable>() throws -> T {
return try decode(transform: T.init)
}
public func decode<T>(transform: (AnyDecoder) throws ->T? ) throws -> T {
if let value = try transform(self) {
return value
} else {
throw DecoderErrorType.failed(T.self, self).error
}
}
public func decode<T: AnyDecodable>() throws -> T? {
return try decode(transform: T.init)
}
public func decode<T>(transform: (AnyDecoder) throws ->T? ) throws -> T? {
return try transform(self)
}
//MARK:- handle object decode
private func handleObjectDecode<T, U>(key: String, action: (T) throws -> U) throws -> U {
return try commitAction(path: .key(key)) {
if let value = anyValue(forKey: key) {
return try castValue(value, action: action)
} else {
throw DecoderErrorType.missing.error
}
}
}
private func handleObjectDecode<T, U>(key: String, throwIfMissing: Bool, action: (T) throws -> U?) throws -> U? {
return try commitAction(path: .key(key)) {
if let value = anyValue(forKey: key) {
return try doActionHandlingNull(value: value) {
return try castValue(value, action: action)
}
} else {
if throwIfMissing {
throw DecoderErrorType.missing.error
} else {
return nil
}
}
}
}
private func handleObjectDecode<T, U>(key: String, valueIfMissing: U, action: (T) throws -> U) throws -> U {
return try commitAction(path: .key(key)) {
if let value = anyValue(forKey: key) {
return try castValue(value, action: action)
} else {
return valueIfMissing
}
}
}
//MARK: - object - object
public func decode<T: AnyDecodable>(key: String) throws -> T {
return try decode(key: key, transform: T.init)
}
public func decode<T>(key: String, transform: (AnyDecoder) throws ->T?) throws -> T {
return try handleObjectDecode(key: key) { (decoder: AnyDecoder) -> T in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyDecodable>(key: String, throwIfMissing: Bool = false) throws -> T? {
return try decode(key: key, throwIfMissing: throwIfMissing, transform: T.init)
}
public func decode<T>(key: String, throwIfMissing: Bool = false, transform: (AnyDecoder) throws ->T?) throws -> T? {
return try handleObjectDecode(key: key, throwIfMissing: throwIfMissing) { (decoder: AnyDecoder) -> T? in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyDecodable>(key: String, valueIfMissing: T) throws -> T {
return try decode(key: key, valueIfMissing: valueIfMissing, transform: T.init)
}
public func decode<T>(key: String, valueIfMissing: T, transform: (AnyDecoder) throws ->T?) throws -> T {
return try handleObjectDecode(key: key, valueIfMissing: valueIfMissing) { (decoder: AnyDecoder) -> T in
try decoder.decode(transform: transform)
}
}
//MARK: - object - value
public func decode<T: AnyValueDecodable>(key: String) throws -> T {
return try decode(key: key, transform: T.init)
}
public func decode<T, ValueType>(key: String, transform: (ValueType) throws ->T?) throws -> T {
return try handleObjectDecode(key: key) { (value: Any) -> T in
try Decoding.decode(value, transform: transform)
}
}
public func decode<T: AnyValueDecodable>(key: String, throwIfMissing: Bool = false) throws -> T? {
return try decode(key: key, throwIfMissing: throwIfMissing, transform: T.init)
}
public func decode<T, ValueType>(key: String, throwIfMissing: Bool = false, transform: (ValueType) throws ->T?) throws -> T? {
return try handleObjectDecode(key: key, throwIfMissing: throwIfMissing) { (value: Any) -> T? in
try Decoding.decode(value, transform: transform)
}
}
public func decode<T: AnyValueDecodable>(key: String, valueIfMissing: T) throws -> T {
return try decode(key: key, valueIfMissing: valueIfMissing, transform: T.init)
}
public func decode<T, ValueType>(key: String, valueIfMissing: T, transform: (ValueType) throws ->T?) throws -> T {
return try handleObjectDecode(key: key, valueIfMissing: valueIfMissing) { (value: Any) -> T in
try Decoding.decode(value, transform: transform)
}
}
//MARK: - array - object
public func decode<T: AnyDecodable>(key: String) throws -> [T] {
return try decode(key: key, transform: T.init)
}
public func decode<T>(key: String, transform: (AnyDecoder) throws ->T?) throws -> [T] {
return try handleObjectDecode(key: key) { (decoder: ArrayDecoder) -> [T] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyDecodable>(key: String, throwIfMissing: Bool = false) throws -> [T]? {
return try decode(key: key, throwIfMissing: throwIfMissing, transform: T.init)
}
public func decode<T>(key: String, throwIfMissing: Bool = false, transform: (AnyDecoder) throws ->T?) throws -> [T]? {
return try handleObjectDecode(key: key, throwIfMissing: throwIfMissing) { (decoder: ArrayDecoder) -> [T] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyDecodable>(key: String, valueIfMissing: [T]) throws -> [T] {
return try decode(key: key, valueIfMissing: valueIfMissing, transform: T.init)
}
public func decode<T>(key: String, valueIfMissing: [T], transform: (AnyDecoder) throws ->T?) throws -> [T] {
return try handleObjectDecode(key: key, valueIfMissing: valueIfMissing) { (decoder: ArrayDecoder) -> [T] in
try decoder.decode(transform: transform)
}
}
//MARK: - array - value
public func decode<T: AnyValueDecodable>(key: String) throws -> [T] {
return try decode(key: key, transform: T.init)
}
public func decode<T, ValueType>(key: String, transform: (ValueType) throws ->T?) throws -> [T] {
return try handleObjectDecode(key: key) { (decoder: ArrayDecoder) -> [T] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyValueDecodable>(key: String, throwIfMissing: Bool = false) throws -> [T]? {
return try decode(key: key, throwIfMissing: throwIfMissing, transform: T.init)
}
public func decode<T, ValueType>(key: String, throwIfMissing: Bool = false, transform: (ValueType) throws ->T?) throws -> [T]? {
return try handleObjectDecode(key: key, throwIfMissing: throwIfMissing) { (decoder: ArrayDecoder) -> [T] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyValueDecodable>(key: String, valueIfMissing: [T]) throws -> [T] {
return try decode(key: key, valueIfMissing: valueIfMissing, transform: T.init)
}
public func decode<T, ValueType>(key: String, valueIfMissing: [T], transform: (ValueType) throws ->T?) throws -> [T] {
return try handleObjectDecode(key: key, valueIfMissing: valueIfMissing) { (decoder: ArrayDecoder) -> [T] in
try decoder.decode(transform: transform)
}
}
//MARK: - nulllable array - object
public func decode<T: AnyDecodable>(key: String) throws -> [T?] {
return try decode(key: key, transform: T.init)
}
public func decode<T>(key: String, transform: (AnyDecoder) throws ->T?) throws -> [T?] {
return try handleObjectDecode(key: key) { (decoder: ArrayDecoder) -> [T?] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyDecodable>(key: String, throwIfMissing: Bool = false) throws -> [T?]? {
return try decode(key: key, throwIfMissing: throwIfMissing, transform: T.init)
}
public func decode<T>(key: String, throwIfMissing: Bool = false, transform: (AnyDecoder) throws ->T?) throws -> [T?]? {
return try handleObjectDecode(key: key, throwIfMissing: throwIfMissing) { (decoder: ArrayDecoder) -> [T?] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyDecodable>(key: String, valueIfMissing: [T?]) throws -> [T?] {
return try decode(key: key, valueIfMissing: valueIfMissing, transform: T.init)
}
public func decode<T>(key: String, valueIfMissing: [T?], transform: (AnyDecoder) throws ->T?) throws -> [T?] {
return try handleObjectDecode(key: key, valueIfMissing: valueIfMissing) { (decoder: ArrayDecoder) -> [T?] in
try decoder.decode(transform: transform)
}
}
//MARK: - nulllable array - value
public func decode<T: AnyValueDecodable>(key: String) throws -> [T?] {
return try decode(key: key, transform: T.init)
}
public func decode<T, ValueType>(key: String, transform: (ValueType) throws ->T?) throws -> [T?] {
return try handleObjectDecode(key: key) { (decoder: ArrayDecoder) -> [T?] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyValueDecodable>(key: String, throwIfMissing: Bool = false) throws -> [T?]? {
return try decode(key: key, throwIfMissing: throwIfMissing, transform: T.init)
}
public func decode<T, ValueType>(key: String, throwIfMissing: Bool = false, transform: (ValueType) throws ->T?) throws -> [T?]? {
return try handleObjectDecode(key: key, throwIfMissing: throwIfMissing) { (decoder: ArrayDecoder) -> [T?] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyValueDecodable>(key: String, valueIfMissing: [T?]) throws -> [T?] {
return try decode(key: key, valueIfMissing: valueIfMissing, transform: T.init)
}
public func decode<T, ValueType>(key: String, valueIfMissing: [T?], transform: (ValueType) throws ->T?) throws -> [T?] {
return try handleObjectDecode(key: key, valueIfMissing: valueIfMissing) { (decoder: ArrayDecoder) -> [T?] in
try decoder.decode(transform: transform)
}
}
//MARK: - dictionary - object
public func decode<T: AnyDecodable>(key: String) throws -> [String: T] {
return try decode(key: key, transform: T.init)
}
public func decode<T>(key: String, transform: (AnyDecoder) throws ->T?) throws -> [String: T] {
return try handleObjectDecode(key: key) { (decoder: [String: Any]) -> [String: T] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyDecodable>(key: String, throwIfMissing: Bool = false) throws -> [String: T]? {
return try decode(key: key, throwIfMissing: throwIfMissing, transform: T.init)
}
public func decode<T>(key: String, throwIfMissing: Bool = false, transform: (AnyDecoder) throws ->T?) throws -> [String: T]? {
return try handleObjectDecode(key: key, throwIfMissing: throwIfMissing) { (decoder: [String: Any]) -> [String: T] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyDecodable>(key: String, valueIfMissing: [String: T]) throws -> [String: T] {
return try decode(key: key, valueIfMissing: valueIfMissing, transform: T.init)
}
public func decode<T>(key: String, valueIfMissing: [String: T], transform: (AnyDecoder) throws ->T?) throws -> [String: T] {
return try handleObjectDecode(key: key, valueIfMissing: valueIfMissing) { (decoder: [String: Any]) -> [String: T] in
try decoder.decode(transform: transform)
}
}
//MARK: - dictionary - value
public func decode<T: AnyValueDecodable>(key: String) throws -> [String: T] {
return try decode(key: key, transform: T.init)
}
public func decode<T, ValueType>(key: String, transform: (ValueType) throws ->T?) throws -> [String: T] {
return try handleObjectDecode(key: key) { (decoder: [String: Any]) -> [String: T] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyValueDecodable>(key: String, throwIfMissing: Bool = false) throws -> [String: T]? {
return try decode(key: key, throwIfMissing: throwIfMissing, transform: T.init)
}
public func decode<T, ValueType>(key: String, throwIfMissing: Bool = false, transform: (ValueType) throws ->T?) throws -> [String: T]? {
return try handleObjectDecode(key: key, throwIfMissing: throwIfMissing) { (decoder: [String: Any]) -> [String: T] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyValueDecodable>(key: String, valueIfMissing: [String: T]) throws -> [String: T] {
return try decode(key: key, valueIfMissing: valueIfMissing, transform: T.init)
}
public func decode<T, ValueType>(key: String, valueIfMissing: [String: T], transform: (ValueType) throws ->T?) throws -> [String: T] {
return try handleObjectDecode(key: key, valueIfMissing: valueIfMissing) { (decoder: [String: Any]) -> [String: T] in
try decoder.decode(transform: transform)
}
}
//MARK: - nulllable dictionary - object
public func decode<T: AnyDecodable>(key: String) throws -> [String: T?] {
return try decode(key: key, transform: T.init)
}
public func decode<T>(key: String, transform: (AnyDecoder) throws ->T?) throws -> [String: T?] {
return try handleObjectDecode(key: key) { (decoder: [String: Any]) -> [String: T?] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyDecodable>(key: String, throwIfMissing: Bool = false) throws -> [String: T?]? {
return try decode(key: key, throwIfMissing: throwIfMissing, transform: T.init)
}
public func decode<T>(key: String, throwIfMissing: Bool = false, transform: (AnyDecoder) throws ->T?) throws -> [String: T?]? {
return try handleObjectDecode(key: key, throwIfMissing: throwIfMissing) { (decoder: [String: Any]) -> [String: T?] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyDecodable>(key: String, valueIfMissing: [String: T?]) throws -> [String: T?] {
return try decode(key: key, valueIfMissing: valueIfMissing, transform: T.init)
}
public func decode<T>(key: String, valueIfMissing: [String: T?], transform: (AnyDecoder) throws ->T?) throws -> [String: T?] {
return try handleObjectDecode(key: key, valueIfMissing: valueIfMissing) { (decoder: [String: Any]) -> [String: T?] in
try decoder.decode(transform: transform)
}
}
//MARK: - nulllable dictionary - value
public func decode<T: AnyValueDecodable>(key: String) throws -> [String: T?] {
return try decode(key: key, transform: T.init)
}
public func decode<T, ValueType>(key: String, transform: (ValueType) throws ->T?) throws -> [String: T?] {
return try handleObjectDecode(key: key) { (decoder: [String: Any]) -> [String: T?] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyValueDecodable>(key: String, throwIfMissing: Bool = false) throws -> [String: T?]? {
return try decode(key: key, throwIfMissing: throwIfMissing, transform: T.init)
}
public func decode<T, ValueType>(key: String, throwIfMissing: Bool = false, transform: (ValueType) throws ->T?) throws -> [String: T?]? {
return try handleObjectDecode(key: key, throwIfMissing: throwIfMissing) { (decoder: [String: Any]) -> [String: T?] in
try decoder.decode(transform: transform)
}
}
public func decode<T: AnyValueDecodable>(key: String, valueIfMissing: [String: T?]) throws -> [String: T?] {
return try decode(key: key, valueIfMissing: valueIfMissing, transform: T.init)
}
public func decode<T, ValueType>(key: String, valueIfMissing: [String: T?], transform: (ValueType) throws ->T?) throws -> [String: T?] {
return try handleObjectDecode(key: key, valueIfMissing: valueIfMissing) { (decoder: [String: Any]) -> [String: T?] in
try decoder.decode(transform: transform)
}
}
}
//MARK: - Dictionary
extension Dictionary where Key == String, Value == Any {
//objects dict
public func decode<T: AnyDecodable>() throws -> [String: T] {
return try decode(transform: T.init)
}
public func decode<T>(transform: (AnyDecoder) throws ->T?) throws -> [String: T] {
return try map { (key, value) in
try commitAction(path: .key(key)) {
return try Decoding.decode(value, transform: transform)
}
}
}
//optional objects dict
public func decode<T: AnyDecodable>() throws -> [String: T?] {
return try decode(transform: T.init)
}
public func decode<T>(transform: (AnyDecoder) throws ->T?) throws -> [String: T?] {
return try map { (key, value) in
try commitAction(path: .key(key)) {
return try doActionHandlingNull(value: value) {
return try Decoding.decode(value, transform: transform)
}
}
}
}
//values dict
public func decode<T: AnyValueDecodable>() throws -> [String: T] {
return try decode(transform: T.init)
}
public func decode<T, ValueType>(transform: (ValueType) throws ->T?) throws -> [String: T] {
return try map { (key, value) in
try commitAction(path: .key(key)) {
try Decoding.decode(value, transform: transform)
}
}
}
//optional values dict
public func decode<T: AnyValueDecodable>() throws -> [String: T?] {
return try decode(transform: T.init)
}
public func decode<T, ValueType>(transform: (ValueType) throws ->T?) throws -> [String: T?] {
return try map { (key, value) in
try commitAction(path: .key(key)) {
return try doActionHandlingNull(value: value) {
return try Decoding.decode(value, transform: transform)
}
}
}
}
}
//MARK: - ArrayDecoder
public protocol ArrayDecoder {
func anyMap<T>(_ transform: ((offset: Int, element: Any)) throws -> T) rethrows -> [T]
}
extension Array: ArrayDecoder {
public func anyMap<T>(_ transform: ((offset: Int, element: Any)) throws -> T) rethrows -> [T] {
return try enumerated().map(transform)
}
}
extension NSArray: ArrayDecoder {
public func anyMap<T>(_ transform: ((offset: Int, element: Any)) throws -> T) rethrows -> [T] {
return try enumerated().map(transform)
}
}
extension ArrayDecoder {
//objects array
public func decode<T: AnyDecodable>() throws -> [T] {
return try decode(transform: T.init)
}
public func decode<T>(transform: (AnyDecoder) throws ->T?) throws -> [T] {
return try anyMap { el in
try commitAction(path: .index(el.offset)) {
return try Decoding.decode(el.element, transform: transform)
}
}
}
//objects optionals array
public func decode<T: AnyDecodable>() throws -> [T?] {
return try decode(transform: T.init)
}
public func decode<T>(transform: (AnyDecoder) throws ->T?) throws -> [T?] {
return try anyMap { el in
try commitAction(path: .index(el.offset)) {
return try doActionHandlingNull(value: el.element) {
return try Decoding.decode(el.element, transform: transform)
}
}
}
}
//values array
public func decode<T: AnyValueDecodable>() throws -> [T] {
return try decode(transform: T.init)
}
public func decode<T, ValueType>(transform: (ValueType) throws ->T?) throws -> [T] {
return try anyMap { el in
try commitAction(path: .index(el.offset)) {
try Decoding.decode(el.element, transform: transform)
}
}
}
//values optionals array
public func decode<T: AnyValueDecodable>() throws -> [T?] {
return try decode(transform: T.init)
}
public func decode<T, ValueType>(transform: (ValueType) throws ->T?) throws -> [T?] {
return try anyMap { el in
try commitAction(path: .index(el.offset)) {
return try doActionHandlingNull(value: el.element) {
return try Decoding.decode(el.element, transform: transform)
}
}
}
}
}
//MARK: - Decoding
public struct Decoding {
//value
public static func decode<T: AnyValueDecodable>(_ value: Any) throws -> T {
return try decode(value, transform: T.init)
}
public static func decode<T: AnyValueDecodable>(_ value: Any) throws -> T? {
return try decode(value, transform: T.init)
}
public static func decode<T, ValueType>(_ value: Any, transform: (ValueType) throws ->T? ) throws -> T {
if let value = try castValue(value) { try transform($0)} {
return value
} else {
throw DecoderErrorType.failed(T.self, value).error
}
}
public static func decode<T, ValueType>(_ value: Any, transform: (ValueType) throws ->T? ) throws -> T? {
return try castValue(value) { try transform($0)}
}
//object
public static func decode<T: AnyDecodable>(_ value: Any) throws -> T {
return try decode(value, transform: T.init)
}
public static func decode<T: AnyDecodable>(_ value: Any) throws -> T? {
return try decode(value, transform: T.init)
}
public static func decode<T>(_ value: Any, transform: (AnyDecoder) throws ->T?) throws -> T {
return try castValue(value) { (decoder: AnyDecoder) in
try decoder.decode(transform: transform)
}
}
public static func decode<T>(_ value: Any, transform: (AnyDecoder) throws ->T?) throws -> T? {
return try castValue(value) { (decoder: AnyDecoder) in
try decoder.decode(transform: transform)
}
}
//objects array
public static func decode<T: AnyDecodable>(_ value: Any) throws -> [T] {
return try decode(value, transform: T.init)
}
public static func decode<T>(_ value: Any, transform: (AnyDecoder) throws ->T?) throws -> [T] {
return try castValue(value) { (decoder: ArrayDecoder) in
try decoder.decode(transform: transform)
}
}
// optional objects array
public static func decode<T: AnyDecodable>(_ value: Any) throws -> [T?] {
return try decode(value, transform: T.init)
}
public static func decode<T>(_ value: Any, transform: (AnyDecoder) throws ->T?) throws -> [T?] {
return try castValue(value) { (decoder: ArrayDecoder) in
try decoder.decode(transform: transform)
}
}
// objects dict
public static func decode<T: AnyDecodable>(_ value: Any) throws -> [String: T] {
return try decode(value, transform: T.init)
}
public static func decode<T>(_ value: Any, transform: (AnyDecoder) throws ->T?) throws -> [String: T] {
return try castValue(value) { (decoder: [String: Any]) in
try decoder.decode(transform: transform)
}
}
// optional objects dict
public static func decode<T: AnyDecodable>(_ value: Any) throws -> [String: T?] {
return try decode(value, transform: T.init)
}
public static func decode<T>(_ value: Any, transform: (AnyDecoder) throws ->T?) throws -> [String: T?] {
return try castValue(value) { (decoder: [String: Any]) in
try decoder.decode(transform: transform)
}
}
}
fileprivate func castValue<T, U>(_ value: Any, action: (T) throws ->U) throws -> U {
if let target = value as? T {
let res = try action(target)
return res
} else {
throw DecoderErrorType.invalidType(T.self, value).error
}
}
fileprivate func castValue<T, U>(_ value: Any, action: (T) throws ->U?) throws -> U? {
if let target = value as? T {
let res = try action(target)
return res
} else {
throw DecoderErrorType.invalidType(T.self, value).error
}
}
//MARK: - utils
fileprivate func commitAction<U>(path: DecoderErrorPathComponent, action: () throws ->U) throws -> U {
do {
return try action()
}
catch (let error as DecoderError) {
throw error.backtraceError(path: path)
}
catch {
throw error
}
}
fileprivate func doActionHandlingNull<U>(value: Any, action: () throws ->U?) throws -> U? {
do {
return try action()
}
catch (let error as DecoderError) {
if value is NSNull {
return nil
} else {
throw error
}
}
catch {
throw error
}
}
| true
|
977b3bc0d2f11a9adcb64b098bd7a29d11dd8649
|
Swift
|
MS-Light/DP4coRUna
|
/DP4coRUna/Controllers/SettingsController.swift
|
UTF-8
| 2,451
| 2.59375
| 3
|
[] |
no_license
|
//
// SettingsController.swift
// DP4coRUna
//
// Created by YANBO JIANG on 8/21/20.
//
import UIKit
import CoreBluetooth
import os
class SettingsController: UIViewController {
let client = Client(host:"192.168.1.152" , port: 80)
let server = Server(port: 80)
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func bluetoothonPressed(_ sender:UIButton) {
}
@IBAction func notificationPressed(_ sender: UIButton) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.alert, .sound])
{ (granted, error) in
}
// Step2 : Create the notification content
let content = UNMutableNotificationContent()
content.title = "DP4coRUna - You might have been exposed"
content.body = "Go take a Covid Test Soon"
// Step3: Create the notification trigger
let date = Date().addingTimeInterval(5) // The notification will pop after 5 seconds running.
let dateComponents = Calendar.current.dateComponents([.year,.month, .day, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
//Step 4: Create the request
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: content , trigger: trigger)
//Step 5: Register the request
center.add(request) { (error) in
}
}
@IBAction func functionButtonPressed(_ sender: UIButton) {
performSegue(withIdentifier: K.switches, sender: self)
}
@IBAction func detectorButtonPressed(_ sender: UIButton) {
performSegue(withIdentifier: K.detectorSettings, sender: self)
}
@IBAction func Startclient(_ sender: Any) {
DispatchQueue.global().async {
self.client.start()
let data = Data("There's a device next to you!".utf8)
self.client.connection.send(data: data)
}
}
@IBAction func Stopclient(_ sender: Any) {
client.stop()
}
@IBAction func Startserver(_ sender: Any) {
DispatchQueue.global().async {
try! self.server.start()
}
}
@IBAction func Sropserver(_ sender: Any) {
server.stop()
}
}
| true
|
2ac777e1d285e67d22072a589aec499849213b5c
|
Swift
|
rungxanh1995/CardWorkoutApp
|
/CardWorkoutB/CardWorkoutB/RulesVC.swift
|
UTF-8
| 2,385
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
//
// RulesVC.swift
// CardWorkoutB
//
// Created by Joe Pham on 2021-06-12.
//
import UIKit
class RulesVC: UIViewController {
let titleLabel = UILabel()
let rulesLabel = UILabel()
let exerciseLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
configureUI()
}
private func configureUI() {
configureTitleLabel()
configureRulesLabel()
configureExerciseLabel()
}
private func configureTitleLabel() {
view.addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.text = "Rules"
titleLabel.font = .systemFont(ofSize: 32, weight: .bold)
titleLabel.textAlignment = .center
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 30),
titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30),
titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30),
])
}
private func configureRulesLabel() {
view.addSubview(rulesLabel)
rulesLabel.translatesAutoresizingMaskIntoConstraints = false
rulesLabel.text = """
The value of each card represents the number of exercise you do.\n
J = 11, Q = 12, K = 13, A = 14
"""
rulesLabel.font = .systemFont(ofSize: 19, weight: .semibold)
rulesLabel.textAlignment = .center
rulesLabel.lineBreakMode = .byWordWrapping
rulesLabel.numberOfLines = 0
NSLayoutConstraint.activate([
rulesLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 25),
rulesLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30),
rulesLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30)
])
}
private func configureExerciseLabel() {
view.addSubview(exerciseLabel)
exerciseLabel.translatesAutoresizingMaskIntoConstraints = false
exerciseLabel.text = """
♠️ = Push-up\n
❤️ = Sit-up\n
♣️ = Burpees\n
♦️ = Jumping Jacks
"""
exerciseLabel.font = .systemFont(ofSize: 19, weight: .semibold)
exerciseLabel.numberOfLines = 0
NSLayoutConstraint.activate([
exerciseLabel.topAnchor.constraint(equalTo: rulesLabel.bottomAnchor, constant: 50),
exerciseLabel.widthAnchor.constraint(equalToConstant: 200),
exerciseLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
}
}
| true
|
508eaa0fa3c1ae000320a0bdfcffa86ac23d0193
|
Swift
|
el3ankaboot/Virtual-Tourist
|
/Virtual Tourist/Virtual Tourist/Controller/TravelLocationsMapViewController.swift
|
UTF-8
| 6,381
| 2.671875
| 3
|
[] |
no_license
|
//
// TravelLocationsMapViewController.swift
// Virtual Tourist
//
// Created by Gamal Gamaleldin on 4/12/19.
// Copyright © 2019 el3ankaboot. All rights reserved.
//
import Foundation
import UIKit
import MapKit
import CoreData
class TravelLocationsMapViewController: UIViewController , MKMapViewDelegate {
//MARK: DataController
var dataController : DataController!
//MARK: Outlets
@IBOutlet weak var mapView: MKMapView!
//MARK: Instance Variables
var pins: [Pin] = []
var mapAnnotationToPin = [MKPointAnnotation: Pin]()
//MARK: View did load
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
//Adding gesture recognizer with action to add the annotation
let tapRecognize = UILongPressGestureRecognizer(target: self, action: #selector(addAnnotation(gestureRecognizer:)))
tapRecognize.minimumPressDuration = 1
mapView.addGestureRecognizer(tapRecognize)
//Adding UserDefaults Persistence to presist the center and zoom of the map.
if UserDefaults.standard.bool(forKey: "HasLaunchedBefore") {
let latDouble = UserDefaults.standard.double(forKey: "Latitude")
let lat = CLLocationDegrees(latDouble)
let longDouble = UserDefaults.standard.double(forKey: "Longitude")
let long = CLLocationDegrees(longDouble)
let center = CLLocationCoordinate2D(latitude: lat, longitude: long)
let latitudeDelta = UserDefaults.standard.double(forKey: "LatitudeDelta")
let longitudeDelta = UserDefaults.standard.double(forKey: "LongitudeDelta")
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta))
self.mapView.setRegion(region, animated: true)
} else {
UserDefaults.standard.set(true, forKey: "HasLaunchedBefore")
let center = mapView.centerCoordinate
AppDelegate.longitude = center.longitude
AppDelegate.latitude = center.latitude
AppDelegate.latitudeDelta = mapView.region.span.latitudeDelta
AppDelegate.longitudeDelta = mapView.region.span.longitudeDelta
}
//Fetching pins and adding them as annotations on map
let fetchRequest : NSFetchRequest<Pin> = Pin.fetchRequest()
if let result = try? dataController.viewContext.fetch(fetchRequest){
pins = result
addLoadedPinsOnMap()
}
}
//MARK: Add loaded pins on map
func addLoadedPinsOnMap(){
for pin in self.pins {
let pinToAnnotation = MKPointAnnotation()
pinToAnnotation.coordinate = CLLocationCoordinate2D(latitude: pin.latitude, longitude: pin.longitude)
self.mapView.addAnnotation(pinToAnnotation)
mapAnnotationToPin[pinToAnnotation] = pin
}
}
//MARK: Getting the center and zoom when moving in the map
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let center = mapView.centerCoordinate
AppDelegate.longitude = center.longitude
AppDelegate.latitude = center.latitude
AppDelegate.latitudeDelta = mapView.region.span.latitudeDelta
AppDelegate.longitudeDelta = mapView.region.span.longitudeDelta
}
//MARK: Displaying Annotations
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard annotation is MKPointAnnotation else { return nil }
let identifier = "Annotation"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView!.canShowCallout = true
} else {
annotationView!.annotation = annotation
}
return annotationView
}
//MARK: The Gesture Recognizer that drops the pin.
@objc func addAnnotation(gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer.state == UIGestureRecognizer.State.began {
let touchPoint = gestureRecognizer.location(in: self.mapView)
let newCoordinate = self.mapView.convert(touchPoint, toCoordinateFrom: self.mapView)
let location = CLLocation(latitude: newCoordinate.latitude, longitude: newCoordinate.longitude)
CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (_, error) in
guard error == nil else {
let alertVC = UIAlertController(title: "Couldn't add location", message: "(An error occured and location was not added.", preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertVC ,animated: true, completion: nil)
return
}
let annotation = MKPointAnnotation()
annotation.coordinate = newCoordinate
self.mapView.addAnnotation(annotation)
//Add it to context
let pin = Pin(context: self.dataController.viewContext)
pin.longitude = newCoordinate.longitude
pin.latitude = newCoordinate.latitude
try? self.dataController.viewContext.save()
self.mapAnnotationToPin[annotation] = pin
})
}
}
//MARK: Navigating to photo album view controller when clicking on annotation
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)
{
let pin = mapAnnotationToPin[view.annotation as! MKPointAnnotation]
let photoAlbumVC = self.storyboard!.instantiateViewController(withIdentifier: "PhotoAlbumViewController") as! PhotoAlbumViewController
photoAlbumVC.thePin = pin
photoAlbumVC.dataController = self.dataController
mapView.deselectAnnotation(view.annotation, animated: true)
self.navigationController!.pushViewController(photoAlbumVC, animated: true)
}
}
| true
|
4292862e394579df7db67b7cc63717d347351492
|
Swift
|
rggras/IssueTraker
|
/IssueTracker/Models/Issue.swift
|
UTF-8
| 849
| 2.703125
| 3
|
[] |
no_license
|
//
// Issue.swift
// IssueTracker
//
// Created by Rodrigo Gras on 05/06/2019.
// Copyright © 2019 Nexton Labs. All rights reserved.
//
import ObjectMapper
class Issue: BaseModel {
var id: String?
var name: String?
var description: String?
var creator: String?
var assignee: String?
var pictureUrl: String?
var priority: String?
var status: String?
var createdAt: String?
required convenience init?(map: Map) {
self.init()
}
override func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
description <- map["description"]
creator <- map["creator"]
assignee <- map["assignee"]
pictureUrl <- map["pictureUrl"]
priority <- map["priority"]
status <- map["status"]
createdAt <- map["createdAt"]
}
}
| true
|
aa36f8a4ec2074825bc208d27a09f9b80e4b1e07
|
Swift
|
borikanes/MetroMesh
|
/View/Customs/MMeshButton.swift
|
UTF-8
| 3,314
| 2.59375
| 3
|
[] |
no_license
|
//
// MMeshButton.swift
// MetroMesh
//
// Created by Oluwabori Oludemi on 1/25/16.
// Copyright © 2016 Oluwabori Oludemi. All rights reserved.
//
import UIKit
import Foundation
@IBDesignable
class MMeshButton: UIButton {
var buttonSpreadView = UIView()
@IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setUpButton()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpButton()
}
func setUpButton() {
self.backgroundColor = UIColor(red: 52.0/255.0, green: 64.0/255.0, blue: 150.0/255.0, alpha: 1.0)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
for touch in touches as Set<UITouch> {
let location = touch.location(in: self)
buttonSpreadView.frame = CGRect(x: 0.0, y: 0.0, width: 20.0, height: 20.0)
buttonSpreadView.center = location
buttonSpreadView.layer.cornerRadius = 22.0
buttonSpreadView.layer.zPosition = -1000
buttonSpreadView.backgroundColor = UIColor(red: 186.0/255.0,
green: 193.0/255.0, blue: 241.0/255.0, alpha: 0.09)
addSubview(buttonSpreadView)
UIView.animate(withDuration: 0.75, delay: 0.0,
options: UIViewAnimationOptions.curveEaseOut,
animations: {
() -> Void in
let (centerX, centerY) = (self.buttonSpreadView.center.x, self.buttonSpreadView.center.y)
let scaleFactor = sqrt(pow(self.frame.size.width - centerX, 2.0) +
pow(self.frame.size.height - centerY, 2.0))
self.buttonSpreadView.transform = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)
}, completion: nil)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
UIView.animate(withDuration: 0.25, delay: 0.0,
options: UIViewAnimationOptions.curveLinear,
animations: { () -> Void in
self.buttonSpreadView.transform = CGAffineTransform.identity
}, completion: { (_: Bool) in
self.buttonSpreadView.removeFromSuperview()
})
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
UIView.animate(withDuration: 0.25, delay: 0.0,
options: UIViewAnimationOptions.curveLinear,
animations: { () -> Void in
self.buttonSpreadView.transform = CGAffineTransform.identity
}, completion: { (_: Bool) in
self.buttonSpreadView.removeFromSuperview()
})
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| true
|
2a543203c4204a1c8e360c80d3bd395e00930c51
|
Swift
|
lapinan/Africa
|
/Africa/View/DetailAnimal/HeadingView.swift
|
UTF-8
| 445
| 3.015625
| 3
|
[] |
no_license
|
//
// HeadingView.swift
// Africa
//
// Created by Андрей Лапин on 05.04.2021.
//
import SwiftUI
struct HeadingView: View {
let image: String
let text: String
var body: some View {
HStack {
Image(systemName: image)
.foregroundColor(.accentColor)
.imageScale(.large)
Text(text)
.font(.title3)
.fontWeight(.bold)
} //: HStack
.padding(.vertical)
}
}
| true
|
a6a4c9f327344cf86f12f158e542cee9cc295327
|
Swift
|
hiraferda/KWK-Lessons
|
/Mini Project 2/Mini Project 2/secondViewController.swift
|
UTF-8
| 1,168
| 2.765625
| 3
|
[] |
no_license
|
//
// secondViewController.swift
// Mini Project 2
//
// Created by Scholar on 7/15/21.
//
import UIKit
class secondViewController: UIViewController {
@IBOutlet weak var mainTitle: UILabel!
@IBOutlet weak var question: UITextField!
@IBOutlet weak var blank1: UITextField!
let newTitle = "🍝🍝"
let newTitle2 = "🍕🍕"
let newTitle3 = "🍔🍔"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func button1(_ sender: UIButton) {
blank1.text = newTitle
}
@IBAction func button2(_ sender: UIButton) {
blank1.text = newTitle2
}
@IBAction func button3(_ sender: UIButton) {
blank1.text = newTitle3
}
/*
// 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
|
5e2406a8c19ae7d357a6d6646dcf587b7a57b753
|
Swift
|
Zekhniddin/InstagramTimeline
|
/InstagramTimeline/screens/HomeScreen.swift
|
UTF-8
| 3,605
| 2.640625
| 3
|
[] |
no_license
|
//
// HomeScreen.swift
// InstagramTimeline
//
// Created by Зехниддин on 21/01/21.
//
import SwiftUI
struct HomeScreen: View {
@EnvironmentObject var status: Status
init() {
UINavigationBar.appearance().titleTextAttributes = [.font : UIFont(name: "Georgia-Bold", size: 20)!]
}
let itemStories = [
ItemStoryModel(name: "John", image_url: "im_person1"),
ItemStoryModel(name: "Anna", image_url: "im_person2"),
ItemStoryModel(name: "John", image_url: "im_person1"),
ItemStoryModel(name: "Anna", image_url: "im_person2"),
ItemStoryModel(name: "John", image_url: "im_person1"),
ItemStoryModel(name: "Anna", image_url: "im_person2"),
ItemStoryModel(name: "John", image_url: "im_person1"),
ItemStoryModel(name: "Anna", image_url: "im_person2")
]
let itemPosts = [
ItemPostModel(user_url: "im_user", user_name: "George", img_url1: "image1", img_url2: "image2", img_url3: "image3"),
ItemPostModel(user_url: "im_person1", user_name: "John", img_url1: "image1", img_url2: "image2", img_url3: "image3"),
ItemPostModel(user_url: "im_person2", user_name: "Anna", img_url1: "image1", img_url2: "image2", img_url3: "image3"),
ItemPostModel(user_url: "im_person1", user_name: "John", img_url1: "image1", img_url2: "image2", img_url3: "image3"),
ItemPostModel(user_url: "im_person2", user_name: "Anna", img_url1: "image1", img_url2: "image2", img_url3: "image3"),
ItemPostModel(user_url: "im_person1", user_name: "John", img_url1: "image1", img_url2: "image2", img_url3: "image3"),
ItemPostModel(user_url: "im_person2", user_name: "Anna", img_url1: "image1", img_url2: "image2", img_url3: "image3"),
ItemPostModel(user_url: "im_person1", user_name: "John", img_url1: "image1", img_url2: "image2", img_url3: "image3"),
ItemPostModel(user_url: "im_person2", user_name: "Anna", img_url1: "image1", img_url2: "image2", img_url3: "image3")
]
var body: some View {
NavigationView {
List {
ScrollView(.horizontal, showsIndicators: false) {
HStack {
AddStory()
ForEach(itemStories) {
ItemStory(img_url: $0.image_url, name: $0.name)
}
}
.padding(.top, 2)
.padding(.leading, 16)
}
ForEach(itemPosts) {
ItemPost(user_url: $0.user_url, user_name: $0.user_name, img_url1: $0.img_url1, img_url2: $0.img_url2)
}
}
.padding(.horizontal, -20)
.listStyle(PlainListStyle())
.navigationBarItems(
leading: Button(action: { }) {
Image(systemName: "camera")
.foregroundColor(.red)
.font(.title3)
},
trailing: Button(action: {
UserDefaults.standard.removeObject(forKey: "key_data")
self.status.listen()
}) {
Image(systemName: "person")
.foregroundColor(.red)
.font(.title3)
})
.navigationBarTitle("Instagram", displayMode: .inline)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct HomeScreen_Previews: PreviewProvider {
static var previews: some View {
HomeScreen()
}
}
| true
|
2c36c6edb8c754057b7af45e832cfae3d5cb404b
|
Swift
|
calpoly-csc431-2184/Take
|
/Take/Extensions/MKMapView.swift
|
UTF-8
| 1,525
| 2.6875
| 3
|
[] |
no_license
|
//
// MKMapView.swift
// Take
//
// Created by Nathan Macfarlane on 6/6/18.
// Copyright © 2018 N8. All rights reserved.
//
import Foundation
import MapKit
extension MKMapView {
func removeAllAnnotations() {
self.annotations.forEach {
if !($0 is MKUserLocation) {
self.removeAnnotation($0)
}
}
}
func removeAllOverlays() {
self.removeOverlays(self.overlays)
}
func visibleDistance() -> Double {
let span = self.region.span
let center = self.region.center
let loc1 = CLLocation(latitude: center.latitude - span.latitudeDelta * 0.5, longitude: center.longitude)
let loc2 = CLLocation(latitude: center.latitude + span.latitudeDelta * 0.5, longitude: center.longitude)
let loc3 = CLLocation(latitude: center.latitude, longitude: center.longitude - span.longitudeDelta * 0.5)
let loc4 = CLLocation(latitude: center.latitude, longitude: center.longitude + span.longitudeDelta * 0.5)
let metersInLatitude = loc1.distance(from: loc2)
let metersInLongitude = loc3.distance(from: loc4)
return metersInLatitude < metersInLongitude ? metersInLatitude : metersInLongitude
}
func centerMapOn(_ location: CLLocation, animated: Bool = true, withRadius radius: Double = 3000) {
let coordinateRegion = MKCoordinateRegion(center: location.coordinate, latitudinalMeters: radius, longitudinalMeters: radius)
self.setRegion(coordinateRegion, animated: animated)
}
}
| true
|
b5df596449280e9d9e89994e03062c193413b419
|
Swift
|
huyLamOffy/TinderLike
|
/TinderLike/Layers/Network/APIRequest.swift
|
UTF-8
| 1,861
| 2.609375
| 3
|
[] |
no_license
|
//
// APIRequest.swift
// TinderLike
//
// Created by HuyLH3 on 9/9/20.
// Copyright © 2020 HuyLH3. All rights reserved.
//
import Alamofire
class APIRequest {
private var sessionManager: Alamofire.Session
init() {
let configuration = URLSessionConfiguration.default
sessionManager = Alamofire.Session(configuration: configuration)
}
deinit {
sessionManager.session.invalidateAndCancel()
}
func requestObject<T: Decodable>(route: URLRequestConvertible, specificKeyPath keyPath: String? = nil, completion: @escaping (Result<T, APIError>) -> Void) {
guard ReachabilityManager.shared.isNetworkAvailable else {
completion(.failure(.noInternet))
return
}
sessionManager
.request(route)
.validate()
.responseDecodableObject(keyPath: keyPath, decoder: decoder) { (response: AFDataResponse<T>) in
switch response.result {
case .success(let object):
completion(.success(object))
case .failure(let error):
switch error {
case .sessionTaskFailed(let sessionTaskFailedError):
if let err = sessionTaskFailedError as? URLError,
err.code == URLError.Code.notConnectedToInternet {
completion(.failure(.noInternet))
return
}
default: break
}
completion(.failure(.custom(message: error.localizedDescription)))
}
}
}
}
fileprivate var decoder: JSONDecoder {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
return decoder
}
| true
|
e585811d08a6fe2b38c4face833504dd333a79f9
|
Swift
|
ALanHua/Swift
|
/language/第三方/SwiftTips/49_COpaquePointer/main.swift
|
UTF-8
| 296
| 2.90625
| 3
|
[] |
no_license
|
//
// main.swift
// 49_COpaquePointer
//
// Created by yhp on 2017/11/19.
// Copyright © 2017年 YouHuaPei. All rights reserved.
//
import Foundation
let callBack:@convention(c) (Int32,Int32) -> Int32 = {
(x,y) -> Int32 in
return x + y
}
let result = callBack(1,2)
print(result)
| true
|
a895e3f56c580debad4933f256d001d2b3b97d88
|
Swift
|
alastaircoote/request-intercept-demo-ios
|
/RequestInterceptDemoApp/SchemeTaskManager.swift
|
UTF-8
| 6,940
| 2.84375
| 3
|
[] |
no_license
|
//
// SchemeTaskManager.swift
// RequestInterceptDemoApp
//
// Created by Alastair on 9/25/18.
// Copyright © 2018 NYTimes. All rights reserved.
//
import Foundation
import WebKit
class SchemeTaskAndDependencies: NSObject {
let schemeTask: WKURLSchemeTask
let dataTask: URLSessionDataTask
init(schemeTask: WKURLSchemeTask, dataTask: URLSessionDataTask) {
self.schemeTask = schemeTask
self.dataTask = dataTask
}
}
/// Our URLSchemeTaskManager pairs up a WKURLSchemeTask with a corresponding HTTP request, and streams the
/// data from the latter to the former as it downloads. Once the download completes, it finishes the WKURLSchemeTask.
class URLSchemeTaskManager: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate {
var urlSession: URLSession!
var currentTasks = Set<SchemeTaskAndDependencies>()
override init() {
super.init()
// We have to create an instance of URLSession in order to use the delegate methods associated with it.
urlSession = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
}
func process(schemeTask: WKURLSchemeTask, httpsURL: URL) {
NSLog("Received request for \(schemeTask.request.url?.absoluteString ?? "unknown URL")")
var request = schemeTask.request
// When it arrives the WKURLSchemeTask will have a requestdemo:// URL. We need to replace that URL with an
// https:// one. But we keep the rest of the URLRequest, so that we can preserve headers etc.
request.url = httpsURL
let dataTask = urlSession.dataTask(with: request)
// Because all of this is happening asynchronously, we need to store both the data task
// and the scheme task internally, for use in the delegate callbacks:
currentTasks.insert(SchemeTaskAndDependencies(schemeTask: schemeTask, dataTask: dataTask))
dataTask.resume()
}
// Called when the webview task is cancelled. Sometimes in response to user request, but not always - the webview
// itself sometimes terminates requests for e.g. videos after downloading a small chunk.
func stop(schemeTask: WKURLSchemeTask) {
guard let existingTask = self.currentTasks.first(where: { $0.schemeTask.isEqual(schemeTask) }) else {
NSLog("Received request to stop download of \(schemeTask.request.url?.absoluteString ?? "unknown URL"), but no download exists")
return
}
NSLog("Stopping download of \(schemeTask.request.url?.absoluteString ?? "unknown URL")")
// We stop our current download...
existingTask.dataTask.cancel()
// ...and then remove the task from our collection, as we no longer need it
currentTasks.remove(existingTask)
}
// Called when we receive the initial response for our request, containing the headers
func urlSession(_: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
NSLog("Received initial response for \(response.url?.absoluteString ?? "unknown URL")")
guard let link = self.currentTasks.first(where: { $0.dataTask == dataTask }) else {
// We've received a response for a data task we don't know about. This
// shouldn't ever happen.
return
}
guard let httpResponse = response as? HTTPURLResponse else {
// Should obviously have a better way of handling this:
fatalError("Response should always be an HTTPURLResponse")
}
guard let responseURL = response.url else {
fatalError("Response should always have a URL")
}
// NSURLSession automatically decodes GZipped responses, so we need to remove any encoding headers, otherwise
// the webview will try to decode a GZipped body again itself
let filteredHeaders = httpResponse.allHeaderFields.filter { ($0.key as? String)?.lowercased() != "content-encoding" }
guard let requestDemoResponse = HTTPURLResponse(url: URLConvert.httpsURLToRequestDemo(originalURL: responseURL), statusCode: httpResponse.statusCode, httpVersion: nil, headerFields: filteredHeaders as? [String:String]) else {
fatalError("Could not create custom HTTP response")
}
// We now forward on the initial response to our WKURLScheme handler:
link.schemeTask.didReceive(requestDemoResponse)
// And then instruct this response to become a stream, so we can send data
// through as soon as it becomes available:
completionHandler(.allow)
}
// Send incoming data from our URLSessionDataTask to the WKURLSchemeTask
func urlSession(_: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard let link = self.currentTasks.first(where: { $0.dataTask == dataTask }) else {
return
}
NSLog("Received \(data.count) bytes for \(link.dataTask.response?.url?.absoluteString ?? "unknown URL")")
do {
try ObjC.catchException {
link.schemeTask.didReceive(data)
}
} catch {
// If the task was cancelled while this runs the didReceive call throws. This error is acceptable
// because it's trying to write data for a request that's already been disregarded.
}
}
// Once the URLSessionTask has finished, we close up the WKURLSchemeTask, passing along any
// error if it occurred.
func urlSession(_: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if error?.localizedDescription == "cancelled" {
// This is called when we manually finish the task in stop(). If we try to call any didFinish()
// method at this point it'll throw an error, because the WKURLSchemeTask is already cancelled.
return
}
guard let link = self.currentTasks.first(where: { $0.dataTask == task }) else {
return
}
do {
try ObjC.catchException {
if let error = error {
NSLog("Failing with error for URL \(link.dataTask.response?.url?.absoluteString ?? "unknown URL")")
link.schemeTask.didFailWithError(error)
} else {
NSLog("Successfully finishing URL \(link.dataTask.response?.url?.absoluteString ?? "unknown URL")")
link.schemeTask.didFinish()
}
}
} catch {
// Similar to the above, the task will throw if it's been cancelled before this. But again, it's fine, because
// the webview isn't listening to any response events any more.
}
currentTasks.remove(link)
}
}
| true
|
7cb0fabf78948a750e062292933f3e99bb71a77a
|
Swift
|
basum/StravaKit
|
/StravaKit/ActivityUpload.swift
|
UTF-8
| 630
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
public struct ActivityUpload: Equatable, Hashable {
public let externalId: String
public let activityType: String
public let url: URL
public let fileName: String
public let dataType: String
public let mimeType: String
public init(
externalId: String,
activityType: String,
url: URL,
fileName: String,
dataType: String,
mimeType: String
) {
self.externalId = externalId
self.activityType = activityType
self.url = url
self.fileName = fileName
self.dataType = dataType
self.mimeType = mimeType
}
}
| true
|
c7ae0f994d85b0f1b2c754660c1ff4b60608118d
|
Swift
|
nullptr97/TestPhotosFlikr
|
/Photos/Api/FlikrApi.swift
|
UTF-8
| 1,519
| 2.875
| 3
|
[] |
no_license
|
//
// FlikrApi.swift
// Photos
//
// Created by Ярослав Стрельников on 10.12.2020.
//
import Foundation
import UIKit
import Alamofire
import PromiseKit
import SwiftyJSON
enum PhotoSize: String {
case preview = "q"
case fullSize = "b"
}
struct Api {
static func getRecentPhotos() -> Promise<Photos> {
let apiUrl = "https://api.flickr.com/services/rest/?"
let parameters: Parameters = [
"method" : "flickr.photos.getRecent",
"api_key" : "da9d38d3dee82ec8dda8bb0763bf5d9c",
"per_page" : 20,
"format" : "json",
"nojsoncallback" : 1
]
return firstly {
Alamofire.request(apiUrl, method: .get, parameters: parameters, encoding: URLEncoding.default).responseData(queue: DispatchQueue.global(qos: .background))
}.compactMap {
if let apiError = ApiError(JSON($0.data)) {
throw FlikrError.api(apiError)
}
guard let decodePhotosJSON = decodeJSON(to: Response.self, from: $0.data) else { throw FlikrError.notParsedJSON("JSON not parsed") }
return decodePhotosJSON.photos
}
}
}
extension Api {
static func decodeJSON<T: Decodable>(to decodable: T.Type, from data: Data?) -> T? {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
guard
let data = data,
let response = try? decoder.decode(decodable.self, from: data)
else { return nil }
return response
}
}
| true
|
0bd19381185b7dc4f61d78788c2bc9d5d4ac9249
|
Swift
|
vapronva/computer_elements-app
|
/computerelements/ContentView.swift
|
UTF-8
| 1,657
| 2.84375
| 3
|
[] |
no_license
|
//
// ContentView.swift
// computerelements
//
// Created by Vladimir Malinovskiy on 21.03.2021.
//
import SwiftUI
struct ContentView: View {
@State private var isShowingInformation: Bool = false
@State var isNavigationBarHidden: Bool = true
@State var chosenCPUType: Int = 0
@State var showingSettingsVariables: Bool = false
var body: some View {
NavigationView {
ZStack {
Color(.sRGB, red: 0.039, green: 0.039, blue: 0.039, opacity: 1.0)
.ignoresSafeArea(edges: .all)
// switch(selection) {
// case 0: InformationView()
// case 1: MainScreenList()
// case 2: InformationView()
// default: InformationView()
// }
// MainScreenList()
MainScreenList(showingSettingsVariables: $showingSettingsVariables, chosenCPUType: $chosenCPUType)
.sheet(isPresented: $isShowingInformation) {
InformationView(isShowingInformation: $isShowingInformation) }
TabViewButt(isShowingInformation: $isShowingInformation, showingSettingsVariables: $showingSettingsVariables, chosenCPUType: $chosenCPUType)
}.navigationBarTitle(Text("Computer Elements"))
.navigationBarHidden(self.isNavigationBarHidden)
.onAppear {
self.isNavigationBarHidden = true
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.preferredColorScheme(.dark)
.previewDevice("iPhone 11 Pro")
}
}
| true
|
3543e6f626c7680d7c339643485a4b819814a2fa
|
Swift
|
tokend/ios-app
|
/TokenDWalletTemplate/Sources/Shared/Workers/ClientRedirections/ClientRedirectsModel.swift
|
UTF-8
| 1,657
| 2.90625
| 3
|
[
"Apache-2.0"
] |
permissive
|
import Foundation
struct ClientRedirectModel {
static let redirectionTypeEmailConfirmation: Int = 1
enum RedirectionType {
case unknown
case emailConfirmation(EmailConfirmationMeta)
}
struct EmailConfirmationMeta {
let token: String
let walletId: String
}
// MARK: - Public properties
let typeValue: Int
let meta: [String: Any]
let type: RedirectionType
// MARK: -
init?(string: String) {
guard let data = string.dataFromBase64 else {
return nil
}
guard let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {
return nil
}
guard
let typeValue = json["type"] as? Int,
let metaValue = json["meta"] as? [String: Any]
else {
return nil
}
self.typeValue = typeValue
self.meta = metaValue
switch typeValue {
case ClientRedirectModel.redirectionTypeEmailConfirmation:
guard
let token = metaValue["token"] as? String,
let walletId = metaValue["wallet_id"] as? String else {
self.type = .unknown
return
}
let emailConfirmationMeta = EmailConfirmationMeta(
token: token,
walletId: walletId
)
self.type = .emailConfirmation(emailConfirmationMeta)
default:
self.type = .unknown
}
}
}
| true
|
a318fa59a014ef916765d89c60bb04c684b58ae4
|
Swift
|
99ios/23.11
|
/23.11 类和结构体.playground/Contents.swift
|
UTF-8
| 1,208
| 4.40625
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
/***************1.类和结构体基本用法**************/
struct point{
var x:Int = 0
var y:Int = 0
}
class map {
//可选类型的属性
var name:String?
var po = point()
}
//成员构造器
var p1 = point(x:10,y:20)
var m1 = map()
m1.name = "地图1"
m1.po = p1
print("\(m1.name!)中的po的坐标点是(\(m1.po.x),\(m1.po.y))")
//打印结果:地图1中的po的坐标点是(10,20)
/***************2.结构体是值类型**************/
enum color{
case R,G,B,A
}
struct point2{
var x:Int = 0
var y:Int = 0
}
var c1 = color.R
var c2 = c1
c2 = .G
if c1 == color.R {
print("枚举是值传递")
}
var p12 = point(x:10,y:10)
var p2 = p12
p2.y = 20
print("p1的坐标是(\(p12.x),\(p12.y))")
print("p2的坐标是(\(p2.x),\(p2.y))")
/***************3.类是引用类型**************/
class map2 {
//可选类型的属性
var name:String?
}
var m12 = map2()
m12.name = "地图1"
var m2 = m12
m2.name = "地图2"
if m12 === m2 {
print("m1恒等于m2")
}
print("m1.name = \(m12.name!),m2.name=\(m2.name!)")
//打印结果:m1恒等于m2
//m1.name = 地图2, m2.name=地图2
| true
|
c54797cd7f35d3f61ca6ea1f07c6ec0e8d6a5c80
|
Swift
|
chiller-whale/VendingMachineDemo
|
/VendingMachineDemo/InventoryManager.swift
|
UTF-8
| 1,226
| 3.53125
| 4
|
[] |
no_license
|
//
// InventoryManager.swift
// VendingMachineDemo
//
// Created by Tyler Freeman on 5/25/16.
// Copyright © 2016 Tyler Freeman. All rights reserved.
//
import Foundation
class InventoryManager {
let inventory: [String : VendingMachineItem] = [String : VendingMachineItem]()
init() {
}
/**
*
* Unwrapping
* ===========================================
* If a value may be nil it must be unwrapped.
*
* The two operators for unwarpping are ! and ?
* The difference between these are:
* ! will throw a run-time error if a nil value is
* is accesed
* ? will allow properties of a possibly nil value
* to be accessed without throwing an error.
*
**/
/**
* Will throw a runtime error if no item exists in with key
**/
func getItemByTitle (itemTitle: String) -> VendingMachineItem {
return inventory[itemTitle]!
}
/**
* Will not throw an error if item does not exist
**/
func tryGetItemPriceByTitle (itemTitle: String) -> Double {
if let itemPrice = inventory[itemTitle]?.price {
return itemPrice
} else {
return Double(0)
}
}
}
| true
|
37fefc13b67f8b1b778866af048cd2887d3612cc
|
Swift
|
avilesdiana/firstStepInSwift
|
/MyPlayground.playground/Contents.swift
|
UTF-8
| 9,582
| 4.0625
| 4
|
[] |
no_license
|
import UIKit
var str = "Hello, playground"
var stringExplícito : String = "Este es un string explícito" //Se pueden poner acentos y ñ en todo
var stringImplícito : String = "Este es un string implícito" //Se pueden poner acentos y ñ en todo
print("Este fue mi primer string: \(stringExplícito)")//Interpolación de string
var edad: Int
edad = 22
print ("Tengo \(edad) años")
edad = 28
print("... y ahora tengo \(edad)")
//edad = 4.5
let saludo : String
saludo = "Hola mundo"
var wave = saludo
let enSwiftNosGustanLosNombresDeVariablesQueSeanDescriptivos : String
enSwiftNosGustanLosNombresDeVariablesQueSeanDescriptivos = "Porque existe el autocompletado"
var 🦆 = 100
print("Ayer tenía \(🦆) pesos y hoy tengo \(🦆+20) pesos y voy a comprar un 🦆 ")
let 🐭 = "ratoncito"
3+7
saludo + 🐭
//saludo + 🦆 //ERROR
saludo + String(🦆)
var booleano = true //o false
var flotante = 3.1415926
var pi = 3.1416
pi = Double.pi
print (pi)
var miDoble = 9.0
miDoble.addingProduct(2.0,3.0)
miDoble.squareRoot()
extension Double{
func saluda(){
print("Hola, soy el double \(self)")
}
}
miDoble.saluda()
7.5.saluda()
//COLECCIONES: ARRAY, DICTIONARY, SET
var arregloExplícito : Array<String> = ["Cosme Fulanito, saluda, 🐭"]
var arregloSemiExplícito : [String] = ["Moe", "Marge", "Bart"]
var arregloImplicito = ["Lisa", "Maggie", "Ayudante de Santa"]
var arregloVacio = [String]()
arregloImplicito[2]
arregloExplícito.count
arregloVacio.isEmpty
arregloExplícito.isEmpty
arregloSemiExplícito.description
miDoble.description
var changuitos = [String] (repeating: "🙈", count: 5)
var monitos = changuitos
print("changuitos tiene \(changuitos)")
print("monitos tiene \(monitos)")
changuitos [2] = "🐒"
print("changuitos tiene \(changuitos)")
print("monitos tiene \(monitos)")
for i in 0..<10{
print(i)
}
for i in 0...10{
print(i)
}
let 🐣 = "Chicken"
let 🐔 = "Hen"
let 📝 = "Pencil"
let 🖋 = "Pen"
var diccionario = [🐣,🐔, 📝 ,🖋]
for i in 0..<diccionario.count{
print("Este es el elemento \(i): \(diccionario[i])")
}
for palabra in diccionario {
print("Este es el elemento: \(palabra)")
}
for (lugar, palabra) in diccionario.enumerated(){
print("La posición \(lugar) es de \(palabra)")
}
let multiplicando = 12
let multiplicador = 5
var resultado = 0
for _ in 1...multiplicando{
resultado += multiplicando
}
print("\(multiplicando)x\(multiplicador)=\(resultado)")
var i = 0
while i < diccionario.count{
print("\(diccionario[i])")
i+=1
}
i = 0
repeat{
print("\(diccionario[i])")
i+=1
} while i<diccionario.count
let diccionarioES_DE: Dictionary<String,String> = ["Perro":"Hund", "Casa":"Haus", "Ceja":"Augenbraue","1":"Eins"]
var diccionarioEs_DE_numeros = [
1:"Eins",
2:"Zwei",
3:"Drei",
4:"Vier"]
print(diccionarioES_DE["Perro"]!)
let llaves = diccionarioES_DE.keys
let valore = diccionarioES_DE.values
diccionarioEs_DE_numeros.removeValue(forKey: 2)
diccionarioEs_DE_numeros.description
let casaEnAleman = diccionarioES_DE["Casa"]
let tiempoEnAleman = diccionarioES_DE["Tiempo"]
let cienEnAleman = diccionarioEs_DE_numeros[100]
print(diccionarioES_DE["Ceja"]!)
if let palabraTraducida = diccionarioES_DE["Ceja"]
{
print(palabraTraducida)
} else{
print("La palabra no está en el diccionario")
}
var numeroTraducido = diccionarioEs_DE_numeros[1] ?? "No existe en el diccionario"
var numeroTraducido2 = diccionarioEs_DE_numeros[2] ?? "No existe en el diccionario"
func saluda(){
print("Hallo Welt")
}
saluda()
func cuentaVotos(votosEmitidos: [String], sentidoDeVotoAContar: String) -> Int{
var cuenta = 0
for voto in votosEmitidos{
if voto == sentidoDeVotoAContar{
cuenta += 1
}
}
return cuenta
}
let pregunta = "¿Te gustan los Simpson?"
let urna = ["si", "si", "no", "no se", "no", "si", "si", "si","si"]
let votosSi = cuentaVotos(votosEmitidos: urna, sentidoDeVotoAContar: "si")
let votosNo = cuentaVotos(votosEmitidos: urna, sentidoDeVotoAContar: "no")
let votosNulos = cuentaVotos(votosEmitidos: urna, sentidoDeVotoAContar: "no se")
print("A \(votosSi) personas le gustan los Simpson, a \(votosNo) no le gustan y \(votosNulos) no saben")
let jefes = cuentaVotos(votosEmitidos: ["Jefes","49s","49s","49s","Jefes","Jefes"], sentidoDeVotoAContar: "Jefes")
func cuentaTodosLosVotos (votosAContar:[String]) -> (votosSi:Int, votosNo:Int, votosNulos:Int){//La tupla va entre parentesis
let votosSi = cuentaVotos(votosEmitidos: votosAContar, sentidoDeVotoAContar: "si")
let votosNo = cuentaVotos(votosEmitidos: votosAContar, sentidoDeVotoAContar: "no")
let votosNulos = votosAContar.count - votosSi - votosNo
return (votosSi, votosNo, votosNulos)
}
let resultados = cuentaTodosLosVotos(votosAContar: urna)
print("Le gustan los Simpson a \(resultados.votosSi) personas")
print ("No le gustan los Simpson a \(resultados.1) personas")
let (si,no, _) = cuentaTodosLosVotos(votosAContar: urna)
print("Le gustan a \(si)")
print("No le gustan a \(no)")
func repiteLaFrase(frase: String, cuantasVeces: Int) ->String{
var resultado = ""
for _ in 0..<cuantasVeces {
resultado += frase
}
return resultado
}
repiteLaFrase(frase: "Hallo Welt", cuantasVeces: 4)
func repiteLaFrase2 (quieroRepetir frase: String, cuantasVeces n:Int) -> String{
var resultado = ""
for _ in 0..<n{
resultado += frase
}
return resultado
}
repiteLaFrase2(quieroRepetir: "D'oh", cuantasVeces: 3)
func repiteLaFrase3(_ frase: String, _ n: Int) ->String{
var resultado = ""
for _ in 0..<n {
resultado += frase
}
return resultado
}
repiteLaFrase3("Ay Caramba",10)
func encuentraPares(arregloDeEnteros: [Int]) -> Array<Int>? {
if arregloDeEnteros.isEmpty{
return nil
}
var numerosEncontrados = [Int] ()
for numero in arregloDeEnteros {
if numero % 2 == 0{
numerosEncontrados.append(numero)
}
}
return numerosEncontrados
}
if let hayPares = encuentraPares(arregloDeEnteros: []){
print(hayPares[0])
} else {
print("Se recibió nil")
}
if let hayPares = encuentraPares(arregloDeEnteros: [1,2,3,4,5]){ //Aquí imprime el 2
print(hayPares[0])
} else {
print("Se recibió nil")
}
if let hayPares = encuentraPares(arregloDeEnteros: [1,3,5,7,9]){
if hayPares.isEmpty{
print("No hubo números pares")
} else {
print(hayPares[0])
}
} else {
print("Se recibió nil")
}
func despidete() {
print("Auf Wiedersehen")
}
despidete()
let chao = despidete
chao()
func funcionQueRecibeUnaFuncion(argumento: () -> ()){
for i in 1...3{
print (i)
argumento()
}
}
funcionQueRecibeUnaFuncion(argumento: chao)
funcionQueRecibeUnaFuncion {
print("Ya no soy Auf Wiedersehen")
let funcionQueImprimeLaFecha = {
let fecha = Date()
print(fecha)
}
funcionQueRecibeUnaFuncion(argumento: funcionQueImprimeLaFecha)
func convierteEnteroAFlotante(enteroAConvertir: Int) -> Float{
return(Float(enteroAConvertir))
}
//funcionQueRecibeUnaFuncion(argumento: convierteEnteroAFlotante(enteroAConvertir: 42))
func elevaAlCuadrado(numero: Int ,funcion: (Int) -> Float) -> Float {
let resultado = powf(funcion(numero), 2.0)
return(resultado)
}
elevaAlCuadrado(numero: 5, funcion: convierteEnteroAFlotante(enteroAConvertir:))
func factorial(de: Int) -> Float{
var resultado = 1
for i in 2...de {
resultado *= i
}
return (Float(resultado))
}
factorial(de:10)
elevaAlCuadrado(numero: 10, funcion: factorial(de:))//(x!)^2 "Equis factorial al cuadrado"
let divideEnteroAFlotante = {
(entero: Int) -> Float in
return (Float(entero/2))
}
elevaAlCuadrado(numero: 7, funcion: divideEnteroAFlotante)
func enterosQueCumplenUnaCondicion(enterosAProbar: [Int], condicion: (Int) -> Bool) -> [Int]? {
if enterosAProbar.isEmpty{return nil}
var arregloARegresar = [Int] ()
for numero in enterosAProbar {
if condicion(numero){
arregloARegresar.append(numero)
}
}
return arregloARegresar
}
let misEnteros = [-2,4,9,-12,8,0,19]
func mayorATres(numero:Int) -> Bool{
return numero > 3
}
enterosQueCumplenUnaCondicion(enterosAProbar: misEnteros, condicion: mayorATres(numero:))
let multiplosDeDos = { //Condicion
(entero: Int) -> Bool in
return entero%2 == 0
}
enterosQueCumplenUnaCondicion(enterosAProbar: misEnteros, condicion: multiplosDeDos)
enterosQueCumplenUnaCondicion(enterosAProbar: misEnteros) {(numero) -> Bool in
return numero < 0
}
var familiaSimpson = ["Marge", "Bart", "Lisa", "Abraham", "Ayudante de Santa", "Bola de Nieve", "Patty", "Homero", "Selma", "Bola de Nieve 2", "Herbert"]
familiaSimpson.sorted()
familiaSimpson.description
func ordenDescendiente (string1: String, string2: String) -> Bool{ //Recibe elemeneto, elemento y regresa Booleano
return string1 > string2
}
familiaSimpson.sorted(by: ordenDescendiente(string1:string2:))
ordenDescendiente(string1: "Zumbes", string2: "Zumbe")
let ordenDescendienteInLine = {
(string1: String, string2: String) -> Bool in
return string1 > string2
}
familiaSimpson.sorted(by: ordenDescendienteInLine)
familiaSimpson.sorted(by: {
(string1: String, string2: String) -> Bool in
return string1 > string2
})
familiaSimpson.sorted(by: {
string1, string2 in return string1 > string2
})
familiaSimpson.sorted(by: {
string1, string2 in string1 > string2
})
print (familiaSimpson.sorted(by:{$0 > $1}))
print (familiaSimpson.sorted(by: > ))
}
| true
|
04916a74a858275eb68d10b1312d07aa9f9d0200
|
Swift
|
NYCgirlLearnsToCode/AC-iOS-MidUnit4Assessment
|
/AC-iOS-MidUnit4Assessment-StudentVersion/Models/NewDeck.swift
|
UTF-8
| 1,061
| 2.9375
| 3
|
[] |
no_license
|
//
// NewDeck.swift
// AC-iOS-MidUnit4Assessment-StudentVersion
//
// Created by Lisa J on 12/22/17.
// Copyright © 2017 C4Q . All rights reserved.
//
import Foundation
struct NewDeck: Codable {
let deck_id: String
}
//https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=6
class NewDeckAPIClient {
private init() {}
static let manager = NewDeckAPIClient()
func getNewDeck(urlStr: String, completionHandler: @escaping (NewDeck) -> Void, errorHandler: @escaping (Error) -> Void) {
guard let url = URL(string: urlStr) else {return}
let request = URLRequest(url: url)
let completion: (Data) -> Void = {(data: Data) in
do {
let allResults = try JSONDecoder().decode(NewDeck.self, from: data)
let decks = allResults
completionHandler(decks)
} catch {
errorHandler(error)
}
}
NetworkHelper.manager.performDataTask(with: request, completionHandler: completion, errorHandler: errorHandler)
}
}
| true
|
a526916d145e7fe092358a398ee19f00a28b09d3
|
Swift
|
stevenyuser/100DaysOfSwiftUI
|
/Converter/Converter/ContentView.swift
|
UTF-8
| 2,530
| 3.453125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// Converter
//
// Created by Steven Yu on 7/24/21.
//
import SwiftUI
struct ContentView: View {
@State private var inputUnit = 0
@State private var outputUnit = 1
@State private var inputNumber = ""
var outputNumber: Double {
let temperature = Double(inputNumber) ?? 0
switch units[inputUnit] {
case "Celsius":
switch units[outputUnit] {
case "Farenheit":
return (temperature * 9/5) + 32
case "Kelvin":
return temperature + 273.15
default:
return temperature
}
case "Farenheit":
switch units[outputUnit] {
case "Celsius":
return (temperature - 32) * 5/9
case "Kelvin":
return (temperature - 32) * 5/9 + 273.15
default:
return temperature
}
case "Kelvin":
switch units[outputUnit] {
case "Celsius":
return temperature - 273.15
case "Farenheit":
return (temperature - 273.15) * 9/5 + 32
default:
return temperature
}
default:
return 0
}
}
let units = ["Celsius", "Farenheit", "Kelvin"]
var body: some View {
NavigationView {
Form {
Section {
TextField("Temperature", text: $inputNumber)
.keyboardType(.decimalPad)
Picker("Original Unit", selection: $inputUnit) {
ForEach(0 ..< units.count) {
Text("\(self.units[$0])")
}
}
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Converted Temperature")) {
Text("\(outputNumber, specifier: "%.1f")")
Picker("Original Unit", selection: $outputUnit) {
ForEach(0 ..< units.count) {
Text("\(self.units[$0])")
}
}
.pickerStyle(SegmentedPickerStyle())
}
}
.navigationBarTitle("Convert Temperature")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
acaf8cb01862682838fda3a8a938febcdd2cb7ce
|
Swift
|
jjamminjim/LicensePlist
|
/Sources/LicensePlistCore/Parser/Parser.swift
|
UTF-8
| 78
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
public protocol Parser {
static func parse(_ content: String) -> [Self]
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.