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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
72448f3f431aa0d9c913c97bf74db89357e18bb9
|
Swift
|
jkolb/Swiftish
|
/Sources/Swiftish/Bounds3.swift
|
UTF-8
| 9,619
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
/*
The MIT License (MIT)
Copyright (c) 2015-2017 Justin Kolb
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public struct Bounds3<T: Vectorable> : Hashable {
public var center: Vector3<T>
public var extents: Vector3<T>
public init() {
self.init(center: Vector3<T>(), extents: Vector3<T>())
}
public init(minimum: Vector3<T>, maximum: Vector3<T>) {
precondition(minimum.x <= maximum.x)
precondition(minimum.y <= maximum.y)
precondition(minimum.z <= maximum.z)
let center = (maximum + minimum) / 2
let extents = (maximum - minimum) / 2
self.init(center: center, extents: extents)
}
public init(center: Vector3<T>, extents: Vector3<T>) {
precondition(extents.x >= 0)
precondition(extents.y >= 0)
precondition(extents.z >= 0)
self.center = center
self.extents = extents
}
public init(union: [Bounds3<T>]) {
var minmax = [Vector3<T>]()
for other in union {
if !other.isNull {
minmax.append(other.minimum)
minmax.append(other.maximum)
}
}
self.init(containingPoints: minmax)
}
public init(containingPoints points: [Vector3<T>]) {
if points.count == 0 {
self.init()
return
}
var minimum = Vector3<T>(+T.greatestFiniteMagnitude, +T.greatestFiniteMagnitude, +T.greatestFiniteMagnitude)
var maximum = Vector3<T>(-T.greatestFiniteMagnitude, -T.greatestFiniteMagnitude, -T.greatestFiniteMagnitude)
for point in points {
if point.x < minimum.x {
minimum.x = point.x
}
if point.x > maximum.x {
maximum.x = point.x
}
if point.y < minimum.y {
minimum.y = point.y
}
if point.y > maximum.y {
maximum.y = point.y
}
if point.z < minimum.z {
minimum.z = point.z
}
if point.z > maximum.z {
maximum.z = point.z
}
}
self.init(minimum: minimum, maximum: maximum)
}
public var minimum: Vector3<T> {
return center - extents
}
public var maximum: Vector3<T> {
return center + extents
}
public var isNull: Bool {
return center == Vector3<T>() && extents == Vector3<T>()
}
public func contains(point: Vector3<T>) -> Bool {
if point.x < minimum.x { return false }
if point.y < minimum.y { return false }
if point.z < minimum.z { return false }
if point.x > maximum.x { return false }
if point.y > maximum.y { return false }
if point.z > maximum.z { return false }
return true
}
/// If `other` bounds intersects current bounds, return their intersection.
/// A `null` Bounds3 object is returned if any of those are `null` or if they don't intersect at all.
///
/// - Note: A Bounds3 object `isNull` if it's center and extents are zero.
/// - Parameter other: The second Bounds3 object to intersect with.
/// - Returns: A Bounds3 object intersection.
public func intersection(other: Bounds3<T>) -> Bounds3<T> {
if isNull {
return self
}
else if other.isNull {
return other
}
else if minimum.x <= other.maximum.x && other.minimum.x <= maximum.x && maximum.y <= other.minimum.y && other.maximum.y <= minimum.y && maximum.z <= other.minimum.z && other.maximum.z <= minimum.z {
let minX = max(minimum.x, other.minimum.x)
let minY = max(minimum.y, other.minimum.y)
let minZ = max(minimum.z, other.minimum.z)
let maxX = min(maximum.x, other.maximum.x)
let maxY = min(maximum.y, other.maximum.y)
let maxZ = min(maximum.z, other.maximum.z)
return Bounds3<T>(minimum: Vector3<T>(minX, minY, minZ), maximum: Vector3<T>(maxX, maxY, maxZ))
}
return Bounds3<T>()
}
public func union(other: Bounds3<T>) -> Bounds3<T> {
if isNull {
return other
}
else if other.isNull {
return self
}
else {
return Bounds3<T>(containingPoints: [minimum, maximum, other.minimum, other.maximum])
}
}
public func union(others: [Bounds3<T>]) -> Bounds3<T> {
var minmax = [Vector3<T>]()
if !isNull {
minmax.append(minimum)
minmax.append(maximum)
}
for other in others {
if !other.isNull {
minmax.append(other.minimum)
minmax.append(other.maximum)
}
}
if minmax.count == 0 {
return self
}
else {
return Bounds3<T>(containingPoints: minmax)
}
}
public var description: String {
return "{\(center), \(extents)}"
}
public var corners: [Vector3<T>] {
let max: Vector3<T> = maximum
let corner0: Vector3<T> = max * Vector3<T>(+1, +1, +1)
let corner1: Vector3<T> = max * Vector3<T>(-1, +1, +1)
let corner2: Vector3<T> = max * Vector3<T>(+1, -1, +1)
let corner3: Vector3<T> = max * Vector3<T>(+1, +1, -1)
let corner4: Vector3<T> = max * Vector3<T>(-1, -1, +1)
let corner5: Vector3<T> = max * Vector3<T>(+1, -1, -1)
let corner6: Vector3<T> = max * Vector3<T>(-1, +1, -1)
let corner7: Vector3<T> = max * Vector3<T>(-1, -1, -1)
return [
corner0, corner1, corner2, corner3,
corner4, corner5, corner6, corner7,
]
}
public static func distance2<T>(_ point: Vector3<T>, _ bounds: Bounds3<T>) -> T {
var distanceSquared: T = 0
let minimum = bounds.minimum
let maximum = bounds.maximum
for index in 0..<3 {
let p = point[index]
let bMin = minimum[index]
let bMax = maximum[index]
if p < bMin {
let delta = bMin - p
distanceSquared = distanceSquared + delta * delta
}
if p > bMax {
let delta = p - bMax
distanceSquared = distanceSquared + delta * delta
}
}
return distanceSquared
}
public func intersectsOrIsInside(_ plane: Plane<T>) -> Bool {
let projectionRadiusOfBox = Vector3<T>.sum(extents * Vector3<T>.abs(plane.normal))
let distanceOfBoxCenterFromPlane = Vector3<T>.dot(plane.normal, center) - plane.distance
let intersects = abs(distanceOfBoxCenterFromPlane) <= projectionRadiusOfBox
let isInside = projectionRadiusOfBox <= distanceOfBoxCenterFromPlane
return intersects || isInside
}
public func intersectsOrIsInside(_ frustum: Frustum<T>) -> Bool {
if isNull {
return false
}
// In order of most likely to cause early exit
if !intersectsOrIsInside(frustum.near) { return false }
if !intersectsOrIsInside(frustum.left) { return false }
if !intersectsOrIsInside(frustum.right) { return false }
if !intersectsOrIsInside(frustum.top) { return false }
if !intersectsOrIsInside(frustum.bottom) { return false }
if !intersectsOrIsInside(frustum.far) { return false }
return true
}
public func intersects(_ plane: Plane<T>) -> Bool {
let projectionRadiusOfBox = Vector3<T>.sum(extents * Vector3<T>.abs(plane.normal))
let distanceOfBoxCenterFromPlane = Swift.abs(Vector3<T>.dot(plane.normal, center) - plane.distance)
return distanceOfBoxCenterFromPlane <= projectionRadiusOfBox
}
public func intersects(_ bounds: Bounds3<T>) -> Bool {
if Swift.abs(center.x - bounds.center.x) > (extents.x + bounds.extents.x) { return false }
if Swift.abs(center.y - bounds.center.y) > (extents.y + bounds.extents.y) { return false }
if Swift.abs(center.z - bounds.center.z) > (extents.z + bounds.extents.z) { return false }
return true
}
public func transform(_ t: Transform3<T>) -> Bounds3<T> {
return Bounds3<T>(containingPoints: corners.map({ $0.transform(t) }))
}
}
| true
|
a359d0a0e235951adc767a9784f2d57299f2dbbf
|
Swift
|
zooTheBear/MoibleGameHandIn
|
/FightTheDead/FightTheDead/Utilities/CGPoint+VectorMath.swift
|
UTF-8
| 2,835
| 3.453125
| 3
|
[] |
no_license
|
//
// CGPoint+VectorMath.swift
// ZombieConga
//
// Created by Kevin Kruusi on 2018-02-15.
// Copyright © 2018 kevin. All rights reserved.
//
import SpriteKit
// MARK: - Vector Math extention
extension CGPoint {
// get the length of self
var length: CGFloat {
return sqrt( x * x + y * y)
}
/// get the unit vector of self
var asUnitVector: CGPoint {
return divide(by: length)
}
/// divide self by a scalar
///
/// - Parameter by: a CGFloat scalar number
/// - Returns: the divided point
func divide(by: CGFloat) -> CGPoint {
return CGPoint(x: self.x / by, y: y / by)
}
/// Simple movement function that starts where you currently are
///
/// - Parameters:
/// - direction: what direction you wish to travel should be a unit vector
/// - velocity: the velocity you wish to travel
/// - time: the time you wish to travel
/// - Returns: the distance you traveled from where you currently are
func travel(in direction: CGPoint, at velocity: CGFloat, for time: TimeInterval) -> CGPoint {
return CGPoint(x: velocity * CGFloat(time) * direction.x + x, y: velocity * CGFloat(time) * direction.y + y)
}
/// add two CGPoints together
///
/// - Parameters:
/// - left: the left side of the addition
/// - right: the right side of the addition
/// - Returns: the result
static func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
static func * (left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x * right, y: left.y * right)
}
/// subtract one CGPoint from another
///
/// - Parameters:
/// - left: the left side of the subtraction
/// - right: the right side of the subtraction
/// - Returns: the result
static func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
/// A simple check to see if you have reached your target by compairing direction vectors
///
/// - Parameter target: the next iteration of your target direction
/// - Returns: true or false you your target vector has mutated in another direction
func didOvershoot(next target: CGPoint) -> Bool {
if (self.x > 0) == (target.x > 0) && (self.y > 0) == (target.y > 0) {
return true
}
return false
}
/// Returns the facing angle of a given direction in radians
///
/// - Parameter direction: the direction you wish to point
/// - Returns: the angel in radians
static func facingAngle(_ direction: CGPoint) -> CGFloat {
return CGFloat( atan2( Double(direction.y), Double(direction.x)))
}
}
| true
|
f8fcd836996bfe140f3f030fefd39404402d33d3
|
Swift
|
vivinjeganathan/ErrorHandling
|
/ErrorHandling/Layer3.swift
|
UTF-8
| 1,156
| 3.03125
| 3
|
[] |
no_license
|
//
// Layer3.swift
// ErrorHandling
//
// Created by Jeganathan, Vivin () on 12/22/15.
// Copyright © 2015 Allstate. All rights reserved.
//
import UIKit
enum MyError : ErrorType
{
case e1
}
class Layer3: NSObject
{
//EXAMPLE
func add(a: Int, b: Int) throws -> Int
{
if (a==0 || b==0)
{
throw MyError.e1
}
return a+b
}
static func layer3Func(url : NSURL, completionHandler : (responseStringFromL3 : String) -> Void) throws -> Void
{
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) { (data, urlResponse, var error) -> Void in
//ASSUMING ERROR OCCURS IN WEB SERVICE CALL
error = NSError(domain: "domain", code: 1, userInfo: nil)
if(error == nil)
{
completionHandler(responseStringFromL3: "abc")
}
else
{
// NEED TO PROPAGATE ERROR TO THE VIEW CONTROLLER WHICH IS THREE LAYERS DEEP
// ???
}
}
task.resume()
}
}
| true
|
f5efab11057083d38c7e21c36a50ea09782113c1
|
Swift
|
zoeyj25/ZoeyJohnston_MAD
|
/lab1/lab1/lab1/ViewController.swift
|
UTF-8
| 952
| 2.65625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// lab1
//
// Created by Zoey Lee Johnston on 9/11/17.
// Copyright © 2017 Zoey Lee Johnston. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var artImage: UIImageView!
@IBOutlet weak var artTitle: UILabel!
@IBAction func artChoice(_ sender: UIButton) {
if sender.tag == 1 {
artImage.image=UIImage(named: "color3")
artTitle.text="Color Influences"
}
else if sender.tag == 2 {
artImage.image=UIImage(named: "black1")
artTitle.text="B&W Influences"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
84464368a638d8d4387d480ecec6e71f2d008d03
|
Swift
|
rohitgarg4989/DemoWeatherForecastApp
|
/DemoWeatherApp/CommonUtility/Extensions/CommonExtensions.swift
|
UTF-8
| 2,454
| 3.15625
| 3
|
[] |
no_license
|
//
// CommonExtensions.swift
// DemoWeatherApp
//
// Created by Rohit Garg on 1/5/19.
// Copyright © 2019 Rohit Garg. All rights reserved.
//
import Foundation
import UIKit
// MARK: - String Helper Methods
extension String {
var isBlank: Bool {
return self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
}
extension Optional where Wrapped == String {
var isValidNonEmptyString: String? {
if let unwrapped = self {
return unwrapped.isBlank ? nil: unwrapped
} else {
return nil
}
}
}
// MARK: - UserDefaults Helper Methods
struct UserDefaultsKeys {
static let kCity = "city"
static let kIsCitySelected = "isCitySelected"
}
extension UserDefaults {
class func bool(forKey key: String) -> Bool {
return self.standard.bool(forKey: key)
}
class func setBool(value: Bool, forKey key: String) {
self.standard.set(value, forKey: key)
}
class func setObject(object: Any, forKey key: String) {
if let data:Data = NSKeyedArchiver.archivedData(withRootObject: object) as Data? {
self.standard.set(data, forKey: key)
self.standard.synchronize()
}
}
class func getObject(forKey key: String) -> Any? {
if let data = self.standard.object(forKey: key) as? Data {
if let object:AnyObject = NSKeyedUnarchiver.unarchiveObject(with: data) as AnyObject? {
return object
}
}
return nil
}
}
extension UIViewController {
func showAlert(withMessage message: String) {
let alert = UIAlertController(title: "Demo Weather App", message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
extension Date {
static func weatherDate(_ dt: Double) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE dd MMM"
let date = Date(timeIntervalSince1970: dt)
return dateFormatter.string(from: date)
}
static func weatherTime(_ dt: Double) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh a"
let date = Date(timeIntervalSince1970: dt)
return dateFormatter.string(from: date)
}
}
| true
|
d765476f1118fdcf9b44c3b3b908f29c5c7b1a90
|
Swift
|
lillianchou94/ios-decal-proj4
|
/bridges/bridges/DashboardTableViewController.swift
|
UTF-8
| 5,284
| 2.515625
| 3
|
[] |
no_license
|
//
// DashboardTableViewController.swift
// bridges
//
// Created by Lilly Chou on 5/1/16.
// Copyright © 2016 Lilly Chou. All rights reserved.
//
import UIKit
var currentUser: User!
class DashboardTableViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var mentorshipsArray = [Mentorship]()
override func viewDidLoad() {
super.viewDidLoad()
//Load Mentorships from plist into Array
let path = NSBundle.mainBundle().pathForResource("Mentorships", ofType: "plist")
let dictArray = NSArray(contentsOfFile: path!)
currentUser = User (name: "Default User", contact: "123-456-7890", liked: ["Let's Rise"], communities: ["High School"])
for mentorshipItem in dictArray! {
let newMentorship : Mentorship = Mentorship(name:(mentorshipItem.objectForKey("name")) as! String, location: (mentorshipItem.objectForKey("location")) as! String, description: (mentorshipItem.objectForKey("description")) as! String, website: (mentorshipItem.objectForKey("website")) as! String, type: (mentorshipItem.objectForKey("type")) as! String, communities: (mentorshipItem.objectForKey("communities")) as! [String])
mentorshipsArray.append(newMentorship)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return mentorshipsArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MentorshipCell") as! MentorshipCell
let mentorship = mentorshipsArray[indexPath.row]
cell.orgName.text = mentorship.name
cell.orgLocation.text = mentorship.location
var comm = mentorship.communities[0]
var index = 1
while index < mentorship.communities.count{
comm += (", " + mentorship.communities[index])
index += 1
}
cell.orgCommunities.text = comm
if currentUser.liked.contains(mentorship.name){
cell.orgLike.selected = true
} else{
cell.orgLike.selected = false
}
return cell
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let mentorshipDetail : Mentorship = mentorshipsArray[indexPath.row]
let controller = segue.destinationViewController as! DetailViewController
// let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.mentorshipDetail = mentorshipDetail
// controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
// controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
088a5ae7603fad42b005a5e7afda04348488457b
|
Swift
|
eliasprog/Buttsssbook
|
/buttsssbook-app/buttsssbook/Form/Row.swift
|
UTF-8
| 402
| 2.578125
| 3
|
[] |
no_license
|
//
// Row.swift
// buttsssbook
//
// Created by Mateus Rodrigues on 13/05/20.
// Copyright © 2020 Mateus Rodrigues. All rights reserved.
//
import Foundation
protocol Row {
var title: String { get }
}
struct TextFieldRow: Row {
var title: String
var isSecureTextEntry: Bool
// var regex: String? = nil
}
struct ButtonRow: Row {
var title: String
var target: Any?
var action: Selector
}
| true
|
363c8df9c08a7231458fec6e49ca9dfa02df68be
|
Swift
|
caelumturc/Ankagram-0.2
|
/Ankagram/Message.swift
|
UTF-8
| 422
| 2.703125
| 3
|
[] |
no_license
|
import Foundation
import Foundation
struct Message {
var fromId: String
var text: String
var toId: String
var timeStamp: Double
init(dictionary: [String: Any]) {
fromId = dictionary["fromId"] as? String ?? ""
text = dictionary["text"] as? String ?? ""
toId = dictionary["toId"] as? String ?? ""
timeStamp = dictionary["timeStamp"] as? Double ?? 0
}
}
| true
|
0efff6de7431a0ecdf56d3f93f2b3d04c0891f0b
|
Swift
|
catverse/Breaking
|
/iOS/Description.swift
|
UTF-8
| 2,018
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
import SwiftUI
struct Description: View {
@Binding var item: Item!
@State private var when = ""
var body: some View {
ScrollView {
HStack {
Text(.init(.key("Provider.\(item.provider)") + ": " + when))
.foregroundColor(.secondary)
Spacer()
}.padding()
HStack {
Text(item.description)
.font(.title)
.foregroundColor(.secondary)
.fixedSize(horizontal: false, vertical: true)
Spacer()
}.padding()
HStack {
Spacer()
Button(action: {
self.item.favourite.toggle()
news.balam.update(self.item!)
}) {
Image(systemName: "heart.fill")
.foregroundColor(item.favourite ? .init("lightning") : .secondary)
}.frame(width: 80, height: 80)
Spacer()
}
HStack {
Spacer()
Button(action: {
UIApplication.shared.open(self.item.link)
}) {
Text("More")
}.frame(width: 180, height: 42)
.font(Font.footnote.bold())
.foregroundColor(.black)
.background(Color("lightning"))
.cornerRadius(6)
Spacer()
}.padding(.bottom, 40)
}.navigationBarTitle(item.title)
.onAppear {
self.when = self.item.date > Calendar.current.date(byAdding: .hour, value: -23, to: .init())!
? RelativeDateTimeFormatter().localizedString(for: self.item.date, relativeTo: .init())
: {
$0.dateStyle = .full
$0.timeStyle = .none
return $0.string(from: self.item.date)
} (DateFormatter())
}
}
}
| true
|
f5183579dde7436323e2a845352e695cc67157d5
|
Swift
|
gongchengxiaofendui/Game-2048
|
/Game2048/MainViewController.swift
|
UTF-8
| 12,220
| 2.671875
| 3
|
[] |
no_license
|
//
// MainViewController.swift
// Game2048
//
// Created by Lancelot on 15/11/13.
// Copyright © 2015年 Lancelot. All rights reserved.
//
import UIKit
enum Animation2048Type
{
case None //无动画
case New //新数动画
case Merge //合并动画
}
class MainViewController:UIViewController{
var dimension:Int = 4
{
didSet{
gmodel.dimension = dimension
}
}//游戏方格维度
var maxnumber:Int = 2048
{
didSet{
gmodel.maxnumber = maxnumber
}
}//游戏过关最大值
var width:CGFloat = 50 //数字格子的宽度
var padding:CGFloat = 6 //格子之间的间距
var backgrounds:Array<UIView>//保存背景图数据
var gmodel:Gamemodel! //游戏数据模型
var tiles:Dictionary<NSIndexPath,TileView> //保存界面上的Label数据
var tileVals:Dictionary<NSIndexPath,Int> //保存实际数字值
var score:ScoreView!
var bestscore:BestScoreView!
init()
{
self.backgrounds = Array<UIView>()
self.tiles = Dictionary()
self.tileVals = Dictionary()
super.init(nibName:nil,bundle:nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad()
{
super.viewDidLoad()
setupBackground()
setupButtons()
setupSwipeGuestures()
setupScoreLabels()
self.gmodel = Gamemodel(dimension: self.dimension,maxnumber:maxnumber,score:score,bestscore:bestscore)
for _ in 0..<2
{
genNumber()
}
}
func setupButtons()
{
let cv = ControlView()
let btnreset = cv.createButton("重置", action: Selector("resetTapped"), sender: self)
btnreset.frame.origin.x = 50
btnreset.frame.origin.y = 450
self.view.addSubview(btnreset)
let btngen = cv.createButton("新数", action: Selector("genTapped"), sender: self)
btngen.frame.origin.x = 170
btngen.frame.origin.y = 450
self.view.addSubview(btngen)
}
func setupScoreLabels()
{
score = ScoreView()
score.frame.origin.x = 50
score.frame.origin.y = 80
score.changeScore(value: 0)
self.view.addSubview(score)
bestscore = BestScoreView()
bestscore.frame.origin.x = 170
bestscore.frame.origin.y = 80
bestscore.changeScore(value: 0)
self.view.addSubview(bestscore)
}
func genTapped()
{
print("gen")
genNumber()
}
func resetTapped()
{
print("reset")
resetUI()
gmodel.initTiles()
genNumber()
genNumber()
}
func initUI()
{
var index:Int
var key:NSIndexPath
var tile:TileView
var tileVal:Int
var success = false
for i in 0..<dimension
{
for j in 0..<dimension
{
index = i * self.dimension + j
key = NSIndexPath(forRow: i, inSection: j)
if(gmodel.tiles[index] >= maxnumber)
{
success = true
}
//原来界面没有值,模型数据中有值
if((gmodel.tiles[index] > 0) && (tileVals.indexForKey(key) == nil))
{
insertTile((i,j), value: gmodel.mtiles[index], atype:Animation2048Type.Merge)
}
//原来有值,现在模型中没有值
if((gmodel.tiles[index] == 0) && (tileVals.indexForKey(key) != nil))
{
tile = tiles[key]!
tile.removeFromSuperview()
tiles.removeValueForKey(key)
tileVals.removeValueForKey(key)
}
//原来有值,现在还是有值
if((gmodel.tiles[index] > 0) && (tileVals.indexForKey(key) != nil))
{
tileVal = tileVals[key]!
if(tileVal != gmodel.tiles[index])
{
tile = tiles[key]!
tile.removeFromSuperview()
tiles.removeValueForKey(key)
tileVals.removeValueForKey(key)
insertTile((i,j), value: gmodel.tiles[index], atype:Animation2048Type.Merge)
}
}
/* if(gmodel.tiles[index] != 0)
{
insertTile((i,j), value: gmodel.mtiles[index])
}
*/
}
}
if(gmodel.isSuccess())
{
let alertView = UIAlertView()
alertView.title = "恭喜"
alertView.message = "您已通关!"
alertView.addButtonWithTitle("确定")
alertView.show()
return
}
}
func resetUI()
{
for(_,tile) in tiles
{
tile.removeFromSuperview()
}
tiles.removeAll(keepCapacity: true)
tileVals.removeAll(keepCapacity: true)
for background in backgrounds
{
background.removeFromSuperview()
}
setupBackground()
score.changeScore(value: 0)
}
func removeKeyTile(key:NSIndexPath)
{
let tile = tiles[key]!
_ = tileVals[key]
tile.removeFromSuperview()
tiles.removeValueForKey(key)
tileVals.removeValueForKey(key)
}
func setupBackground()
{
var x:CGFloat = 30
var y:CGFloat = 150
for _ in 0..<dimension
{
y = 150
for _ in 0..<dimension
{
let background = UIView(frame:CGRectMake(x,y,width,width))
background.backgroundColor = UIColor.darkGrayColor()
self.view.addSubview(background)
backgrounds += [background]
y += padding + width
}
x += padding + width
}
}
func setupSwipeGuestures()
{
let upSwipe = UISwipeGestureRecognizer(target:self, action: Selector("swipeUp"))
upSwipe.numberOfTouchesRequired = 1
upSwipe.direction = UISwipeGestureRecognizerDirection.Up
self.view.addGestureRecognizer(upSwipe)
let downSwipe = UISwipeGestureRecognizer(target:self, action: Selector("swipeDown"))
downSwipe.numberOfTouchesRequired = 1
downSwipe.direction = UISwipeGestureRecognizerDirection.Down
self.view.addGestureRecognizer(downSwipe)
let leftSwipe = UISwipeGestureRecognizer(target:self, action: Selector("swipeLeft"))
leftSwipe.numberOfTouchesRequired = 1
leftSwipe.direction = UISwipeGestureRecognizerDirection.Left
self.view.addGestureRecognizer(leftSwipe)
let rightSwipe = UISwipeGestureRecognizer(target:self, action: Selector("swipeRight"))
rightSwipe.numberOfTouchesRequired = 1
rightSwipe.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(rightSwipe)
}
func printTiles(tiles:Array<Int>)
{
let count = tiles.count
for var i = 0; i < count; i++
{
if(i + 1) % Int(dimension) == 0
{
print("\(tiles[i])\n")
}
else
{
print("\(tiles[i])\t")
}
}
}
func swipeUp()
{
print("swipeup")
gmodel.reflowUp()
gmodel.mergeUp()
gmodel.reflowUp()
printTiles(gmodel.tiles)
printTiles(gmodel.mtiles)
// resetUI()
initUI()
if(!gmodel.isSuccess())
{
genNumber()
}
/*
for i in 0..<dimension
{
for j in 0..<dimension
{
var row:Int = i
var col:Int = j
var key = NSIndexPath(forRow: row, inSection: col)
if(tileVals.indexForKey(key) != nil)
{
//if row>3 move up one line
if(row > 0)
{
var value = tileVals[key]
removeKeyTile(key)
var index = row * dimension + col - dimension
row = Int(index / dimension)
col = index - row * dimension
insertTile((row,col), value:value!)
}
}
}
}
*/
}
func swipeDown()
{
print("swipedown")
gmodel.reflowDown()
gmodel.mergeDown()
gmodel.reflowDown()
printTiles(gmodel.tiles)
printTiles(gmodel.mtiles)
// resetUI()
initUI()
if(!gmodel.isSuccess())
{
genNumber()
}
}
func swipeLeft()
{
print("swipeleft")
gmodel.reflowLeft()
gmodel.mergeLeft()
gmodel.reflowLeft()
printTiles(gmodel.tiles)
printTiles(gmodel.mtiles)
// resetUI()
initUI()
if(!gmodel.isSuccess())
{
genNumber()
}
}
func swipeRight()
{
print("swiperight")
gmodel.reflowRight()
gmodel.mergeRight()
gmodel.reflowRight()
printTiles(gmodel.tiles)
printTiles(gmodel.mtiles)
// resetUI()
initUI()
if(!gmodel.isSuccess())
{
genNumber()
}
}
func genNumber()
{
let randv = Int(arc4random_uniform(10))
print(randv)
var seed:Int = 2
if(randv == 1)
{
seed = 4
}
let col = Int(arc4random_uniform(UInt32(dimension)))
let row = Int(arc4random_uniform(UInt32(dimension)))
if(gmodel.isfull())
{
print("位置已经满了")
let alertView = UIAlertView()
alertView.title = "Game Over!"
alertView.message = "Game Over!"
alertView.addButtonWithTitle("确定")
alertView.show()
return
}
if(gmodel.setPosition(row, col: col, value: seed) == false)
{
genNumber()
return
}
insertTile((row,col),value:seed,atype:Animation2048Type.New)
}
func insertTile(pos:(Int,Int),value:Int,atype:Animation2048Type)
{
let (row,col)=pos;
let x = 30 + CGFloat(col) * (width + padding)
let y = 150 + CGFloat(row) * (width + padding)
let tile = TileView(pos:CGPointMake(x,y),width:width,value:value)
self.view.addSubview(tile)
self.view.bringSubviewToFront(tile)
let index = NSIndexPath(forRow: row, inSection: col)
tiles[index] = tile
tileVals[index] = value
if(atype == Animation2048Type.None)
{
return
}
else if(atype == Animation2048Type.New)
{
tile.layer.setAffineTransform(CGAffineTransformMakeScale(0.05, 0.05))
}
else if(atype == Animation2048Type.Merge)
{
tile.layer.setAffineTransform(CGAffineTransformMakeScale(0.8, 0.8))
}
tile.layer.setAffineTransform(CGAffineTransformMakeScale(0.05, 0.05))
UIView.animateWithDuration(0.3, delay: 0.1, options: UIViewAnimationOptions.TransitionNone, animations:
{
() -> Void in
tile.layer.setAffineTransform(CGAffineTransformMakeScale(1, 1))
}, completion:
{
(finished:Bool) -> Void in
UIView.animateWithDuration(0.08, animations: {
() -> Void in
tile.layer.setAffineTransform(CGAffineTransformIdentity)
})
})
}
}
| true
|
f08a9e5f633f68c89f4271acb8f1b9dbb60b6790
|
Swift
|
WHuangz88/SwiftDuxNavigation
|
/Sources/AppNavigation/UI/Route.swift
|
UTF-8
| 1,301
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
import SwiftDux
import SwiftUI
/// Starts a new Route with a given name.
public struct Route<Content>: View where Content: View {
@Environment(\.actionDispatcher) private var dispatch
public var name: String
public var content: Content
/// Initiate a Route with a name.
///
/// - Parameters:
/// - name: The name of the route.
/// - content: A closure that returns the content of the waypoint.
public init(name: String, @ViewBuilder content: () -> Content) {
self.name = name
self.content = content()
}
public var body: some View {
let waypoint = Waypoint(
routeName: name,
path: "/",
isDetail: false,
isActive: Binding(get: { true }, set: { _ in }),
destination: .constant("")
)
return
content
.environment(\.waypoint, waypoint)
.transformPreference(VerifiedPathPreferenceKey.self) { preference in
if preference.primaryPath.isEmpty {
preference.primaryPath = "/"
}
}
.onPreferenceChange(VerifiedPathPreferenceKey.self) { preference in
let primaryPath = preference.primaryPath
let detailPath = preference.detailPath
dispatch(NavigationAction.verifyRoutePaths(primaryPath: primaryPath, detailPath: detailPath, routeName: name))
}
}
}
| true
|
2570de5cc5373e2a7468d53e283cfb856bb50316
|
Swift
|
paulnguyen/cmpe202
|
/swift/quickstart/07.optional.swift
|
UTF-8
| 1,129
| 4.15625
| 4
|
[] |
no_license
|
/*
A Swift Tour
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html
*/
// You can use if and let together to work with values that might be missing.
// These values are represented as optionals. An optional value either
// contains a value or contains nil to indicate that a value is missing. Write
// a question mark (?) after the type of a value to mark the value as
// optional.
// optional values & if let -- Write a question mark (?) after
// the type of a value to mark the value as optional.
print( "\noptional values & if let" )
print( "------------------------" )
var optionalString: String? = "Hello"
print("optionalString == nil: ", optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
print("optionalName: ", optionalName)
if let name = optionalName {
greeting = "Hello, \(name)"
print( "greeting: ", greeting )
}
var optionalName2: String? = nil
print("optionalName2: ", optionalName2)
if let name = optionalName2 {
greeting = "Hello, \(name)"
print( "greeting: ", greeting )
}
| true
|
df1b6adc8bb64bbd78a227fce8b034fe46bb4f85
|
Swift
|
TkachenkoBogdan/PopFiction
|
/PopFiction/ArticleCategory.swift
|
UTF-8
| 868
| 3.25
| 3
|
[] |
no_license
|
//
// ArticleCategory.swift
//
//
// Created by Богдан Ткаченко on 9/4/19.
//
import UIKit
enum ArticleCategory {
enum ShareType: String {
case email, facebook, twitter
}
case mostEmailed, mostShared(ShareType), mostViewed
var title: String {
switch self {
case .mostEmailed:
return "Most Emailed"
case .mostShared:
return "Most Shared"
case .mostViewed:
return "Most Viewed"
}
}
var image: UIImage {
var image: UIImage
switch self {
case .mostEmailed:
image = #imageLiteral(resourceName: "emailed")
case .mostShared:
image = #imageLiteral(resourceName: "shared")
case .mostViewed:
image = #imageLiteral(resourceName: "viewed")
}
return image
}
}
| true
|
90510b2d84c621b6b6124b1a82b8b11dfa1994f4
|
Swift
|
DiegoBergondo/WatchPrimeNumber
|
/PrimeNumber WatchKit Extension/InterfaceController.swift
|
UTF-8
| 3,131
| 3.328125
| 3
|
[] |
no_license
|
//
// InterfaceController.swift
// PrimeNumber WatchKit Extension
//
// Created by Diego Bergondo Cañas on 03/12/2019.
// Copyright © 2019 Diego Bergondo Cañas. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
// Declaración de los tres cuadros de texto de la pantalla
@IBOutlet var numero: WKInterfaceTextField!
@IBOutlet var respuesta: WKInterfaceTextField!
@IBOutlet var divisiblePor: WKInterfaceTextField!
// Variable creada para contener el número por el que es divisible el objetivo.
var esDivisible:Int = 0
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
}
// Función asociada al texto que recibe el número objetivo, es llamada al confirmar
// el texto ingresado por parte del usuario.
@IBAction func nuevoNumero(_ value: NSString?) {
// Si el usuario cancela el ingreso de texto, se devuelve nil, por lo que es
// necesario controlarlo
if(value != nil){
// Se verifica que el texto ingresado sea un número
if let numeroAux = Int(value! as String) {
// Llamada a la función que determina si es primo y que, al devolver un
// boolean, sólo puede tener dos posibilidades
switch esPrimo(n: numeroAux) {
// Si es primo se muestra esa respuesta en el segundo recuadro de texto
// y se indica en el tercer recuadro que sólo es divisible por 1 y por él
// mismo
case true:
respuesta.setText("Es primo")
divisiblePor.setText("Div. por: 1 y \(numeroAux)")
// De lo contrario, se indica que no es primo y el número por el que es
// divisible mostrando la variable que se ha modificado a tal efecto
default:
respuesta.setText("No es primo")
divisiblePor.setText("Div. por: \(esDivisible)")
}
}
else{
numero.setText("Debe ser número")
}
}
}
// Función que determina si un número es primo utilizando el algoritmo más común.
func esPrimo(n: Int) -> Bool
{
if (n <= 1){
return false;
}
for i in 2..<n{
// En caso de encontrar divisibilidad, se devolverá false (no primo), y, además,
// se asociará el divisor con la variable antes definida para contener el
// número por el que es divisible el objetivo
if (n % i == 0){
self.esDivisible=i
return false;
}
}
return true
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
| true
|
442b1440d193e084ee42876ff9f4b434b5097f85
|
Swift
|
CYXT2017/SwiftLocalSave
|
/demoSwift/TestModle.swift
|
UTF-8
| 919
| 2.625
| 3
|
[] |
no_license
|
//
// TestModle.swift
// demoSwift
//
// Created by 陈涛 on 2018/9/1.
// Copyright © 2018年 陈涛. All rights reserved.
//
import UIKit
class TestModle: NSObject, Codable {
var name: String = ""
var age: Int = 0
var psw = ""
static var user: TestModle {
let ud = UserDefaults.standard
guard let data = ud.data(forKey: "lqUser_savedData") else {
// 如果获取失败则重新创建一个返回
return TestModle()
}
guard let us = try? JSONDecoder().decode(TestModle.self, from: data) else {
return TestModle()
}
return us
}
private override init() {
}
func saved() {
if let data = try? JSONEncoder().encode(self) {
let us = UserDefaults.standard
us.set(data, forKey: "lqUser_savedData")
us.synchronize()
}
}
}
| true
|
21d0e356e8b7d6dd7fcbdac730ebadea2370b333
|
Swift
|
ahueni/ASD_iPad_App
|
/src/Spectrometer/FileWriteManager.swift
|
UTF-8
| 3,813
| 2.796875
| 3
|
[] |
no_license
|
//
// BackgroundFileWriteManager.swift
// Spectrometer
//
// Created by Andreas Lüscher on 28.02.17.
// Copyright © 2017 YARX GmbH. All rights reserved.
//
import Foundation
class FileWriteManager{
// serial Queue to only queue one file at once
let serialQueue = DispatchQueue(label: "fileWriteQueue")
// Singleton instance
static let sharedInstance = FileWriteManager()
private init() { }
func addToQueueRaw(spectrums : [FullRangeInterpolatedSpectrum], settings: MeasurmentSettings)
{
serialQueue.sync {
for spectrum in spectrums
{
let relativeFilePath = createNewFilePath(settings: settings)
let fileWriter = IndicoWriter(path: relativeFilePath, settings: settings)
fileWriter.writeRaw(spectrum: spectrum)
}
}
}
func addToQueueReflectance(spectrums : [FullRangeInterpolatedSpectrum], whiteRefrenceSpectrum: FullRangeInterpolatedSpectrum, settings: MeasurmentSettings)
{
serialQueue.sync {
for spectrum in spectrums
{
let relativeFilePath = createNewFilePath(settings: settings)
let fileWriter = IndicoWriter(path: relativeFilePath, settings: settings)
fileWriter.writeReflectance(spectrum: spectrum, whiteRefrenceSpectrum: whiteRefrenceSpectrum)
}
}
}
func addToQueueRadiance(spectrums : [FullRangeInterpolatedSpectrum], radianceCalibrationFiles: RadianceCalibrationFiles, settings: MeasurmentSettings, fileSuffix :String = "")
{
serialQueue.sync {
for spectrum in spectrums
{
let relativeFilePath = createNewFilePath(settings: settings, fileSuffix: fileSuffix)
let fileWriter = IndicoWriter(path: relativeFilePath, settings: settings)
fileWriter.writeRadiance(spectrum: spectrum, radianceCalibrationFiles: radianceCalibrationFiles)
}
}
}
func createNewFilePath(settings: MeasurmentSettings, fileSuffix :String = "") -> String{
let index = getHighestIndex(filePath: settings.path, fileName: settings.fileName) + 1
// padd the index to 5 with zeros -> Example: test_00001.asd
let fileName = settings.fileName + fileSuffix + String(format: "_%05d", index) + ".asd"
let relativeFilePath = settings.path.appendingPathComponent(fileName).relativePath
return relativeFilePath
}
func addFinishWritingCallBack(callBack: ()->Void){
serialQueue.sync {
callBack()
}
}
internal func getHighestIndex(filePath : URL, fileName: String)-> Int{
var index = 0
do{
// read all files and filter by asd extension
let directoryContents = try FileManager.default.contentsOfDirectory(at: filePath, includingPropertiesForKeys: nil, options: [])
let asdFiles = directoryContents.filter{ $0.pathExtension == "asd" }
for asdFile in asdFiles{
// remove extension
let fileNameWithoutExtension = asdFile.deletingPathExtension()
// split by _
let asdFileNameComponents = fileNameWithoutExtension.lastPathComponent.characters.split{$0 == "_"}.map(String.init)
if(asdFileNameComponents.first == fileName){
// get index
let fileIndex = Int(asdFileNameComponents.last!)!
//compare with currentIndex and take higher
index = fileIndex > index ? fileIndex : index
}
}
}catch{
print("Error in IO")
//return 0 or highest found index if something went wrong
}
return index
}
}
| true
|
692ab1e77741a0ac6dda2d2a17aa549bca8b6843
|
Swift
|
kukushi/Linker
|
/BangumiKit/BangumiKit/Manager/NetRequester.swift
|
UTF-8
| 3,612
| 2.625
| 3
|
[] |
no_license
|
//
// NetRequester.swift
// BangumiKit
//
// Created by kukushi on 11/8/14.
// Copyright (c) 2014 kukushiStudio. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
public enum NetRequesterErrorType: Int {
case Success
case NoUpdate
case Unreachable
case ParseFail
}
public typealias BangumisFetcherCallback = (bangumis:[Bangumi]!, errorType:NetRequesterErrorType) -> Void
public typealias SPFetcherCallback = (episodes:[Episode]!, errorType:NetRequesterErrorType) -> Void
//public typealias BangumiSearchResultCallback
/**
* Net
*/
class NetRequester {
// MARK: Singleton
class var sharedRequester: NetRequester {
struct Static {
static let sharedRequester = NetRequester()
}
return Static.sharedRequester
}
// MARK:
private let host = "http://api.bilibili.com"
private class var BilibiliAPIkey: String {
return "0f38c1b83b2de0a0"
}
// MARK: Fetch Bangumis
class func fetchBangumis(callback: BangumisFetcherCallback) {
let session = NSURLSession.sharedSession()
let bangumisFetchingURL = NSURL(string: "http://www.bilibili.tv/index/bangumi.json")
session.dataTaskWithURL(bangumisFetchingURL!, completionHandler: { (data, response, error) -> Void in
var cachedBangumis: [Bangumi]!
var errorType: NetRequesterErrorType
if response != nil {
if let bangumis = self.parseBangumis(data) {
cachedBangumis = bangumis
errorType = .Success
}
else {
errorType = .ParseFail
}
} else {
println("\(error)")
errorType = .Unreachable
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
callback(bangumis: cachedBangumis, errorType: errorType)
})
}).resume()
}
// MARK: Fetch SP
class func fetchSPEpisodes(#spID: Int, callback: SPFetcherCallback) {
var parameters : [String: AnyObject] = [
"appkey": BilibiliAPIkey,
"bangumi": 1,
"platform": "ios",
"season_id": 0,
"spid": spID,
"type": "",
]
Alamofire.request(.GET, "123", parameters: parameters).response { (request, repsonse, data, error) -> Void in
let JSONData = JSON(data: data as NSData)
if let list = JSONData["list"].array {
var episodes = [Episode]()
for dict in list {
episodes.append(Episode(dict: dict))
}
callback(episodes: episodes, errorType: .Success)
}
else {
}
}
//}
}
// func fetchSearchResult(keyword: String, callback: )
}
// MARK: Implementation
extension NetRequester {
private class func parseBangumis(data: NSData) -> [Bangumi]? {
/*
let JSONData = JSON(data: data)
var bangumis = [Bangumi]()
if let array = JSONData.array {
for dict in array {
bangumis.append(Bangumi(dict: dict))
}
return bangumis
}
else {
// Alamofire.Manager.sharedInstance.request(<#method: Method#>, <#URLString: URLStringConvertible#>, parameters: <#[String : AnyObject]?#>, encoding: <#ParameterEncoding#>)
return nil
}
*/
return nil
}
}
| true
|
2cbd378e6f2c506098dbd18181d9b43aac27acd9
|
Swift
|
gsampaio/SwiftLint
|
/Source/SwiftLintFramework/Rules/SwitchCaseOnNewlineRule.swift
|
UTF-8
| 3,143
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
//
// SwitchCaseOnNewlineRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 10/15/2016.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct SwitchCaseOnNewlineRule: ConfigurationProviderRule, Rule, OptInRule {
public let configurationDescription = "N/A"
public var configuration = SeverityConfiguration(.Warning)
public init() { }
public static let description = RuleDescription(
identifier: "switch_case_on_newline",
name: "Switch Case on Newline",
description: "Cases inside a switch should always be on a newline",
nonTriggeringExamples: [
"case 1:\n return true",
"default:\n return true",
"case let value:\n return true",
"/*case 1: */return true",
"//case 1:\n return true",
"let x = [caseKey: value]",
"let x = [key: .default]",
"if case let .someEnum(value) = aFunction([key: 2]) {",
"guard case let .someEnum(value) = aFunction([key: 2]) {",
"for case let .someEnum(value) = aFunction([key: 2]) {"
],
triggeringExamples: [
"case 1: return true",
"case let value: return true",
"default: return true",
"case \"a string\": return false"
]
)
public func validateFile(file: File) -> [StyleViolation] {
let pattern = "(case[^\n]*|default):[^\\S\n]*[^\n]"
return file.rangesAndTokensMatching(pattern).filter { range, tokens in
guard let firstToken = tokens.first where tokenIsKeyword(firstToken) else {
return false
}
let tokenString = contentForToken(firstToken, file: file)
guard ["case", "default"].contains(tokenString) else {
return false
}
// check if the first token in the line is `case`
let lineAndCharacter = file.contents.lineAndCharacterForByteOffset(range.location)
guard let (lineNumber, _) = lineAndCharacter else {
return false
}
let line = file.lines[lineNumber - 1]
let lineTokens = file.syntaxMap.tokensIn(line.byteRange).filter(tokenIsKeyword)
guard let firstLineToken = lineTokens.first else {
return false
}
let firstTokenInLineString = contentForToken(firstLineToken, file: file)
return firstTokenInLineString == tokenString
}.map {
StyleViolation(ruleDescription: self.dynamicType.description,
severity: self.configuration.severity,
location: Location(file: file, characterOffset: $0.0.location))
}
}
private func tokenIsKeyword(token: SyntaxToken) -> Bool {
return SyntaxKind(rawValue: token.type) == .Keyword
}
private func contentForToken(token: SyntaxToken, file: File) -> String {
return file.contents.substringWithByteRange(start: token.offset,
length: token.length) ?? ""
}
}
| true
|
9bf2de61e22844ef2048ce0dd9308f2acd2512db
|
Swift
|
sudowarp/WeatherApp_Edit
|
/WeathR/City.swift
|
UTF-8
| 4,089
| 2.734375
| 3
|
[] |
no_license
|
//
// City.swift
// WeathR
//
// Created by Shivam Kapur on 01/03/16.
// Copyright © 2016 Shivam Kapur. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
import MapKit
import CoreLocation
class City {
private var _cityName:String!//Done
private var _latitude:CLLocationDegrees!//Done
private var _longitude:CLLocationDegrees!//Done
private var _countryCode:String!//Done
private var _weatherDescription:String!//Done
private var _temperature:Double!//Done
private var _temperatureMin:Double!//Done
private var _temperatureMax:Double!//Done
private var _humidity:Double!//Done
private var _windSpeed:Double!//Done
private var _windDirection:Double!//Done
var cityName:String {
return _cityName
}
var countryCode:String {
return _countryCode
}
var weatherDescription:String {
return _weatherDescription
}
var temperature:Double {
return _temperature
}
var temperatureMin:Double {
return _temperatureMin
}
var temperatureMax:Double {
return _temperatureMax
}
var humidity:Double {
return _humidity
}
var windSpeed:Double {
return _windSpeed
}
var windDirection:Double {
return _windDirection
}
var latitude:CLLocationDegrees {
return _latitude
}
var longitude:CLLocationDegrees {
return _longitude
}
init() {
}
convenience init(lat:CLLocationDegrees,lon:CLLocationDegrees) {
self.init()
self._latitude = lat
self._longitude = lon
}
func downloadWeatherInfo(completed:downloadWeatherDetails) {
let url = "\(BASE_URL)\(LATITUDE)\(self._latitude)\(LONGITUDE)\(self._longitude)\(API_KEY)\(UNITS)"
let nsurl = NSURL(string: url)!
Alamofire.request(.GET, nsurl).responseJSON { (response) -> Void in
if let response = response.result.value as? Dictionary<String,AnyObject> {
print(response)
if let name = response["name"] as? String {
self._cityName = name
}
if let sys = response["sys"] as? Dictionary<String,AnyObject> {
if let country = sys["country"] as? String {
self._countryCode = country
}
}
if let main = response["main"] as? Dictionary<String,AnyObject> {
if let temp = main["temp"] as? Double {
self._temperature = temp
}
if let temp_min = main["temp_min"] as? Double {
self._temperatureMin = temp_min
}
if let temp_max = main["temp_max"] as? Double {
self._temperatureMax = temp_max
}
if let humidity = main["humidity"] as? Double {
self._humidity = humidity
}
}
if let wind = response["wind"] as? Dictionary<String,AnyObject> {
if let speed = wind["speed"] as? Double {
self._windSpeed = speed
}
if let deg = wind["deg"] as? Double {
self._windDirection = deg
}
}
if let weather = response["weather"] as? [Dictionary<String,AnyObject>] {
if let description = weather[0] as? Dictionary<String,AnyObject> {
if let desc = description["description"] as? String {
self._weatherDescription = desc
}
}
}
}
completed()
}
}
}
| true
|
c6ded33b625b4449303a42cd2dcb10a1dee3298b
|
Swift
|
ivlevAstef/TelegramCharts
|
/TelegramChart/Charts/Views/Internal/ColumnsView/ColumnsViewFabric.swift
|
UTF-8
| 990
| 2.5625
| 3
|
[] |
no_license
|
//
// ColumnsViewFabric.swift
// TelegramCharts
//
// Created by Alexander Ivlev on 09/04/2019.
// Copyright © 2019 CFT. All rights reserved.
//
import UIKit
internal final class ColumnsViewFabric
{
internal static func makeColumnViews(by types: [ColumnViewModel.ColumnType], parent: UIView) -> [ColumnViewLayerWrapper] {
let views: [ColumnViewLayerWrapper] = types.map { type in
switch type {
case .line:
return PolyLineLayerWrapper()
case .area:
return AreaLayerWrapper()
case .bar:
return BarLayerWrapper()
}
}
for layer in parent.layer.sublayers ?? [] {
layer.removeFromSuperlayer()
}
for view in views {
parent.layer.addSublayer(view.layer)
}
for view in views {
parent.layer.addSublayer(view.selectorLayer)
}
return views
}
}
| true
|
3918db6349a4661a7bf59e7ec9738957a6314554
|
Swift
|
sergiymomot/Stackviewer-App-Project
|
/Stackview/Cells/PostTableViewCell.swift
|
UTF-8
| 795
| 2.8125
| 3
|
[] |
no_license
|
//
// PostTableViewCell.swift
// Stackview
//
// Created by Sergiy Momot on 9/13/17.
// Copyright © 2017 Sergiy Momot. All rights reserved.
//
import UIKit
class PostTableViewCell: GenericCell<Post> {
@IBOutlet weak var postTypeLabel: UILabel!
@IBOutlet weak var postedDateLabel: UILabel!
@IBOutlet weak var scoreLabel: ScoreLabel!
@IBOutlet weak var postTitleLabel: UILabel!
override func setup(for post: Post) {
if let type = post.type {
postTypeLabel.text = type == .question ? "Question" : "Answer"
postedDateLabel.text = post.creationDate!.getCreationTimeText()
scoreLabel.text = (post.score ?? 0).toString()
scoreLabel.isAccepted = false
postTitleLabel.text = post.title?.htmlUnescape()
}
}
}
| true
|
5334793d8290d7478ecb61edd9ae9953dea3bfc4
|
Swift
|
Esri/arcgis-runtime-toolkit-ios
|
/Sources/ArcGISToolkit/FloorFilter/FloorFilterViewModel.swift
|
UTF-8
| 4,710
| 2.734375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Copyright 2022 Esri.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import UIKit
import ArcGIS
/// View Model class that contains the Data Model of the Floor Filter
/// Also contains the business logic to filter and change the map extent based on selected site/level/facility
final class FloorFilterViewModel {
/// The MapView, Map and Floor Manager are set in the FloorFilterViewController when the map is loaded
var mapView: AGSMapView?
var floorManager: AGSFloorManager? {
return mapView?.map?.floorManager
}
var sites: [AGSFloorSite] {
return floorManager?.sites ?? []
}
/// Facilities in the selected site
/// If no site is selected then the list is empty
/// If the sites data does not exist in the map, then use all the facilities in the map
var facilities: [AGSFloorFacility] {
guard let floorManager = floorManager else { return [] }
return sites.isEmpty ? floorManager.facilities : floorManager.facilities.filter { $0.site == selectedSite }
}
/// Levels that are visible in the expanded Floor Filter levels table view
/// Sort the levels by verticalOrder in a descending order
var visibleLevelsInExpandedList: [AGSFloorLevel] {
guard let floorManager = floorManager else { return [] }
return facilities.isEmpty ? floorManager.levels : floorManager.levels.filter {
$0.facility == selectedFacility
}.sorted {
$0.verticalOrder > $1.verticalOrder
}
}
/// All the levels in the map
/// make this property public so it can be accessible to test
var allLevels: [AGSFloorLevel] {
return floorManager?.levels ?? []
}
/// The site, facility, and level that are selected by the user
var selectedSite: AGSFloorSite?
var selectedFacility: AGSFloorFacility?
var selectedLevel: AGSFloorLevel?
/// Gets the default level for a facility
/// Uses level with vertical order 0 otherwise gets the lowest level
func defaultLevel(for facility: AGSFloorFacility?) -> AGSFloorLevel? {
return allLevels.first(where: { level in
level.facility == facility && level.verticalOrder == .zero
}) ?? lowestLevel()
}
/// Returns the AGSFloorLevel with the lowest verticalOrder.
private func lowestLevel() -> AGSFloorLevel? {
let sortedLevels = allLevels.sorted {
$0.verticalOrder < $1.verticalOrder
}
return sortedLevels.first {
$0.verticalOrder != .min && $0.verticalOrder != .max
}
}
/// Sets the visibility of all the levels on the map based on the vertical order of the current selected level
func filterMapToSelectedLevel() {
guard let selectedLevel = selectedLevel else { return }
allLevels.forEach {
$0.isVisible = $0.verticalOrder == selectedLevel.verticalOrder
}
}
/// Zooms to the facility if there is a selected facility, otherwise zooms to the site.
func zoomToSelection() {
if let selectedFacility = selectedFacility {
zoom(to: selectedFacility)
} else if let selectedSite = selectedSite {
zoom(to: selectedSite)
}
}
private func zoom(to floorSite: AGSFloorSite) {
zoomToExtent(mapView: mapView, envelope: floorSite.geometry?.extent)
}
private func zoom(to floorFacility: AGSFloorFacility) {
zoomToExtent(mapView: mapView, envelope: floorFacility.geometry?.extent)
}
private func zoomToExtent(mapView: AGSMapView?, envelope: AGSEnvelope?) {
guard let mapView = mapView,
let envelope = envelope
else { return }
let padding = 1.5
let envelopeWithBuffer = AGSEnvelope(
center: envelope.center,
width: envelope.width * padding,
height: envelope.height * padding
)
if !envelopeWithBuffer.isEmpty {
let viewPoint = AGSViewpoint(targetExtent: envelopeWithBuffer)
mapView.setViewpoint(viewPoint, duration: 0.5, completion: nil)
}
}
}
| true
|
48d028ef48e5e39e510da0ea84909465c4d54d11
|
Swift
|
sw1ftmikh6il/swiftcourse
|
/Swift lessons/4LessonPlayground.playground/Contents.swift
|
UTF-8
| 1,287
| 4.40625
| 4
|
[] |
no_license
|
// Основы Swift / Урок 4 / Условия
let firstCard = 11
let secondCard = 8
if firstCard + secondCard == 21 {
print("You are Win!")
} else if (firstCard + secondCard) > 18 && (firstCard + secondCard) < 21 {
print("Nice Ass")
} else {
print("Regular cards")
}
let age1 = 12
let age2 = 21
if age1 > 18 && age2 > 18 {
print("Both are over 18")
}
if age1 > 18 || age2 > 18 {
print("At least one over 18")
}
/*
switch значение для сопоставления {
case значение 1:
инструкция для значения 1
case значение 2:
инструкция для значения 2
case значение 3:
инструкция для значения 3
default:
инструкция, если совпадений с шаблоном не найдено
}
*/
let weather = "snow"
switch weather {
case "rain": print("Bring an umbrella")
case "snow": print("Wrap up warm")
case "sunny": print("Wear glasses")
fallthrough
default: print("Enjoy your day")
}
switch age2 {
case 0...10 : print("You are too young")
case 11..<20: print("You are teenager")
case 20...60: print("You are grown man")
case 80...: print("You are old man")
default: print("How old are you?")
}
| true
|
5dcb619f3c6fbaeb23dc58db64bee8fd6fe48986
|
Swift
|
zpg6/StockManageriOS
|
/StockManageriOS/Models/Location/LocationType.swift
|
UTF-8
| 606
| 2.921875
| 3
|
[] |
no_license
|
//
// LocationType.swift
//
//
// Created By Zachary Grimaldi and Joseph Paul on 5/23/20.
//
/// A string enumeration describing the type of location an `InventoryItem` is stored at.
enum LocationType: String, Codable {
case jHook = "J-Hook"
case sideStack = "Side Stack"
case shelfSpace = "Shelf Space"
case pod = "Pod"
case floorModel = "Floor Model"
case topStock = "Top Stock"
case backroomStock = "Backroom Stock"
case incoming = "Incoming"
case outgoing = "Outgoing"
case unprocessed = "Unprocessed"
case bottomStock = "Bottom Stock"
case unknown = "Unknown"
}
| true
|
2e218901be92956c65a7cf1d2816c1981c4b723b
|
Swift
|
Marat-Dzh/Hookah_project
|
/HookahProject/VIPER modules/Feed/FeedProtocols.swift
|
UTF-8
| 662
| 2.5625
| 3
|
[] |
no_license
|
//
// FeedProtocols.swift
// HookahProject
//
// Created by Nikita Kuznetsov on 19.10.2020.
//
import Foundation
import UIKit
protocol FeedViewInput: class{
func setStories(storiesList: [UIImage])
func setNews(newsList: [News])
}
protocol FeedViewOutput : class{
func fetchImageStories()
func fetchNews()
}
protocol FeedModuleInput: class{
func getNews()
func getStocks()
}
protocol FeedModuleOutput: class{
}
protocol FeedInteractorInput{
func fetchNewsFromFB()
func fetchStoriesFromFB()
}
protocol FeedInteractorOutput: class{
func updateStories(images: [URL])
func updateNews()
}
protocol FeedRouterInput{
}
| true
|
fa4ec4dc26f63f4e7ef4d04dc8797e00d79f3e0f
|
Swift
|
BeSmartiOs/AirBag2
|
/AirBag/Controllers/AbstractViewController/AbstractViewController.swift
|
UTF-8
| 4,849
| 2.78125
| 3
|
[] |
no_license
|
//
// AbstractViewController.swift
// AirBag
//
// Created by Geek on 8/16/18.
// Copyright © 2018 Geek. All rights reserved.
//
import UIKit
import Reachability
import JGProgressHUD
class AbstractViewController: UIViewController {
let hud = JGProgressHUD(style: .light)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// class func showHud() {
// hud.textLabel.text = ConstantStrings.pleaseWait
// }
class func isValidEmail(testStr: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: testStr)
}
//Minimum 8 and Maximum 10 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character: [!$@#%])
class func isValidPasword(testStr: String) -> Bool {
let password = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%&#^])[A-Za-z\\d$@$!%&#^]{8,}"
let passwordTest = NSPredicate(format:"SELF MATCHES %@", password)
return passwordTest.evaluate(with: testStr)
}
class func validateFeildsRegister(firstName: String,lastName: String, password : String,confirmPassword : String,email: String, phone : String, address : String) -> Bool{
if(firstName.isEmpty == true || password.isEmpty == true || email.isEmpty == true || firstName == "" || password == "" || email == "" || lastName.isEmpty == true || lastName == "" || confirmPassword == "" || confirmPassword.isEmpty == true || phone == "" || phone .isEmpty == true || address.isEmpty == true || address == ""){
return false
}else{
return true
}
}
class func validateLogin(userType: Int,email: String, password : String) -> Bool{
if( password == "" || email == "" || password.isEmpty == true || email.isEmpty == true || userType == 0){
return false
}else{
return true
}
}
class func validateNum(number: String) -> Bool{
let numbersTest = number
if let number = Int(numbersTest){
print(number)//contains onlyy number
return true
}else{
print("notnumber")//Not number
return false
}
}
class func validateNumCount(number: String) -> Bool{
let numbersTest = number
if let number = Int(numbersTest){
print(number)//contains onlyy number
if(numbersTest.count == 6){
return true
}else{
return false
}
}else{
print("notnumber")//Not number
return false
}
}
class func validateNumDouble(number: String) -> Bool{
let numbersTest = number
if let number = Double(numbersTest){
print(number)//contains onlyy number
return true
}else{
print("notnumber")//Not number
return false
}
}
//MARK:- Connectivity Func
class func connected() -> Bool {
let reachability = Reachability()!
if reachability.connection != .none {
if reachability.connection == .wifi {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
return true
} else {
print("Network not reachable")
return false
}
}
//
// Convert String to base64
//
class func convertImageToBase64(image: UIImage) -> String {
let imageData = UIImagePNGRepresentation(image)!
return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
print(imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters))
}
//
// Convert base64 to String
//
class func convertBase64ToImage(imageString: String) -> UIImage {
let imageData = Data(base64Encoded: imageString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
return UIImage(data: imageData)!
}
}
| true
|
3223660400c2fb77ccae254d900c9e4288d6c32e
|
Swift
|
mumer92/LNPopupUI
|
/LNPopupUIExample/LNPopupUIExample/IntroWebView/WebController.swift
|
UTF-8
| 970
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// WebController.swift
// LNPopupUIExample
//
// Created by Leo Natan on 10/14/20.
//
import UIKit
import WebKit
class WebController: UIViewController {
private let webView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
webView.load(URLRequest(url: URL(string: "https://github.com/LeoNatan/LNPopupUI")!))
webView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(webView)
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: webView.topAnchor),
view.bottomAnchor.constraint(equalTo: webView.bottomAnchor),
view.leadingAnchor.constraint(equalTo: webView.leadingAnchor),
view.trailingAnchor.constraint(equalTo: webView.trailingAnchor),
])
popupItem.title = "Welcome to LNPopupUI"
popupItem.image = UIImage(named: "genre10")
popupItem.barButtonItems = [
UIBarButtonItem(image: UIImage(systemName: "suit.heart.fill"), style: .done, target: nil, action: nil)
]
}
}
| true
|
ec6cbfac0b448ddd89c5a83da9a03053f31c486d
|
Swift
|
albertopeam/nearby-resources
|
/NearbyResources/NearbyResources/View/NearbyResourcesView.swift
|
UTF-8
| 2,222
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// ResourcesView.swift
// NearbyResources
//
// Created by Alberto Penas Amor on 25/08/2020.
// Copyright © 2020 com.github.albertopeam. All rights reserved.
//
import UIKit
import GoogleMaps
final class NearbyResourcesView: UIView {
let mapView: GMSMapView
let activityIndicator: UIActivityIndicatorView
let snackBarView: SnackBarView
init(_ camera: GMSCameraPosition) {
mapView = GMSMapView.map(withFrame: .zero, camera: camera)
activityIndicator = .init(style: .large)
snackBarView = .init()
super.init(frame: .zero)
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private extension NearbyResourcesView {
enum ViewTraits {
static var indicator: UIEdgeInsets = .init(top: 16, left: 0, bottom: 0, right: -16)
}
func setup() {
translatesAutoresizingMaskIntoConstraints = false
mapView.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
snackBarView.translatesAutoresizingMaskIntoConstraints = false
mapView.settings.indoorPicker = false
activityIndicator.hidesWhenStopped = true
activityIndicator.color = .black
addSubview(mapView)
addSubview(snackBarView)
addSubview(activityIndicator)
NSLayoutConstraint.activate([
mapView.topAnchor.constraint(equalTo: topAnchor),
mapView.trailingAnchor.constraint(equalTo: trailingAnchor),
mapView.bottomAnchor.constraint(equalTo: bottomAnchor),
mapView.leadingAnchor.constraint(equalTo: leadingAnchor),
activityIndicator.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: ViewTraits.indicator.top),
activityIndicator.trailingAnchor.constraint(equalTo: trailingAnchor, constant: ViewTraits.indicator.right),
snackBarView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor),
snackBarView.leadingAnchor.constraint(equalTo: leadingAnchor),
snackBarView.trailingAnchor.constraint(equalTo: trailingAnchor)
])
}
}
| true
|
8791fb55707e0df7ad433800974978e6bb29ae86
|
Swift
|
daminz97/HCIProject
|
/HCIProject4/popUpViewController.swift
|
UTF-8
| 2,347
| 2.578125
| 3
|
[] |
no_license
|
//
// popUpViewController.swift
// HCIProject4
//
// Created by Humad Syed on 12/15/17.
// Copyright © 2017 HCI. All rights reserved.
//
import UIKit
class popUpViewController: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var platformLabel: UILabel!
@IBOutlet weak var nameArrow: UIImageView!
@IBOutlet weak var dateArrow: UIImageView!
@IBOutlet weak var platformArrow: UIImageView!
@IBOutlet weak var nameButton: UIButton!
@IBOutlet weak var dateButton: UIButton!
@IBOutlet weak var platformButton: UIButton!
@IBOutlet weak var dismissButton: UIButton!
// 0 == not selected, 1 == ascending, 2 == descending
var sortByName = 0
var sortByDate = 0
var sortByPlatform = 0
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func nameButtonPressed(_ sender: Any){
dateArrow.image = nil
platformArrow.image = nil
sortByDate = 0
sortByPlatform = 0
if (sortByName == 0 || sortByName == 2) {
sortByName = 1
nameArrow.image = UIImage(named: "arrow_up")
} else {
sortByName = 2
nameArrow.image = UIImage(named: "arrow_down")
}
}
@IBAction func dateButtonPressed(_ sender: Any){
nameArrow.image = nil
platformArrow.image = nil
sortByName = 0
sortByPlatform = 0
if (sortByDate == 0 || sortByDate == 2) {
sortByDate = 1
dateArrow.image = UIImage(named: "arrow_up")
} else {
sortByDate = 2
dateArrow.image = UIImage(named: "arrow_down")
}
}
@IBAction func platformButtonPressed(_ sender: Any){
nameArrow.image = nil
dateArrow.image = nil
sortByName = 0
sortByDate = 0
if (sortByPlatform == 0 || sortByPlatform == 2) {
sortByPlatform = 1
platformArrow.image = UIImage(named: "arrow_up")
} else {
sortByPlatform = 2
platformArrow.image = UIImage(named: "arrow_down")
}
}
@IBAction func dismissButtonPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
| true
|
e3b712472a34e037d9b231f4e98a78255c0fc7b3
|
Swift
|
islamnurdin/Career-Fair
|
/Career Fair/Menu Files/Partners/PartnersViewController.swift
|
UTF-8
| 2,693
| 2.65625
| 3
|
[] |
no_license
|
//
// PartnersViewController.swift
// Career Fair
//
// Created by ITLabAdmin on 9/17/18.
// Copyright © 2018 Islam & Co. All rights reserved.
//
import UIKit
import Alamofire
class PartnersViewController: UIViewController {
@IBOutlet weak var collView: UICollectionView!
@IBOutlet weak var detailLabel: UITextView!
var partners = [Partners]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Партнеры и Медиа-партнеры"
getPartnersData {
self.collView.reloadData()
}
}
func getPartnersData(completed: @escaping () -> ()) {
let url = URL(string: "http://138.68.86.126/partner")
Alamofire.request(url!).responseJSON { response in
let data = response.data
do {
self.partners = try JSONDecoder().decode([Partners].self, from: data!)
DispatchQueue.main.async {
completed()
}
}
catch let e{
print(e)
}
}
}
}
extension PartnersViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return partners.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "partnersCell", for: indexPath) as! PartnersCollectionViewCell
cell.name.text = partners[indexPath.row].full_name
let urlString = partners[indexPath.row].logo_url
let url = URL(string: urlString)
cell.image.downloadedFrom(url: url!)
cell.image.applyStylesToImage()
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
detailLabel.text = partners[indexPath.row].description
if let cell = self.collView.cellForItem(at: indexPath) as? PartnersCollectionViewCell {
UICollectionViewCell.animate(withDuration: 1, animations: {
cell.image.reloadView()
})
}
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if let cell = self.collView.cellForItem(at: indexPath) as? PartnersCollectionViewCell {
UICollectionViewCell.animate(withDuration: 1, animations: {
cell.image.reloadView()
})
}
}
}
| true
|
66937a01fb06a0190c7fabb4ffa95ecc6c73c6c9
|
Swift
|
imvm/PetPlanner
|
/PetPlanner/Views/FormRows/ListRow.swift
|
UTF-8
| 1,485
| 3.015625
| 3
|
[] |
no_license
|
//
// SetRow.swift
// PetPlanner
//
// Created by Ian Manor on 20/12/20.
//
import SwiftUI
struct ListRow: View {
var label: String
var placeholder: String
@Binding var list: [String]
var body: some View {
VStack(alignment: .leading) {
NavigationLink(destination: EditableList(placeholder: placeholder, list: $list)) {
Text(label)
}
if !list.isEmpty {
Text(list.joined(separator: ", "))
.padding(.vertical, 5)
}
}
}
}
struct EditableList: View {
@EnvironmentObject var interfaceState: InterfaceState
var placeholder: String
@Binding var list: [String]
var body: some View {
Form {
ForEach(list.indices) { index in
HStack {
Text(list[index])
Spacer()
Button {
list.remove(at: index)
} label: {
Image(systemName: "xmark")
}
}
}
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
interfaceState.showTextFieldAlert(title: "Add new \(placeholder):") {
list.append($0)
}
} label: {
Image(systemName: "plus")
}
}
}
}
}
| true
|
9359e394b737b7ce826beba54f2d6fb5ec6330b8
|
Swift
|
CUATLAS/Fall14-MAD-class-examples
|
/media/media/ViewController.swift
|
UTF-8
| 5,884
| 2.703125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// media
//
// Created by Aileen Pierce on 11/14/14.
// Copyright (c) 2014 Aileen Pierce. All rights reserved.
//
import UIKit
import MobileCoreServices
import MediaPlayer
import AVFoundation
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
var image: UIImage?
var videoURL : NSURL?
var audioPlayer : AVAudioPlayer?
@IBAction func cameraButtonTapped(sender: UIBarButtonItem) {
//checks the device to make sure it has a camera
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
//creates an instance of the image picker controller
var imagePickerController=UIImagePickerController()
//sets the delegate so it can find out when the picture is ready
imagePickerController.delegate=self
//use the camera interface
imagePickerController.sourceType=UIImagePickerControllerSourceType.Camera
//display camera controls
imagePickerController.mediaTypes=[kUTTypeImage, kUTTypeMovie]
//present the camera interface
self.presentViewController(imagePickerController, animated: true, completion: nil)
}
else {
println("Can't access the camera")
}
}
//UIImagePickerControllerDelegate method
//called after successfully taking a picture or video
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
//media type tell us whether it was a picture or a video
let mediaType = info[UIImagePickerControllerMediaType] as String
image = nil
imageView.image = nil
videoURL = nil
if mediaType == kUTTypeImage { //image
//the original, unmodified image from the camera
image = info[UIImagePickerControllerOriginalImage] as? UIImage
imageView.image=image
}
else if mediaType == kUTTypeMovie { //movie
videoURL = info[UIImagePickerControllerMediaURL] as? NSURL
}
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func actionButonTapped(sender: UIBarButtonItem) {
let actionSheet=UIAlertController(title: "Media Action", message: "What would you like to do with your media?", preferredStyle: UIAlertControllerStyle.ActionSheet)
let roll=UIAlertAction(title: "Camera Roll", style:UIAlertActionStyle.Default, handler: { action in
var imagePickerController=UIImagePickerController()
imagePickerController.delegate=self
imagePickerController.sourceType=UIImagePickerControllerSourceType.SavedPhotosAlbum
imagePickerController.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(.SavedPhotosAlbum)!
self.presentViewController(imagePickerController, animated: true, completion: nil)
})
actionSheet.addAction(roll)
let cancel=UIAlertAction(title: "Cancel", style:UIAlertActionStyle.Cancel, handler: nil)
actionSheet.addAction(cancel)
if (image != nil) {
let save=UIAlertAction(title: "Save Image", style:UIAlertActionStyle.Default, handler: { action in
UIImageWriteToSavedPhotosAlbum(self.image, self, Selector("image:didFinishSavingWithError:contextInfo:"), nil)
})
actionSheet.addAction(save)
}
if (videoURL != nil) {
let urlString = videoURL?.path
if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlString){
let save=UIAlertAction(title: "Save Video", style:UIAlertActionStyle.Default, handler: { action in
UISaveVideoAtPathToSavedPhotosAlbum(urlString, self, Selector("image:didFinishSavingWithError:contextInfo:"), nil)
})
actionSheet.addAction(save)
}
}
let audio=UIAlertAction(title: "Play Audio", style:UIAlertActionStyle.Default, handler: { action in
let audioFilePath = NSBundle.mainBundle().pathForResource("Hall of Fame ring tone", ofType: "m4r")
let fileURL = NSURL(fileURLWithPath: audioFilePath!)
self.audioPlayer = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
if self.audioPlayer != nil {
self.audioPlayer!.play()
}
})
actionSheet.addAction(audio)
presentViewController(actionSheet, animated: true, completion: nil)
}
func image(image: AnyObject, didFinishSavingWithError error: NSError?, contextInfo: UnsafePointer<Void>) {
if let saveError=error{
let errorAlert=UIAlertController(title: "Error", message:saveError.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction=UIAlertAction(title: "OK", style:UIAlertActionStyle.Default, handler: nil)
errorAlert.addAction(cancelAction)
presentViewController(errorAlert, animated: true, completion: nil)
}
else {
let successAlert=UIAlertController(title: "Success", message: "Successfully saved to camera roll.", preferredStyle: UIAlertControllerStyle.Alert)
let okAction=UIAlertAction(title: "OK", style:UIAlertActionStyle.Default, handler: nil)
successAlert.addAction(okAction)
presentViewController(successAlert, animated: true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
186aa2c5652eaf73807e9374ed934c3d854690b5
|
Swift
|
chaviv85/AppHamburguesas
|
/Hamburguesas/Datos.swift
|
UTF-8
| 971
| 3.03125
| 3
|
[] |
no_license
|
//
// Datos.swift
// Hamburguesas
//
// Created by Maria Viviana Chaves Flecha on 26/4/16.
// Copyright © 2016 Maria Viviana Chaves Flecha. All rights reserved.
//
import Foundation
class ColeccionDePaises {
let paises = ["Alemania", "Australia", "Argentina", "Arabia Saudita", "Aruba", "Austria", "Bélgica", "Bolivia", "Brasil", "Bulgaria", "Canadá", "Chile", "China", "Dinamarca", "EEUU", "México", "Panamá", "Puerto Rico", "Uruguay", "Venezuela"]
func obtenPais() -> String{
let posicion = Int(arc4random()) % paises.count
return paises[posicion]
}
}
class ColeccionDeHamburguesas {
let hamburguesas = ["Papa", "Pollo", "Kurepa", "Pescado", "Soja", "Premium", "Belgium", "Boli", "Vegetariana", "Vegana", "Surubi", "Doble Carne", "Big Mac", "Cheedar", "king", "3/4 libra", "Lenteja", "Porki", "Queen", "Triple Carne"]
func obtenHamburguesa() -> String{
let posicion = Int(arc4random()) % hamburguesas.count
return hamburguesas[posicion]
}
}
| true
|
46a3c99326d9afa11f07040696feb190e13fb285
|
Swift
|
igor1309/Factory-Model
|
/Factory Model/Supporting Views/DataBlockView.swift
|
UTF-8
| 1,434
| 3.125
| 3
|
[] |
no_license
|
//
// DataBlockView.swift
// Factory Model
//
// Created by Igor Malyarov on 01.09.2020.
//
import SwiftUI
extension Color {
static var random: Color {
return Color(
red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1)
)
}
}
struct DataBlockView: View {
var dataBlock: DataBlock
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Label(dataBlock.title, systemImage: dataBlock.icon)
.font(.subheadline)
.padding(.bottom, 3)
ForEach(dataBlock.data) { item in
FinancialRow(item)
.foregroundColor(.secondary)
}
Divider().padding(.vertical, 3)
HStack {
Spacer()
Text(dataBlock.value)
Text((-2).formattedPercentageWith1Decimal).hidden()
}
.font(.footnote)
}
.padding(.vertical, 3)
}
}
struct DataBlockView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
List {
DataBlockView(dataBlock: DataBlock.example)
}
.listStyle(InsetGroupedListStyle())
.navigationBarTitle("Test Factory", displayMode: .inline)
}
.preferredColorScheme(.dark)
}
}
| true
|
3c4dc01d5811c705d95cd6c1faa9a21cb864efaf
|
Swift
|
WayneLi7/ios_decal
|
/hw2/Hangman/Hangman/HangmanGame.swift
|
UTF-8
| 374
| 2.578125
| 3
|
[] |
no_license
|
//
// HangmanGame.swift
// Hangman
//
// Created by weili on 2/13/18.
// Copyright © 2018 iOS DeCal. All rights reserved.
//
import Foundation
class HangmanGame {
public var stringToGuess : String
private var currentGuess : Character?
init() {
let phrase = HangmanPhrases()
self.stringToGuess = phrase.getRandomPhrase()
}
}
| true
|
77e3bd50b73370f9a6b26712159e5ddc07466d72
|
Swift
|
Darkcou/ProjetQuizz
|
/ProjetQuizz/Information.swift
|
UTF-8
| 1,461
| 2.890625
| 3
|
[] |
no_license
|
//
// Information.swift
// ProjetQuizz
//
// Created by AxelGilbin on 17/03/2020.
// Copyright © 2020 Benjamin Gronier. All rights reserved.
//
import SwiftUI
struct InformationScreen: View {
let info:Informations
var body: some View {
ZStack{
VStack(alignment: .center){
Spacer().frame(height:50)
Image(info.image).resizable().frame(width:250, height: 250)
Spacer().frame(height:100)
Text(info.text)
Spacer()
Button(
action: {
// self.info.lien
},
label: {
Text("Visiter le site officiel")
.bold()
.foregroundColor(Color.white)
}
)
.frame(width:200,height:50)
.background(Color.blue)
.border(/*@START_MENU_TOKEN@*/Color.black/*@END_MENU_TOKEN@*/, width: /*@START_MENU_TOKEN@*/1/*@END_MENU_TOKEN@*/)
.cornerRadius(10)
Spacer().frame(height: 100)
}
}
}
}
struct InformationScreen_Previews: PreviewProvider {
static var previews: some View {
InformationScreen(info: Informations(image: "", text: "", lien: ""))
}
}
| true
|
920c67fc898072014314071a77fa8bd912fd2aa2
|
Swift
|
BENABDESSALEM/PrayersTimingsBiannatTask
|
/SalwatTimes/ViewModels/PrayersTimesVM.swift
|
UTF-8
| 7,071
| 2.59375
| 3
|
[] |
no_license
|
//
// PrayersTimesVM.swift
// SalwatTimes
//
// Created by Yousef Mohamed on 12/02/2021.
import Foundation
import CoreLocation
protocol PrayersTimeVMProtocol: class {
func getCurentMonthPrayersTimes()
func getCellData(indexPath: IndexPath, data: (_ weekDay: String, _ monthDay: String) -> ())
func getDayPrayersTiming() -> [String]
func getDaysCount() -> Int
func didSelectDate(indexPath: IndexPath)
func isSelectedDay(indexPath: IndexPath) -> Bool
func getUserCurrentLocation()
func getCurrentDate()
func getNextMonth()
func getPreviousMonth()
}
class PrayersTimesVM: PrayersTimeVMProtocol {
private weak var view: PrayersTimesVCProtocol?
private let dateFormatter = DateFormatter()
private let locationManager = LoactionManger.shared() // Location Manager object
private var monthPrayersData = [PrayersData]()
private var year = Int()
private var month = Int()
private var day = Int()
private var selectedDayIndexPath = IndexPath()
init(view: PrayersTimesVCProtocol) {
self.view = view
}
internal func getCurrentDate() {
let curentDate = Date()
let calendar = Calendar.current
self.year = calendar.component(.year, from: curentDate)
self.month = calendar.component(.month, from: curentDate)
self.day = calendar.component(.day, from: curentDate)
// self.selectedIndex = day + 1
dateFormatter.dateFormat = "MMMM, yyy"
let date = dateFormatter.string(from: curentDate)
self.view?.updateDateLabel(date: date)
}
internal func getUserCurrentLocation() {
//cheack if locations permisions are set and okay
if CLLocationManager.locationServicesEnabled() {
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
//locationManager.startUpdatingLocation()
let currentLocation = locationManager.location
// Make sure is loactaion is set and not Nil
if let currentLocation = currentLocation {
UserDefaultsManager.shared().longitude = String(currentLocation.coordinate.longitude)
UserDefaultsManager.shared().latitude = String(currentLocation.coordinate.latitude)
}
}
}
internal func getCurentMonthPrayersTimes() {
view?.showLoader()
APIManager.getTimes(month: month, year: year) { [weak self] (result) in
guard let self = self else { return }
switch result {
case .success(let prayersTimesData):
self.monthPrayersData = prayersTimesData.monthData
self.view?.reloadColleCtionview()
self.dayToSelect()
self.view?.setTimesData()
self.updateDateLabel()
self.view?.hideLoader()
case .failure(let error):
self.view?.hideLoader()
print(error)
}
}
}
//Return numbers of Days in the curent month
//based on count of days that back from the api call
//
internal func getDaysCount() -> Int {
return monthPrayersData.count
}
// collection view cell data for monthDay number
internal func getCellData(indexPath: IndexPath, data: (_ weekDay: String, _ monthDay: String) -> ()) {
let timestamp = Double(monthPrayersData[indexPath.row].date.timestamp)!
let date = Date(timeIntervalSince1970: Double(timestamp))
let weekDayFormat = "E"
let monthDayFormat = "d"
dateFormatter.dateFormat = weekDayFormat
let weekday = dateFormatter.string(from: date)
dateFormatter.dateFormat = monthDayFormat
let monthDay = dateFormatter.string(from: date)
data(weekday, monthDay)
}
//Prayers timnings peer day
internal func getDayPrayersTiming() -> [String] {
let dayTimings = monthPrayersData[selectedDayIndexPath.row].timings
let mirroredObject = Mirror(reflecting: dayTimings)
var timingsArr = [String]()
// Convert struct proprities values into array
for (_ , attr) in mirroredObject.children.enumerated() {
if let propertyValue = attr.value as? String {
if let index = propertyValue.range(of: " ")?.lowerBound {
let subString = propertyValue.prefix(through: index)
let string = String(subString)
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.date(from: string)
dateFormatter.dateFormat = "h:mm a"
let date12 = dateFormatter.string(from: date!)
timingsArr.append(date12)
}
}
}
return timingsArr
}
internal func didSelectDate(indexPath: IndexPath) {
self.selectedDayIndexPath = indexPath
self.view?.setTimesData()
}
internal func isSelectedDay(indexPath: IndexPath) -> Bool {
let selected = indexPath == selectedDayIndexPath ? true : false
return selected
}
//MARK:- Control User intents
// This method called after next button pressed
// And it call api to get prayers timings for next month after modify needed data
internal func getNextMonth(){
if month < 12 {
month += 1
getCurentMonthPrayersTimes()
} else if month == 12 {
year += 1
month = 1
getCurentMonthPrayersTimes()
}
}
// This method called after previous button pressed
// And it call api to get prayers timings for previous month after modify needed data
internal func getPreviousMonth() {
if month > 1 {
month -= 1
getCurentMonthPrayersTimes()
} else if month == 1 {
month = 12
year -= 1
getCurentMonthPrayersTimes()
}
}
}
extension PrayersTimesVM {
private func updateDateLabel() {
let timestamp = Double(monthPrayersData[selectedDayIndexPath.row].date.timestamp)!
let date = Date(timeIntervalSince1970: Double(timestamp))
dateFormatter.dateFormat = "MMMM, yyy"
let dateAsString = dateFormatter.string(from: date)
self.view?.updateDateLabel(date: dateAsString)
}
private func dayToSelect() {
//This function to select and view frist day of the month when user navigate between monthes
let curentDate = Date()
let calendar = Calendar.current
let year = calendar.component(.year, from: curentDate)
let month = calendar.component(.month, from: curentDate)
let day = calendar.component(.day, from: curentDate)
if month == monthPrayersData[0].date.gregorian.month.number &&
year == Int(monthPrayersData[0].date.gregorian.year) {
view?.selectCell(index: day-1)
} else {
view?.selectCell(index: 0)
}
}
}
| true
|
b3405b42cbc683f43106652cfdfdacad9bf287cc
|
Swift
|
oalejel/Picasso
|
/Picasso/ViewController.swift
|
UTF-8
| 1,032
| 2.75
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Picasso
//
// Created by Omar Alejel on 12/20/15.
// Copyright © 2015 Omar Alejel. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var color = UIColor.red
@IBOutlet weak var radiusSlider: UISlider!
@IBAction func buttonPressed(_ sender: UIButton) {
color = sender.titleLabel!.textColor
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let t = touches.first
let loc = t?.location(in: view)
let p = UIBezierPath(arcCenter: loc!, radius: CGFloat(radiusSlider.value), startAngle: 0, endAngle: CGFloat(M_PI * 2.0), clockwise: false)
let shape = CAShapeLayer()
shape.path = p.cgPath
shape.fillColor = color.cgColor
view.layer.addSublayer(shape)
}
@IBAction func tap(_ sender: AnyObject) {
for layer in view.layer.sublayers! {
if layer is CAShapeLayer {
layer.removeFromSuperlayer()
}
}
}
}
| true
|
5ce9e500d07bf1a479cfad21cff066c9c0dedf3a
|
Swift
|
lalaphoon/TaxCalculator
|
/TaxCalculator/AboutViewController.swift
|
UTF-8
| 1,531
| 2.609375
| 3
|
[] |
no_license
|
//
// AboutViewController.swift
// TaxCalculator
//
// Created by Mengyi LUO on 2016-10-22.
// Copyright © 2016 WTC Tax. All rights reserved.
//
import UIKit
class AboutViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
initUI()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initUI() {
let ver : String = appVersion as! String
let build : String = appBuildVersion as! String
var version: String = "Version: \(ver).\(build)"
self.addImage("icon.png", self.view.bounds.width/2-50, 100, 100, 100)
self.view.addHeader("TaxPro", self.view.bounds.width/2, 220, 80, 20)
self.view.addText("\(version)", self.view.bounds.width/2, 250, 280, 20)
self.addImage("TITLE.png", self.view.bounds.width/2-80, self.view.bounds.height-150, 150, 35)
self.view.addText("Contact Us: info@wtctax.ca", self.view.bounds.width/2-5, self.view.bounds.height-100, 250,35 )
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
98508d9fae1678fab18b188b86360e84668cf1bf
|
Swift
|
MonaQora/NearByHaversine
|
/NearByCustomers/Services/HavListOfCustomersService.swift
|
UTF-8
| 1,609
| 3.015625
| 3
|
[] |
no_license
|
//
// HavListOfCustomersService.swift
// NearByCustomers
//
// Created by Mona Qora on 1/27/20.
// Copyright © 2020 Mona Qora. All rights reserved.
//
import Foundation
protocol ListOfCustomersServiceProtocol {
func loadListOfCustomers(completion: @escaping ([Customer]?, ErrorResponse?) -> ())
}
class ListOfCustomersService: ListOfCustomersServiceProtocol {
func loadListOfCustomers(completion: @escaping ([Customer]?, ErrorResponse?) -> ()) {
DispatchQueue.global(qos: .userInitiated).async {
let url = URLString.listOfCustomers
let customerResource = ResourceList<Customer>(urlString: url) { data in
var customerArr = [Customer]()
if let textFile = String(data: data, encoding: .utf8) {
let customersArr = textFile.split{$0 == "\n"}.map(String.init)
let customerJsonString = "[\(customersArr.string)]"
let jsonData = customerJsonString.data(using: .utf8)!
if let user: [Customer] = try? JSONDecoder().decode([Customer].self, from: jsonData) {
customerArr = user
}
}
return customerArr
}
let service = ServiceClient()
service.load(resource: customerResource){ result in
switch result {
case .success(let customersList) :
completion(customersList, nil)
case .failure(let error) :
completion(nil, error)
}
}
}
}
}
| true
|
8017ee57eaeec547a6f802e1e3e3155866b70e27
|
Swift
|
03128crz/Cosmos
|
/Cosmos/Cosmos/TextShape.swift
|
UTF-8
| 4,205
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
// Copyright © 2016 C4
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: The above copyright
// notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import QuartzCore
import UIKit
import Foundation
/// TextShape defines a concrete subclass of Shape that draws a bezier curve whose shape looks like text.
public class TextShape: Shape {
/// The text used to define the shape's path. Defaults to "C4".
public var text: String = "C4" {
didSet {
updatePath()
}
}
/// The font used to define the shape's path. Defaults to AvenirNext-DemiBold, 80pt.
public var font = Font(name: "AvenirNext-DemiBold", size: 80)! {
didSet {
updatePath()
}
}
/// Initializes an empty TextShape.
override init() {
super.init()
lineWidth = 0.0
fillColor = C4Pink
}
/// Initializes a new TextShape from a specifed string and a font
///
/// ````
/// let f = Font(name:"Avenir Next", size: 120)
/// let t = TextShape(text:"C4", font: f)
/// t.center = canvas.center
/// canvas.add(t)
/// ````
///
/// - parameter text: The string to be rendered as a shape
/// - parameter font: The font used to define the shape of the text
public convenience init?(text: String, font: Font) {
self.init()
self.text = text
self.font = font
updatePath()
origin = Point()
}
/// Initializes a new TextShape from a specifed string, using C4's default font.
///
/// ````
/// let t = TextShape(text:"C4")
/// t.center = canvas.center
/// canvas.add(t)
/// ````
///
/// - parameter text: text The string to be rendered as a shape
public convenience init?(text: String) {
guard let font = Font(name: "AvenirNext-DemiBold", size: 80) else {
return nil
}
self.init(text: text, font: font)
}
override func updatePath() {
path = TextShape.createTextPath(text: text, font: font)
adjustToFitPath()
}
internal class func createTextPath(text text: String, font: Font) -> Path? {
let ctfont = font.CTFont as CTFont?
if ctfont == nil {
return nil
}
var unichars = [UniChar](text.utf16)
var glyphs = [CGGlyph](count: unichars.count, repeatedValue: 0)
if !CTFontGetGlyphsForCharacters(ctfont!, &unichars, &glyphs, unichars.count) {
// Failed to encode characters into glyphs
return nil
}
var advances = [CGSize](count: glyphs.count, repeatedValue: CGSize())
CTFontGetAdvancesForGlyphs(ctfont!, .Default, &glyphs, &advances, glyphs.count)
let textPath = CGPathCreateMutable()
var invert = CGAffineTransformMakeScale(1, -1)
var origin = CGPoint()
for i in 0..<glyphs.count {
let glyphPath = CTFontCreatePathForGlyph(ctfont!, glyphs[i], &invert)
var translation = CGAffineTransformMakeTranslation(origin.x, origin.y)
CGPathAddPath(textPath, &translation, glyphPath)
origin.x += CGFloat(advances[i].width)
origin.y += CGFloat(advances[i].height)
}
return Path(path: textPath)
}
}
| true
|
a76e00785d863b252263e2ed21843d4fa5c5c622
|
Swift
|
rickeycode/UINSamplePlaygrounds
|
/Common/LazyProperty/lazyProperty.playground/Contents.swift
|
UTF-8
| 1,775
| 3.28125
| 3
|
[] |
no_license
|
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
var targetString: String = "1"
var contents: String {
return targetString
}
lazy var lazyContents: String = {
return targetString
}()
override func loadView() {
let innnerView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
innnerView.backgroundColor = .white
let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = .black
view.addSubview(innnerView)
self.view = view
view.layoutIfNeeded()
let lazyRect = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height / 2)
let lazyLabel = UILabel(frame: lazyRect)
lazyLabel.font = UIFont.systemFont(ofSize: 32)
lazyLabel.text = targetString
lazyLabel.textAlignment = .center
view.addSubview(lazyLabel)
let contentsRect = CGRect(x: 0, y: view.frame.height / 2, width: view.frame.width, height: view.frame.height / 2)
let contentsLabel = UILabel(frame: contentsRect)
contentsLabel.font = UIFont.systemFont(ofSize: 32)
contentsLabel.text = targetString
contentsLabel.textAlignment = .center
view.addSubview(contentsLabel)
targetString = "2"
lazyLabel.text = lazyContents
contentsLabel.text = contents
targetString = "3"
lazyLabel.text = lazyContents
contentsLabel.text = contents
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
| true
|
6d1134349b3c47ba8166aec3e261951071d34d18
|
Swift
|
huangmubin/The_Day
|
/The_Day/The_Day/Classes/Globals/Tools/MCalendar.swift
|
UTF-8
| 8,257
| 3.34375
| 3
|
[] |
no_license
|
//
// Date.swift
// The_Day
//
// Created by 黄穆斌 on 2017/2/23.
// Copyright © 2017年 黄穆斌. All rights reserved.
//
import UIKit
class MCalendar {
// MARK: Value
var calendar: Calendar
var date: Date
// MARK: Init
init(identifier: Calendar.Identifier = Calendar.current.identifier, date: Date = Date()) {
self.calendar = Calendar(identifier: identifier)
self.date = date
}
init(identifier: Calendar.Identifier = Calendar.current.identifier, date: TimeInterval) {
self.calendar = Calendar(identifier: identifier)
self.date = Date(timeIntervalSince1970: date)
}
// MARK: Date
var year: Int {
return calendar.component(Calendar.Component.year, from: date)
}
var month: Int {
return calendar.component(Calendar.Component.month, from: date)
}
var day: Int {
return calendar.component(Calendar.Component.day, from: date)
}
/// Sunday is 1
var week: Int {
return calendar.component(Calendar.Component.weekday, from: date) - 1
}
var hour: Int {
return calendar.component(Calendar.Component.hour, from: date)
}
var minute: Int {
return calendar.component(Calendar.Component.minute, from: date)
}
var second: Int {
return calendar.component(Calendar.Component.second, from: date)
}
var weekOfMonth: Int {
return calendar.component(Calendar.Component.weekOfMonth, from: date)
}
var weekOfYear: Int {
return calendar.component(Calendar.Component.weekOfYear, from: date)
}
var age: Int {
let today = Double(Int(Date().timeIntervalSince1970 / 86400) * 86400)
let space = date.timeIntervalSince1970 - today
if space > 0 {
return Int(space / 86400)
} else {
return Int(space / 86400) - 1
}
}
// MARK: Counts
var daysInMonth: Int {
let total = self.year * 12 + self.month
let year = total / 12
let month = total % 12
switch month {
case 2:
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 29 : 28
case 4, 6, 9, 11:
return 30
default:
return 31
}
}
var daysInYear: Int {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 366 : 365
}
// MARK: First
func firstDayInYear() -> Date? {
return calendar.date(from: calendar.dateComponents([.year], from: date))
}
func firstDayInMonth() -> Date? {
return calendar.date(from: calendar.dateComponents([.year, .month], from: date))
}
func firstDayInWeek() -> Date? {
var weekFirst: Date = Date()
var interval: TimeInterval = 0
if calendar.dateInterval(of: .weekOfYear, start: &weekFirst, interval: &interval, for: date) {
return weekFirst
} else {
return nil
}
}
func firstTimeInDay() -> Date? {
return calendar.date(from: calendar.dateComponents([.year, .month, .day], from: date))
}
// MARK: Advand
func adding(time: TimeInterval) -> Date {
return date.addingTimeInterval(time)
}
// MARK: String
var sYear: String {
return "\(year)"
}
var sMonth: String {
return MCalendar.English.Months[month]
}
var sDay: String {
return "\(day)"
}
var sWeek: String {
return MCalendar.English.Weeks[week]
}
var sAge: String {
let age = self.age
switch age {
case 0:
return "Today"
case 1:
return "Tomorrow"
case 2:
return "Day after tomorrow"
case -1:
return "Yeasterday"
case -2:
return "Day before yesterday"
case 0 ..< Int.max:
return "After \(age) days"
default:
return "\(age) days ago"
}
}
}
// MARK: - Timestamp enums
extension MCalendar {
enum Timestamp: TimeInterval {
case minute = 60.0
case hour = 3600.0
case day = 86400.0
case week = 604800.0
subscript(offset: Int) -> Double {
return rawValue * Double(offset)
}
}
}
// MARK: - String
extension MCalendar {
static let English: (
Months: [String],
Weeks: [String]
) = (
["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
)
static let Chinese: (
Era: [String],
CelestialStems: [String],
EarthlyBranches: [String],
Zodiacs: [String],
Months: [String],
Days: [String],
Weeks: [String]
) = (
[
"甲子", "乙丑", "丙寅", "丁卯", "午辰", "己巳", "庚午", "辛未", "壬申", "癸酉",
"甲戌", "乙亥", "丙子", "丁丑", "午寅", "己卯", "庚辰", "辛巳", "壬午", "癸未",
"甲申", "乙酉", "丙戌", "丁亥", "午子", "己丑", "庚寅", "辛卯", "壬辰", "癸巳",
"甲午", "乙未", "丙申", "丁酉", "午戌", "己亥", "庚子", "辛丑", "壬寅", "癸卯",
"甲辰", "乙巳", "丙午", "丁未", "午申", "己酉", "庚戌", "辛亥", "壬子", "癸丑",
"甲寅", "乙卯", "丙辰", "丁巳", "午午", "己未", "庚申", "辛酉", "壬戌", "癸亥"
],
["甲", "乙", "丙", "丁", "午", "己", "庚", "辛", "壬", "癸"],
["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"],
["鼠", "牛", "虎", "兔", "龙", "色", "马", "羊", "猴", "鸡", "狗", "猪"],
["正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "冬月", "腊月"],
[
"初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十",
"十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
"廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十"
],
["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
)
}
// MARK: - Tools
extension MCalendar {
// MARK: Count
class func range(_ date: Double, days: Int = 1) -> (Double, Double) {
let start = Double(Int(date / 86400) * 86400)
return (start, start + Double(days * 86400))
}
// MARK: Day Info
class func year(_ date: Double) -> Int {
return Calendar.current.component(Calendar.Component.year, from: Date(timeIntervalSince1970: date))
}
class func month(_ date: Double) -> Int {
return Calendar.current.component(Calendar.Component.month, from: Date(timeIntervalSince1970: date))
}
class func day(_ date: Double) -> Int {
return Calendar.current.component(Calendar.Component.day, from: Date(timeIntervalSince1970: date))
}
class func week(_ date: Double) -> Int {
return Calendar.current.component(Calendar.Component.weekday, from: Date(timeIntervalSince1970: date)) - 1
}
class func sYear(_ date: Double) -> String {
return "\(Calendar.current.component(Calendar.Component.year, from: Date(timeIntervalSince1970: date)))"
}
class func sMonth(_ date: Double) -> String {
return MCalendar.English.Months[Calendar.current.component(Calendar.Component.month, from: Date(timeIntervalSince1970: date)) - 1]
}
class func sDay(_ date: Double) -> String {
return "\(Calendar.current.component(Calendar.Component.day, from: Date(timeIntervalSince1970: date)))"
}
class func sWeek(_ date: Double) -> String {
return MCalendar.English.Weeks[Calendar.current.component(Calendar.Component.weekday, from: Date(timeIntervalSince1970: date)) - 1]
}
}
| true
|
16a21d6e43580023a7ee4c383583a0ae97500821
|
Swift
|
TheHelixPro/Math-2
|
/Math/DataStoreManager.swift
|
UTF-8
| 3,821
| 2.984375
| 3
|
[] |
no_license
|
//
// DataStoreManager.swift
// Math
//
// Created by D_Key on 02.08.2021.
//
import Foundation
import CoreData
class DataStoreManager{
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Math")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
lazy var viewContext: NSManagedObjectContext = {
return persistentContainer.viewContext
}()
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func addTask(title: String, isLock: Bool, color1: String, color2 : String, img: String , levels:[Levels]) -> Task {
// let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Task")
// fetchRequest.predicate = NSPredicate(format: "isMain = true")
// if let tasks = try? viewContext.fetch(fetchRequest) as? [Task],!tasks.isEmpty {
// return tasks.first!
// }
// else {
let task = Task(context: viewContext)
task.title = title
task.isLock = isLock
task.color1 = color1
task.color2 = color2
task.img = img
task.isMain = true
for i in 0...task.levels!.count {
let level = Level(context: viewContext)
level.id = Int16(levels[i].id)
level.stars = Int16(levels[i].stars)
level.isLock = Bool(levels[i].isLock)
level.task = task
}
do{
try viewContext.save()
print (viewContext)
}catch let error{
print("Error: \(error)")
}
return task
// }
}
func AllTask() -> [Task] {
let fetchReuest:NSFetchRequest<Task> = Task.fetchRequest()
let tasks = try? viewContext.fetch(fetchReuest)
let i = 0
if ((tasks?.isEmpty) == true){
print("Записи не найдены")
}else{
for i in 0...tasks!.count-1{
// print("-----\(i)-----")
let re = (tasks?[i].levels)
print(re)
//
}
}
return tasks ?? []
}
func UpdateTask(with name:String) {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Task")
fetchRequest.predicate = NSPredicate(format: "isMain = true")
if let tasks = try? viewContext.fetch(fetchRequest) as? [Task]{
guard let mainTask = tasks.first else { return }
mainTask.title = name
try? viewContext.save()
}
// guard let name = textFiel.text else { return }
// dataStoreManager.updateMainUser(with: name)
}
func removeMainUser(){
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Task")
fetchRequest.predicate = NSPredicate(format: "isMain = true")
if let tasks = try? viewContext.fetch(fetchRequest) as? [Task] {
guard let mainTask = tasks.first else { return }
viewContext.delete(mainTask)
try? viewContext.save()
}
}
}
| true
|
87a3ea2f38374cd2d03c74561b0f198644beed2a
|
Swift
|
Abhinav034/MusicAppProject
|
/MusicApp/ViewController.swift
|
UTF-8
| 6,153
| 2.71875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// MusicApp
//
// Created by Abhinav Bhardwaj on 2019-11-20.
// Copyright © 2019 Abhinav Bhardwaj. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
var audioPlayer = AVAudioPlayer()
class ViewController: UIViewController {
var isplaying = false
var shuffle = false
@IBOutlet weak var timeBar: UISlider!
@IBOutlet weak var albumImage: UIImageView!
@IBOutlet weak var PlayPauseButton: UIButton!
@IBOutlet weak var shuffleBtn: UIButton!
@IBOutlet weak var timeUp: UILabel!
@IBOutlet weak var songNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setupSong()
}
func setupSong() {
let songName = songs[currSong].name
songNameLabel.text = songName
// getting path for the songs
let sound = Bundle.main.path(forResource: songName, ofType: "mp3")
do{
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound!))
try
AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: [AVAudioSession.CategoryOptions.mixWithOthers])
let playerItem = AVPlayerItem(url: URL(fileURLWithPath: sound!))
let metadataList = playerItem.asset.metadata as [AVMetadataItem]
for item in metadataList {
if item.commonKey == nil{
continue
}
if let key = item.commonKey, let value = item.value {
print(key)
print(value)
if key.rawValue == "title" {
//trackLabel.text = value as? String
}
if key.rawValue == "artist" {
//artistLabel.text = value as? String
}
if key.rawValue == "artwork" {
if let audioImage = UIImage(data: (value as! NSData) as Data) {
//println(audioImage.description)
albumImage.image = audioImage
}
}
}
}
}
catch{
print(error)
}
timeBar.maximumValue = Float(audioPlayer.duration)
Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.updateSlider), userInfo: nil, repeats: true)
audioPlayer.stop()
audioPlayer.play()
PlayPauseButton.setImage(UIImage(named: "media-pause"), for: .normal)
isplaying = true
}
@objc func updateSlider(){
timeBar.value = Float(audioPlayer.currentTime)
let (_, cm ,cs) = secondsToHoursMinutesSeconds(seconds: Int(audioPlayer.currentTime))
let (_, tm, ts) = secondsToHoursMinutesSeconds(seconds: Int(audioPlayer.duration))
let cTime = String(cm) + ":" + String(cs)
let tTime = String(tm) + ":" + String(ts)
timeUp.text = cTime + "/" + tTime
if (Int(timeBar.value) >= Int(audioPlayer.duration)) {
setNext()
}
}
func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
@IBAction func dragTimeBar(_ sender: UISlider) {
audioPlayer.currentTime = TimeInterval(Float(timeBar.value)) // slider interaction
}
@IBAction func onTimeBarTouch(_ sender: UISlider) {
setPlayPause()
}
@IBAction func onTouchExit(_ sender: UISlider) {
setPlayPause()
}
@IBAction func playPausePressed(_ sender: UIButton) {
setPlayPause()
}
func setPlayPause(){
if isplaying {
audioPlayer.pause()
isplaying = false
PlayPauseButton.setImage(UIImage(named: "media-play"), for: .normal)
}
else{
audioPlayer.play()
isplaying = true
PlayPauseButton.setImage(UIImage(named: "media-pause"), for: .normal)
}
}
@IBAction func previousPressed(_ sender: UIButton) {
setPrevious()
}
func setPrevious(){
if (shuffle) {
currSong = Int.random(in: 0..<songs.count)
}
else if(currSong == 0){
currSong = songs.count-1
}
else{
currSong = currSong-1
}
setupSong()
}
@IBAction func nextPressed(_ sender: UIButton) {
setNext()
}
func setNext(){
if (shuffle) {
currSong = Int.random(in: 0..<songs.count)
}
else if (currSong == songs.count - 1) {
currSong = 0
}
else{
currSong = currSong+1
}
setupSong()
}
@IBAction func SufflePressed(_ sender: UIButton) {
if (!shuffle) {
shuffleBtn.setImage(UIImage(named: "shuffle.png"), for: .normal)
} else {
shuffleBtn.setImage(UIImage(named: "shuffleno.png"), for: .normal)
}
shuffle = !shuffle
}
@IBAction func ListButtonPressed(_ sender: UIButton) {
// navigationController?.popToRootViewController(animated: true)
}
}
| true
|
bb957ec050f0e28a4bc726d5cdbc2420374dec66
|
Swift
|
miguelc95/EventItRecuperacion
|
/EventItRecuperacion/EventoViewController.swift
|
UTF-8
| 2,630
| 2.609375
| 3
|
[] |
no_license
|
//
// EventoViewController.swift
// Event it
//
// Created by Luis Felipe Salazar on 10/11/15.
// Copyright © 2015 Luis Felipe Salazar. All rights reserved.
//
import UIKit
import MapKit
class EventoViewController: UIViewController, MKMapViewDelegate {
var nombre = "Nombre"
var lugar = "Lugar del evento"
var location = "location"
var descripcion = "Descripcion"
var imagen = "nombre de la imagen"
var fecha = "fecha evento"
var costo = 0
var latitude = 25.663883
var longitude = -100.419892
@IBOutlet weak var fechaEvento: UILabel!
@IBOutlet weak var imagenEvento: UIImageView!
@IBOutlet weak var descripcionEvento: UITextView!
@IBOutlet weak var lugarEvento: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = nombre
fechaEvento.text = fecha
imagenEvento.image = UIImage(named: imagen)
descripcionEvento.text = descripcion
lugarEvento.setTitle(lugar, forState: UIControlState.Normal)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func registrarse(sender: AnyObject) {
}
@IBAction func eventoTap(sender: AnyObject) {
/*
var lat1 : NSString = self.latitude
var lng1 : NSString = self.longitude
*/
let latitute:CLLocationDegrees = latitude
let longitute:CLLocationDegrees = longitude
let regionDistance:CLLocationDistance = 10000
let coordinates = CLLocationCoordinate2DMake(latitute, longitute)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
let options = [
MKLaunchOptionsMapCenterKey: NSValue(MKCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(MKCoordinateSpan: regionSpan.span)
]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = "\(self.nombre)"
mapItem.openInMapsWithLaunchOptions(options)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
a2ae4387ec871efdf3a698161250d3c8e5f21dfb
|
Swift
|
rodrigolimco/Westeros
|
/WesterosTests/EpisodeTest.swift
|
UTF-8
| 1,213
| 2.890625
| 3
|
[] |
no_license
|
//
// EpisodeTest.swift
// Westeros
//
// Created by Rodrigo Limpias Cossio on 21/8/17.
// Copyright © 2017 Rodrigo Limpias Cossío. All rights reserved.
//
import XCTest
@testable import Westeros
class EpisodeTest: XCTestCase {
var season1: Season!
var season2: Season!
var episode1: Episode!
var episode11: Episode!
override func setUp() {
super.setUp()
season1 = Season(name: "Season 1", releaseDate: Date.dateFromString(date: "2011/04/17")!)
season2 = Season(name: "Season 2", releaseDate: Date.dateFromString(date: "2012/04/01")!)
episode1 = Episode(title: "Winter is coming", emissionDate: Date.dateFromString(date: "2011/04/17")!, season: season1)
episode11 = Episode(title: "The North Remembers", emissionDate: Date.dateFromString(date: "2012/04/01")!, season: season2)
}
func testEpisodeDescription(){
XCTAssertNotNil(episode1)
}
func testEpisodeEquatable(){
XCTAssertNotEqual(episode1, episode11)
}
func testEpisodeHashable(){
XCTAssertNotNil(episode1.hashValue)
}
func testEpisodeComparable(){
XCTAssertLessThan(episode11, episode1)
}
}
| true
|
b312970c787748a600047b8890e60debfb97780a
|
Swift
|
ZawnH/EduCake
|
/eduCake/TopicViewModel.swift
|
UTF-8
| 5,831
| 3.5
| 4
|
[] |
no_license
|
import Foundation
struct Answer {
var videoURL: String?
var textAnswer: String = ""
var upvotes: Int = 0
var downvotes: Int = 0
mutating func upVote() {
upvotes += 1
}
mutating func downVote() {
downvotes += 1
}
}
struct Post: Identifiable {
var id: Int
var question: String
var answers: [Answer]
func getBestAnswerID() -> Int {
var maxVote = 0
var maxID = 0
for index in 0..<answers.count {
if (answers[index].upvotes > maxVote) {
maxVote = answers[index].upvotes
maxID = index
}
}
return maxID
}
mutating func getNextBestAnswerID(watchedAnswerIndex: [Int]) -> Int {
var maxVote = 0
var maxID = 0
for index in 0..<answers.count {
if (answers[index].upvotes > maxVote && !watchedAnswerIndex.contains(index)) {
maxVote = answers[index].upvotes
maxID = index
}
}
return maxID
}
}
struct Topic: Identifiable {
var id: Int
let imageName: String
let courseName: String
var posts: [Post] = []
}
class TopicViewModel {
var topics = [Topic]()
init() {
// MARK: CS
let CSTopic = Topic(id: 0, imageName: "CS", courseName: "COMPUTER SCIENCE", posts: [
Post(id: 0, question: "What is Structs in Swift?",
answers: [Answer(videoURL: "video1", textAnswer: "answer cs1", upvotes: 30, downvotes: 2),
Answer(videoURL: "video2", textAnswer: "tra loi", upvotes: 60, downvotes: 30),
Answer(videoURL: "video3", textAnswer: "answer cs3", upvotes: 10, downvotes: 23),
Answer(videoURL: "video4", textAnswer: "answer cs4", upvotes: 70, downvotes: 21),
]),
Post(id: 1, question: "What are Views?",
answers: [Answer(textAnswer: "Are one of the named types in Swift that allow you to encapsulate related properties and behaviors", upvotes: 30, downvotes: 2),
Answer(textAnswer: "applications", upvotes: 0, downvotes: 30),
]),
Post(id: 2, question: "What is a class?",
answers: [Answer(textAnswer: "C L A S S", upvotes: 30, downvotes: 2),
Answer(textAnswer: "answer 2", upvotes: 0, downvotes: 30),
]),
Post(id: 3, question: "Object Oriented Programming vs Functional Programming?",
answers: [Answer(textAnswer: "traloi 1", upvotes: 30, downvotes: 2),
Answer(textAnswer: "answer 2", upvotes: 0, downvotes: 30),
]),
])
//MARK: MATH
let MathTopic = Topic(id: 1, imageName: "Phys", courseName: "PHYSICS", posts: [
Post(id: 0, question: "What is ",
answers: [Answer(textAnswer: "answer cs1", upvotes: 30, downvotes: 2),
Answer(textAnswer: "tra loi", upvotes: 0, downvotes: 30),
]),
Post(id: 1, question: "What is a struct?",
answers: [Answer(textAnswer: "traloi 1", upvotes: 30, downvotes: 2),
Answer(textAnswer: "answer 2", upvotes: 0, downvotes: 30),
]),
])
//MARK: PHYS
let PhysTopic = Topic(id: 2, imageName: "Chem", courseName: "CHEMISTRY", posts: [
Post(id: 0, question: "An 80kg person A and a 60kg person B pull on opposite ends of a massless rope in a tug of war. Comparison of what forces determines who wins?",
answers: [Answer(textAnswer: "Friction forces. Because abc xyz", upvotes: 30, downvotes: 2),
Answer(textAnswer: "Hello abc", upvotes: 0, downvotes: 30),
]),
Post(id: 1, question: "Cau hoi khac",
answers: [Answer(textAnswer: "traloi 1", upvotes: 30, downvotes: 2),
Answer(textAnswer: "answer 2", upvotes: 0, downvotes: 30),
]),
])
//MARK: BIO
let BioTopic = Topic(id: 3, imageName: "His", courseName: "HISTORY", posts: [
Post(id: 0, question: "What are cells?",
answers: [Answer(textAnswer: "Cells are the basic building blocks of all living things.", upvotes: 30, downvotes: 2),
Answer(textAnswer: "hehe", upvotes: 0, downvotes: 30),
]),
Post(id: 1, question: "Is ionizing radiation always harmful?",
answers: [Answer(textAnswer: "no", upvotes: 30, downvotes: 2),
Answer(textAnswer: "yes, of course", upvotes: 0, downvotes: 30),
]),
])
//MARK: PHIL
let PhilTopic = Topic(id: 4, imageName: "Geo", courseName: "GEOGRAPHY", posts: [
Post(id: 0, question: "What is quicksort?",
answers: [Answer(textAnswer: "answer cs1", upvotes: 30, downvotes: 2),
Answer(textAnswer: "tra loi", upvotes: 0, downvotes: 30),
]),
Post(id: 1, question: "What is a struct?",
answers: [Answer(textAnswer: "traloi 1", upvotes: 30, downvotes: 2),
Answer(textAnswer: "answer 2", upvotes: 0, downvotes: 30),
]),
])
topics.append(CSTopic)
topics.append(MathTopic)
topics.append(PhysTopic)
topics.append(BioTopic)
topics.append(PhilTopic)
}
}
| true
|
dca6c41309081eeb25aedbcd92bf887343d26b16
|
Swift
|
xiaoallocinit/APPStore
|
/XZBAPPStore/XZBAPPStore/CardView.swift
|
UTF-8
| 1,280
| 2.671875
| 3
|
[] |
no_license
|
//
// CardView.swift
// XZBAPPStore
//
// Created by 🍎上的豌豆 on 2018/10/12.
// Copyright © 2018年 xiao. All rights reserved.
//
import UIKit
class CardView: UIView {
let titleLabel = UILabel()
let subtitleLabel = UILabel()
let imageView = UIImageView.init()
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .regular))
required init?(coder aDecoder: NSCoder) { fatalError() }
override init(frame: CGRect) {
super.init(frame: frame)
clipsToBounds = true
titleLabel.font = UIFont.boldSystemFont(ofSize: 30)
subtitleLabel.font = UIFont.systemFont(ofSize: 16)
imageView.contentMode = .scaleAspectFill
addSubview(imageView)
addSubview(visualEffectView)
addSubview(titleLabel)
addSubview(subtitleLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = bounds
visualEffectView.frame = CGRect(x: 0, y: bounds.height - 90, width: bounds.width, height: 90)
titleLabel.frame = CGRect(x: 20, y: bounds.height - 70, width: bounds.width - 40, height: 30)
subtitleLabel.frame = CGRect(x: 20, y: bounds.height - 40, width: bounds.width - 40, height: 30)
}
}
| true
|
e4e540ee4ed93b4a18fa71c91ae6785657c7c4e6
|
Swift
|
gerardogrisolini/ZenMQTT
|
/Sources/ZenMQTT/Models/MQTTPacket.swift
|
UTF-8
| 1,718
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
//
// MQTTPacket.swift
//
//
// Created by Gerardo Grisolini on 01/02/2020.
//
import Foundation
public class MQTTPacket {
let header: MQTTPacketFixedHeader
init(header: MQTTPacketFixedHeader) {
self.header = header
}
func variableHeader() -> Data {
// To be implemented in subclasses
return Data()
}
func payload() -> Data {
// To be implemented in subclasses
return Data()
}
func networkPacket() -> Data {
return finalPacket(variableHeader(), payload: payload())
}
// Creates the actual packet to be sent using fixed header, variable header and payload
// Automatically encodes remaining length
private func finalPacket(_ variableHeader: Data, payload: Data) -> Data {
var remainingData = variableHeader
remainingData.append(payload)
var finalPacket = Data(capacity: 1024)
finalPacket.append(header.networkPacket())
finalPacket.mqtt_encodeRemaining(length: remainingData.count) // Remaining Length
finalPacket.append(remainingData) // Remaining Data = Variable Header + Payload
return finalPacket
}
// private func remainingLen(len: UInt32) -> [UInt8] {
// var bytes: [UInt8] = []
// var digit: UInt8 = 0
//
// var len = len
// repeat {
// digit = UInt8(len % 128)
// len = len / 128
// // if there are more digits to encode, set the top bit of this digit
// if len > 0 {
// digit = digit | 0x80
// }
// bytes.append(digit)
// } while len > 0
//
// return bytes
// }
}
| true
|
c3be8b749ad71efdec546c4bcc68f587d71f7008
|
Swift
|
makemakeway/WorkTable
|
/Swift/MySNS/MySNS/View/Screen/Notification/NotificationCell.swift
|
UTF-8
| 4,524
| 2.8125
| 3
|
[] |
no_license
|
//
// NotificationCell.swift
// MySNS
//
// Created by 박연배 on 2021/07/18.
//
import SwiftUI
import Kingfisher
struct NotificationCell: View {
var isFollowed: Bool { return viewModel.notification.isFollowed ?? false }
@StateObject var viewModel: NotificationCellViewModel
var body: some View {
HStack {
if let user = viewModel.notification.user {
NavigationLink(
destination: ProfileView(user: user, throughSearch: true).navigationBarTitle("\(user.userID)", displayMode: .inline),
label: {
if viewModel.notification.profileImageUrl.isEmpty {
Image(systemName: "person.fill")
.resizable()
.scaledToFill()
.frame(width: 40, height: 40)
.background(Color(.systemGray4))
.foregroundColor(.primary)
.cornerRadius(20)
} else {
KFImage(URL(string: viewModel.notification.profileImageUrl))
.resizable()
.scaledToFill()
.frame(width: 40, height: 40)
.cornerRadius(20)
}
Text(viewModel.notification.userId)
.fontWeight(.semibold)
.font(.system(size: 14)) +
Text("\(viewModel.notification.type.notificationMessage)").font(.system(size: 15)) +
Text(" \(viewModel.timestampString)").font(.system(size: 14)).foregroundColor(.gray)
})
}
Spacer()
if viewModel.notification.type != .follow {
if let post = viewModel.notification.post {
NavigationLink(
destination: PostView(viewModel: FeedCellViewModel(post: post))
.navigationBarTitleDisplayMode(.inline).toolbar {
ToolbarItem(placement: .principal) {
VStack {
Text("\(post.ownerUserId)")
.font(.system(size: 13, weight: .bold))
.foregroundColor(Color.gray)
Text("게시물")
.font(.system(size: 15, weight: .bold))
}
}
},
label: {
KFImage(URL(string: post.imageUrl))
.resizable()
.scaledToFill()
.frame(width: 40, height: 40)
.padding(.horizontal, 20)
})
}
} else {
Button(action: { isFollowed ? viewModel.unfollow() : viewModel.follow() }, label: {
if isFollowed {
Text("팔로잉")
.font(.system(size: 14, weight: .semibold))
.foregroundColor(.primary)
.padding(.horizontal, 20)
.padding(.vertical, 8)
.background(RoundedRectangle(cornerRadius: 10).stroke(Color.gray, lineWidth: 0.8))
}
else {
Text("팔로우")
.foregroundColor(.white)
.font(.system(size: 14, weight: .semibold))
.padding(.horizontal, 20)
.padding(.vertical, 8)
.background(Color(#colorLiteral(red: 0.1141172731, green: 0.541489393, blue: 1, alpha: 1)))
}
})
.cornerRadius(7)
}
}
.padding(.horizontal)
}
}
| true
|
53c4068a0418e2d990e0b3e9cc30db74f3ceeb45
|
Swift
|
AbhigyaWangoo/HelpApp
|
/HelpApp/MsgPage.swift
|
UTF-8
| 2,722
| 3.390625
| 3
|
[] |
no_license
|
//
// MsgPage.swift
// ChatBox
//
// Created by Abhigya Wangoo on 6/19/20.
// Copyright © 2020 Abhigya Wangoo. All rights reserved.
//
import SwiftUI
import Firebase
import FirebaseFirestore
struct Message {
var content: String
var user: String
var avatar: String
}
struct MsgPage: View{
@State var msgContent = ""
var user = ""
var avatar = ""
@State private var isImportant = true;
@State private var data = ""
var body: some View {
VStack{
//insert the list of messages here
HStack{
TextField("CREATE A MESSAGE", text: $msgContent).cornerRadius(20)
Button(action: {
self.data = self.getDocument(self.addMessage(Message(content: self.msgContent, user: self.user, avatar: self.avatar), self.isImportant)) //adding the message on the buttonclick, as well as assigning the returnvalue to var data
}){
Image(systemName: "paperplane")
}.background(Color.red.opacity(50))
}
}
}
func addMessage(_ message: Message,_ isUrgent: Bool) -> String{
let db = Firestore.firestore()
var ref: DocumentReference? = nil
ref = db.collection("Messages").addDocument(data: [
"isUrgent": true,
"Content": "\(message.content)",
"User": "\(message.avatar)"
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
}
}
return ref?.documentID ?? "Couldn't find the document"
}
private func getDocument(_ docID:String) -> String{ //function gets the document's data as a string according to the docid argument
// [START get_document]
let db = Firestore.firestore()
var documentData = ""
let docRef = db.collection("Messages").document("\(docID)")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
documentData = document.data().map(String.init(describing:)) ?? "nil"
} else {
print("Document does not exist")
}
}
return documentData
}
}
/*struct MsgPage_Previews: PreviewProvider {
static var previews: some View {
MsgPage(contentMessage: "This is just the sample view ")
}
}
*/
struct MsgPage_Previews: PreviewProvider {
static var previews: some View {
/*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/
}
}
| true
|
f843096db94389e64fc4187e65669261ac16adaa
|
Swift
|
Abner0902/ASA_Health_Clinic
|
/ASA Health Clinic/Alert.swift
|
UTF-8
| 1,012
| 2.78125
| 3
|
[] |
no_license
|
//
// Alert.swift
// ASA Health Clinic
//
// Created by zhenyu on 20/6/17.
// Copyright © 2017 zhenyu. All rights reserved.
//
import UIKit
class Alert: NSObject {
//show alert view
func showAlert(msg: String, view: UIViewController) {
let alertController = UIAlertController(title: "Notice", message: msg, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
NSLog("Alert ok clicked")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (result : UIAlertAction) -> Void in
view.dismiss(animated: true) { () -> Void in
NSLog("Alert Cancel clicked")
}
}
alertController.addAction(okAction)
alertController.addAction(cancelAction)
view.present(alertController, animated: true, completion: nil)
}
}
| true
|
01a3b37a7786ede1f75f399cbe78350bafddd005
|
Swift
|
Flight-School/Rate
|
/Tests/RateTests/RateTests.swift
|
UTF-8
| 1,853
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
import XCTest
@testable import Rate
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
final class RateTests: XCTestCase {
func testInitialization() {
let rate = Rate<UnitMass, UnitLength>(value: 1, unit: .kilograms, per: .meters)
XCTAssertEqual(rate.value, 1)
XCTAssertEqual(rate.numeratorUnit, .kilograms)
XCTAssertEqual(rate.denominatorUnit, .meters)
XCTAssertEqual(rate.symbol, "kg/m")
}
func testAddition() {
let rate = Rate<UnitVolume, UnitDuration>(value: 1, unit: .liters, per: .seconds)
let sum = rate + rate
XCTAssertEqual(sum.value, 2)
XCTAssertEqual(sum.numeratorUnit, .liters)
}
func testSubtraction() {
let rate = Rate<UnitVolume, UnitDuration>(value: 1, unit: .liters, per: .seconds)
let difference = rate - rate
XCTAssertEqual(difference.value, 0)
XCTAssertEqual(difference.numeratorUnit, .liters)
}
func testMultiplicationByMeasurement() {
let rate = Rate<UnitVolume, UnitDuration>(value: 1, unit: .liters, per: .seconds)
let duration = Measurement<UnitDuration>(value: 1, unit: .minutes)
let volume = rate * duration
XCTAssertEqual(volume.value, 60)
XCTAssertEqual(volume.unit, .liters)
}
func testMultiplicationByScalar() {
let rate = Rate<UnitVolume, UnitDuration>(value: 1, unit: .liters, per: .seconds)
let scaledRate = rate * 10
XCTAssertEqual(scaledRate.value, 10)
XCTAssertEqual(scaledRate.numeratorUnit, .liters)
}
func testDivisionByScalar() {
let rate = Rate<UnitVolume, UnitDuration>(value: 1, unit: .liters, per: .seconds)
let scaledRate = rate / 10
XCTAssertEqual(scaledRate.value, 1 / 10)
XCTAssertEqual(scaledRate.numeratorUnit, .liters)
}
}
| true
|
98d96f452d1e75f45c1b84d6441f753656eb1ea3
|
Swift
|
huangzhouhong/DeclareLayoutSwift
|
/DeclareLayoutSwift/DeclareLayoutSwift/Source/Layoutable/Base/DisposeBag.swift
|
UTF-8
| 951
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// DisposeBag.swift
// DeclareLayoutSwift
//
// Created by 黄周鸿 on 2018/4/10.
// Copyright © 2018年 com.yasoon. All rights reserved.
//
import Foundation
private class DisposeBag {
var objs: [AnyObject] = []
}
private var disposeBagKey: Int = 0
public protocol SupportDisposeBag: SupportStoreProperty {}
extension SupportDisposeBag {
fileprivate var disposeBag: DisposeBag {
get {
if let value = getValue(key: &disposeBagKey) as? DisposeBag {
return value
} else {
let value = DisposeBag()
setValue(key: &disposeBagKey, value: value)
return value
}
}
set {
setValue(key: &disposeBagKey, value: newValue)
}
}
}
extension NSObject: SupportDisposeBag {}
public extension NSObject {
func retain(owner: SupportDisposeBag) {
owner.disposeBag.objs.append(self)
}
}
| true
|
b1c588ab88a5cffb002e9ce1b4136c48557c0f32
|
Swift
|
daikiumehara/GitHubAPI_Practice
|
/GitHubAPI_Practice/WebViewController.swift
|
UTF-8
| 772
| 2.90625
| 3
|
[] |
no_license
|
//
// WebViewController.swift
// GitHubAPI_Practice
//
// Created by daiki umehara on 2021/06/07.
//
import UIKit
import WebKit
class WebViewController: UIViewController {
@IBOutlet var webView: WKWebView!
private var url: URL?
override func viewDidLoad() {
super.viewDidLoad()
guard let url = url else {
dismiss(animated: true, completion: nil)
return
}
let request = URLRequest(url: url)
webView.load(request)
}
static func instantiate(url: String) -> WebViewController {
let webVC = UIStoryboard.init(name: "WebView", bundle: nil).instantiateInitialViewController() as! WebViewController
webVC.url = URL(string: url)
return webVC
}
}
| true
|
cff4acb851733742b51b4c9aea953b1c2a1a5221
|
Swift
|
danielpanzer/Kalah
|
/Kalah/View/SeedView.swift
|
UTF-8
| 954
| 2.671875
| 3
|
[] |
no_license
|
//
// SeedView.swift
// Kalah
//
// Created by Daniel Panzer on 3/23/18.
// Copyright © 2018 Daniel Panzer. All rights reserved.
//
import UIKit
class SeedView : UIView {
var uuid: UUID {
return _uuid
}
private var _uuid: UUID!
static func seed(with uuid: UUID, color: UIColor) -> SeedView {
let seed = SeedView(frame: CGRect(origin: .zero, size: Constants.kSeedSize))
seed._uuid = uuid
seed.translatesAutoresizingMaskIntoConstraints = false
seed.isUserInteractionEnabled = false
seed.backgroundColor = color
seed.layer.cornerRadius = Constants.kSeedSize.width/2
seed.layer.borderColor = UIColor.black.cgColor
seed.layer.borderWidth = 1
return seed
}
override var collisionBoundsType: UIDynamicItemCollisionBoundsType {
return .ellipse
}
override var hash: Int {
return _uuid.hashValue
}
}
| true
|
4e7eef83b216a89bbdc66aca4163dfe824a6114f
|
Swift
|
mokoranyAli/DesignPatternsBySwift
|
/DesignPatterns/Behavioral/Strategy/Example2/Logger.swift
|
UTF-8
| 722
| 3.84375
| 4
|
[] |
no_license
|
//
// Logger.swift
// DesignPatterns
//
// Created by Mohamed Korany on 5/13/21.
// Copyright © 2021 Mohamed Korany Ali. All rights reserved.
//
import Foundation
// What
protocol LoggerStrategy {
func log(_ message: String)
}
// Who
struct Logger {
let strategy: LoggerStrategy
func log(_ message: String) {
strategy.log(message)
}
}
// How
struct LowercaseStrategy: LoggerStrategy {
func log(_ message: String) {
print(message.lowercased())
}
}
struct UppercaseStrategy: LoggerStrategy {
func log(_ message: String) {
print(message.uppercased())
}
}
struct CapitalizedStrategy: LoggerStrategy {
func log(_ message: String) {
print(message.capitalized)
}
}
| true
|
231b6a74f84b4605b6adc01dce6c1a161680fc9d
|
Swift
|
serejaonly/Trump-Quotes
|
/ObjectList/Views/LoadingView/LoadingView.swift
|
UTF-8
| 1,223
| 2.765625
| 3
|
[] |
no_license
|
//
// LoadingView.swift
// ObjectList
//
// Created by Сергей Новиков on 15/12/2019.
// Copyright © 2019 Сергей Новиков. All rights reserved.
//
import UIKit
class LoadingView: UIView {
@IBOutlet private var titleLabel: UILabel!
@IBOutlet private var refreshButton: UIButton!
private var isFirstLoading = true
var reload: (() -> Void)?
@IBAction private func refresh(_ sender: UIButton) {
reload?()
}
override func awakeFromNib() {
super.awakeFromNib()
layer.addShadow(withRadius: 0)
backgroundColor = Style.Color.background
}
func minimizeIfNeeded() {
guard !isFirstLoading else {
isFirstLoading.toggle()
return
}
frame = CGRect(x: 0, y: Bounds.fullHeight - 44.0,
width: Bounds.fullWidth, height: 44)
titleLabel.font = .systemFont(ofSize: 15)
backgroundColor = Style.Color.foreground
superview?.layoutIfNeeded()
}
func showError() {
titleLabel.text = "Loading error"
refreshButton.isHidden = false
}
func showLoading() {
titleLabel.text = "LOADING..."
refreshButton.isHidden = true
}
}
| true
|
cd12b94a7133e591d8b83d2f347be2cfde0e4d74
|
Swift
|
stephen-sh-chen/CMPE297
|
/HW5_Map_Kit/HW5_Map_Kit/ViewController.swift
|
UTF-8
| 1,829
| 2.609375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// HW5_Map_Kit
//
// Created by Stephen on 9/22/17.
// Copyright © 2017 Stephen. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var fromStreet: UITextField!
@IBOutlet weak var fromCity: UITextField!
@IBOutlet weak var fromState: UITextField!
@IBOutlet weak var fromZipCode: UITextField!
@IBOutlet weak var toStreet: UITextField!
@IBOutlet weak var toCity: UITextField!
@IBOutlet weak var toState: UITextField!
@IBOutlet weak var toZipCode: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let fromPlace = fromStreet.text! + ", " + fromCity.text! + ", " + fromState.text! + ", " + fromZipCode.text! + ", US"
let toPlace = toStreet.text! + ", " + toCity.text! + ", " + toState.text! + ", " + toZipCode.text! + ", US"
if let destinationVC = segue.destination as? MapViewController {
destinationVC.fromPlace = fromPlace
destinationVC.toPlace = toPlace
if segue.identifier == "showMap" { //show Map
destinationVC.showType = "map"
} else if segue.identifier == "showRoute" { //show Route
destinationVC.showType = "route"
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func route(_ sender: Any) {
}
}
| true
|
e5c11356fcc1923eda2c451abb8b586bce7fd8ee
|
Swift
|
diiq/CameraStylus
|
/Renderers/StampedStrokeRendererExtension.swift
|
UTF-8
| 2,145
| 3.203125
| 3
|
[] |
no_license
|
import Darwin
// These are compound methods that build on the universal atoms defined in the
// Renderer protocol.
typealias BezierPoints = (a: Point, cp1: Point, cp2: Point, b: Point)
extension Renderer {
func stampedLine(start start: Point, end: Point, stamper: (point: Point, renderer: Renderer) -> (), minimumGap: Double) {
guard (end - start).length() > minimumGap else { return }
let midPoint = (start + ((end - start) / 2)).withWeight((start.weight + end.weight) / 2)
stamper(point: midPoint, renderer: self)
stampedLine(start: start, end: midPoint, stamper: stamper, minimumGap: minimumGap)
stampedLine(start: midPoint, end: end, stamper: stamper, minimumGap: minimumGap)
}
func stampedLinear(points: [Point], stamper: (point: Point, renderer: Renderer) -> (), minimumGap: Double) {
var lastPoint = points[0]
points[1..<points.count].forEach {
stamper(point: lastPoint, renderer: self)
stampedLine(start: lastPoint, end: $0, stamper: stamper, minimumGap: minimumGap)
lastPoint = $0
}
}
func stampedBezier(
points: BezierPoints,
stamper: (point: Point, renderer: Renderer) -> (),
minimumGap: Double,
tStart: Double = 0,
tEnd: Double = 1) {
let start = bezierPoint(points, t: tStart)
let end = bezierPoint(points, t: tEnd)
let avgWeight = (start.weight + end.weight) / 2
let length = (start - end).length()
let stampCount = max(Int(length / (minimumGap * avgWeight) ), 1)
for i in 0..<stampCount {
let point = bezierPoint(points, t: Double(i)/Double(stampCount))
stamper(point: point, renderer: self)
}
}
// Returns a point along a smooth bezier curve, where 0 <= t <= 1
func bezierPoint(points: BezierPoints, t: Double) -> Point {
let aContrib = pow(1 - t, 3) * points.a
let cp1Contrib = 3 * pow((1 - t), 2) * t * points.cp1
let cp2Contrib = 3 * (1 - t) * pow(t, 2) * points.cp2
let bContrib = pow(t, 3) * points.b
let weight = points.a.weight + t*(points.b.weight - points.a.weight)
return (aContrib + cp1Contrib + cp2Contrib + bContrib).withWeight(weight)
}
}
| true
|
32355f480fa40babb00b429c76ef340264963cb8
|
Swift
|
levibostian/PleaseHold-iOS
|
/Example/PleaseHold_ExampleUITests/ViewControllerTests.swift
|
UTF-8
| 1,103
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
@testable import Pods_PleaseHold_Example
import XCTest
class ViewControllerTests: XCTestCase {
var app: XCUIApplication!
var viewController: ViewControllerPageObject!
override func setUp() {
continueAfterFailure = false
app = XCUIApplication()
app.launchArguments.append("--uitesting")
viewController = ViewControllerPageObject(app: app)
}
override func tearDown() {}
func test_coldStart_viewShowingCorrectViews() {
app.launch()
viewController.pleaseHoldView.assertShown()
viewController.titleLabel.assertShown()
viewController.messageLabel.assertShown()
}
}
class ViewControllerPageObject {
let app: XCUIApplication
var pleaseHoldView: XCUIElement {
return app.otherElements[AccessibilityIdentifiers.pleaseHoldView]
}
var titleLabel: XCUIElement {
return app.staticTexts["Please wait..."]
}
var messageLabel: XCUIElement {
return app.staticTexts["Wait for this thing to happen."]
}
init(app: XCUIApplication) {
self.app = app
}
}
| true
|
c879399b4aa6a492816ba3df078cef43aff42a70
|
Swift
|
cuonghx2709/Checkin-Student
|
/Checkin-Student/Extensions/UIImage+.swift
|
UTF-8
| 638
| 2.609375
| 3
|
[] |
no_license
|
//
// UIImage+.swift
// fGoal
//
// Created by Phạm Xuân Tiến on 5/24/19.
// Copyright © 2019 Sun*. All rights reserved.
//
extension UIImage {
func maskWith(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context = UIGraphicsGetCurrentContext()
let rect = CGRect(origin: CGPoint.zero, size: size)
color.setFill()
draw(in: rect)
context?.setBlendMode(.sourceIn)
context?.fill(rect)
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImage ?? UIImage()
}
}
| true
|
07c51728881b664c82bf5af7072c1064471e4b03
|
Swift
|
ifecdr/SimpsonAppIfe
|
/SimpsonsAppIfe/SimpsonsAppIfe/Service/SimpsonsSerive.swift
|
UTF-8
| 2,917
| 2.59375
| 3
|
[] |
no_license
|
//
// SimpsonsSerive.swift
// SimpsonsApp
//
// Created by MAC Consultant on 3/2/19.
// Copyright © 2019 MAC Consultant. All rights reserved.
//
import Foundation
import UIKit
class SimpsonsService {
// static let shared = SimpsonsService()
// private let session: URLSession
// private init() {
// let config = URLSessionConfiguration.default
// config.allowsCellularAccess = false
// config.requestCachePolicy = .returnCacheDataElseLoad
// session = URLSession.init(configuration: config)
//
// // or just
// // session = URLSession.shared
// }
//static let shared = SimpsonsService()
var simpsonsCollection = [Simpsons.RelatedTopics]()
func downloadSimpsons(completion: @escaping (Simpsons)->()) {
let url = URL(string: "https://api.duckduckgo.com/?q=simpsons+characters&format=json")!
var request = URLRequest(url: url,
cachePolicy: .returnCacheDataElseLoad,
timeoutInterval: 3.0)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request)
{ (data, response, error) in
if let dat = data {
// parse the data
let decoder = JSONDecoder()
do {
//let jsonResponse = try JSONSerialization.jsonObject(with: dat, options: [])
//print(jsonResponse)
let simpsons = try decoder.decode(Simpsons.self, from: dat)
//self.simpsonsCollection = simpsons.relatedTopics
//self.downloadPicture(for: simpsons, completion: completion)
completion(simpsons)
//let jsonDict = try JSONSerialization.jsonObject(with: simpsons, options: .mutableLeaves) as! [[String:Any]]
//print(self.simpsonsCollection)
}
catch {
// error, something
print(error)
}
}
}
task.resume()
}
func downloadPicture(for simp: Simpsons.RelatedTopics,
completion: @escaping (Simpsons.ImageStruct)->()) {
let urlString = simp.url.url
guard let url = URL(string: urlString) else {
// error here
return
}
let dataTaskComp: (Data?, URLResponse?, Error?)->() =
{ (data, _, _) in
let image = Simpsons.ImageStruct.init(image: data)
completion(image)
print("34")
// self.inProgressCalls.remove(urlString)
}
let dataTask = URLSession.shared.dataTask(with: url, completionHandler: dataTaskComp)
dataTask.resume()
}
}
| true
|
1f1d139b661903df42e0a06f5af68e91741aa0a5
|
Swift
|
wwwshe/Samples
|
/PinchSnapShotSample/PinchSnapShotSample/ZoomViewController.swift
|
UTF-8
| 2,076
| 2.96875
| 3
|
[] |
no_license
|
//
// ZoomViewController.swift
// PinchSnapShotSample
//
// Created by jungwook on 2019/11/19.
// Copyright © 2019 jungwook. All rights reserved.
//
import UIKit
class ZoomViewController: ViewControllerHelper {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var snapShotImageView: UIImageView!
var image : UIImage!
override func viewDidLoad() {
super.viewDidLoad()
snapShotImageView.image = image
scrollViewSetting()
}
func scrollViewSetting(){
self.scrollView.alwaysBounceVertical = false
self.scrollView.alwaysBounceHorizontal = false
self.scrollView.minimumZoomScale = 1.0
self.scrollView.maximumZoomScale = 5.0
self.scrollView.delegate = self
print(scrollView.contentSize)
}
}
extension ZoomViewController : UIScrollViewDelegate{
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.snapShotImageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
if scrollView.zoomScale > 1 {
if let image = snapShotImageView.image {
let ratioW = snapShotImageView.frame.width / image.size.width
let ratioH = snapShotImageView.frame.height / image.size.height
let ratio = ratioW < ratioH ? ratioW:ratioH
let newWidth = image.size.width*ratio
let newHeight = image.size.height*ratio
let left = 0.5 * (newWidth * scrollView.zoomScale > snapShotImageView.frame.width ? (newWidth - snapShotImageView.frame.width) : (scrollView.frame.width - scrollView.contentSize.width))
let top = 0.5 * (newHeight * scrollView.zoomScale > snapShotImageView.frame.height ? (newHeight - snapShotImageView.frame.height) : (scrollView.frame.height - scrollView.contentSize.height))
scrollView.contentInset = UIEdgeInsets(top: top, left: left, bottom: top, right: left)
}
} else {
scrollView.contentInset = .zero
}
}
}
| true
|
4f4da5b34461d0d0537404e079d9360220190679
|
Swift
|
svenbacia/RealmAccessPropertyCrash
|
/RealmCrash/ViewController.swift
|
UTF-8
| 748
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// RealmCrash
//
// Created by Sven Bacia on 30/01/2017.
// Copyright © 2017 Sven Bacia. All rights reserved.
//
import UIKit
import RealmSwift
class ViewController: UIViewController {
@IBAction func addObject() {
do {
let realm = try Realm()
try? realm.write {
realm.add(Show())
}
print("Added show")
} catch {
print("Could not create realm. \(error)")
}
}
@IBAction func crash() {
do {
let realm = try Realm()
let shows = realm.objects(Show.self)
print("Access realm property on (\(shows.count) shows)")
for show in shows {
_ = show.id
}
} catch {
print("Could not create realm. \(error)")
}
}
}
| true
|
325115d554e4002008f924ecf695ec38ff582d6f
|
Swift
|
kaweerutk/CommonKeyboard
|
/Example/CommonKeyboardExample/ChatViewController.swift
|
UTF-8
| 1,496
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// ChatViewController.swift
// KeyboardExample
//
// Created by Kaweerut Kanthawong on 8/9/2019.
// Copyright © 2019 Kaweerut Kanthawong. All rights reserved.
//
import UIKit
import CommonKeyboard
class ChatViewController: UIViewController {
@IBOutlet var tableView: UITableView!
@IBOutlet var textField: UITextField!
@IBOutlet var bottomConstraint: NSLayoutConstraint!
lazy var keyboardObserver = CommonKeyboardObserver()
override func viewDidLoad() {
super.viewDidLoad()
// drag down to dismiss keyboard
tableView.keyboardDismissMode = .interactive
keyboardObserver.subscribe(events: [.willChangeFrame, .dragDown]) { [weak self] (info) in
guard let self = self else { return }
let bottom = info.isShowing
? (-info.visibleHeight) + self.view.safeAreaInsets.bottom
: 0
UIView.animate(info, animations: { [weak self] in
self?.bottomConstraint.constant = bottom
self?.view.layoutIfNeeded()
})
}
}
}
extension ChatViewController: CommonKeyboardContainerProtocol {
// Return specific scrollViewContainer
// as UIScrollView or an inherited class (e.g., UITableView or UICollectionView)
//
// *** This doesn't work with UITableViewController because they have a built-in handler ***
//
var scrollViewContainer: UIScrollView {
return tableView
}
}
extension UIView {
var backwardSafeAreaInsets: UIEdgeInsets {
if #available(iOS 11, *) {
return safeAreaInsets
}
return .zero
}
}
| true
|
2828c1a34d739ffa1f6d5e258da4b315f55133a6
|
Swift
|
gsegovia2018/seniorDesignFinal
|
/DriveAndShare/SeniorDesign/ViewController/SearchViewController.swift
|
UTF-8
| 4,343
| 2.671875
| 3
|
[] |
no_license
|
//
// SearchViewController.swift
// SeniorDesign
//
// Created by Guillermo Segovia Marcos on 11/24/19.
// Copyright © 2019 Guillermo Segovia. All rights reserved.
//
import UIKit
import Foundation
import Firebase
class SearchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
private var trips = [Trip]()
private var tripsCollectionRef : CollectionReference!
override func viewDidLoad() {
super.viewDidLoad()
//tableView.register(UITableViewCell, forCellReuseIdentifier: "TripCell")
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 80
tableView.rowHeight = 150//UITableView.automaticDimension
//setUpElements()
assignBackground()
tripsCollectionRef = Firestore.firestore().collection("trips")
}
func assignBackground(){
let background = UIImage(named: "homeBackground.jpg")
var imageView : UIImageView!
imageView = UIImageView(frame: view.bounds)
imageView.contentMode = UIView.ContentMode.right
imageView.clipsToBounds = true
imageView.image = background
imageView.center = view.center
view.addSubview(imageView)
self.view.sendSubviewToBack(imageView)
}
override func viewWillAppear(_ animated: Bool) {
tripsCollectionRef.getDocuments { (snapshot, error) in
if let err = error {
debugPrint ("Error fetching trips: \(err)")
}
else {
guard let snap = snapshot else { return }
for document in snap.documents {
let data = document.data()
let driverName = data["driverName"] as? String ?? ""
let fromWhere = data["fromWhere"] as? String ?? ""
let toWhere = data["toWhere"] as? String ?? ""
let day = data["day"] as? String ?? ""
let price = data["price"] as? Int ?? 10
let time = data["time"] as? String ?? ""
let uidDriver = data["driverUid"] as? String ?? ""//document.documentID
let newTrip = Trip(uidDriver: uidDriver, fromWhere: fromWhere, toWhere: toWhere, price: price, driverName: driverName, day: day, time: time)
if (!self.trips.contains(newTrip)){
self.trips.append(newTrip)
}
//NEED TO DO SOMETHING SO IT JUST HAS ONE PER UID DRIVER
}
}
self.tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return trips.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "TripCell", for: indexPath) as? TripCell{
cell.configureCell(trip: trips[indexPath.row])
return cell
} else {
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle:nil)
let vc = storyboard.instantiateViewController(withIdentifier: "JoinViewController") as? JoinViewController
vc?.nameLabel = trips[indexPath.row].driverName
vc?.uidDriver = trips[indexPath.row].uidDriver
vc?.fromLabel = trips[indexPath.row].fromWhere
vc?.toLabel = trips[indexPath.row].toWhere
vc?.dayLabel = trips[indexPath.row].day
vc?.timeLabel = trips[indexPath.row].time
vc?.priceLabel = trips[indexPath.row].price
self.navigationController?.pushViewController(vc!, animated: true)
}
// //IF YOU WANT TO ADD SWITCHES TO THE APP
// let mySwitch = UISwitch()
// mySwitch.addTarget(self, action: #selector(didChangeSwitch(_ :)), for: .valueChanged)
// cell.accessoryView = mySwitch
//
// return cell
// }
// @objc func didChangeSwitch(_ sender: UISwitch) {
// if sender.isOn {
// print("Is on")
// }
// else{
// print("Is off")
// }
// }
}
| true
|
91983ce451768f873481327f2e3c94c56c09e7ff
|
Swift
|
raminpapo/walk-to-circle-ios
|
/walk to circle/iiOutputView.swift
|
UTF-8
| 617
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// iiOutputView.swift
//
// Show debug messages in a label of the current view controller.
// Used by iiTickTock to measure performace.
//
// Created by Evgenii Neumerzhitckii on 11/10/2014.
// Copyright (c) 2014 Evgenii Neumerzhitckii. All rights reserved.
//
import UIKit
class iiOutputView {
class func show(text: String) {
if let viewConctroller = UIApplication.sharedApplication().delegate?.window??.rootViewController as? MapViewController {
viewConctroller.outputLabel.text = text
viewConctroller.outputLabel.hidden = false
}
}
}
protocol iiOutputViewController {
weak var outputLabel: UILabel! { get }
}
| true
|
1f9f62b46e92968356074fadf526562edf19164a
|
Swift
|
128keaton/macOS-Utilities
|
/macOS Utilities/Helpers/Repository/Models/RepositoryItem.swift
|
UTF-8
| 555
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// RepositoryItem.swift
// macOS Utilities
//
// Created by Keaton Burleson on 4/4/19.
// Copyright © 2019 Keaton Burleson. All rights reserved.
//
import Foundation
import AppKit
import CocoaLumberjack
class RepositoryItem: NSObject {
private(set) var id: String = ""
private(set) var searchableEntityName: String = ""
private(set) var sortNumber: NSNumber? = nil
private(set) var sortString: String? = nil
func addToRepo() { }
static func == (lhs: RepositoryItem, rhs: RepositoryItem) -> Bool {
return lhs.id == rhs.id
}
}
| true
|
3b9feeea398a0740c58e249fb4875a840e91044c
|
Swift
|
bolivarbryan/RappStore
|
/RappStore/Model/App.swift
|
UTF-8
| 2,962
| 2.78125
| 3
|
[] |
no_license
|
//
// App.swift
// RappStore
//
// Created by Bryan A Bolivar M on 10/24/16.
// Copyright © 2016 Bolivar. All rights reserved.
//
import UIKit
import CoreData
class App: NSObject {
var category: Category!
var image: String!
var name: String!
var price: String!
var artist: String!
var summary: String!
var title: String!
var link: NSURL!
override init () {
super.init()
}
convenience init(_ dictionary: Dictionary<String, AnyObject>) {
self.init()
//getting the latest image is the biggest one of the current array
image = ((dictionary["im:image"] as! NSArray).object(at: (dictionary["im:image"] as! NSArray).count - 1) as! NSDictionary).object(forKey: "label") as! String
title = (dictionary["title"] as! NSDictionary).object(forKey: "label") as! String
link = NSURL(string: ((dictionary["link"] as! NSDictionary).object(forKey: "attributes") as! NSDictionary).object(forKey: "href") as! String)
summary = (dictionary["summary"] as! NSDictionary).object(forKey: "label") as! String
name = (dictionary["im:name"] as! NSDictionary).object(forKey: "label") as! String
artist = (dictionary["im:artist"] as! NSDictionary).object(forKey: "label") as! String
//getting price of the app
let currency = ((dictionary["im:price"] as! NSDictionary).object(forKey: "attributes") as! NSDictionary).object(forKey: "currency") as! String
let amount = ((dictionary["im:price"] as! NSDictionary).object(forKey: "attributes") as! NSDictionary).object(forKey: "amount") as! String
let appPrice = NumberFormatter().number(from: amount)!.decimalValue
if appPrice == 0 {
price = "Free"
}else{
price = String(describing: appPrice) + " " + currency
}
category = Category(dictionary["category"] as! Dictionary<String, AnyObject>)
storeApp()
}
func storeApp() {
let context = ApiRequests.getContext()
//retrieve the entity that we just created
let entity = NSEntityDescription.entity(forEntityName: "Application", in: context)
let app = NSManagedObject(entity: entity!, insertInto: context)
//set the entity values
app.setValue(image, forKey: "image")
app.setValue(title, forKey: "title")
app.setValue(link.absoluteString, forKey: "link")
app.setValue(summary, forKey: "summary")
app.setValue(name, forKey: "name")
app.setValue(artist, forKey: "artist")
app.setValue(price, forKey: "price")
app.setValue(category.label, forKey: "category")
//save the object
do {
try context.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
}
| true
|
27f13d0d3e94edbe283579d877c5c1d18ab71731
|
Swift
|
siddharth-daga/sid-test
|
/SidTest/SidTest/Helper/Extentions.swift
|
UTF-8
| 5,584
| 2.890625
| 3
|
[] |
no_license
|
//
// Extentions.swift
// SidTest
//
// Created by Siddharth Daga on 20/07/20.
// Copyright © 2020 Siddharth Daga. All rights reserved.
//
import UIKit
extension Collection {
/// Returns the element at the specified index if it is within bounds, otherwise nil.
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
extension UITableView {
func registerNibs(identifiers: [CellIdentifiers]) {
for identifier in identifiers {
self.register(UINib(nibName: identifier.rawValue, bundle: nil), forCellReuseIdentifier: identifier.rawValue)
}
}
}
extension UIImageView {
func loadImage(urlString: String?, placeholderImage: UIImage? = nil) {
let imageUrl = urlString?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
self.sd_setImage(with: URL(string: imageUrl ?? ""), placeholderImage: nil, options: [.scaleDownLargeImages], completed: nil)
self.sd_imageTransition = .fade
}
}
extension UIView {
func addCornerRadius(radius: CGFloat) {
layer.cornerRadius = radius
layer.masksToBounds = true
}
func addBorder(color: UIColor? = UIColor.lightGray.withAlphaComponent(0.5)) {
layer.borderWidth = 1.0
layer.borderColor = color?.cgColor
}
}
extension Int64 {
func formatUsingAbbrevation() -> String? {
let numFormatter = NumberFormatter()
typealias Abbrevation = (threshold:Double, divisor:Double, suffix:String)
let abbreviations:[Abbrevation] = [(0, 1, ""),
(1000.0, 1000.0, "K"),
(100_000.0, 1_000_000.0, "M"),
(100_000_000.0, 1_000_000_000.0, "B")]
let startValue = Double (abs(self))
let abbreviation:Abbrevation = {
var prevAbbreviation = abbreviations[0]
for tmpAbbreviation in abbreviations {
if (startValue < tmpAbbreviation.threshold) {
break
}
prevAbbreviation = tmpAbbreviation
}
return prevAbbreviation
} ()
let value = Double(self) / abbreviation.divisor
numFormatter.positiveSuffix = abbreviation.suffix
numFormatter.negativeSuffix = abbreviation.suffix
numFormatter.allowsFloats = true
numFormatter.minimumIntegerDigits = 1
numFormatter.minimumFractionDigits = 0
numFormatter.maximumFractionDigits = 1
return numFormatter.string(from: NSNumber(value: value))
}
}
extension String {
func toDate(dateFormat: DateFormats) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat.rawValue
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.date(from: self)
}
}
extension Date {
func toString(dateFormat: DateFormats) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat.rawValue
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.string(from: self)
}
func timeAgoSince() -> String {
let calendar = Calendar.current
let now = Date()
let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfYear, .month, .year]
let components = (calendar as NSCalendar).components(unitFlags, from: self, to: now, options: [])
if let year = components.year, year >= 2 {
return "\(year) years ago"
}
if let year = components.year, year >= 1 {
return "Last year"
}
if let month = components.month, month >= 2 {
return "\(month) months ago"
}
if let month = components.month, month >= 1 {
return "Last month"
}
if let week = components.weekOfYear, week >= 2 {
return "\(week) weeks ago"
}
if let week = components.weekOfYear, week >= 1 {
return "Last week"
}
if let day = components.day, day >= 2 {
return "\(day) days"
}
if let day = components.day, day >= 1 {
return "Yesterday"
}
if let hour = components.hour, hour >= 1 {
return "\(hour) hr"
}
if let minute = components.minute, minute >= 1 {
return "\(minute) min"
}
return "a moments ago"
}
}
extension NSMutableAttributedString {
convenience init(string: String, type: FontTypeEnum, size: CGFloat, textColor: UIColor?) {
let attrs: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.font: UIFont.setFont(type: type, size: size) ?? UIFont(),
NSAttributedString.Key.foregroundColor: textColor ?? UIColor.black
]
self.init(string: string, attributes: attrs)
}
}
extension UIFont {
static func setFont(type: FontTypeEnum, size: CGFloat) -> UIFont? {
switch type {
case .regular: return UIFont(name: "HelveticaNeue", size: size)
case .bold: return UIFont(name: "HelveticaNeue-Bold", size: size)
}
}
}
extension CodingUserInfoKey {
static let context = CodingUserInfoKey(rawValue: "context")
}
| true
|
5f3e218a05b8f2ee4a003bd49f9adf23d101b3c6
|
Swift
|
carabina/RxSwiftTipDemo
|
/RxSwiftTipDemo/Demo/RxDelegateDemo.swift
|
UTF-8
| 3,088
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// RxDelegateDemo.swift
// RxSwiftTipDemo
//
// Created by ENUUI on 2017/8/1.
// Copyright © 2017年 FUHUI. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
extension Reactive where Base: Demo {
// 实现这个,创建的类(本文是Demo)类的对象就可以点出rx了
var delegate: DelegateProxy {
return RxDelegateDemoDelegateProxy.proxyForObject(base)
}
// 实现这个,创建的类(本文是Demo)类的对象就可以点出rx了
var didSetName: ControlEvent<String> {
/**
DelegateProxy的对象方法 methodInvoked 。
点到这个方法里,有一大坨的注释解释这个方法。
大概的意思是说methodInvoked方法只能监听返回值是Void的代理方法。
有返回值的代理方法要用PublishSubject这个监听,还给了个例子,有兴趣可以点进去看一下。
*/
let source = delegate.methodInvoked(#selector(DemoDelegate.demo(d:didSetName:))).map({ (a:[Any]) -> String in
// map函数可以接收到代理方法的参数。可以是单个参数,也可以是多个参数。根据需要取值就可以了,根据参数在代理方法中的位置,下标从0开始。本文实现中,只需要第二个参数,数以取1.
let i = try castOrThrow(String.self, a[1])
return i
})
// 创建event返回
return ControlEvent(events: source)
}
}
class RxDelegateDemoDelegateProxy: RxCocoa.DelegateProxy, DelegateProxyType, DemoDelegate {
override public class func createProxyForObject(_ object: AnyObject) -> AnyObject {
let p: Demo = castOrFatalError(object)
return p.createRxDelegateProxy()
}
public class func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) {
let p: Demo = castOrFatalError(object)
p.delegate = castOptionalOrFatalError(delegate)
}
public class func currentDelegateFor(_ object: AnyObject) -> AnyObject? {
let p: Demo = castOrFatalError(object)
return p.delegate
}
}
extension Demo {
public func createRxDelegateProxy() -> RxDelegateDemoDelegateProxy {
return RxDelegateDemoDelegateProxy(parentObject: self)
}
}
// MARK: - 以下四个函数都是rxSwift的错误处理方法, 没有公开, 拷贝了下.
func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
func castOptionalOrFatalError<T>(_ value: Any?) -> T? {
if value == nil {
return nil
}
let v: T = castOrFatalError(value)
return v
}
func castOrFatalError<T>(_ value: Any!) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
rxFatalError("Failure converting from &&\(value)&& to \(T.self)")
}
return result
}
func rxFatalError(_ lastMessage: String) -> Never {
fatalError(lastMessage)
}
| true
|
533382a1cac23734d1d44ed02a7f105a453efc7b
|
Swift
|
ameethakkar/CarDealership
|
/CoxAutomotive/CoxAutomotiveTests/DataHelper.swift
|
UTF-8
| 1,243
| 2.546875
| 3
|
[] |
no_license
|
//
// DataHelper.swift
// CoxAutomotiveTests
//
// Created by Thakkar, Amee on 4/18/19.
// Copyright © 2019 Thakkar, Amee. All rights reserved.
//
import Foundation
import XCTest
class DataHelper {
func AssertThrowsKeyNotFound<T: Decodable>(_ expectedKey: String, decoding: T.Type, from data: Data, file: StaticString = #file, line: UInt = #line) {
XCTAssertThrowsError(try JSONDecoder().decode(decoding, from: data), file: file, line: line) { error in
if case .keyNotFound(let key, _)? = error as? DecodingError {
XCTAssertEqual(expectedKey, key.stringValue, "Expected missing key '\(key.stringValue)' to equal '\(expectedKey)'.", file: file, line: line)
} else {
XCTFail("Expected '.keyNotFound(\(expectedKey))' but got \(error)", file: file, line: line)
}
}
}
}
extension Data {
func json(deletingKeyPaths keyPaths: String...) throws -> Data {
let decoded = try JSONSerialization.jsonObject(with: self, options: .mutableContainers) as AnyObject
for keyPath in keyPaths {
decoded.setValue(nil, forKeyPath: keyPath)
}
return try JSONSerialization.data(withJSONObject: decoded)
}
}
| true
|
2de94bfdfdf4add52e1042af34390ffab8a97f6f
|
Swift
|
preachermys/NetworkingWorkshop
|
/NetworkingWorkshop/Duel/DuelsService.swift
|
UTF-8
| 4,430
| 2.5625
| 3
|
[] |
no_license
|
//
// DuelsService.swift
// NetworkingWorkshop
//
// Created by Admin on 31.03.2021.
//
import Foundation
import CoreData
import UIKit
struct AnsweredQuestion {
struct Answer {
let id: String
let timestamp: Int
}
let id: String
let answer: Answer
}
class DuelsService {
static let shared = DuelsService()
var duels = [DuelEntity]()
var finishedDuelsIds: [String] = []
var duelStartedIds: [String?] = []
var deletedDuels: [DuelEntity] = []
private let duelsManager = DuelsManager()
let privateMOC = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
var isRequestStarted = false
var fetchedResultsController: NSFetchedResultsController<DuelEntity>
private init() {
privateMOC.persistentStoreCoordinator = CoreDataStack.shared.createPersistentStoreCoordinator()
privateMOC.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
let fetchRequest = NSFetchRequest<DuelEntity>(entityName: "DuelEntity")
let sort = NSSortDescriptor(key: "publishedAt", ascending: false)
fetchRequest.sortDescriptors = [sort]
fetchedResultsController = NSFetchedResultsController<DuelEntity>(fetchRequest: fetchRequest,
managedObjectContext: privateMOC,
sectionNameKeyPath: nil, cacheName: nil)
}
func getDuelForId(duelId: String) -> DuelEntity? {
guard let duel = duels.first(where: { $0.id == duelId }) else { return nil }
return duel
}
func getDuelsByIds(ids: [String], completionHandler: @escaping ([DuelEntity]) -> Void) {
if !isRequestStarted {
isRequestStarted = true
duelsManager.getDuels(by: 0) { [weak self] duels in
self?.isRequestStarted = false
completionHandler(duels)
}
}
}
func getDuelsBy(ids: [String], completionHandler: @escaping ([DuelEntity]) -> Void) {
if !isRequestStarted {
isRequestStarted = true
duelsManager.getDuels(by: ids) { [weak self] duels in
self?.isRequestStarted = false
completionHandler(duels)
}
}
}
func getDuels(page: Int, complation: @escaping ([DuelEntity]) -> Void) {
if !isRequestStarted {
isRequestStarted = true
duelsManager.getDuels(by: page) { (duels) in
self.isRequestStarted = false
complation(duels)
}
}
}
func postDuelGameFinish(gameId: String,
gameEnd: Int,
gameStart: Int,
answers: [AnsweredQuestion],
completion: @escaping () -> ()) {
var dict = [String: Any]()
dict["game_end"] = gameEnd
dict["game_start"] = gameStart
dict["game_id"] = gameId
var gameAnswers = [[String: Any]]()
for answer in answers {
var dict = [String: Any]()
dict["id"] = answer.id
var answerDict = [String: Any]()
answerDict["id"] = answer.answer.id
answerDict["timestamp"] = answer.answer.timestamp
dict["answer"] = answerDict
gameAnswers.append(dict)
}
dict["questions"] = gameAnswers
finishedDuelsIds.append(gameId)
}
func loadDuelsFromDb(duelIds: [String]? = nil, complated: @escaping ([DuelEntity]) -> Void) {
var fetchedDuels: [DuelEntity] = []
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "DuelEntity")
guard let results = try? privateMOC.fetch(fetchRequest),
let duelsList = results as? [DuelEntity] else { return }
if duelIds != nil {
fetchedDuels = duelsList.filter({ duelIds?.contains($0.id ?? "") ?? false })
} else {
fetchedDuels = duelsList
}
duels = fetchedDuels
complated(duels)
}
func saveCards() {
self.privateMOC.perform {
do {
try self.privateMOC.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}
}
}
| true
|
479237c93ea5d8df4a04f055b622eaba2cfe3a67
|
Swift
|
carlotaprat/Marvel
|
/Marvel/View Models/Collection View Cell/CharacterListCellViewModel.swift
|
UTF-8
| 400
| 2.890625
| 3
|
[] |
no_license
|
import Foundation
class CharacterListCellViewModel {
private var character: Character?
func setCharacter(character: Character) {
self.character = character
}
func getCharacterName() -> String {
return self.character?.name ?? ""
}
func getPicturePortrait() -> String {
return character?.picture?.urlPortrait ?? ""
}
}
| true
|
f95fd652fb08bfe14dcd87ca6a072a1925abb556
|
Swift
|
NeoTeo/XcodeSwapTwo
|
/SwapTwo/SourceEditorCommand.swift
|
UTF-8
| 1,848
| 2.921875
| 3
|
[] |
no_license
|
//
// SourceEditorCommand.swift
// SwapTwo
//
// Created by Teo Sartori on 14/06/2018.
// Copyright © 2018 teos. All rights reserved.
//
import Foundation
import XcodeKit
class SourceEditorCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void {
// Implement your command here, invoking the completion handler when done. Pass it nil on success, and an NSError on failure.
_ = swapSelection(0, invocation)
completionHandler(nil)
}
func swapSelection(_ index: Int, _ invocation: XCSourceEditorCommandInvocation) -> String? {
guard index < invocation.buffer.selections.count else { return nil }
let selection = invocation.buffer.selections[index] as! XCSourceTextRange
let lines = invocation.buffer.lines as! [String]
// Swap two requires the selection to be on the same line
guard selection.start.line == selection.end.line else { return nil }
var line = lines[selection.start.line]
let original = line
let start = line.index(line.startIndex, offsetBy: selection.start.column)
let end = line.index(line.startIndex, offsetBy: selection.end.column)
let selectionRange = start ..< end
line = String(line[selectionRange])
let components = line.split(separator: ",")
// We only swap two comma separated strings
guard components.count == 2 else { return nil }
let swapString = String(components[1] + ", " + components[0]).trimmingCharacters(in: .whitespacesAndNewlines)
invocation.buffer.lines[selection.start.line] = original.replacingCharacters(in: selectionRange, with: swapString)
return swapString
}
}
| true
|
149937c927b6a13afcf5b79154ff3c5a50ef7758
|
Swift
|
richardhsieh18/swift
|
/week3/break_point/break_point/main.swift
|
UTF-8
| 119
| 2.734375
| 3
|
[] |
no_license
|
var x:String
x = "abc"
print(x)
x = "888888888"
print(x)
x = "helllllooooo"
print(x)
x = "變變變"
print(x)
| true
|
cd68b88828ab6ffd0a65bb07944f2e874585e28a
|
Swift
|
wjc2118/SwiftyDB
|
/SwiftyDB/SwiftyDB/ResultSet.swift
|
UTF-8
| 3,784
| 3.078125
| 3
|
[] |
no_license
|
//
// ResultSet.swift
// SwiftyDB
//
// Created by y7 on 2017/9/5.
// Copyright © 2017年 y7. All rights reserved.
//
import Foundation
struct ResultSet {
private let _stmt: Statement
init(stmt: Statement) {
_stmt = stmt
}
}
extension ResultSet {
func next() -> Bool {
return _stmt.step() == SQLITE_ROW
}
}
// MARK: - value for column index
extension ResultSet {
func intForColumn(at index: Int32) -> Int {
return _stmt.columnValue(idx: index, type: .integer) as? Int ?? 0
}
func uintForColumn(at index: Int32) -> UInt {
return UInt(intForColumn(at: index))
}
func boolForColumn(at index: Int32) -> Bool {
return intForColumn(at: index) != 0
}
func doubleForColumn(at index: Int32) -> Double {
return _stmt.columnValue(idx: index, type: .real) as? Double ?? 0.0
}
func stringForColumn(at index: Int32) -> String {
return _stmt.columnValue(idx: index, type: .text) as? String ?? ""
}
func dataForColumn(at index: Int32) -> Data {
return _stmt.columnValue(idx: index, type: .blob) as? Data ?? Data()
}
func dateForColumn(at index: Int32) -> Date {
return Date(timeIntervalSince1970: doubleForColumn(at: index))
}
subscript(idx: Int32) -> Int {
return intForColumn(at: idx)
}
subscript(idx: Int32) -> UInt {
return uintForColumn(at: idx)
}
subscript(idx: Int32) -> Bool {
return boolForColumn(at: idx)
}
subscript(idx: Int32) -> Double {
return doubleForColumn(at: idx)
}
subscript(idx: Int32) -> String {
return stringForColumn(at: idx)
}
subscript(idx: Int32) -> Data {
return dataForColumn(at: idx)
}
subscript(idx: Int32) -> Date {
return dateForColumn(at: idx)
}
}
// MARK: - value for column name
extension ResultSet {
func intForColumn(name: String) -> Int {
return intForColumn(at: _stmt.columnIndex(for: name))
}
func uintForColumn(name: String) -> UInt {
return uintForColumn(at: _stmt.columnIndex(for: name))
}
func boolForColumn(name: String) -> Bool {
return boolForColumn(at: _stmt.columnIndex(for: name))
}
func doubleForColumn(name: String) -> Double {
return doubleForColumn(at: _stmt.columnIndex(for: name))
}
func stringForColumn(name: String) -> String {
return stringForColumn(at: _stmt.columnIndex(for: name))
}
func dataForColumn(name: String) -> Data {
return dataForColumn(at: _stmt.columnIndex(for: name))
}
func dateForColumn(name: String) -> Date {
return dateForColumn(at: _stmt.columnIndex(for: name))
}
subscript(name: String) -> Int {
return intForColumn(name: name)
}
subscript(name: String) -> UInt {
return uintForColumn(name: name)
}
subscript(name: String) -> Bool {
return boolForColumn(name: name)
}
subscript(name: String) -> Double {
return doubleForColumn(name: name)
}
subscript(name: String) -> String {
return stringForColumn(name: name)
}
subscript(name: String) -> Data {
return dataForColumn(name: name)
}
subscript(name: String) -> Date {
return dateForColumn(name: name)
}
}
extension ResultSet: Sequence {
func makeIterator() -> ResultSet {
return self
}
}
extension ResultSet: IteratorProtocol {
func next() -> ResultSet? {
if next() {
return self
} else {
return nil
}
}
}
| true
|
d0ede1be5231d763a81fd89a4df7f7b190bb465d
|
Swift
|
squadss/squad-ios-New
|
/Squads/Tool/BrickInputFieldStyle.swift
|
UTF-8
| 1,817
| 2.734375
| 3
|
[] |
no_license
|
//
// BrickInputFieldStyle.swift
// Squads
//
// Created by 武飞跃 on 2020/7/9.
// Copyright © 2020 Squads. All rights reserved.
// 方块形状的文本框样式
import UIKit
protocol BrickInputFieldStyle: class {
func configInputField(_ textField: UITextField, placeholder: String)
}
extension BrickInputFieldStyle where Self: UIViewController {
func configInputField(_ textField: UITextField, placeholder: String) {
textField.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.3)
textField.borderStyle = .none
textField.font = UIFont.systemFont(ofSize: 16)
textField.clearButtonMode = .whileEditing
textField.textColor = .white
textField.tintColor = .white
textField.leftViewMode = .always
textField.inputAssistantItem.leadingBarButtonGroups = []
textField.inputAssistantItem.trailingBarButtonGroups = []
textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 18, height: 40))
if #available(iOS 13.0, *) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .left
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [
.foregroundColor: UIColor(white: 1, alpha: 0.7),
.font: UIFont.systemFont(ofSize: 16),
.paragraphStyle: paragraphStyle
])
} else {
textField.placeholder = placeholder
textField.setValue(UIColor(white: 1, alpha: 0.7), forKeyPath: "_placeholderLabel.textColor")
textField.setValue(UIFont.systemFont(ofSize: 16), forKeyPath: "_placeholderLabel.font")
textField.setValue(NSTextAlignment.left.rawValue, forKeyPath: "_placeholderLabel.textAlignment")
}
}
}
| true
|
6614ecf7e8e27758ba07e354f95aae0b88718180
|
Swift
|
ThePowerOfSwift/QR-Scores-iOS
|
/LoadingViewController.swift
|
UTF-8
| 1,896
| 2.78125
| 3
|
[] |
no_license
|
//
// LoadingViewController.swift
// QR Scores
//
// Created by Erick Sanchez on 1/2/19.
// Copyright © 2018 LinnierGames. All rights reserved.
//
import UIKit
class LoadingViewController: UIViewController {
// MARK: - VARS
@IBOutlet private var loadingIndicator: UIActivityIndicatorView!
// MARK: - RETURN VALUES
// MARK: - METHODS
func present() {
let window = UIWindow.applicationAlertWindow
view.alpha = 0
//if the loading is shown for less than 0.25 seconds, the user will not see the loading indicator
Timer.scheduledTimer(withTimeInterval: 0.25, repeats: false) { [weak self] _ in
window.rootViewController = self
guard let unwrappedSelf = self else { return }
UIView.animate(withDuration: 0.15, animations: {
unwrappedSelf.view.alpha = 1
})
}
window.makeKey()
window.isHidden = false
}
func dismiss(completion: @escaping () -> Void) {
let window = UIWindow.applicationAlertWindow
window.isHidden = true
guard let appWindow = UIApplication.shared.delegate!.window! else {
return completion()
}
UIWindow.applicationAlertWindow.rootViewController = nil
appWindow.makeKey()
completion()
}
// MARK: - IBACTIONS
// MARK: - LIFE CYCLE
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let indicator = self.loadingIndicator {
indicator.startAnimating()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let indicator = self.loadingIndicator {
indicator.stopAnimating()
}
}
}
| true
|
960e00eff2c9575823470b1c7c8a4c3e50a6b3d6
|
Swift
|
NhatDuy918/FileManagement
|
/FileManagement_TTB/ViewController.swift
|
UTF-8
| 7,795
| 2.78125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// UISearchController
//
// Created by Cntt02 on 5/3/17.
// Copyright © 2017 Cntt02. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIAlertViewDelegate {
var fileManager: FileManager?
var documentDir:NSString?
var filePath:NSString?
override func viewDidLoad() {
super.viewDidLoad()
fileManager=FileManager.default
let dirPaths:NSArray=NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
documentDir=dirPaths[0] as? NSString
print("path : \(String(describing: documentDir))")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnCreateFileClicked(_ sender: Any) {
filePath = documentDir?.appendingPathComponent("file1.txt") as NSString?
fileManager?.createFile(atPath: filePath! as String, contents: nil, attributes: nil)
filePath=documentDir?.appendingPathComponent("file2.txt") as! NSString
fileManager?.createFile(atPath: filePath! as String, contents: nil, attributes: nil)
self.showSuccessAlert(titleAlert: "Success", messageAlert: "File created successfully")
}
func showSuccessAlert(titleAlert:NSString,messageAlert:NSString)
{
let alert:UIAlertController=UIAlertController(title:titleAlert as String, message: messageAlert as String, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default)
{
UIAlertAction in
}
alert.addAction(okAction)
if UIDevice.current.userInterfaceIdiom == .phone
{
self.present(alert, animated: true, completion: nil)
}
}
@IBOutlet weak var btnCreateDirectoryCliecked: UIButton!
@IBAction func btnCreateDirectoryClicked(_ sender: Any) {
do{
try filePath=documentDir?.appendingPathComponent("/folder1") as NSString?
try fileManager?.createDirectory(atPath: filePath! as String, withIntermediateDirectories: false, attributes: nil)
try self.showSuccessAlert(titleAlert: "Success", messageAlert: "Directory created successfully")
}
catch let error as NSError{
print("errorrr \(String(describing: error))")
}
// self.showSuccessAlert(titleAlert: "Success", messageAlert: "Directory created successfully")
// let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
// let documentsDirectory: AnyObject = paths[0] as AnyObject
// let dataPath = documentsDirectory.appendingPathComponent("/folder1")!
//
// do {
// try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
// } catch let error as NSError {
// print(error.localizedDescription);
// }
}
@IBAction func btnWriteFileCliecked(_ sender: Any) {
let content:NSString=NSString(string: "helllo how are you?")
let fileContent:NSData=content.data(using: String.Encoding.utf8.rawValue)! as NSData
fileContent.write(toFile: (documentDir?.appendingPathComponent("file1.txt"))!, atomically: true)
self.showSuccessAlert(titleAlert: "Success", messageAlert: "Content written successfully") }
@IBAction func btnReadFileClicked(_ sender: Any) {
filePath=documentDir?.appendingPathComponent("/file1.txt") as NSString?
var fileContent:NSData?
fileContent=fileManager?.contents(atPath: filePath! as String)! as! NSData
let str:NSString=NSString(data: fileContent! as Data, encoding: String.Encoding.utf8.rawValue)!
self.showSuccessAlert(titleAlert: "Success", messageAlert: "data : \(str)" as NSString)
}
@IBAction func btnMoveFileClicked(_ sender: Any) {
let oldFilePath:String=documentDir!.appendingPathComponent("/folder1/move.txt") as String
let newFilePath:String=documentDir!.appendingPathComponent("temp.txt") as String
do{
try fileManager?.moveItem(atPath: oldFilePath, toPath: newFilePath)
}
catch let err as NSError{
print("errorrr \(String(describing: err))")
}
self.showSuccessAlert(titleAlert: "Success", messageAlert: "File moved successfully")
}
@IBOutlet weak var btnCopyFileClicked: UIButton!
@IBAction func btnCopyFileClicked(sender: AnyObject)
{
filePath = documentDir?.appendingPathComponent("temp.txt") as NSString?
let originalFile=documentDir?.appendingPathComponent("temp.txt")
let copyFile=documentDir?.appendingPathComponent("copy.txt")
do{
try fileManager?.copyItem(atPath: originalFile!, toPath: copyFile!)
}
catch{
}
self.showSuccessAlert(titleAlert: "Success", messageAlert:"File copied successfully")
}
@IBAction func btnFilePermissionsClicked(_ sender: Any) {
filePath = documentDir?.appendingPathComponent("temp.txt") as NSString?
var filePermissions:NSString = ""
if(fileManager?.isWritableFile(atPath: filePath! as String))!
{
filePermissions=filePermissions.appending("file is writable. ") as NSString
}
if(fileManager?.isReadableFile(atPath: (filePath! as String) as String))!
{
filePermissions=filePermissions.appending("file is readable. ") as NSString
}
if(fileManager?.isExecutableFile(atPath: ((filePath! as String) as String) as String))!
{
filePermissions=filePermissions.appending("file is executable.") as NSString
}
self.showSuccessAlert(titleAlert: "Success", messageAlert: "\(filePermissions)" as NSString)
}
@IBAction func btnEqualityClicked(_ sender: Any) {
let filePath1=documentDir?.appendingPathComponent("temp.txt")
let filePath2=documentDir?.appendingPathComponent("copy.txt")
if(fileManager? .contentsEqual(atPath: filePath1!, andPath: filePath2!))!
{
self.showSuccessAlert(titleAlert: "Message", messageAlert: "Files are equal.")
}
else
{
self.showSuccessAlert(titleAlert: "Message", messageAlert: "Files are not equal.")
}
}
@IBAction func btnDirectoryContantsClicked(_ sender: Any) {
//fileManager = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask)
do{
let arrDirContent = try fileManager?.contentsOfDirectory(atPath: documentDir! as String)
self.showSuccessAlert(titleAlert: "Success", messageAlert: "Content of directory \(String(describing: arrDirContent))" as NSString)
}
catch let error as NSError
{
print("Error: \(error.localizedDescription)")
}
}
@IBAction func btnRemoveFileClicked(_ sender: Any) {
filePath = documentDir?.appendingPathComponent("temp.txt") as NSString?
do{
try fileManager?.removeItem(atPath: filePath! as String)
}
catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
self.showSuccessAlert(titleAlert: "Message", messageAlert: "File removed successfully.")
}
}
| true
|
dc36ce6330406ee5c1e0b44ee365c6e1cd5a994b
|
Swift
|
philipshen/PacketHeader
|
/PacketReaderTests/Extensions/UInt64ExtensionTests.swift
|
UTF-8
| 963
| 2.609375
| 3
|
[] |
no_license
|
//
// UInt64ExtensionTests.swift
// PacketReaderTests
//
// Created by Philip Shen on 3/10/18.
// Copyright © 2018 Philip Shen. All rights reserved.
//
@testable import PacketReader
import XCTest
class UInt64ExtensionTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testInitWithUInt8Array() {
// Given
let expectedOutput: UInt64 = 513
let input: [UInt8] = [1, 2, 0, 0, 0, 0, 0, 0]
// When
let actualOutput = UInt64(bytes: input)
// Then
XCTAssertEqual(expectedOutput, actualOutput!, "Initializing with [UInt8] should return the correct value")
}
}
| true
|
eb455a7c0f663d335eda26490c40b250aa7a5383
|
Swift
|
dmaulikr/Connect
|
/RoundedButton.swift
|
UTF-8
| 639
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// RoundedButton.swift
// Connnect
//
// Created by Stella Su on 11/22/16.
// Copyright © 2016 iOS-Connect. All rights reserved.
//
import UIKit
class RoundedButton: UIButton{
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureRoundedCorners()
}
override init(frame: CGRect) {
super.init(frame: frame)
configureRoundedCorners()
}
private func configureRoundedCorners() {
self.backgroundColor = .clear
self.layer.cornerRadius = 10
self.layer.borderWidth = 2
self.layer.borderColor = self.tintColor.cgColor
}
}
| true
|
00e7cb57ebf96ae2c5f6400f6572426dc54265f3
|
Swift
|
DorianZet/100-Days-Of-Swift
|
/39-Project39/Project39/PlayData.swift
|
UTF-8
| 3,645
| 3.84375
| 4
|
[] |
no_license
|
//
// PlayData.swift
// Project39
//
// Created by Mateusz Zacharski on 30/07/2020.
// Copyright © 2020 Mateusz Zacharski. All rights reserved.
//
import Foundation
class PlayData {
var allWords = [String]()
var wordCounts: NSCountedSet! // NSCountedSet is a set data type, which means that items can only be added once. It keeps track of how many times items you tried to add and remove each item, which means it can handle de-duplicating our words while storing how often they are used (so we don't have to use the dicitionary 'wordCounts = [String: Int]()' anymore).
private(set) var filteredWords = [String]() // that marks the setter of 'filteredWords' - the code that handles writing - as private, which means ONLY CODE INSIDE THE 'PlayData' CLASS CAN USE IT. The getter - the code that handles reading - is unaffected.
init() {
if let path = Bundle.main.path(forResource: "plays", ofType: "txt") {
if let plays = try? String(contentsOfFile: path) {
allWords = plays.components(separatedBy: CharacterSet.alphanumerics.inverted) // we split the text in "plays.text" by splitting on anything that ISN'T a letter or number, which can be achieved by inverting the alphanumeric character set.
allWords = allWords.filter { $0 != ""} // filter all empty lines from the 'allWords' array and remove them.
wordCounts = NSCountedSet(array: allWords) // creates a counted set from all the words, which immediately de-duplicates and counts them all.
// allWords = wordCounts.allObjects as! [String] // updates the 'allWords' array to be the words from the counted set, this ensuring they are unique.
let sorted = wordCounts.allObjects.sorted { wordCounts.count(for: $0) > wordCounts.count(for: $1) } // sort the array so that the most frequent words appear at the top of the table. The closure needs to accept two strins ($0 and $1) and needs to return true if the first string coems before the second. We call 'count(for:)' on each of those strings, so this code will return true ("sort before") if the count for $0 is higher than the code for $1.
allWords = sorted as! [String]
}
}
applyUserFilter("swift") // show "swift"" words at the launch of the app.
}
func applyUserFilter (_ input: String) {
if let userNumber = Int(input) { // Int(input) is a failable initializer (it means it can return nil). In this situation, we'll get nil back if Swift was unable to convert the string ('input') we gave it into an integer. This line means "if the user's input is an integer...").
applyFilter { self.wordCounts.count(for: $0) >= userNumber } // creates an array out of words with a count greater or equal to the number the user entered. $0 here means "every word in 'allWords'.
} else { // "if the user's input is NOT an integer..." (then of course it has to be a string):
// we got a string!
applyFilter { $0.range(of: input, options: .caseInsensitive) != nil } // creates an array out of words that contain the user's text as a substring. $0 here means "every word in 'allWords'. We may read it as "give me all words from 'allWords' array that have an 'input' string in their range.
}
}
func applyFilter(_ filter: (String) -> Bool) { // this function accepts a single parameter, which must be a function that takes a string and returns a boolean. This is exactly what 'filter()' wants, so we can just pass that parameter straight on:
filteredWords = allWords.filter(filter)
}
}
| true
|
6937c3f8ea204031f875d47adf4800d9fdb06070
|
Swift
|
protectapp/ios
|
/Protect_Security/Notifications/BadgeManager.swift
|
UTF-8
| 2,572
| 2.796875
| 3
|
[] |
no_license
|
//
// BadgeManager.swift
// Protect_Security
//
// Created by Jatin Garg on 16/01/19.
// Copyright © 2019 Jatin Garg. All rights reserved.
//
import UIKit
enum BadgeType {
case report, chat
}
class BadgeManager: NSObject {
@objc dynamic var reportBadgeCount: Int {
get {
return UserDefaults.standard.value(forKey: "reportBadges") as? Int ?? 0
}set{
UserDefaults.standard.set(newValue, forKey: "reportBadges")
NotificationCenter.default.post(name: reportBadgeChanged, object: newValue)
updateApplicationBadge()
}
} //indicates total number of unseen incident reports
@objc dynamic var chatBadgeCount: Int {
get{
return UserDefaults.standard.value(forKey: "chatBadges") as? Int ?? 0
}set{
UserDefaults.standard.set(newValue, forKey: "chatBadges")
NotificationCenter.default.post(name: chatBadgeChanged, object: newValue)
updateApplicationBadge()
}
} //indicates total number of senders that have >0 unread count for this user
private func updateApplicationBadgeIcon() {
let totalBadges = reportBadgeCount + chatBadgeCount
UIApplication.shared.applicationIconBadgeNumber = totalBadges
}
public static let shared = BadgeManager()
public func incrementBadgeCount(for badgeType: BadgeType) {
switch badgeType {
case .chat:
chatBadgeCount += 1
case .report:
reportBadgeCount += 1
}
}
public func decrementBadgeCount(for badgeType: BadgeType) {
switch badgeType {
case .chat:
chatBadgeCount -= 1
case .report:
reportBadgeCount -= 1
}
}
public func resetBadgeCount(for badgeType: BadgeType) {
switch badgeType {
case .chat:
chatBadgeCount = 0
case .report:
reportBadgeCount = 0
}
}
public func getBadCount(for badgeType: BadgeType) -> Int {
switch badgeType {
case .chat:
return chatBadgeCount
case .report:
return reportBadgeCount
}
}
private func updateApplicationBadge() {
UIApplication.shared.applicationIconBadgeNumber = chatBadgeCount + reportBadgeCount
}
public let chatBadgeChanged = Notification.Name(rawValue: "chatbadgechangednotification")
public let reportBadgeChanged = Notification.Name(rawValue: "reportbadgechangednotification")
}
| true
|
bdb5f75467f834c33f4beff9818a8d47d765e2b5
|
Swift
|
Hollylord/DingGuang
|
/DingGuang/DGAdvert.swift
|
UTF-8
| 4,450
| 2.59375
| 3
|
[] |
no_license
|
//
// DGAdvert.swift
// DingGuang
//
// Created by apple on 16/1/21.
// Copyright © 2016年 dingguangiPhone. All rights reserved.
//
import Foundation
class DGAdvertViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
@IBOutlet weak var advertCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.advertCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "advertCell")
}
//MARK: - 代理
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1;
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 6;
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("advertCell", forIndexPath: indexPath)
cell.bounds = self.view.bounds
let imageView = UIImageView(image: UIImage(named: "advert1"))
imageView.frame = cell.bounds
cell.contentView.addSubview(imageView)
// cell.contentView.backgroundColor = UIColor.redColor()
// print(cell.contentView.subviews)
return cell
}
//MARK: - 隐藏状态栏
override func prefersStatusBarHidden() -> Bool {
return true
}
}
//MARK: - 自定义CollectionView布局
class DGAdvertFlowLayout: UICollectionViewFlowLayout {
var itemX :CGFloat = 0.0
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.minimumLineSpacing = 0;
//这列可以用UISCreen来替代
self.itemSize = CGSizeMake(UIScreen.mainScreen().bounds.width,UIScreen.mainScreen().bounds.height)
self.scrollDirection = UICollectionViewScrollDirection.Horizontal
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
//这个rect不准,要用可视范围
let attributes = super.layoutAttributesForElementsInRect(rect)
// 可视范围
let visibleRect = CGRectMake((self.collectionView?.contentOffset.x)!, (self.collectionView?.contentOffset.y)!, (self.collectionView?.bounds.size.width)!, (self.collectionView?.bounds.size.height)!)
let array = super.layoutAttributesForElementsInRect(visibleRect)
let centerItem = array![0]
itemX = centerItem.frame.origin.x
return attributes
}
override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
//1. 手一松开,CollectionView的offset值
let currentOffset = self.collectionView?.contentOffset
//往右滑
if proposedContentOffset.x < currentOffset?.x || currentOffset?.x < 0{
let finalPoint = CGPointMake(itemX, (currentOffset?.y)!)
return finalPoint
}
else {
let finalPoint = CGPointMake(itemX + (self.collectionView?.bounds.width)!, (currentOffset?.y)!)
return finalPoint
}
}
}
//class DGAdvertView: UIImageView {
// //加required是因为这是指定初始化器,表示子类要继承这个方法
// required init?(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
//// self.image = UIImage(named: "advert1")
//
// }
//
//}
//class DGCartoonView: UIImageView {
// required init?(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
//
// self.image = UIImage(named: "design")
// let scaleTransform = CGAffineTransformMakeScale(3, 3)
// let rotationTransform = CGAffineTransformMakeRotation( CGFloat(M_PI) )
//
// self.transform = CGAffineTransformConcat(scaleTransform ,rotationTransform)
//
// UIView.animateWithDuration(0.8, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
// self.transform = CGAffineTransformIdentity
// }, completion: nil)
// }
//
//
//}
| true
|
645e5d337ea49da394a1047b6e6daef6cef57c27
|
Swift
|
koalahl/SwiftAlgorithm
|
/CoderAlgorithm/Sort/MergeSort.swift
|
UTF-8
| 1,960
| 3.796875
| 4
|
[
"MIT"
] |
permissive
|
//
// MergeSort.swift
// CoderAlgorithm
//
// Created by HanLiu on 2018/3/17.
// Copyright © 2018 HanLiu. All rights reserved.
//
import Foundation
/*
归并排序
时间复杂度 Nlog(N): log(N)表示划分的层级,N表示每一层最多遍历一次n个元素。
算法思想:分治 :从左到右依次遍历两个序列,每次取最小的。这种做法的前提就是需要保证每个序列都是已经排序的。
算法特点:需要额外开辟O(N)的空间。
稳定排序
*/
func mergeSort<T:Comparable>(array:[T]) -> [T]{
guard array.count > 1 else {
return array
}
let mid = array.count/2
let leftArray = mergeSort(array: Array(array[0..<mid]))
let rightArray = mergeSort(array: Array(array[mid..<array.count]))
return merge(larr: leftArray, rarr: rightArray)
}
fileprivate func merge<T:Comparable>(larr:[T],rarr:[T]) -> [T]{
var leftIndex = 0
var rightIndex = 0
var orderedArray = [T]()
while leftIndex < larr.count && rightIndex < rarr.count {
if larr[leftIndex] < rarr[rightIndex] {
orderedArray.append(larr[leftIndex])
leftIndex += 1
}else if larr[leftIndex] > rarr[rightIndex] {
orderedArray.append(rarr[rightIndex])
rightIndex += 1
}else {
orderedArray.append(larr[leftIndex])
leftIndex += 1
orderedArray.append(rarr[rightIndex])
rightIndex += 1
}
}
//经过上面的循环后, left Array 或者 right Array 肯定有一个会完全合并入 orderedArray 中。 所以就不用在进行比较了,直接把剩余的数组放入 orderedArray 中即可。
while leftIndex < larr.count {
orderedArray.append(larr[leftIndex])
leftIndex += 1
}
while rightIndex < rarr.count {
orderedArray.append(rarr[rightIndex])
rightIndex += 1
}
return orderedArray
}
| true
|
11cd280893e7b935da8a9ab3ea3d7a1f76dccddb
|
Swift
|
manelmontilla/AbemApp
|
/Shared/ViewError.swift
|
UTF-8
| 398
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewError.swift
// AbemApp
//
// Created by Manel Montilla on 27/12/20.
//
import Foundation
enum ViewError:Error {
case LogicalError(description: String)
}
extension ViewError: LocalizedError {
public var errorDescription: String? {
switch self {
case .LogicalError(let description):
return NSLocalizedString(description,comment: "")
}
}
}
| true
|
c0bcda0ef5e6fe80163fd30767f14ca7aae8e7af
|
Swift
|
farazhaider88/SwiftuiMVVMStockApp
|
/StockApp/StockApp/ViewModel/StockViewModel.swift
|
UTF-8
| 471
| 2.984375
| 3
|
[] |
no_license
|
//
// StockViewModel.swift
// StockApp
//
// Created by Faraz Haider on 08/01/2021.
//
import Foundation
struct StockViewModel{
let stock : Stocks
var symbol : String{
return self.stock.symbol.uppercased()
}
var description:String{
return self.stock.description
}
var price : String{
return String(format: "%.2f", self.stock.price)
}
var change :String{
return self.stock.change
}
}
| true
|
72e27b5280adecada079a19719d90da735bd09fb
|
Swift
|
luizdefranca/iOS_Quaddro_Course_200hours
|
/swift-100/desafio_carteira_motorista.playground/Contents.swift
|
UTF-8
| 417
| 3.53125
| 4
|
[] |
no_license
|
var idade = 18
var valorNoBolso = 800.00
switch(idade >= 18, valorNoBolso >= 800.00){
case (true, true):
print("Ok, você pode tirar a carteira")
case(false, true):
print("Você precisa esperar \(idade - 18) anos")
case(true, false):
print("Você precisa juntar mais \(valorNoBolso - 800) reais")
default:
print("Você precisa esperar \(idade - 18) anos e juntar mais \(valorNoBolso - 800) reais")
}
| true
|
41d21f025dc654bbd6f63cdee323967ca3ec909d
|
Swift
|
clyksb0731/Summaries_Practices
|
/RxSwift_Sample/RxSwift_Sample/Responses.swift
|
UTF-8
| 349
| 2.609375
| 3
|
[] |
no_license
|
//
// Responses.swift
// RxSwift_Sample
//
// Created by Yongseok Choi on 16/07/2019.
// Copyright © 2019 Yongseok Choi. All rights reserved.
//
import Foundation
struct ReturnedData: Codable {
var id: String
var contentValue: String
enum CodingKeys: String, CodingKey {
case id
case contentValue = "content_value"
}
}
| true
|
085ac33174beb5581e5b87ac63f16c235ccaf0f9
|
Swift
|
jtomanik/pokeparty-ios
|
/PokeParty/Common/Others/DateFormatter.swift
|
UTF-8
| 742
| 2.921875
| 3
|
[] |
no_license
|
//
// DateFormatter.swift
// Switchboard
//
// Created by Sebastian Osiński on 13/05/16.
// Copyright © 2016 nowthisnews. All rights reserved.
//
import Foundation
// TODO: make this conditional taking into account localization
let dateFormat = "MM / dd / YYYY"
let dateAndTimeFormat = "MM / dd / YYYY hh:mm a"
class DateFormatter {
static let sharedFormatter = DateFormatter()
private let dateFormatter: NSDateFormatter
private init() {
dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
}
func stringFromDate(date: NSDate, format: String = dateFormat) -> String {
dateFormatter.dateFormat = format
return dateFormatter.stringFromDate(date)
}
}
| true
|
f66c1e7419ca6485166ebeb9c6a1b7b7caabf33d
|
Swift
|
lauracalinoiu/Stanford_Calculator
|
/Assign1_Calculator/ViewController.swift
|
UTF-8
| 1,917
| 3.09375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Assign1_Calculator
//
// Created by Laura Calinoiu on 15/07/16.
// Copyright © 2016 3smurfs. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet private weak var display: UILabel!
@IBOutlet weak var debugDisplay: UILabel!
private var userIsInMiddleOfEditing = false
@IBAction private func numberPressed(sender: UIButton) {
let item = sender.currentTitle
if userIsInMiddleOfEditing{
let savedOldDisplay = display.text!
display.text = display.text! + item!
if displayValue == nil{
display.text = savedOldDisplay
}
} else{
display.text = item
}
userIsInMiddleOfEditing = true
}
private var displayValue: Double?{
get{
return Double(display.text!)
}
set{
display.text = String(newValue!)
}
}
private var calculatorBrain = CalculatorBrain()
@IBAction private func operationPerformed(sender: UIButton) {
if userIsInMiddleOfEditing{
calculatorBrain.setOperand(displayValue!)
userIsInMiddleOfEditing = false
}
if let mathematicalSymbol = sender.currentTitle{
calculatorBrain.performOperation(mathematicalSymbol)
}
displayValue = calculatorBrain.result
debugDisplay.text = calculatorBrain.description + calculatorBrain.postfix
}
@IBAction func clearDisplaysAndStates(sender: UIButton) {
display.text = "0"
debugDisplay.text = " "
calculatorBrain.clear()
}
@IBAction func arrowMPressed(sender: UIButton) {
if let val = displayValue{
let p = calculatorBrain.program
calculatorBrain.variableValues[calculatorBrain.M] = val
calculatorBrain.program = p
displayValue = calculatorBrain.result
}
}
@IBAction func mPressed(sender: UIButton) {
calculatorBrain.setOperand("M")
displayValue = calculatorBrain.result
}
}
| true
|
0319fab19616d1e42ad57335af138600c473a0b7
|
Swift
|
jmacalupur/CursoSwift2018
|
/13. ForWhile.playground/Contents.swift
|
UTF-8
| 615
| 3.0625
| 3
|
[] |
no_license
|
import Foundation
var accountTotal : Float = 1_000_000
var transactions : [Float] = [20, 10, 100]
var total : Float = 0
for transaction in transactions {
total += (transaction * 100)
}
print(total)
print(accountTotal)
accountTotal -= total
print(accountTotal)
var transactionsDict : [String: [Float]] = [
"1nov" : [20,10,100.0],
"2nov" : [],
"3nov" : [1000],
"4nov" : [],
"5nov" : [10]
]
var total2 : Float = 0.0
for key in transactionsDict.keys {
for transaction in transactionsDict[key] ?? [] {
total2 += transaction
}
}
print(transactionsDict)
print(total2)
| true
|
d4d1b48d860ddd7ded045c6741af96a426542ca4
|
Swift
|
cuappdev/pollo-ios
|
/Pollo/Views/Cards/PollsDateCell.swift
|
UTF-8
| 3,466
| 2.671875
| 3
|
[] |
no_license
|
//
// PollsDateCell.swift
// Pollo
//
// Created by Kevin Chan on 9/17/18.
// Copyright © 2018 CornellAppDev. All rights reserved.
//
import UIKit
class PollsDateCell: UICollectionViewCell {
// MARK: - View vars
var dateLabel: UILabel!
var greyView: UIView!
var rightArrowButtonImageView: UIImageView!
var indicatorDot: UIView!
// MARK: - Constants
let cellCornerRadius: CGFloat = 5
let dateLabelFontSize: CGFloat = 16
let dateLabelLeftPadding: CGFloat = 7
let greyViewInset: CGFloat = 16
let rightArrowButtonImageViewHeight: CGFloat = 15
let rightArrowButtonImageViewRightPadding: CGFloat = 13
let indicatorDotLeftPadding: CGFloat = 10
let indicatorDotHeight: CGFloat = 8
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .darkestGrey
setupViews()
}
// MARK: - Layout
func setupViews() {
greyView = UIView()
greyView.backgroundColor = .darkGrey
greyView.layer.cornerRadius = cellCornerRadius
contentView.addSubview(greyView)
dateLabel = UILabel()
dateLabel.textColor = .white
dateLabel.font = UIFont.boldSystemFont(ofSize: dateLabelFontSize)
contentView.addSubview(dateLabel)
rightArrowButtonImageView = UIImageView()
rightArrowButtonImageView.image = #imageLiteral(resourceName: "forward_arrow")
rightArrowButtonImageView.contentMode = .scaleAspectFit
contentView.addSubview(rightArrowButtonImageView)
indicatorDot = UIView()
indicatorDot.backgroundColor = .polloGreen
indicatorDot.layer.cornerRadius = indicatorDotHeight / 2
contentView.addSubview(indicatorDot)
}
override func setNeedsUpdateConstraints() {
greyView.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(greyViewInset)
make.top.bottom.equalToSuperview()
}
dateLabel.snp.makeConstraints { make in
make.leading.equalTo(indicatorDot.snp.trailing).offset(dateLabelLeftPadding)
make.centerY.equalToSuperview()
}
rightArrowButtonImageView.snp.makeConstraints { make in
make.trailing.equalTo(greyView.snp.trailing).inset(rightArrowButtonImageViewRightPadding)
make.centerY.equalToSuperview()
make.height.equalTo(rightArrowButtonImageViewHeight)
}
indicatorDot.snp.makeConstraints { make in
make.leading.equalTo(greyView.snp.leading).offset(indicatorDotLeftPadding)
make.centerY.equalToSuperview()
make.height.width.equalTo(indicatorDotHeight)
}
super.updateConstraints()
}
// MARK: - Configure
func configure(for pollsDateModel: PollsDateModel) {
dateLabel.text = reformatDate(pollsDateModel.dateValue)
indicatorDot.isHidden = !pollsDateModel.polls.contains(where: { $0.state == .live })
}
// MARK: - Helpers
// Converts Unix timestamp to MMMM d format
func reformatDate(_ date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM d"
dateFormatter.timeZone = .current
return dateFormatter.string(from: date)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
c6466bc789b62cecca5c40a36be9908e8049fbb7
|
Swift
|
hernangonzalez/SwiftExtensions
|
/Sources/SwiftExtensions/FileManager.swift
|
UTF-8
| 735
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import ReactiveSwift
import Logger
public extension FileManager {
enum Error: Swift.Error {
case noData
}
func content(atURL url: URL) -> SignalProducer<Data, Error> {
let queue = DispatchQueue.global()
return SignalProducer { observer, lifetime in
queue.async {
guard let data = url.data else {
logger.verbose("No data at: " + url.path)
observer.send(error: Error.noData)
return
}
logger.info("Loaded: " + url.path)
observer.send(value: data)
observer.sendCompleted()
}
}
}
}
| true
|
2ecbb462db9798a5b027273fe763e073fcff7837
|
Swift
|
iX0ness/CoreDataSchool
|
/CoreDataSchool/CoreData/Entities/ExampleCoreDataStack.swift
|
UTF-8
| 2,607
| 2.671875
| 3
|
[] |
no_license
|
//
// ExampleCoreDataStack.swift
// CoreDataSchool
//
// Created by Mykhaylo Levchuk on 09/02/2021.
//
import Foundation
import CoreData
class ExampleCoreDataStack{
public init() {
}
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(
name:"CoreDataUnitTesting")
container.loadPersistentStores(
completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
var applicationDocumentsDirectory: NSURL = {
let urls = FileManager.default.urls(for:
.documentDirectory, in: .userDomainMask)
return urls[urls.count - 1] as NSURL
}()
public var managedObjectModel: NSManagedObjectModel = {
var modelPath = Bundle.main.path(
forResource: "CoreDataUnitTesting",
ofType: "momd")
var modelURL = NSURL.fileURL(withPath: modelPath!)
var model = NSManagedObjectModel(contentsOf: modelURL)!
return model
}()
public lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let url = self.applicationDocumentsDirectory.appendingPathComponent("CoreDataUnitTesting.sqlite")
var options = [NSInferMappingModelAutomaticallyOption: true, NSMigratePersistentStoresAutomaticallyOption: true]
var psc = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
do {
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName:nil, at: url, options: options)
} catch {
NSLog("Error when creating persistent store \(error)")
fatalError()
}
return psc
}()
public lazy var rootContext: NSManagedObjectContext = {
var context: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
context.persistentStoreCoordinator = self.persistentStoreCoordinator
return context
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| true
|
64fe3eb2bf3aa38b09349646417b78682b9c51bb
|
Swift
|
oic313/GgrMemo
|
/GgrMemoUtility/Extension/ClassNameProtocol.swift
|
UTF-8
| 313
| 2.8125
| 3
|
[] |
no_license
|
public protocol ClassNameProtocol {
static var className: String { get }
var className: String { get }
}
public extension ClassNameProtocol {
static var className: String { String(describing: self) }
var className: String { type(of: self).className }
}
extension NSObject: ClassNameProtocol {}
| true
|
bc890116e7ae3d1b80549b54b91a070215d77edd
|
Swift
|
ezequielg/LocalNotificationWrapper
|
/LocalNotificationWrapper/Classes/LocalNotificationScheduler.swift
|
UTF-8
| 1,618
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import UserNotifications
internal class LocalNotificationScheduler {
private let localNotificationBuilder = LocalNotificationBuilder()
internal init() {}
func schedule(notification : LocalNotification) {
if #available(iOS 10, *) {
let content = self.localNotificationBuilder.build(notification)
self.scheduleForiOS10(content: content)
return
}
let localNotification = self.localNotificationBuilder.assemble(notification)
self.scheduleForiOS9(localNotification)
}
func schedule(messageBody : String) {
if #available(iOS 10, *) {
let content = self.localNotificationBuilder.build(messageBody: messageBody)
self.scheduleForiOS10(content: content)
return
}
let localNotification = self.localNotificationBuilder.assemble(messageBody: messageBody)
self.scheduleForiOS9(localNotification)
}
@available(iOS 10, *)
internal func scheduleForiOS10(content : UNNotificationContent) {
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { (error) in
if error != nil {
print("There was an error adding the notification request")
return
}
print("The notification was added correctly")
}
}
private func scheduleForiOS9(_ localNotification : UILocalNotification) {
UIApplication.shared.scheduleLocalNotification(localNotification)
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.