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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
25652e641cf07da015fa5e9d8239886a94b90b68
|
Swift
|
danielaraujos/guia-calouro-ios
|
/Guia do Calouro/ManagementDetailViewController.swift
|
UTF-8
| 3,449
| 2.84375
| 3
|
[] |
no_license
|
//
// ManagementDetailViewController.swift
// Guia do Calouro
//
// Created by Daniel Araújo on 21/02/17.
// Copyright © 2017 Daniel Araújo Silva. All rights reserved.
//
import UIKit
class ManagementDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
//ManagementDetailCell
var conteudo: Management!
override func viewDidLoad() {
super.viewDidLoad()
self.title = self.conteudo.function!
}
func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}else if section == 1{
return 1
}else if section == 2{
return 1
}else if section == 3{
return 1
}else if section == 4 {
return 1
}
return 0
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Cargo:"
}else if section == 1{
return "Nome:"
}else if section == 2{
return "Número da sala:"
}else if section == 3{
return "E-mail:"
}else if section == 4 {
return "Telefone:"
}
return ""
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ManagementDetailCell", for: indexPath)
if indexPath.section == 0 {
cell.textLabel?.text = conteudo.function!
}else if indexPath.section == 1{
cell.textLabel?.text = conteudo.name!
}else if indexPath.section == 2{
cell.textLabel?.text = conteudo.room!
}else if indexPath.section == 3{
cell.textLabel?.text = conteudo.email!
}else if indexPath.section == 4 {
cell.textLabel?.text = conteudo.phone!
}
return cell
}
// func open(scheme: String) {
// if let url = URL(string: scheme) {
// if #available(iOS 10.0, *) {
// UIApplication.shared.open(url, options: [:], completionHandler: {
// (success) in
// print("Open \(scheme): \(success)")
// })
// } else {
// // Fallback on earlier versions
// }
// }
// }
//
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 0 {
}else if indexPath.section == 1{
}else if indexPath.section == 2{
}else if indexPath.section == 3{
if let url = NSURL(string: "mailto://\(self.conteudo.email!)")
{
UIApplication.shared.openURL(url as URL)
}
}else if indexPath.section == 4 {
//open(scheme: "tel://\(conteudo.phone!)")
if let url = NSURL(string: "telprompt://\(self.conteudo.phone!)")
{
UIApplication.shared.openURL(url as URL)
}
}
}
}
| true
|
4b159cee9d3791e1c624e7a1271145c6198e16c1
|
Swift
|
ericrisco/NaturalLanguageForecast
|
/iOs/Helpers/Extensions/UIView.swift
|
UTF-8
| 518
| 2.53125
| 3
|
[] |
no_license
|
//
// AdidasChallenge
//
// Created by Eric Risco de la Torre on 05/12/2017.
// Copyright © 2017 ERISCO. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name:
kCAMediaTimingFunctionEaseInEaseOut)
animation.type = kCATransitionFade
animation.duration = duration
layer.add(animation, forKey: kCATransitionFade)
}
}
| true
|
f81b4e476b595f0975ba25e621b378b398a52791
|
Swift
|
rcedwards/TienLen
|
/TienLenTests/InstantWinTests.swift
|
UTF-8
| 6,437
| 3.21875
| 3
|
[] |
no_license
|
//
// InstantWinTests.swift
// TienLen
//
// Created by Robert Edwards on 3/5/16.
// Copyright © 2016 Panko. All rights reserved.
//
import XCTest
import PlayingCards
@testable import TienLen
class InstantWinTests: XCTestCase {
/*
Insant Wins
Four 2s
Six pairs (In sequence, Ex. 44,55,66,77,88,99)
Three triples (In sequence, Ex. 444,555,666) (three triples are rarer than six pairs).
Dragon's Head (Dragon): A special sequence that runs from 3 through ace. A dragon can only be defeated by another dragon of higher suit. A dragon of hearts can't be defeated. This type of sequence is the longest in the game. The dragon is the sequence that has all individual cards, like 3♠ 4♠ 5 ♠ 6♠ 7♠ 8♠ 9♠ 10♠ J♠ Q♠ K♠ A♠ 2♠.
The last instant win occasion, ultimate dragon, is the most difficult to attain. The ultimate dragon must contain two things in order for the player to receive an automatic victory: the 3♠, and the A♥. These two cards are essential in an ultimate dragon, because the three of spades commences the game, and the player can run the sequence straight to the ace of hearts. This makes the entire dragon completely unstoppable, therefore leaving the player with one remaining card, resulting in a victory.
*/
func testFourTwosInstantWin() {
let twoOfHearts = TienLen.Card(rank: .two, suit: .heart)
let twoOfSpades = TienLen.Card(rank: .two, suit: .spade)
let twoOfClubs = TienLen.Card(rank: .two, suit: .club)
let twoOfDiamonds = TienLen.Card(rank: .two, suit: .diamond)
guard let fourTwos = Hand(cards: [twoOfHearts,
twoOfSpades,
twoOfClubs,
twoOfDiamonds,
TienLen.Card(rank: .ace, suit: .spade),
TienLen.Card(rank: .five, suit: .spade),
TienLen.Card(rank: .nine, suit: .spade),
TienLen.Card(rank: .jack, suit: .spade),
TienLen.Card(rank: .three, suit: .spade),
TienLen.Card(rank: .three, suit: .heart),
TienLen.Card(rank: .three, suit: .diamond),
TienLen.Card(rank: .six, suit: .spade),
TienLen.Card(rank: .jack, suit: .diamond)
]) else {
XCTFail("Failed to create hand")
return
}
XCTAssertTrue(fourTwos.containsInstantWin)
}
func testSixPairsInstantWin() {
guard let sixPairs = Hand(cards: [
TienLen.Card(rank: .four, suit: .heart),
TienLen.Card(rank: .four, suit: .spade),
TienLen.Card(rank: .three, suit: .heart),
TienLen.Card(rank: .three, suit: .diamond),
TienLen.Card(rank: .ten, suit: .club),
TienLen.Card(rank: .ten, suit: .spade),
TienLen.Card(rank: .king, suit: .diamond),
TienLen.Card(rank: .king, suit: .club),
TienLen.Card(rank: .ace, suit: .spade),
TienLen.Card(rank: .ace, suit: .heart),
TienLen.Card(rank: .two, suit: .heart),
TienLen.Card(rank: .two, suit: .diamond),
TienLen.Card(rank: .two, suit: .spade)
]) else {
XCTFail("Failed to create hand")
return
}
XCTAssertTrue(sixPairs.containsInstantWin)
}
func testThreeTriplesInstantWin() {
guard let threeTriples = Hand(cards: [
TienLen.Card(rank: .four, suit: .heart),
TienLen.Card(rank: .four, suit: .spade),
TienLen.Card(rank: .four, suit: .club),
TienLen.Card(rank: .ten, suit: .diamond),
TienLen.Card(rank: .ten, suit: .club),
TienLen.Card(rank: .ten, suit: .spade),
TienLen.Card(rank: .king, suit: .diamond),
TienLen.Card(rank: .king, suit: .club),
TienLen.Card(rank: .king, suit: .spade),
TienLen.Card(rank: .ace, suit: .heart),
TienLen.Card(rank: .three, suit: .heart),
TienLen.Card(rank: .five, suit: .diamond),
TienLen.Card(rank: .six, suit: .spade)
]) else {
XCTFail("Failed to create hand")
return
}
XCTAssertTrue(threeTriples.containsInstantWin)
}
func testDragonsHead() {
guard let dragonHead = Hand(cards: [
TienLen.Card(rank: .three, suit: .spade),
TienLen.Card(rank: .four, suit: .spade),
TienLen.Card(rank: .five, suit: .club),
TienLen.Card(rank: .six, suit: .diamond),
TienLen.Card(rank: .seven, suit: .club),
TienLen.Card(rank: .eight, suit: .spade),
TienLen.Card(rank: .nine, suit: .diamond),
TienLen.Card(rank: .ten, suit: .club),
TienLen.Card(rank: .jack, suit: .spade),
TienLen.Card(rank: .queen, suit: .heart),
TienLen.Card(rank: .king, suit: .heart),
TienLen.Card(rank: .ace, suit: .heart),
TienLen.Card(rank: .two, suit: .spade)
]) else {
XCTFail("Failed to create hand")
return
}
XCTAssertTrue(dragonHead.containsInstantWin)
}
func testUltimateDragon() {
guard let ultimate = Hand(cards: [
TienLen.Card(rank: .three, suit: .spade),
TienLen.Card(rank: .four, suit: .heart),
TienLen.Card(rank: .four, suit: .spade),
TienLen.Card(rank: .five, suit: .club),
TienLen.Card(rank: .six, suit: .diamond),
TienLen.Card(rank: .seven, suit: .club),
TienLen.Card(rank: .eight, suit: .spade),
TienLen.Card(rank: .nine, suit: .diamond),
TienLen.Card(rank: .ten, suit: .club),
TienLen.Card(rank: .jack, suit: .spade),
TienLen.Card(rank: .queen, suit: .heart),
TienLen.Card(rank: .king, suit: .heart),
TienLen.Card(rank: .ace, suit: .heart)
]) else { XCTFail("Failed to create hand")
return
}
XCTAssertTrue(ultimate.containsInstantWin)
}
}
| true
|
a057ae10f6a4deeab1f82886aba5e02301c941e3
|
Swift
|
Igloo302/ARNY
|
/ARNY/ViewController/SubjectViewController.swift
|
UTF-8
| 7,735
| 2.578125
| 3
|
[] |
no_license
|
//
// SubjectViewController.swift
// ARNY
//
// Created by Igloo on 2020/11/23.
//
import UIKit
class SubjectViewController: UIViewController {
@IBOutlet weak var lessonCard1: UIView!
@IBOutlet weak var lessonCard2: UIView!
@IBOutlet weak var lessonCard3: UIView!
@IBOutlet weak var subjectName: UILabel!
// 主题信息
var subjectID:Int = 999
var currentSubject:Subject!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 设置圆角
lessonCard1.layer.cornerRadius = 20
lessonCard2.layer.cornerRadius = 20
lessonCard3.layer.cornerRadius = 20
}
override func viewDidLoad() {
super.viewDidLoad()
initSP()
updateUI()
// Do any additional setup after loading the view.
// 配置手势
lessonCard1.addGestureRecognizer(setGestureRecognizer())
lessonCard1.layer.applySketchShadow(color: UIColor(red: 0.44, green: 0.53, blue: 0.82, alpha: 1.00), alpha: 0.2, x: 0, y: 10, blur: 30, spread: 0)
lessonCard2.addGestureRecognizer(setGestureRecognizer())
lessonCard2.layer.applySketchShadow(color: UIColor(red: 0.44, green: 0.53, blue: 0.82, alpha: 1.00), alpha: 0.2, x: 0, y: 10, blur: 30, spread: 0)
lessonCard3.addGestureRecognizer(setGestureRecognizer())
lessonCard3.layer.applySketchShadow(color: UIColor(red: 0.44, green: 0.53, blue: 0.82, alpha: 1.00), alpha: 0.2, x: 0, y: 10, blur: 30, spread: 0)
}
func initSP(){
// 主题信息初始化
if subjectID != 999 {
print("从上级页面接收subjectID=", subjectID)
} else {
subjectID = 8001
print("未从上级页面接收到subjectID,设置为默认值8001")
}
print("当前主题位于",subjectID)
currentSubject = subjectData[subjectData.firstIndex(where: { $0.id == subjectID })!]
}
func updateUI(){
subjectName.text = currentSubject.name
// 这个地方建议以后用ScrollView封装,现在强制三个子课程
// 卡片1
var subLessonID = currentSubject.subLessons[0].id
var subLessonInfo = lessonData[lessonData.firstIndex(where: { $0.id == subLessonID})!]
(lessonCard1.viewWithTag(10) as! UILabel).text = subLessonInfo.category.uppercased()
(lessonCard1.viewWithTag(1) as! UILabel).text = subLessonInfo.name
if !subLessonInfo.isWithAR {
(lessonCard1.viewWithTag(13) as! UIButton).isHidden = true
}
(lessonCard1.viewWithTag(4) as! UIImageView).image = UIImage(named: subLessonInfo.imageName)
(lessonCard1.viewWithTag(4) as! UIImageView).contentMode = .scaleAspectFill
(lessonCard1.viewWithTag(5) as! UITextView).text = subLessonInfo.intro
// 卡片2
subLessonID = currentSubject.subLessons[1].id
subLessonInfo = lessonData[lessonData.firstIndex(where: { $0.id == subLessonID})!]
(lessonCard2.viewWithTag(10) as! UILabel).text = subLessonInfo.category.uppercased()
(lessonCard2.viewWithTag(1) as! UILabel).text = subLessonInfo.name
if !subLessonInfo.isWithAR {
(lessonCard2.viewWithTag(23) as! UIButton).isHidden = true
}
(lessonCard2.viewWithTag(4) as! UIImageView).image = UIImage(named: subLessonInfo.imageName)
(lessonCard2.viewWithTag(4) as! UIImageView).contentMode = .scaleAspectFill
(lessonCard2.viewWithTag(5) as! UITextView).text = subLessonInfo.intro
// 卡片3
subLessonID = currentSubject.subLessons[2].id
subLessonInfo = lessonData[lessonData.firstIndex(where: { $0.id == subLessonID})!]
(lessonCard3.viewWithTag(10) as! UILabel).text = subLessonInfo.category.uppercased()
(lessonCard3.viewWithTag(1) as! UILabel).text = subLessonInfo.name
if !subLessonInfo.isWithAR {
(lessonCard3.viewWithTag(33) as! UIButton).isHidden = true
}
(lessonCard3.viewWithTag(4) as! UIImageView).image = UIImage(named: subLessonInfo.imageName)
(lessonCard3.viewWithTag(4) as! UIImageView).contentMode = .scaleAspectFill
(lessonCard3.viewWithTag(5) as! UITextView).text = subLessonInfo.intro
}
// MARK: - UI Interaction
@IBAction func buttonBack(_ sender: Any) {
//self.dismiss(animated: true, completion:nil)
navigationController?.popViewController(animated: true)
}
@IBAction func buttonAR(_ sender: Any) {
print("启动AR Mode")
// // Segue方式跳转
// performSegue(withIdentifier: "ToARView", sender: self)
// Navigation模式生效
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let newVC = (storyboard.instantiateViewController(withIdentifier: "arMode") ) as! ARViewController
//傻不拉几的区分方法
switch (sender as! UIButton).tag {
case 13:
newVC.lessonID = currentSubject.subLessons[0].id
case 23:
newVC.lessonID = currentSubject.subLessons[1].id
case 33:
newVC.lessonID = currentSubject.subLessons[2].id
default:
newVC.lessonID = 999
}
self.navigationController?.pushViewController(newVC, animated: true)
}
@IBAction func buttonBasic(_ sender: Any) {
print("启动Basic Mode")
// Navigation模式生效
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let newVC = (storyboard.instantiateViewController(withIdentifier: "basicView") ) as! BasicViewController
//傻不拉几的区分方法
switch (sender as! UIButton).tag {
case 12:
newVC.lessonID = currentSubject.subLessons[0].id
case 22:
newVC.lessonID = currentSubject.subLessons[1].id
case 32:
newVC.lessonID = currentSubject.subLessons[2].id
default:
newVC.lessonID = 999
}
print("跳转基本模式")
self.navigationController?.pushViewController(newVC, animated: true)
}
func setGestureRecognizer() -> UITapGestureRecognizer {
var Recognizer = UITapGestureRecognizer()
Recognizer = UITapGestureRecognizer (target: self, action: #selector(startLessonView(gesture:)))
Recognizer.numberOfTapsRequired = 1
return Recognizer
}
@objc func startLessonView(gesture:UITapGestureRecognizer){
print("启动Lesson View")
// Navigation模式生效
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let newVC = (storyboard.instantiateViewController(withIdentifier: "lessonView") ) as! LessonViewController
switch gesture.view!.tag {
case 101:
newVC.lessonID = currentSubject.subLessons[0].id
case 102:
newVC.lessonID = currentSubject.subLessons[1].id
case 103:
newVC.lessonID = currentSubject.subLessons[2].id
default:
newVC.lessonID = 999
}
self.navigationController?.pushViewController(newVC, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
dd65215a2c9660653c609ebecdd838bf58b0cc59
|
Swift
|
zanqging/HelloSweet
|
/Sweet Grass/Sweet Grass/TBVC4.swift
|
UTF-8
| 1,450
| 2.625
| 3
|
[] |
no_license
|
//
// TBVC4.swift
// Sweet Grass
//
// Created by 도다솜 on 2016. 3. 26..
// Copyright © 2016년 HanFang. All rights reserved.
//
import Foundation
import UIKit
class TableviewController4: UITableViewController {
var names = [String]()
var identities = [String]()
override func viewDidLoad() {
names = ["Collard Greens","Aspargus","Fried okra","Side Caesar","Carolina Slaw","House Fries","Green Beans","Side Salad","Mashed Potatoes","Grit Cake","Fresh Cut Chips","Sweet Potato Fries"]
identities = ["AB","CD","EF","GH","IJ","KL","MN","OP","QR","ST","UV","WX"]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
cell?.textLabel!.text = names[indexPath.row]
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let vcName = identities[indexPath.row]
let viewController4 = storyboard?.instantiateViewControllerWithIdentifier(vcName)
self.navigationController?.pushViewController(viewController4!, animated: true)
}
}
| true
|
a3f72bfd78fea104ab48e0b805e0c529a59292d6
|
Swift
|
agupta73/cKDMS
|
/iKDMS/iKDMS/iKDMS/Devotee.swift
|
UTF-8
| 5,882
| 2.546875
| 3
|
[] |
no_license
|
//
// Devotee.swift
// iKDMS
//
// Created by Gupta, Anil on 1/24/19.
// Copyright © 2019 Gupta, Anil. All rights reserved.
//
import UIKit
import os.log
class Devotee {
//MARK: Properties
var firstName: String?
var lastName: String?
var devoteeKey: String?
var devoteeType: String?
var devoteeIdType: String?
var devoteeIdNumber: String?
var devoteeStation: String?
var devoteePhone: String?
var devoteeRemarks: String?
var devoteeAccoId: String?
var devoteeAccoName: String?
var devoteePhoto: UIImage?
var devoteeIdImage: UIImage?
required convenience init?(coder aDecoder: NSCoder) {
//Name is required. If we cant decode a name string, the initializer should fail
guard let devoteeKey = aDecoder.decodeObject(forKey: PropertyKey.devoteeKey) as? String
else {
os_log("Unable to decode the devotee key for a Devotee Record Object", log: OSLog.default, type: .debug)
return nil
}
let firstName = aDecoder.decodeObject(forKey: PropertyKey.firstName) as? String
let lastName = aDecoder.decodeObject(forKey: PropertyKey.lastName) as? String
//let devoteeKey = aDecoder.decodeObject(forKey: PropertyKey.devoteeKey) as String
let devoteeType = aDecoder.decodeObject(forKey: PropertyKey.devoteeType) as? String
let devoteeIdType = aDecoder.decodeObject(forKey: PropertyKey.devoteeIdType) as? String
let devoteeIdNumber = aDecoder.decodeObject(forKey: PropertyKey.devoteeIdNumber) as? String
let devoteeStation = aDecoder.decodeObject(forKey: PropertyKey.devoteeStation) as? String
let devoteePhone = aDecoder.decodeObject(forKey: PropertyKey.devoteePhone) as? String
let devoteeRemarks = aDecoder.decodeObject(forKey: PropertyKey.devoteeRemarks) as? String
let devoteeAccoId = aDecoder.decodeObject(forKey: PropertyKey.devoteeAccoId) as? String
let devoteeAccoName = aDecoder.decodeObject(forKey: PropertyKey.devoteeAccoName) as? String
let devoteePhoto = aDecoder.decodeObject(forKey: PropertyKey.devoteePhoto) as? UIImage
let devoteeIdImage = aDecoder.decodeObject(forKey: PropertyKey.devoteeIdImage) as? UIImage
// self.init(name: name, photo: photo, rating: rating)
self.init(firstName: firstName, lastName: lastName, devoteeKey: devoteeKey, devoteeType: devoteeType, devoteeIdType: devoteeIdType, devoteeIdNumber: devoteeIdNumber, devoteeStation: devoteeStation, devoteePhone: devoteePhone, devoteeRemarks: devoteeRemarks, devoteeAccoId: devoteeAccoId,devoteeAccoName: devoteeAccoName, devoteePhoto: devoteePhoto, devoteeIdImage: devoteeIdImage )
}
func encode(with aCoder: NSCoder) {
aCoder.encode(firstName, forKey:PropertyKey.firstName)
aCoder.encode(lastName, forKey:PropertyKey.lastName)
aCoder.encode(devoteeKey, forKey:PropertyKey.devoteeKey)
aCoder.encode(devoteeType, forKey:PropertyKey.devoteeType)
aCoder.encode(devoteeIdType, forKey:PropertyKey.devoteeIdType)
aCoder.encode(devoteeIdNumber, forKey:PropertyKey.devoteeIdNumber)
aCoder.encode(devoteeStation, forKey:PropertyKey.devoteeStation)
aCoder.encode(devoteePhone, forKey:PropertyKey.devoteePhone)
aCoder.encode(devoteeRemarks, forKey:PropertyKey.devoteeRemarks)
aCoder.encode(devoteeAccoId, forKey:PropertyKey.devoteeAccoId)
aCoder.encode(devoteeAccoName, forKey:PropertyKey.devoteeAccoName)
aCoder.encode(devoteePhoto, forKey:PropertyKey.devoteePhoto)
aCoder.encode(devoteeIdImage, forKey:PropertyKey.devoteeIdImage)
//aCoder.encode(rating, forKey: PropertyKey.rating)
}
//MARK: Archiving Path
static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("devotee")
//MARK: Type
struct PropertyKey {
static let firstName = "firstName"
static let lastName = "lastName"
static let devoteeKey = "devoteeKey"
static let devoteeType = "devoteeType"
static let devoteeIdType = "devoteeIdType"
static let devoteeIdNumber = "devoteeIdNumber"
static let devoteeStation = "devoteeStation"
static let devoteePhone = "devoteePhone"
static let devoteeRemarks = "devoteeRemarks"
static let devoteeAccoId = "devoteeAccoID"
static let devoteeAccoName = "devoteeAccoName"
static let devoteePhoto = "devoteePhoto"
static let devoteeIdImage = "devoteeIdImage"
// static let rating = "rating"
}
//MARK: Initialization
init?(firstName: String?, lastName: String?, devoteeKey: String, devoteeType: String?, devoteeIdType: String?, devoteeIdNumber: String?, devoteeStation: String?, devoteePhone: String?, devoteeRemarks: String?, devoteeAccoId: String?, devoteeAccoName: String?, devoteePhoto: UIImage?, devoteeIdImage: UIImage?){
//Initilization should fail if there is no devotee Key or rating
// guard !devoteeKey.isEmpty else {
// return nil
// }
//Add other validations here (like raiting must be between 0 and 5 inclusively)
//
self.firstName = firstName
self.lastName = lastName
self.devoteeKey = devoteeKey
self.devoteeType = devoteeType
self.devoteeIdType = devoteeIdType
self.devoteeIdNumber = devoteeIdNumber
self.devoteeStation = devoteeStation
self.devoteePhone = devoteePhone
self.devoteeRemarks = devoteeRemarks
self.devoteeAccoId = devoteeAccoId
self.devoteeAccoName = devoteeAccoName
self.devoteePhoto = devoteePhoto
self.devoteeIdImage = devoteeIdImage
}
}
| true
|
b015e8b48bba9fa5c83edfa29933284af70dac27
|
Swift
|
PacktPublishing/iOS-10-Programming-for-Beginners
|
/source code/chapter 10/completed/letseat/letseat/MapDataManager.swift
|
UTF-8
| 968
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// MapDataManager.swift
// LetsEat
//
// Created by Craig Clayton on 11/15/16.
// Copyright © 2016 Craig Clayton. All rights reserved.
//
import Foundation
import MapKit
class MapDataManager:DataManager {
fileprivate var items:[RestaurantAnnotation] = []
var annotations:[RestaurantAnnotation] {
return items
}
func fetch(completion: (_ annotations:[RestaurantAnnotation]) -> ()) {
if items.count > 0 { items.removeAll() }
for data in load(file: "MapLocations") {
items.append(RestaurantAnnotation(dict: data))
}
completion(items)
}
func currentRegion(latDelta:CLLocationDegrees, longDelta:CLLocationDegrees) -> MKCoordinateRegion {
guard let item = items.first else { return MKCoordinateRegion() }
let span = MKCoordinateSpanMake(latDelta, longDelta)
return MKCoordinateRegion(center: item.coordinate, span: span)
}
}
| true
|
7b78009d40d4aba60ba4efbdba2b5c63c09b282a
|
Swift
|
truongtaihoa/CleanArchitecture
|
/VinIDLight/VinIDLight/Sources/Domain/UseCase/SearchTaskUseCase.swift
|
UTF-8
| 894
| 2.796875
| 3
|
[] |
no_license
|
//
// SearchTaskUseCase.swift
// VinIDLight
//
// Created by Truong Huu Hoa on 11/17/20.
// Copyright © 2020 VinID. All rights reserved.
//
import Foundation
import RxSwift
protocol SearchTaskUseCaseType {
func execute(query: String) -> Observable<[Task]>
}
class SearchTaskUseCase: SearchTaskUseCaseType {
let repository: TaskRepositoryType
init(repository: TaskRepositoryType) {
self.repository = repository
}
func execute(query: String) -> Observable<[Task]> {
return Observable<String>.just(query)
.flatMap { [unowned self] query -> Observable<[Task]> in
if query.isEmpty {
return self.repository.getAllTasks()
}
return self.repository.getTasks(query: query)
}
}
}
| true
|
7c4e284bdf2d602c6a598c99e4d5f016f9b4f10b
|
Swift
|
shritekale/ECommerceStore
|
/ECommerceStoreAPI/ECommerceStoreAPIRequests.swift
|
UTF-8
| 2,846
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
//
// ECommerceStoreAPI.swift
// ECommerceStoreAPI
//
// Created by Shrikantreddy Tekale on 30/03/2020.
// Copyright © 2020 Shrikantreddy Tekale. All rights reserved.
//
import Foundation
import Fetch
public typealias ProductResult<ProductResponse> = Result<ProductResponse, Error>
public typealias AddToCartResult<AddToCartResponse> = Result<AddToCartResponse, Error>
public typealias GetCartResult<CartResponse> = Result<CartResponse, Error>
public typealias DeleteFromCartResult<DeleteFromCartResponse> = Result<DeleteFromCartResponse, Error>
public protocol ECommerceStoreAPI {
static func fetchProducts(completion: @escaping (ProductResult<ProductResponse>) -> Void)
static func addProductToCart(productId:Int, completion: @escaping (AddToCartResult<AddToCartResponse>) -> Void)
static func fetchCart(completion: @escaping (GetCartResult<CartResponse>) -> Void)
static func deleteProductFromCart(cartId:Int, completion: @escaping (DeleteFromCartResult<DeleteFromCartResponse>) -> Void)
}
public class ECommerceStoreAPIRequests: ECommerceStoreAPI {
public static func fetchProducts(completion: @escaping (ProductResult<ProductResponse>) -> Void) {
let session = Session()
let request = ProductRequest()
session.perform(request) { (result: FetchResult<ProductResponse>) in
switch result {
case .success(let response):
completion(.success(response))
case .failure(let error):
completion(.failure(error))
}
}
}
public static func addProductToCart(productId:Int, completion: @escaping (AddToCartResult<AddToCartResponse>) -> Void) {
let session = Session()
let request = AddToCartRequest(productId: String(productId))
session.perform(request) { (result: FetchResult<AddToCartResponse>) in
switch result {
case .success(let response):
completion(.success(response))
case .failure(let error):
completion(.failure(error))
}
}
}
public static func fetchCart(completion: @escaping (GetCartResult<CartResponse>) -> Void) {
let session = Session()
let request = CartRequest()
session.perform(request) { (result: FetchResult<CartResponse>) in
switch result {
case .success(let response):
completion(.success(response))
case .failure(let error):
completion(.failure(error))
}
}
}
public static func deleteProductFromCart(cartId:Int, completion: @escaping (DeleteFromCartResult<DeleteFromCartResponse>) -> Void) {
let session = Session()
let request = DeleteFromCartRequest(cartId: String(cartId))
session.perform(request) { (result: FetchResult<DeleteFromCartResponse>) in
switch result {
case .success(let response):
completion(.success(response))
case .failure(let error):
completion(.failure(error))
}
}
}
}
| true
|
dd35fee81ebcc47dbdcb047f194656cbd86ed511
|
Swift
|
xxKRASHxx/Redux-ReactiveSwift
|
/Redux-ReactiveSwift/Tests/Logic/Store/StoreSpec.Helpers.swift
|
UTF-8
| 5,169
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
//
// StoreSpec.Helpers.swift
// CocoaPods-Redux-ReactiveSwift-iOSTests
//
// Created by Petro Korienev on 5/31/20.
//
import Foundation
import Redux_ReactiveSwift
import ReactiveSwift
extension Int: Defaultable {
public static var defaultValue: Int {
return 0
}
}
// MARK: Helpers
enum IntegerArithmeticAction {
case increment
case decrement
case add(Int)
case subtract(Int)
}
class StoreSpecHelpers {
static func createStore<State, Action>(reducer: @escaping (State, Action) -> State,
initialValue: State) -> (Store<State, Action>, CallSpy) {
let callSpy = CallSpy.makeCallSpy(f2: reducer)
let store: Store<State,Action> = .init(state: initialValue, reducers: [callSpy.1])
return (store, callSpy.0)
}
static func createStore<State, Action>(reducers first: @escaping (State, Action) -> State,
_ second: @escaping (State, Action) -> State,
initialValue: State) -> (Store<State, Action>, CallSpy, CallSpy) {
let callSpy1 = CallSpy.makeCallSpy(f2: first)
let callSpy2 = CallSpy.makeCallSpy(f2: second)
let store: Store<State,Action> = .init(state: initialValue, reducers: [callSpy1.1, callSpy2.1])
return (store, callSpy1.0, callSpy2.0)
}
static func createStore<State, Action>(reducers: [(State, Action) -> State],
initialValue: State) -> (Store<State, Action>) {
let store: Store<State,Action> = .init(state: initialValue, reducers: reducers)
return store
}
static func createStrongConsistencyStore<State, Action>(reducer: @escaping (State, Action) -> State,
initialValue: State) -> (StrongConsistencyStore<State, Action>, CallSpy) {
let callSpy = CallSpy.makeCallSpy(f2: reducer)
let store: StrongConsistencyStore<State,Action> = .init(state: initialValue, reducers: [callSpy.1])
return (store, callSpy.0)
}
static func createStrongConsistencyStore<State, Action>(reducers first: @escaping (State, Action) -> State,
_ second: @escaping (State, Action) -> State,
initialValue: State) -> (StrongConsistencyStore<State, Action>, CallSpy, CallSpy) {
let callSpy1 = CallSpy.makeCallSpy(f2: first)
let callSpy2 = CallSpy.makeCallSpy(f2: second)
let store: StrongConsistencyStore<State,Action> = .init(state: initialValue, reducers: [callSpy1.1, callSpy2.1])
return (store, callSpy1.0, callSpy2.0)
}
static func createStrongConsistencyStore<State, Action>(reducers: [(State, Action) -> State],
initialValue: State) -> (StrongConsistencyStore<State, Action>) {
let store: StrongConsistencyStore<State,Action> = .init(state: initialValue, reducers: reducers)
return store
}
static func observeValues<S: PropertyProtocol, State>(of store: S,
with observer: @escaping (State) -> ()) -> CallSpy
where S.Value == State {
let callSpy = CallSpy.makeCallSpy(f1: observer)
store.signal.observeValues(callSpy.1)
return callSpy.0
}
static func observeValuesViaProducer<S: PropertyProtocol, State>(of store: S,
with observer: @escaping (State) -> ()) -> CallSpy
where S.Value == State {
let callSpy = CallSpy.makeCallSpy(f1: observer)
store.producer.startWithValues(callSpy.1)
return callSpy.0
}
static func intReducer(state: Int, event: IntegerArithmeticAction) -> Int {
switch event {
case .increment: return state + 1;
case .decrement: return state - 1;
case .add(let operand): return state + operand;
case .subtract(let operand): return state - operand;
}
}
static func nsNumberReducer(state: NSNumber, event: IntegerArithmeticAction) -> NSNumber {
switch event {
case .increment: return NSNumber(integerLiteral: state.intValue + 1);
case .decrement: return NSNumber(integerLiteral: state.intValue - 1);
case .add(let operand): return NSNumber(integerLiteral: state.intValue + operand);
case .subtract(let operand): return NSNumber(integerLiteral: state.intValue - operand);
}
}
static func stringReducer(state: String, event: IntegerArithmeticAction) -> String {
switch event {
case .increment: return state + "1";
case .decrement: return String(state.dropLast());
case .add(let operand): return state + (1...operand).map {"\($0)"}.joined(separator: "");
case .subtract(let operand): return String(state.dropLast(operand));
}
}
static func observeIntValues(values: Int) {}
static func observeNumberValues(values: NSNumber) {}
}
| true
|
38d723cf95c67dfa60b8e3dbf114f7f1179abb79
|
Swift
|
AlexRossWK/SimpleFlickrApp
|
/BL_Flickr/OnePhotoCollectionView.swift
|
UTF-8
| 2,564
| 2.53125
| 3
|
[] |
no_license
|
import UIKit
private let imageCell = "OneImageCell"
//MARK: - VIEW LOADS AND OUTLETS
class OnePhotoCollectionView: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if DataManager.shared.dataSource.count == 0 { getListRequest() } else { OnePhotoCollectionV.reloadData() }
}
@IBOutlet weak var OnePhotoCollectionV: UICollectionView!
fileprivate let insetForSection: CGFloat = 1
fileprivate let insetBetweenCells: CGFloat = 0
fileprivate let numberOfItemsInLine = 1
}
//MARK: - COLLECTION VIEW DELEGATE
extension OnePhotoCollectionView: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return DataManager.shared.dataSource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imageCell, for: indexPath)
let imageView = cell.contentView.viewWithTag(2) as! UIImageView
let model = DataManager.shared.dataSource[indexPath.row]
imageView.kf.setImage(with: URL(string: model.url ?? ""))
return cell
}
}
//MARK: - COLLECTION VIEW LAYOUT
extension OnePhotoCollectionView: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = OnePhotoCollectionV.frame.width
return CGSize(width: size, height: size)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return insetBetweenCells
}
}
//MARK: - SEND REQUEST
extension OnePhotoCollectionView {
fileprivate func getListRequest() {
GetPopularPhotosManager.getList(success: { [weak self] (photos) in
DispatchQueue.main.async { [weak self] in
DataManager.shared.dataSource.removeAll()
DataManager.shared.dataSource.append(contentsOf: photos)
self?.OnePhotoCollectionV.reloadData()
}
}) { (requestError) in
print(requestError)
}
}
}
| true
|
060294f1b1a632c5457ffe3909df91b8f0ca7b9c
|
Swift
|
kickerchen/DesignPatternPlayground
|
/Structural/Facade.playground/Contents.swift
|
UTF-8
| 1,265
| 3.8125
| 4
|
[] |
no_license
|
/// Facade
/// Analogous to a facade in architecture, a facade is an object that serves as
/// a front-facing interface masking more complex underlying or structural code.
/// A facade can:
/// - improve the readability and usability of a software library by masking interaction with
/// more complex components behind a single (and often simplified) API
/// - provide a context-specific interface to more generic functionality (complete with
/// context-specific input validation)
/// - serve as a launching point for a broader refactor of monolithic or
/// tightly-coupled systems in favor of more loosely-coupled code
protocol Shape {
func draw()
}
class Circle: Shape {
func draw() {
print("circle")
}
}
class Rectangle: Shape {
func draw() {
print("rectangle")
}
}
class Square: Shape {
func draw() {
print("square")
}
}
class ShapeMaker {
private var circle = Circle()
private var rect = Rectangle()
private var square = Square()
func drawCircle() {
circle.draw()
}
func drawRectangle() {
rect.draw()
}
func drawSquare() {
square.draw()
}
}
let facade = ShapeMaker()
facade.drawCircle()
facade.drawSquare()
facade.drawRectangle()
| true
|
909c3e6a917c88f25dd4d7aac1965faf92297682
|
Swift
|
nicklu717/Dribblone
|
/Dribble Training/Training/BallTracker/BallTrackerView.swift
|
UTF-8
| 1,857
| 2.5625
| 3
|
[] |
no_license
|
//
// BallTrackerView.swift
// Dribble Training
//
// Created by 陸瑋恩 on 2019/8/30.
// Copyright © 2019 陸瑋恩. All rights reserved.
//
import UIKit
import AVFoundation
class BallTrackerView: UIView {
// MARK: - Property Declaration
weak var videoOutputDelegate: AVCaptureVideoDataOutputSampleBufferDelegate? {
didSet {
setUpCaptureSession()
setUpCameraLayer()
}
}
let cameraLayer = AVCaptureVideoPreviewLayer()
let captureSession = AVCaptureSession()
// MARK: - Instance Method
func layoutCameraLayer() {
cameraLayer.frame = bounds
}
// MARK: - Private Method
private func setUpCaptureSession() {
captureSession.sessionPreset = .high
guard let camera =
AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front) else { return }
do {
let cameraInput = try AVCaptureDeviceInput(device: camera)
captureSession.addInput(cameraInput)
let videoDataOutput = AVCaptureVideoDataOutput()
let videoDataOutputQueue = DispatchQueue.global()
videoDataOutput.setSampleBufferDelegate(self.videoOutputDelegate, queue: videoDataOutputQueue)
captureSession.addOutput(videoDataOutput)
} catch {
print(error)
}
}
private func setUpCameraLayer() {
cameraLayer.session = captureSession
cameraLayer.videoGravity = .resizeAspectFill
cameraLayer.connection?.videoOrientation = .landscapeLeft
layer.addSublayer(cameraLayer)
}
}
| true
|
5facf5ae967acb27a89b232d4e24e559c4635889
|
Swift
|
cxa/MenuItemKit
|
/Demo/Demo/ViewController.swift
|
UTF-8
| 2,143
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// Demo
//
// Created by CHEN Xian’an on 1/16/16.
// Copyright © 2016 lazyapps. All rights reserved.
//
import UIKit
import MenuItemKit
class ViewController: UIViewController {
@IBOutlet var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button.addTarget(self, action: #selector(self.tapButton(_:)), for: .touchUpInside)
}
@objc func tapButton(_ sender: AnyObject?) {
let controller = UIMenuController.shared
let textItem = UIMenuItem(title: "Text") { [weak self] _ in
self?.showAlertWithTitle("text item tapped")
}
let image = UIImage(named: "Image")
let imageItem = UIMenuItem(title: "Image", image: image) { [weak self] _ in
self?.showAlertWithTitle("image item tapped")
}
let colorImage = UIImage(named: "ColorImage")
let colorImageItem = UIMenuItem(title: "ColorImage", image: colorImage) { [weak self] _ in
self?.showAlertWithTitle("color image item tapped")
}
let nextItem = UIMenuItem(title: "Show More Items...") { _ in
let action: MenuItemAction = { [weak self] in self?.showAlertWithTitle($0.title + " tapped") }
let item1 = UIMenuItem(title: "1", action: action)
let item2 = UIMenuItem(title: "2", action: action)
let item3 = UIMenuItem(title: "3", action: action)
controller.menuItems = [item1, item2, item3]
if #available(iOS 13.0, *) {
controller.isMenuVisible = true
} else {
controller.setMenuVisible(true, animated: true)
}
}
controller.menuItems = [textItem, imageItem, colorImageItem, nextItem]
if #available(iOS 13.0, *) {
controller.showMenu(from: button, rect: button.bounds)
} else {
controller.setTargetRect(button.bounds, in: button)
controller.setMenuVisible(true, animated: true)
}
}
func showAlertWithTitle(_ title: String) {
let alertVC = UIAlertController(title: title, message: nil, preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { _ in }))
present(alertVC, animated: true, completion: nil)
}
}
| true
|
980234215ed7bd037db9f921898a0db212dacbd0
|
Swift
|
ChunsuKim/Task
|
/OOP.playground/Pages/Basic.xcplaygroundpage/Contents.swift
|
UTF-8
| 2,275
| 4.8125
| 5
|
[
"MIT"
] |
permissive
|
//: [Previous](@previous)
/*:
# Class
*/
/***************************************************
Value Type => struct, enum, Int (Stack 에 저장)
Reference Type => class (Heap 에 저장)
메모리 : Code, Data, Heap, Stack
***************************************************/
/***************************************************
class <#ClassName#>: <#SuperClassName#>, <#ProtocolName...#> {
<#PropertyList#>
}
<#ClassName()#> // heap에 데이터 저장 // instance 생성 // 변수에 저장하지 않으면 사라짐
class - 정의
instance - class 를 메모리에 생성한 것
object - instance 를 담아두고 실제 사용하는 놈
let <#instanceName#> = <#ClassName()#>
instanceName.<#propertyName#>
instanceName.<#functionName()#> = methodName()
***************************************************/
class Dog {
var color = "White"
var eyeColor = "Black"
var height = 30.0
var weight = 6.0
func sit() {
print("sit")
}
func layDown() {
print("layDown")
}
func shake() {
print("shake")
}
}
let bobby: Dog = Dog()
bobby.color
bobby.color = "Gray"
bobby.color
bobby.sit()
let tory = Dog()
tory.color = "Brown"
tory.layDown()
// stack, heap
// stack - bobby = 주소값 0x0001 -> heap - bobby`s dog data
/*:
---
### Question
- 자동차 클래스 정의 및 객체 생성하기
---
*/
/***************************************************
자동차 클래스
- 속성: 차종(model), 연식(model year), 색상(color) 등
- 기능: 운전하기(drive), 후진하기(reverse) 등
***************************************************/
class Car1 {
let model = "BMW 3 series"
let modelYear = "2016"
let color = "Navy"
func drive() {
print("전진")
}
func reverse() {
print("후진")
}
func driveSlowly() {
print("서행")
}
}
let car1 = Car1()
car1.model
car1.modelYear
car1.color
car1.drive()
car1.reverse()
/*:
---
### Answer
---
*/
class Car {
let model = "리어카"
let modelYear = 2016
let color = "Cream White"
func drive() {
print("전진")
}
func reverse() {
print("후진")
}
}
let car = Car()
car.model
car.modelYear
car.color
car.drive()
car.reverse()
//: [Next](@next)
| true
|
f4e674bb82b257238768ba07d505e2c8110953fc
|
Swift
|
sbravotalero/Pokedex
|
/Pokedex/Extensions/UIViewController/UIViewController+StoryboardIdentifiable.swift
|
UTF-8
| 492
| 2.546875
| 3
|
[] |
no_license
|
//
// UIViewController+StoryboardIdentifiable.swift
// Pokedex
//
// Created by Sergio David Bravo Talero on 10/11/18.
// Copyright © 2018 Sergio David Bravo Talero. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController: StoryboardIdentifiable {}
protocol StoryboardIdentifiable {
static var storyboardIdentifier: String { get }
}
extension StoryboardIdentifiable where Self: UIViewController {
static var storyboardIdentifier: String {
return String(describing: self)
}
}
| true
|
b279c9eb5e0d09cfea610ad7c083e41f3f4da153
|
Swift
|
ShennyO/Mobile6
|
/Class Example 1/Class Example 1/GameScene.swift
|
UTF-8
| 6,729
| 2.984375
| 3
|
[] |
no_license
|
//
// GameScene.swift
// Class Example 1
//
// Created by Sunny Ouyang on 2/22/18.
// Copyright © 2018 Sunny Ouyang. All rights reserved.
//
import SpriteKit
import GameplayKit
enum Direction {
case up
case down
case right
case left
}
class GameScene: SKScene {
private var label : SKLabelNode?
private var spinnyNode : SKShapeNode?
var player: SKSpriteNode!
var swipeUp: UISwipeGestureRecognizer!
var swipeDown: UISwipeGestureRecognizer!
var swipeRight: UISwipeGestureRecognizer!
var swipeLeft: UISwipeGestureRecognizer!
var boxDirection: Direction!
var enemies: [SKSpriteNode] = []
var enemyPoints: [CGPoint] = []
override func didMove(to view: SKView) {
makeBoard(rows: 3, cols: 3)
makePlayer()
setUpGestures()
configureEnemyPoints()
restartTimer()
}
func configureEnemyPoints() {
//points for the right side
let screenHeight = self.frame.height
let screenWidth = self.frame.width
for x in -1 ... 1 {
let y = screenHeight/2 + CGFloat(x * 60)
let point = CGPoint(x: self.frame.width, y: y)
self.enemyPoints.append(point)
}
//points for the top side
for x in -1 ... 1 {
let x = screenWidth/2 + CGFloat(x * 60)
let point = CGPoint(x: x, y: self.frame.height)
self.enemyPoints.append(point)
}
//points for the left side
for x in -1 ... 1 {
let y = screenHeight/2 + CGFloat(x * 60)
let point = CGPoint(x: 0, y: y)
self.enemyPoints.append(point)
}
//points for the bottom side
for x in -1 ... 1 {
let x = screenWidth/2 + CGFloat(x * 60)
let point = CGPoint(x: x, y: 0)
self.enemyPoints.append(point)
}
}
func makeBoard(rows: Int, cols: Int) {
let screenWidth = self.size.width
let screenHeight = self.size.height
for i in -1 ... 1 {
let stripe = self.makeStripe(width: screenWidth, height: 60)
addChild(stripe)
stripe.position.x = screenWidth / 2
stripe.position.y = (screenHeight / 2) + (65 * CGFloat(i))
}
for i in -1 ... 1 {
let stripe = self.makeStripe(width: 60, height: screenHeight)
addChild(stripe)
stripe.position.x = (screenWidth / 2) + (65 * CGFloat(i))
stripe.position.y = screenHeight / 2
}
}
func restartTimer(){
let wait:SKAction = SKAction.wait(forDuration: 1)
let finishTimer:SKAction = SKAction.run {
let random = Int(arc4random_uniform(UInt32(self.enemyPoints.count)))
let randomPoint = self.enemyPoints[random]
let newEnemy = self.makeEnemy(pos: randomPoint)
if newEnemy.position.x == 0 {
self.moveEnemy(node: newEnemy, direction: Direction.right)
} else if newEnemy.position.x == self.frame.width {
self.moveEnemy(node: newEnemy, direction: Direction.left)
} else if newEnemy.position.y == self.frame.height {
self.moveEnemy(node: newEnemy, direction: Direction.down)
} else if newEnemy.position.y == 0 {
self.moveEnemy(node: newEnemy, direction: Direction.up)
}
self.restartTimer()
}
let seq:SKAction = SKAction.sequence([wait, finishTimer])
self.run(seq)
}
func makePlayer() {
let color = UIColor.red
let size = CGSize(width: 40, height: 40)
player = SKSpriteNode(color: color, size: size)
addChild(player)
let playerPoint = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
player.position = playerPoint
}
func makeEnemy(pos: CGPoint) -> SKSpriteNode {
let color = UIColor.black
let size = CGSize(width: 40, height: 40)
let enemy = SKSpriteNode(color: color, size: size)
enemy.position = pos
addChild(enemy)
self.enemies.append(enemy)
return enemy
}
func moveEnemy(node: SKSpriteNode, direction: Direction) {
let removeNode = SKAction.removeFromParent()
var move: SKAction!
switch direction {
case .up:
let endPoint = CGFloat(self.frame.height + 30)
move = SKAction.moveTo(y: endPoint, duration: 1)
case .down:
let endPoint = CGFloat(-30)
move = SKAction.moveTo(y: endPoint, duration: 1)
case .right:
let endPoint = CGFloat(self.frame.width + 30)
move = SKAction.moveTo(x: endPoint, duration: 1)
case .left:
let endPoint = CGFloat(-30)
move = SKAction.moveTo(x: endPoint, duration: 1)
}
let sequence = SKAction.sequence([move, removeNode])
node.run(sequence)
}
func makeStripe(width: CGFloat, height: CGFloat) -> SKSpriteNode {
let color = UIColor(white: 1, alpha: 0.2)
let size = CGSize(width: width, height: height)
let stripe = SKSpriteNode(color: color, size: size)
return stripe
}
func setUpGestures() {
self.swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
swipeUp.direction = UISwipeGestureRecognizerDirection.up
self.view?.addGestureRecognizer(self.swipeUp)
self.swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
swipeDown.direction = UISwipeGestureRecognizerDirection.down
self.view?.addGestureRecognizer(self.swipeDown)
self.swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
swipeLeft.direction = UISwipeGestureRecognizerDirection.left
self.view?.addGestureRecognizer(self.swipeLeft)
self.swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
self.view?.addGestureRecognizer(self.swipeRight)
}
@objc func handleSwipe(gesture: UISwipeGestureRecognizer) {
print("swipe")
switch gesture.direction {
case .up:
player.position.y += 60
case .down:
player.position.y -= 60
case .right:
player.position.x += 60
case .left:
player.position.x -= 60
default:
return
}
}
}
| true
|
5a52d4eb752bc815ab94d339005de3b840b36154
|
Swift
|
Veregorn/swift-rock-paper-scissors
|
/RockPaperScissors/ContentView.swift
|
UTF-8
| 4,105
| 3.40625
| 3
|
[] |
no_license
|
//
// ContentView.swift
// RockPaperScissors
//
// Created by Rul-ex on 8/9/21.
//
import SwiftUI
struct MoveImage: View {
var move: String
var body: some View {
Image(move)
.resizable(resizingMode: .stretch)
.aspectRatio(contentMode: .fit)
.padding(.horizontal)
}
}
struct ContentView: View {
@State private var moves = ["rock", "paper", "scissors"]
@State private var iaChoice = Int.random(in: 0...2)
@State private var shouldWin = Bool.random()
@State private var score = 0
@State private var scoreTitle = ""
@State private var showingScore = false
var body: some View {
VStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: 30) {
VStack {
Text("My move is")
Text(moves[iaChoice])
.font(.largeTitle)
.bold()
.foregroundColor(.blue)
}
VStack {
Text("What move do you need to")
if shouldWin {
Text("WIN?")
.bold()
.foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
.padding(.bottom)
} else {
Text("LOSE?")
.bold()
.foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
.padding(.bottom)
}
HStack {
ForEach(0 ..< 3) { number in
Button(action: {
self.moveTapped(number)
}) {
MoveImage(move: self.moves[number])
}
}
}
}
Text("Your current score is: \(score)")
}
.padding(.top)
.alert(isPresented: $showingScore) {
Alert(title: Text(scoreTitle), message: Text("Your score is \(score)"), dismissButton: .default(Text("Continue")) {
self.resetGame()
})
}
}
func moveTapped(_ number: Int) {
if number == iaChoice {
scoreTitle = "Tie"
} else if shouldWin {
if iaChoice == 0 {
if number == 1 {
scoreTitle = "Win! Great work"
score += 1
} else {
scoreTitle = "Lose :-("
}
} else if iaChoice == 1 {
if number == 0 {
scoreTitle = "Lose :-("
} else {
scoreTitle = "Win! Great work"
score += 1
}
} else {
if number == 0 {
scoreTitle = "Win! Great work"
score += 1
} else {
scoreTitle = "Lose :-("
}
}
} else { // You need to lose
if iaChoice == 0 {
if number == 1 {
scoreTitle = "Win, but needed to lose..."
} else {
scoreTitle = "Lose! Great work"
score += 1
}
} else if iaChoice == 1 {
if number == 0 {
scoreTitle = "Lose! Great work"
score += 1
} else {
scoreTitle = "Win, but needed to lose..."
}
} else {
if number == 0 {
scoreTitle = "Win, but needed to lose..."
} else {
scoreTitle = "Lose! Great work"
score += 1
}
}
}
showingScore = true
}
func resetGame() {
iaChoice = Int.random(in: 0...2)
shouldWin = Bool.random()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
eb08bfeab8fc2be93c73ae63fb9df133509b1444
|
Swift
|
navneet1990/BitCoin
|
/BCoinTests/BCoinTests.swift
|
UTF-8
| 6,179
| 2.96875
| 3
|
[] |
no_license
|
//
// BCoinTests.swift
// BCoinTests
//
// Created by Navneet Singh on 04/05/18.
// Copyright © 2018 Navneet. All rights reserved.
//
import XCTest
@testable import BCoin
class BCoinTests: XCTestCase {
var viewModal: BCViewModel?
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
//All functionaly and data handling is done by View model which uses MVVM architecure
// Initializing the View Modal
viewModal = BCViewModel.init()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
//MARK: Today Coin test cases
func testTodayCoinCurrencyChange(){
// Here we check the coin rate the for Today for different currency is not same and also currency code is different
//By default it will always take Euro
let intialEuroValue = viewModal?.currentRateCoin?.value?.0
XCTAssertEqual(intialEuroValue!.code, CurrencyCodes(rawValue: CurrencyCodes.EUR.rawValue))
// We will change currancy to Dollar(USD)
viewModal?.changeCurrencyCode(CurrencyCodes.USD.rawValue)
//Now we must get currency as USD
let finalDollarValue = viewModal?.currentRateCoin?.value?.0
XCTAssertEqual(finalDollarValue!.code, CurrencyCodes(rawValue: CurrencyCodes.USD.rawValue))
//Last we check the our current coin object stores the value according to currency selected
XCTAssertNotEqual(finalDollarValue?.rate, intialEuroValue?.rate)
XCTAssertNotEqual(finalDollarValue?.code, intialEuroValue?.code)
}
func testForIfTodayCoinDataChangesAfter60Seconds(){
//First we will put on sleep to 5 seconds so, that we get the response from server, otherwise it will read data from shared container, if available
sleep(5)
// Check initial value of coin on first time service call
let intialValue = viewModal?.currentRateCoin?.value?.1
//Now we will wait for 65 secs and check for data change
sleep(65)
// We will compare string , which stores last updated date
let finalValue = viewModal?.currentRateCoin?.value?.1
XCTAssertNotEqual(intialValue, finalValue)
}
func testDataStoredInSharedContainerIsALwaysUpdated() {
// Here we check we are storing data in Userdefaults in shared container
// it will fail when we fetch data first time
let todayData = SharedData.init().fetchDataFromSharedContainer()
XCTAssertNotNil(todayData)
// Clearning shared Data
SharedData.init().resetTodayDataContainer()
let someEmptyData = fetchDataTodayDataFomSharedContainer()
XCTAssertNil(someEmptyData)
// We always update the Shared data when service refresh after every 60 secs
// But for testing we will call manually
viewModal?.fetchTodayBitCoinRateFromServer()
XCTAssertNotNil(fetchDataTodayDataFomSharedContainer)
}
func fetchDataTodayDataFomSharedContainer()-> TodayCoinModel?{
return SharedData.init().fetchDataFromSharedContainer()
}
//MARK: Last two weeks data
func testForOldDatesWithDifferentCurrency(){
// Here we check the coin rate the for Last two weeks for different currency is not same w also currency code is different
//By default it will always take Euro
let euro = viewModal?.previousDaysRateCoin?.value?.list.values.first
viewModal?.changeCurrencyCode(CurrencyCodes.GBP.rawValue)
let gbp = viewModal?.previousDaysRateCoin?.value?.list.values.first
XCTAssertNotEqual(euro, gbp)
}
func testNotUpdatingOldDataAfter60Seconds(){
//First we will put on sleep to 5 seconds so, that we get the response from server, otherwise it will read data from shared container, if available
sleep(5)
// Check initial value of coin on first time service call
let intialValue = viewModal?.previousDaysRateCoin?.value?.time
//Now we will wait for 65 secs and check for data change
sleep(65)
// We will compare string , which stores last updated date
let finalValue = viewModal?.previousDaysRateCoin?.value?.time
XCTAssertEqual(intialValue, finalValue)
}
func testDataDecodeForWrongObject() {
// here we check that if we pass wrong Mapper object
checkForResponse { (data, error) in
do{
XCTAssertThrowsError(try JSONDecoder().decode(Coins.self, from: data), "", { (error) in
XCTFail("Will always Failed because of wrong mapper object class")
})
}
catch{
}
}
}
func checkForResponse(completion: @escaping (Data,Error?)->Void){
NetworkHandler.callWebServicefor(ApiType.Today.rawValue) { (response) in
switch response{
case .success(let data):
completion(data,nil)
default:
print("Ignore")
}
}
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
viewModal?.fetchTodayBitCoinRateFromServer()
}
}
func testPerformanceForTodayServiceResponse() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
for _ in 0 ... 5{
viewModal?.fetchTodayBitCoinRateFromServer()
}
}
}
}
| true
|
8f665bf97d66c2accc1b3c2fee58af8266e6711a
|
Swift
|
ataetgi/AppStore-CompositionalLayout
|
/AppStore-CompositionalLayout/Controllers/MainTabbarController.swift
|
UTF-8
| 1,412
| 2.765625
| 3
|
[] |
no_license
|
//
// MainTabbarController.swift
// AppStore-CompositionalLayout
//
// Created by Ata Etgi on 27.04.2021.
//
import UIKit
class MainTabbarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
viewControllers = [
createController(viewController: AppsViewController(), title: "Apps", image: UIImage(systemName: "square.stack.3d.up.fill")),
createController(viewController: GamesViewController(), title: "Games", image: UIImage(systemName: "gamecontroller.fill")),
createController(viewController: ArcadeViewController(), title: "Arcade", image: UIImage(systemName: "a.circle.fill")),
createController(viewController: SearchViewController(), title: "Search", image: UIImage(systemName: "magnifyingglass"))
]
}
fileprivate func createController(viewController: UIViewController, title: String, image: UIImage?) -> UIViewController {
viewController.view.backgroundColor = .systemBackground
viewController.navigationItem.title = title
let navController = UINavigationController(rootViewController: viewController)
navController.tabBarItem.image = image
navController.tabBarItem.title = title
navController.navigationBar.prefersLargeTitles = true
return navController
}
}
| true
|
24f8689d100d84686d21f48eda02c9157e909569
|
Swift
|
ThePowerOfSwift/RxSwift
|
/4 Day/RxSwift/RxSwift/RxSwiftPlayground.playground/Contents.swift
|
UTF-8
| 2,105
| 3.03125
| 3
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import RxSwift
import UIKit
//example("without observeon") {
// _ = Observable.of(1, 2, 3)
// .subscribe(onNext: {
// print("\(Thread.current): ", $0)
// }, onError: {
// print($0)
// }, onCompleted: {
// print("Completed")
// }, onDisposed: {
// print("onDisposed")
// })
//}
//
//
//example("observeOn") {
// _ = Observable.of(1, 2, 3)
// .observeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS: .background))
// .subscribe(onNext: {
// print("\(Thread.current): ", $0)
// }, onError: {
// print($0)
// }, onCompleted: {
// print("Completed")
// }, onDisposed: {
// print("onDisposed")
// })
//}
/*
---Example of: without observeon ---
<NSThread: 0x60000007c240>{number = 1, name = main}: 1
<NSThread: 0x60000007c240>{number = 1, name = main}: 2
<NSThread: 0x60000007c240>{number = 1, name = main}: 3
Completed
onDisposed
---Example of: observeOn ---
<NSThread: 0x61800007ed00>{number = 4, name = (null)}: 1
<NSThread: 0x61800007ed00>{number = 4, name = (null)}: 2
<NSThread: 0x61800007ed00>{number = 4, name = (null)}: 3
Completed
*/
example("SubscribeOn and observeOn") {
let queue1 = DispatchQueue.global(qos: .default)
let queue2 = DispatchQueue.global(qos: .default)
print("\(Thread.current)")
_ = Observable<Int>.create({ (observer) -> Disposable in
print("Observable thread: \(Thread.current)")
// generate
observer.on(.next(1))
observer.on(.next(2))
observer.on(.next(3))
return Disposables.create()
}).subscribeOn(SerialDispatchQueueScheduler(internalSerialQueueName: "queue1")).subscribeOn(SerialDispatchQueueScheduler(internalSerialQueueName: "queue2")).subscribe(onNext: {
print("Observable thread: \(Thread.current)", $0)
})
}
| true
|
1146b8c01f22e9de63897ae80bb24b4cd8fd7855
|
Swift
|
Laxmanraju/LXCurrencyExchangeApp
|
/LXSwensonHe/Data/LXExchangeRate.swift
|
UTF-8
| 2,901
| 2.96875
| 3
|
[] |
no_license
|
//
// LXExchangeRate.swift
//
// Created by Laxman Penmesta on 5/16/19
// Copyright (c) Laxman. All rights reserved.
//
import Foundation
import SwiftyJSON
public final class LXExchangeRate: NSCoding {
// MARK: Declaration for string constants to be used to decode and also serialize.
private struct SerializationKeys {
static let base = "base"
static let date = "date"
static let timestamp = "timestamp"
static let rates = "rates"
static let success = "success"
}
// MARK: Properties
public var base: String?
public var date: String?
public var timestamp: Int?
public var rates: LXRates?
public var success: Bool? = false
// MARK: SwiftyJSON Initializers
/// Initiates the instance based on the object.
///
/// - parameter object: The object of either Dictionary or Array kind that was passed.
/// - returns: An initialized instance of the class.
public convenience init(object: Any) {
self.init(json: JSON(object))
}
/// Initiates the instance based on the JSON that was passed.
///
/// - parameter json: JSON object from SwiftyJSON.
public required init(json: JSON) {
base = json[SerializationKeys.base].string
date = json[SerializationKeys.date].string
timestamp = json[SerializationKeys.timestamp].int
rates = LXRates(json: json[SerializationKeys.rates])
success = json[SerializationKeys.success].boolValue
}
/// Generates description of the object in the form of a NSDictionary.
///
/// - returns: A Key value pair containing all valid values in the object.
public func dictionaryRepresentation() -> [String: Any] {
var dictionary: [String: Any] = [:]
if let value = base { dictionary[SerializationKeys.base] = value }
if let value = date { dictionary[SerializationKeys.date] = value }
if let value = timestamp { dictionary[SerializationKeys.timestamp] = value }
if let value = rates { dictionary[SerializationKeys.rates] = value.dictionaryRepresentation() }
dictionary[SerializationKeys.success] = success
return dictionary
}
// MARK: NSCoding Protocol
required public init(coder aDecoder: NSCoder) {
self.base = aDecoder.decodeObject(forKey: SerializationKeys.base) as? String
self.date = aDecoder.decodeObject(forKey: SerializationKeys.date) as? String
self.timestamp = aDecoder.decodeObject(forKey: SerializationKeys.timestamp) as? Int
self.rates = aDecoder.decodeObject(forKey: SerializationKeys.rates) as? LXRates
self.success = aDecoder.decodeBool(forKey: SerializationKeys.success)
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(base, forKey: SerializationKeys.base)
aCoder.encode(date, forKey: SerializationKeys.date)
aCoder.encode(timestamp, forKey: SerializationKeys.timestamp)
aCoder.encode(rates, forKey: SerializationKeys.rates)
aCoder.encode(success, forKey: SerializationKeys.success)
}
}
| true
|
a96d8c56cd9afd672ba95c4c937f77af6fb1c597
|
Swift
|
emilia98/Swift-Training-Advanced
|
/Day 23/Tasks/Task 2/GetKMaxElements.swift
|
UTF-8
| 1,294
| 3.328125
| 3
|
[
"MIT"
] |
permissive
|
func getKMax(_ arr : [Int], _ k : Int) -> [Int] {
if k <= 0 || arr.count == 0 {
return []
}
var arr = arr
var index = 1
var prev = arr[0]
var current: Int
var lastSwapped: Int? = nil
let elementsToGet = min(k, arr.count)
while index < arr.count {
current = arr[index]
if prev < current {
if lastSwapped == nil {
lastSwapped = index
}
(arr[index - 1], arr[index]) = (arr[index], arr[index - 1])
index -= 1
if index == 0 {
index = 1
}
prev = arr[index - 1]
}
else {
if let _ = lastSwapped {
lastSwapped = nil
}
index += 1
prev = current
}
}
return Array(arr[0..<elementsToGet])
}
var arr = [10, 1, 7, 9, 8, 0, 12]
var k = 3
var res = getKMax(arr, k)
print(res)
arr = [1, 2, 3, 4]
k = 2
res = getKMax(arr, k)
print(res)
arr = [5, 3, 3, 5, 6, 7]
k = 5
res = getKMax(arr, k)
print(res)
arr = [1]
k = 2
res = getKMax(arr, k)
print(res)
arr = [1, 2, 3, 3, 3, 6, 6, 8, 9]
k = 5
res = getKMax(arr, k)
print(res)
arr = [0, 4, 6, 1, 8, 2]
k = 2
res = getKMax(arr, k)
print(res)
| true
|
5b62076289c489370e452e083b6a41211efab2be
|
Swift
|
RinniSwift/Diary-app
|
/DiaryIt/Controller/ImagePopUpViewController.swift
|
UTF-8
| 880
| 2.65625
| 3
|
[] |
no_license
|
//
// ImagePopUpViewController.swift
// DiaryIt
//
// Created by Rinni Swift on 3/24/19.
// Copyright © 2019 Rinni Swift. All rights reserved.
//
import UIKit
class ImagePopUpViewController: UIViewController, UIScrollViewDelegate {
// TODO: when tapped on view, dismiss the view controller
// MARK: - Variables
var imageToFill: UIImage? = nil
// MARK: - Outlets
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = imageToFill
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first?.location(in: view)
if (touch?.y)! > (view.frame.height - 60) || (touch?.y)! < CGFloat(15)/*doesnt work*/{
self.dismiss(animated: true, completion: nil)
}
}
}
| true
|
1d8fcfddc1c354c7238a9367ab869fe52d4555fc
|
Swift
|
mohamedmagdy94/Owange-Pranks-iOS-Task
|
/Owange-Pranks-iOS-Task/Common/Extension/UIView.swift
|
UTF-8
| 4,501
| 2.65625
| 3
|
[] |
no_license
|
//
// UIViewExtenstion.swift
//
// Created by Mohamed Eltaweel on 12/20/18.
// Copyright © 2018 Mohamed Eltaweel All rights reserved.
//
import Foundation
import UIKit
import SDWebImage
extension UIView {
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
@IBInspectable
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable
var borderColor: UIColor? {
get {
if let color = layer.borderColor {
return UIColor(cgColor: color)
}
return nil
}
set {
if let color = newValue {
layer.borderColor = color.cgColor
} else {
layer.borderColor = nil
}
}
}
@IBInspectable
var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
@IBInspectable
var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
@IBInspectable
var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
@IBInspectable
var shadowColor: UIColor? {
get {
if let color = layer.shadowColor {
return UIColor(cgColor: color)
}
return nil
}
set {
if let color = newValue {
layer.shadowColor = color.cgColor
} else {
layer.shadowColor = nil
}
}
}
func makeViewCircular(){
self.layer.cornerRadius = self.frame.size.width/2
self.clipsToBounds = true
self.layer.borderColor = UIColor.clear.cgColor
self.layer.borderWidth = 5.0
}
func setVerticalGradientBackground(topColor: UIColor,bottomColor: UIColor,opacity: Float = 1.0) {
let gradient:CAGradientLayer = CAGradientLayer()
gradient.frame.size = frame.size
gradient.colors = [topColor.cgColor,bottomColor.cgColor]
gradient.opacity = opacity
layer.addSublayer(gradient)
}
func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
@IBDesignable
public class Gradient: UIView {
@IBInspectable var startColor: UIColor = .black { didSet { updateColors() }}
@IBInspectable var endColor: UIColor = .white { didSet { updateColors() }}
@IBInspectable var startLocation: Double = 0.05 { didSet { updateLocations() }}
@IBInspectable var endLocation: Double = 0.95 { didSet { updateLocations() }}
@IBInspectable var horizontalMode: Bool = false { didSet { updatePoints() }}
@IBInspectable var diagonalMode: Bool = false { didSet { updatePoints() }}
override public class var layerClass: AnyClass { CAGradientLayer.self }
var gradientLayer: CAGradientLayer { layer as! CAGradientLayer }
func updatePoints() {
if horizontalMode {
gradientLayer.startPoint = diagonalMode ? .init(x: 1, y: 0) : .init(x: 0, y: 0.5)
gradientLayer.endPoint = diagonalMode ? .init(x: 0, y: 1) : .init(x: 1, y: 0.5)
} else {
gradientLayer.startPoint = diagonalMode ? .init(x: 0, y: 0) : .init(x: 0.5, y: 0)
gradientLayer.endPoint = diagonalMode ? .init(x: 1, y: 1) : .init(x: 0.5, y: 1)
}
}
func updateLocations() {
gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
}
func updateColors() {
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
}
override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updatePoints()
updateLocations()
updateColors()
}
}
| true
|
8fd4ac3b0e6b8ad979dd5075122cb321baf08285
|
Swift
|
jelena54321/dz-04
|
/dz-04/dz-04/Services/ResultService.swift
|
UTF-8
| 6,246
| 3.109375
| 3
|
[] |
no_license
|
//
// ResultService.swift
// dz-02
//
// Created by Jelena Šarić on 18/05/2019.
// Copyright © 2019 Jelena Šarić. All rights reserved.
//
import Foundation
/// Enum which presents *HTTP* answer.
enum HttpAnswer: Int {
/// Token does not exist.
case UNAUTHORIZED = 401
/// Provided token is not corresponding to given user.
case FORBIDDEN = 403
/// Quiz with provided quiz id does not exist.
case NOT_FOUND = 404
/// Sent request is of illegal format.
case BAD_REQUEST = 400
/// Success.
case OK = 200
}
/// Class which provides posting quiz results on server.
class ResultService {
/// `String` representation of *URL* source for posting results.
private static let postResultsStringUrl: String = "https://iosquiz.herokuapp.com/api/result"
/// `String` representation of *URL* source for fetching results.
private static let fetchResultsStringUrl: String = "https://iosquiz.herokuapp.com/api/score"
/// Single `ResultService` instance.
static let shared: ResultService = ResultService()
private init() {}
/**
Posts quiz results on server with *URL* address represented with default *stringUrl*.
- Parameters:
- quizId: id for which quiz results are being posted
- time: total quiz solving time
- noOfCorrect: number of correctly answered questions
- onComplete: action which will be executed once post is finished
*/
func postQuizResults(quizId: Int, time: Double, noOfCorrect: Int, onComplete: @escaping ((HttpAnswer?) -> Void)) {
if let url = URL(string: ResultService.postResultsStringUrl) {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(
"application/json",
forHTTPHeaderField: "Content-Type"
)
request.setValue(
UserDefaults.standard.string(forKey: "token"),
forHTTPHeaderField: "Authorization"
)
let data: [String: Any] = [
"quiz_id": quizId,
"user_id": UserDefaults.standard.integer(forKey: "userId"),
"time": time,
"no_of_correct": noOfCorrect
]
request.httpBody = try? JSONSerialization.data(
withJSONObject: data,
options: []
)
let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let httpResponse = response as? HTTPURLResponse {
onComplete(HttpAnswer(rawValue: httpResponse.statusCode))
} else {
onComplete(nil)
}
}
dataTask.resume()
} else {
onComplete(nil)
}
}
/**
Fetches quiz results from server.
- Parameters:
- quizId: quiz for which results are inquired
- onComplete: action which will be executed once fetch is finished
*/
func fetchResults(quizId: Int, onComplete: @escaping (([Score]?) -> Void)) {
var urlComponents = URLComponents(string: ResultService.fetchResultsStringUrl)
urlComponents?.queryItems = [
URLQueryItem(name: "quiz_id", value: String(quizId))
]
if let url = urlComponents?.url {
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue(
"application/json",
forHTTPHeaderField: "Content-Type"
)
request.setValue(
UserDefaults.standard.string(forKey: "token"),
forHTTPHeaderField: "Authorization"
)
let dataTask = URLSession.shared.dataTask(with: request) { [weak self] (data, response, error) in
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let scores = self?.parseData(json: json) {
onComplete(self?.getBestTwentyScores(scores: scores))
} else {
onComplete(nil)
}
} catch {
onComplete(nil)
}
} else {
onComplete(nil)
}
}
dataTask.resume()
} else {
onComplete(nil)
}
}
/**
Parses provided *json* object into an array of `Score` objects.
- Parameters:
- json: *json* representation of a `Score` array
- Returns: an array of `Score` objects if *json* can be interpreted as such,
`nil` otherwise
*/
private func parseData(json: Any) -> [Score]? {
guard let jsonDictionary = json as? [[String: Any]] else {
return nil
}
let decoder = JSONDecoder()
var scores = [Score]()
for score in jsonDictionary {
if let data = try? JSONSerialization.data(withJSONObject: score, options: []),
let decodedScore = try? decoder.decode(Score.self, from: data) {
scores.append(decodedScore)
}
}
return scores
}
/**
Returns new `Score` array with size of 20 with scores in descending order according
to *score* member.
- Parameters:
- scores: array which will be reduced to 20 sorted memebers
- Returns: reduced array of 20 best `Score` elements according to *score* member
*/
private func getBestTwentyScores(scores: [Score]) -> [Score] {
let sortedScores = scores.sorted { (firstScore, secondScore) -> Bool in
firstScore.score > secondScore.score
}
return Array(sortedScores.prefix(20))
}
}
| true
|
f98b36f69de6f03a2f642ab8c7ae6074819f6d3d
|
Swift
|
Krisloveless/daily-coding-challenges
|
/swift/Problem 193/Problem 193/Solution.swift
|
UTF-8
| 1,665
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
//
// Solution.swift
// Problem 193
//
// Created by sebastien FOCK CHOW THO on 2019-12-04.
// Copyright © 2019 sebastien FOCK CHOW THO. All rights reserved.
//
import Foundation
extension Array where Element == Int {
typealias TransactionState = (holdingStock: Bool, profits: Int)
func optimizeTransactions(withSellingFees: Int) -> Int {
let initialState: TransactionState = (false, 0)
let candidates = allTransactionPath(currentState: initialState, sellingFees: withSellingFees)
let sorted = candidates.sorted{ $0.profits > $1.profits }
return sorted.first?.profits ?? 0
}
func allTransactionPath(currentState: TransactionState, sellingFees: Int) -> [TransactionState] {
var result: [TransactionState] = []
if !currentState.holdingStock {
result.append(currentState)
for i in 0..<count {
let state: TransactionState = (!currentState.holdingStock, currentState.profits-self[i])
let futureTransactions = Array(suffix(count-i-1))
result.append(contentsOf: futureTransactions.allTransactionPath(currentState: state, sellingFees: sellingFees))
}
} else {
for i in 0..<count {
let state: TransactionState = (!currentState.holdingStock, currentState.profits+self[i]-sellingFees)
let futureTransactions = Array(suffix(count-i-1))
result.append(contentsOf: futureTransactions.allTransactionPath(currentState: state, sellingFees: sellingFees))
}
}
return result
}
}
| true
|
6c7c99ee73ee4d88e96bfdd735700e9d8d1ac50b
|
Swift
|
Olimpia1988/REVIEW-UI
|
/REVIEW-UI/ViewController.swift
|
UTF-8
| 1,775
| 2.921875
| 3
|
[] |
no_license
|
import UIKit
class ViewController: UIViewController {
var foodView = TableviewView()
var recepies = [MoreData]() {
didSet {
foodView.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
getUsData()
setDelegation()
addSubviews()
}
func setDelegation() {
foodView.tableView.delegate = self
foodView.tableView.dataSource = self
}
func getUsData() {
APIManager.manager.getData { (result) in
switch result {
case .failure(let error):
print(error)
case .success(let data):
self.recepies = data
}
}
}
func addSubviews() {
self.view.addSubview(foodView.tableView)
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recepies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "fooCell") as? RecepiesCell else { return UITableViewCell() }
var singleRecepie = recepies[indexPath.row]
cell.name.text = singleRecepie.recipe.label
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let singleRecepie = recepies[indexPath.row]
let detailedVC = DetailedViewController()
detailedVC.singleRecepie = singleRecepie
self.navigationController?.pushViewController(detailedVC, animated: true)
}
}
| true
|
d28e2c437378a2cd33ad6cf6aa331027a48bfd20
|
Swift
|
andynguyen-swdev/E.Z-Lean
|
/E.Z Lean/Screens/Tools/CircleTransition.swift
|
UTF-8
| 2,865
| 2.984375
| 3
|
[] |
no_license
|
import UIKit
import Utils
class CircularTransition: NSObject {
var startingPoint = CGPoint.zero
var circleColor = UIColor.white
var duration = 0.5 as Double
var circle: UIView!
enum CircularTransitionMode:Int {
case present, dismiss, pop
}
var transitionMode:CircularTransitionMode = .present
deinit {
print("Deinit-CircularTransition")
}
}
extension CircularTransition: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let fromView = transitionContext.view(forKey: .from)!
let toView = transitionContext.view(forKey: .to)!
let toVC = transitionContext.viewController(forKey: .to)!
toView.frame = transitionContext.finalFrame(for: toVC)
circle = UIView()
circle.backgroundColor = circleColor
let size = AppDelegate.instance.window!.frame.size
let radius = sqrt(size.width*size.width + size.height*size.height)
circle.frame.size = CGSize(width: radius*2, height: radius*2)
circle.layer.cornerRadius = radius
circle.center = startingPoint
if transitionMode == .present {
circle.transform = .init(scaleX: 17 / radius, y: 17 / radius)
let placeHolder = UIView(frame: toView.bounds)
placeHolder.alpha = 0.99
placeHolder.layer.mask = circle.layer
placeHolder.layer.addSublayer(toView.layer)
containerView.addSubview(placeHolder)
UIView.animate(withDuration: duration, animations: { [unowned self] in
self.circle.transform = .identity
placeHolder.alpha = 1
}, completion: { completed in
containerView.addSubview(toView)
transitionContext.completeTransition(completed)
})
}
else if transitionMode == .pop {
containerView.addSubview(toView)
containerView.sendSubview(toBack: toView)
fromView.layer.mask = circle.layer
fromView.alpha = 0.99
UIView.animate(withDuration: duration, animations: { [unowned self] in
fromView.alpha = 1
self.circle.transform = .init(scaleX: 17 / radius, y: 17 / radius)
}) { completed in
fromView.removeFromSuperview()
containerView.bringSubview(toFront: toView)
transitionContext.completeTransition(completed)
}
}
}
}
| true
|
dbc1baa151c428661088d9773a740d898bc3a4af
|
Swift
|
Nikita-IOS/Social-Network
|
/Social Network/Social Network/FriendsPhoto/Like.swift
|
UTF-8
| 739
| 3.09375
| 3
|
[] |
no_license
|
//
// Like.swift
// Social Network
//
// Created by Nikita Gras on 13.12.2020.
//
import UIKit
@IBDesignable class Like: UIButton {
@IBInspectable var filled: Bool = true
@IBInspectable var strokeWidth: CGFloat = 2.0
@IBInspectable var strokeColor: UIColor?
override func draw(_ rect: CGRect) {
let bezierPath = UIBezierPath(heartIn: self.bounds)
if self.strokeColor != nil {
self.strokeColor!.setStroke()
} else {
self.tintColor.setStroke()
}
bezierPath.lineWidth = self.strokeWidth
bezierPath.stroke()
if self.filled {
self.tintColor.setFill()
bezierPath.fill()
}
}
}
| true
|
2f861c184adeead4d3bf67aa3f8335cc04494a28
|
Swift
|
Darr758/Swift-Algorithms-and-Data-Structures
|
/Algorithms/LLAddTwoNumbers.playground/Contents.swift
|
UTF-8
| 1,055
| 3.796875
| 4
|
[
"MIT"
] |
permissive
|
//Add two numbers represented by a linked list.
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
let primary = ListNode(0)
var node:ListNode = primary
var leftNode = l1
var rightNode = l2
var leftVal = 0
var rightVal = 0
while let val = leftNode?.val {
leftNode = leftNode?.next
leftVal += val
guard leftNode != nil else { continue }
leftVal = leftVal * 10
}
while let val = rightNode?.val{
rightNode = rightNode?.next
rightVal += val
guard rightNode != nil else { continue }
rightVal = rightVal * 10
}
var finalVal = leftVal + rightVal
while(finalVal > 0){
node.next = ListNode(finalVal % 10)
finalVal = finalVal/10
node = node.next!
}
node = ListNode(finalVal)
return primary.next
}
| true
|
49d7e93b471d44afcb5de4525cabbd5629664cd3
|
Swift
|
AlperenAysel/Exercism-Swift
|
/accumulate/Sources/Accumulate/Accumulate.swift
|
UTF-8
| 267
| 2.890625
| 3
|
[] |
no_license
|
//Solution goes in Sources
extension Array {
func accumulate<U>(_ operation: (Element) -> U) -> Array<U> {
var collection = Array<U>()
for index in self {
collection.append(operation(index))
}
return collection
}
}
| true
|
a94ce4c0863f38479c00a886ab8723c2cf081456
|
Swift
|
DavidPerezP124/CuadrilateralUIView
|
/ShapeView.swift
|
UTF-8
| 2,645
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// ShapeView.swift
// UXtestApp
//
// Created by David Perez on 1/3/19.
// Copyright © 2019 David Perez P. All rights reserved.
//
import Foundation
//
// ShapeView.swift
// UI exp
//
// Created by David Perez on 9/19/18.
// Copyright © 2018 David Perez P. All rights reserved.
//
import UIKit
class ShapeView: UIView {
var shape: UIBezierPath!
var color: UIColor? {
didSet {
self.setNeedsDisplay()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .clear
self.layer.cornerRadius = 5
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
let maxX = rect.maxX
let maxY = rect.maxY
let midY = rect.midY
let maxX10 = maxX * 0.10
let maxX9 = maxX * 0.9
context.beginPath()
context.move(to: CGPoint(x: maxX10 , y: midY))
context.addCurve(to:
CGPoint(x: maxX * 0.12 ,y: maxY * 0.4),
control1: CGPoint(x: maxX10,y: maxY * 0.4),
control2: CGPoint(x: maxX10 ,y: maxY * 0.4)
)
context.addCurve(to:
CGPoint(x: maxX9 ,y: maxY * 0.2),
control1: CGPoint(x: maxX9 ,y: maxY * 0.2),
control2: CGPoint(x: maxX9 ,y: maxY * 0.1)
)
context.addCurve(to:
CGPoint(x: maxX9 ,y: maxY * 0.8),
control1: CGPoint(x: maxX9 ,y: maxY * 0.8),
control2: CGPoint(x: maxX9 ,y: maxY * 0.8)
)
context.addCurve(to:
CGPoint(x: maxX * 0.12 ,y: maxY * 0.6),
control1: CGPoint(x: maxX9,y: maxY * 0.95),
control2: CGPoint(x: maxX * 0.95 ,y: maxY * 0.9)
)
context.addCurve(to:
CGPoint(x: maxX10 ,y: midY),
control1: CGPoint(x: maxX10,y: maxY * 0.6),
control2: CGPoint(x: maxX10 ,y: maxY * 0.6)
)
context.closePath()
context.setFillColor((color?.cgColor)!)
context.fillPath()
}
}
| true
|
f957388d6cf08d2f34db47c736bb35ff1e5d1b2d
|
Swift
|
TitouanVanBelle/iRecorder
|
/iRecorder/main.swift
|
UTF-8
| 2,318
| 2.84375
| 3
|
[] |
no_license
|
//
// main.swift
// DeviceDetector
//
// Created by Titouan Van Belle on 08.02.18.
// Copyright © 2018 Titouan Van Belle. All rights reserved.
//
import Cocoa
import Foundation
// Command Line part
let cli = CommandLine()
let name = StringOption(shortFlag: "n", longFlag: "name", required: false, helpMessage: "Device Name.")
let id = StringOption(shortFlag: "i", longFlag: "id", required: false, helpMessage: "Device ID.")
let outFile = StringOption(shortFlag: "o", longFlag: "out", required: true, helpMessage: "Output File.")
let quality = StringOption(shortFlag: "q", longFlag: "quality", required: false, helpMessage: "Recording quality (low, medium, high - defaults to high)")
let list = BoolOption(shortFlag: "l", longFlag: "list", helpMessage: "List available capture devices.")
let force = BoolOption(shortFlag: "f", longFlag: "force", helpMessage: "Overwrite existing file.")
let help = BoolOption(shortFlag: "h", longFlag: "help", helpMessage: "Prints a help message.")
cli.addOptions(name, id, outFile, quality, list, force, help)
let (success, error) = cli.parse()
if !success {
print(error!)
cli.printUsage()
exit(EX_USAGE)
}
// Command Line part is done
// Conditions are met to start recording
var outValue = outFile.value!
var forceValue = force.value
var settings: RecordSettings
var recordQuality: RecordQuality = .high
if let qualityValue = quality.value {
if let q = RecordQuality(rawValue: qualityValue) {
recordQuality = q
}
}
if let deviceName = name.value {
settings = RecordSettings(quality: recordQuality, deviceName: deviceName, output: outValue, force: forceValue)
} else if let deviceId = id.value {
settings = RecordSettings(quality: recordQuality, deviceId: deviceId, output: outValue, force: forceValue)
} else {
cli.printUsage()
exit(EX_USAGE)
}
let recorder = Recorder()
Trap.handle(.interrupt) { (code) -> (Void) in
print("Interrupt")
recorder.stopRecording()
}
Trap.handle(.abort) { (code) -> (Void) in
print("Abort")
recorder.stopRecording()
}
Trap.handle(.termination) { (code) -> (Void) in
print("Termination")
recorder.stopRecording()
}
Trap.handle(.kill) { (code) -> (Void) in
print("Kill")
recorder.stopRecording()
}
recorder.startRecording(settings: settings)
RunLoop.main.run()
| true
|
6679e4a7f233ff1b1a91f59ca06c6860bc3b0cfc
|
Swift
|
noushad-clickapps/Coding-Test
|
/Coding-Test/CustomCells/CountryCell.swift
|
UTF-8
| 5,678
| 2.921875
| 3
|
[] |
no_license
|
//
// CountryCell.swift
// Coding-Test
//
// Created by Noushad on 8/24/18.
// Copyright © 2018 Noushad. All rights reserved.
//
import UIKit
protocol CountryCellDelegate {
func rowDeletedFor(cell:CountryCell)
func updateCountryViewModel(_ viewModel:CountryViewModel, forCell cell:CountryCell)
func userStartsSwipingFor(cell:CountryCell)
}
class CountryCell: UITableViewCell {
let deleteIconAnchorPoint = 100.0
//frontView: Showing the text fetched from API
@IBOutlet weak var frontView: UIView!
//backView: Used for displaying the bomb icon and placing purple color as per the requirment
@IBOutlet weak var backView: UIView!
//Contraints IBOuletes for both leading and traling so that we can move the frontView as user moves his finger or tries to swipe
@IBOutlet weak var frontViewTLC: NSLayoutConstraint!
@IBOutlet weak var frontViewLC : NSLayoutConstraint!
@IBOutlet weak var lblCountryName: UILabel!
@IBOutlet weak var lblCountryCurrency: UILabel!
@IBOutlet weak var lblCountryLanguage: UILabel!
//required to determine the distance user swiped from right to left
var panStartpoint:CGPoint?
var currentPoint:CGPoint?
var delta = 0.0
var delegate:CountryCellDelegate?
//Setting countriesViewModel property, gets called whenever this property assigned a value and set the text to CountryCell UILabel's
var countriesViewModel : CountryViewModel! {
didSet {
lblCountryName.text = countriesViewModel.name
lblCountryCurrency.text = "Currency: \(countriesViewModel.currency)"
lblCountryLanguage.text = "Language: \(countriesViewModel.language)"
}
}
//Adding pangesture so that we can show the puple view as user moves his finger to left of the screen
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
backView.backgroundColor = UIColor.purple
self.selectionStyle = .none
let pangesture = UIPanGestureRecognizer(target: self, action: #selector(panGestureTriggered(_ :)))
pangesture.delegate = self
self.addGestureRecognizer(pangesture)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
//MARK:- panGestureTriggered
//Detecting the distance user's finger travelled on the cell and with what speed, on basis of that showing and hiding the bomb icon and deleteing the cells
@objc func panGestureTriggered(_ gesture: UIPanGestureRecognizer) {
switch gesture.state {
case UIGestureRecognizerState.began:
//self.panStartPoint = [recognizer translationInView:self.myContentView];
panStartpoint = gesture.translation(in: self)
self.delegate?.userStartsSwipingFor(cell: self)
break
case UIGestureRecognizerState.changed:
currentPoint = gesture.translation(in: self)
delta = Double((panStartpoint?.x)! - currentPoint!.x)
if delta > 0 {
frontViewTLC.constant = CGFloat(delta)
frontViewLC.constant = CGFloat(-delta)
UIView.animate(withDuration: 0.5, animations: {
self.layoutIfNeeded()
})
}
break
case UIGestureRecognizerState.ended:
let swipeVelocity = gesture.velocity(in: self).x
if delta > deleteIconAnchorPoint {
if swipeVelocity < -500 {
// we have fast swipe delete entire row
print("delete row")
self.delegate?.rowDeletedFor(cell: self)
} else {
//we passed anchor point and velocity is slow so only show the bomb icon
countriesViewModel.isBombIconVisible = true
self.delegate?.updateCountryViewModel(countriesViewModel, forCell: self)
setConstantForConstraints(value: CGFloat(deleteIconAnchorPoint), animated: true)
UIView.animate(withDuration: 0.5, animations: {
self.layoutIfNeeded()
})
}
} else {
// we are beyond delta point
if swipeVelocity > -500 {
//speed is slow so cancel the swipe action
countriesViewModel.isBombIconVisible = false
self.delegate?.updateCountryViewModel(countriesViewModel, forCell: self)
setConstantForConstraints(value: 0, animated: true)
}
}
break
case UIGestureRecognizerState.cancelled:
break
default:
break
}
}
//MARK:- gestureRecognizer
// required so that our cell and UITableView recognize other gesture's too
override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
//MARK:- setConstantForConstraints
//setting the frontView leading and trailing constriant value with or without animation
func setConstantForConstraints(value:CGFloat, animated:Bool) {
frontViewTLC.constant = CGFloat(value)
frontViewLC.constant = CGFloat(-value)
if animated {
UIView.animate(withDuration: 0.5, animations: {
self.layoutIfNeeded()
})
}
}
}
| true
|
137dd2dcab50094d3049c67ea2ee28ef1808d474
|
Swift
|
Tian-0v0/ZTShow
|
/ZTShow/ZTShow/ZTShowContentView/ZTToast/ZTTextToastView.swift
|
UTF-8
| 816
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// ZTTextToastView.swift
// ZTShow
//
// Created by zhangtian on 2021/6/5.
//
import UIKit
class ZTTextToastView: ZTBaseToastView {
lazy var textLabel: UILabel = {
let l = UILabel()
l.textColor = ZTToastPodfile.tintColor
l.numberOfLines = 0
l.textAlignment = ZTToastPodfile.textAlignment
return l
}()
override func appendUI() {
self.addSubview(textLabel)
}
override func layoutUI() {
textLabel.snp.makeConstraints { (make) in
make.width.lessThanOrEqualTo(220)
make.left.equalTo(5)
make.right.equalTo(-5)
make.top.equalTo(3)
make.bottom.equalTo(-3)
}
}
convenience init(msg: String) {
self.init()
self.textLabel.text = msg
}
}
| true
|
1c1dce6886665ab1a76d65b02fcc84e798c8f461
|
Swift
|
rama25/Video-Claassifciation-Based-on-text
|
/YoutubeApp/YoutubeApp/VideoDetailViewController.swift
|
UTF-8
| 2,583
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// VideoDetailViewController.swift
// YoutubeApp
//
// Created by Ramapriya Ranganath on 6/26/17.
// Copyright © 2017 Ramapriya Ranganath. All rights reserved.
//
import UIKit
class VideoDetailViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
var selectedVideo:Video?
@IBOutlet weak var webViewHeightConstraint: NSLayoutConstraint!
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.
}
override func viewDidAppear(_ animated: Bool) {
if let vid = self.selectedVideo{
self.titleLabel.text = vid.videoTitle
self.descriptionLabel.text = vid.videoDescription
let width = self.view.frame.size.width
let height = width/320 * 180
self.webViewHeightConstraint.constant = height
//let videoEmbedString = "<html><head><style type=\"text/css\">body {background-color: transparent;color: white;}</style></head><body style=\"margin:0\"><iframe frameBorder=\"0\" height=\"" + String(describing: height) + "\" width=\"" + String(describing: width) + "\" src=\"http://www.youtube.com/embed/" + vid.videoId + "?showinfo=0&modestbranding=1&frameborder=0&rel=0\"></iframe></body></html>"
let videoEmbedString = "<html><head><style type=\"text/css\">body {background-color: transparent;color: white;}</style></head><body style=\"margin:0\"><iframe frameBorder=\"0\" height=\"" + String(describing: height) + "\" width=\"" + String(describing: width) + "\" src=\"https://www.youtube.com/embed/?listType=playlist&list=" + String(vid.videoId) + "&modestbranding=1&frameborder=0&rel=0\"></iframe></body></html>"
self.webView.loadHTMLString(videoEmbedString, baseURL: nil)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
9ab3212d46481ca996f19dba1b0ff1a59d5fd885
|
Swift
|
niendo/FintechDemo
|
/FintechDemo/Commons/Network/ServiceConnectionHelper.swift
|
UTF-8
| 3,567
| 2.734375
| 3
|
[] |
no_license
|
//
// ServiceConnectionHelper.swift
// FintechDemo
//
// Created by Eduardo Nieto on 03/02/2019.
// Copyright © 2019 Eduardo Nieto. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
typealias ServiceHandler = (_ response: NetworkResponse?, _ error: Error?) -> Void
public class ServiceConnectionHelper {
private var serviceHandler: ServiceHandler?
let userHeaders: [String: String] = {
return [
"content-type": "application/json",
"cache-control": "no-cache",
"Accept": "application/json;charset=UTF-8",
"Accept-Language": "es"
]
}()
}
extension ServiceConnectionHelper {
func makePetition(urlString: String, method: String, headers: [String: String]?, params: [String: AnyObject?]?, handle: @escaping ServiceHandler) {
var newHeaders = headers
if newHeaders == nil {
newHeaders = userHeaders
}
let url = URL(string: urlString)!
var request = URLRequest(url: url)
print("request url \(url)")
print("params \(String(describing: params))")
print("headers \(String(describing: newHeaders)))")
print("method \(method)")
request.allHTTPHeaderFields = newHeaders
request.httpMethod = method
var newParams: [String: AnyObject] = [:]
if params != nil {
for param in params! where param.value != nil {
print("not null \(param)")
newParams[param.key] = param.value
}
request.httpBody = try? JSONSerialization.data(withJSONObject: newParams, options: [])
}
request.timeoutInterval = 300
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "HH:mm:ss"
Alamofire.request(request).responseJSON { response in
if let requestBody = request.httpBody {
do {
let jsonArray = try JSONSerialization.jsonObject(with: requestBody, options: [])
print("Array: \(jsonArray)")
}
catch {
print("Error: \(error)")
}
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
if utf8Text.contains("<body>") {
let text1 = utf8Text.components(separatedBy: "<body>")
let text2 = text1[1].components(separatedBy: "</body>")
print("Data: \(text2[0])")
} else {
print("Data: \(utf8Text)")
}
}
print("RESPONSE CODE: \(response.response?.statusCode ?? 0)")
let error: Error? = response.error
var networkResponse: NetworkResponse?
if response.response != nil {
if let responseCode = response.response?.statusCode {
if responseCode == 200 {
networkResponse = NetworkResponse()
networkResponse?.responseCode = response.response?.statusCode
networkResponse?.response = response.result.value as AnyObject
}
}
}
handle(networkResponse,error)
}
}
}
| true
|
b3c7f5d37ea886aee7c719055d6ffad6630439bd
|
Swift
|
lmdragun/MOB-DC-04
|
/Classwork/Lesson04/Class04.playground/Contents.swift
|
UTF-8
| 1,303
| 4.34375
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var name: String?
let age = 45
name = "Lindsey"
//if name != nil {
// print("your name is \(name!)")
//}else {
// print("I don't know your name yet")
//}
if let myname = name {
print("Your name is \(myname)")
}
name
age
func sayHello() {
print("hello world")
print("Running function")
}
sayHello()
func sayHelloName(name: String) {
print("hello \(name)")
}
sayHelloName("Lindsey")
func sayHelloNameAndLastName(first: String, last: String) {
print("hello, \(first + last)")
}
sayHelloNameAndLastName("Lindsey", last: "Dragun")
func findAreaOfSquare(width: Int, height: Int) {
print("The area is \(width + height)")
}
findAreaOfSquare(5, height: 10)
func findAreaOfTriangle(base: Float, height: Float) {
print("The area is \(0.5 * base * height)")
}
findAreaOfTriangle(16, height: 3)
func getArea(width: Double, height: Double) -> Double {
let area: Double = width * height
return area
}
func displayArea(area: Double) {
print("The area is \(area)")
}
//var mySquare = getArea(12, height: 12)
//displayArea(mySquare)
displayArea(getArea(23, height: 12))
func functionThatJustReturnsSomething() -> String {
return "Returns a String"
}
| true
|
3af07723af55988702b959c5c0c2a232efd70d94
|
Swift
|
Mesterduc/cocktails-swiftui
|
/cocktails/View/Search/SearchView.swift
|
UTF-8
| 4,232
| 2.828125
| 3
|
[] |
no_license
|
//
// SearchView.swift
// cocktails
//
// Created by Duc hong cai on 20/07/2021.
//
import SwiftUI
import SDWebImageSwiftUI
struct SearchView_Previews: PreviewProvider {
static var previews: some View {
SearchView()
}
}
struct SearchView: View {
@StateObject var viewModel = SearchViewModel()
@State private var clearButton = false
@State private var hidden = false
@State private var cocktailName: String = ""
var body: some View {
VStack(alignment: .leading){
//search field
VStack(alignment: .leading){
Text("Inserted cocktail name: \(self.cocktailName)")
HStack{
Image(systemName: "magnifyingglass")
.padding()
.foregroundColor(.black.opacity(0.4))
TextField("Cocktail name....", text: self.$cocktailName)
.onChange(of: self.cocktailName, perform: { value in
if !self.cocktailName.isEmpty {
self.clearButton = true
}
viewModel.fetchCocktailList(drink: self.cocktailName)
})
Button(action:
{
self.cocktailName = ""
self.clearButton = false
})
{
Text("Clear")
}
.padding(.trailing, 8)
.opacity(clearButton ? 1 : 0)
.animation(.easeInOut)
}
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.black.opacity(0.4), lineWidth: 2)
)
}
// results
VStack(alignment:.center){
Text("Cocktails")
.font(.title.bold())
}
// ForEach(viewModel.cocktailList, id:\.idDrink) { cocktail in
// Text(cocktail.strDrink)
// }
ScrollView(.vertical){
VStack(alignment: .leading){
ForEach(viewModel.cocktailList, id:\.self){ drink in
NavigationLink(
destination: CocktailView(item: drink),
label: {
HStack(spacing: 15){
WebImage(url: URL(string: "\(drink.strDrinkThumb)"))
.resizable()
.frame(width: 60, height: 60)
.cornerRadius(10)
.shadow(radius: 5)
VStack(alignment: .leading, spacing: 5){
Text(drink.strDrink)
.font(.headline)
Text(drink.strCategory)
.font(.subheadline)
}
}
.padding(.horizontal, 10)
.foregroundColor(.black)
.opacity(0.8)
})
}
.opacity(hidden ? 1 : 0)
.animation(.linear)
}
}
.onChange(of: cocktailName, perform: { value in
withAnimation(.easeInOut(duration: 2)){
self.hidden = true
}
})
.onAppear(perform: {
withAnimation(.easeInOut(duration: 2)){
self.hidden = true
}
})
Spacer()
}
.padding(.horizontal, 10)
.navigationTitle("Find Cocktail")
}
}
extension UIApplication {
func endEditing() {
sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
| true
|
f9e798056a95395bc2bc9a287bcddb7a3236ec45
|
Swift
|
oldster189/clean_swift
|
/miniTopgun/CreateSkillOtherInteractor.swift
|
UTF-8
| 2,477
| 2.546875
| 3
|
[] |
no_license
|
//
// CreateSkillOtherInteractor.swift
// miniTopgun
//
// Created by itthipon wiwatthanasathit on 7/30/2560 BE.
// Copyright (c) 2560 Izpal. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
protocol CreateSkillOtherBusinessLogic
{
var skillOtherEditDict:SkillOtherData? { get set }
func createSkillOther(request: CreateSkillOther.Create.Request)
func updateSkillOther(request: CreateSkillOther.Update.Request)
func fetchLevelSkill(requst: CreateSkillOther.MDLevelSkill.Request)
func showSkillOtherToEdit(request: CreateSkillOther.Edit.Request)
}
protocol CreateSkillOtherDataStore
{
//var name: String { get set }
var skillOtherEditDict:SkillOtherData? { get set }
}
class CreateSkillOtherInteractor: CreateSkillOtherBusinessLogic, CreateSkillOtherDataStore
{
var presenter: CreateSkillOtherPresentationLogic?
var worker: CreateSkillOtherWorker?
var skillOtherEditDict:SkillOtherData?
// MARK: Do something
func createSkillOther(request: CreateSkillOther.Create.Request)
{
worker = CreateSkillOtherWorker()
worker?.createSkillOther(request: request, completion: { (list) in
let response = CreateSkillOther.Create.Response(SkillOtherList: list)
self.presenter?.presentCreateSkillOther(response: response)
})
}
func updateSkillOther(request: CreateSkillOther.Update.Request)
{
worker = CreateSkillOtherWorker()
worker?.updateSkillOther(request: request, completion: { (list) in
let response = CreateSkillOther.Update.Response(SkillOtherList: list)
self.presenter?.presentUpdateSkillOther(response: response)
})
}
func showSkillOtherToEdit(request: CreateSkillOther.Edit.Request){
if let dict = skillOtherEditDict {
let response = CreateSkillOther.Edit.Response(SkillOtherList: dict)
self.presenter?.presentSkillOtherToEdit(response: response)
}
}
func fetchLevelSkill(requst: CreateSkillOther.MDLevelSkill.Request){
worker = CreateSkillOtherWorker()
worker?.fetchLevelSkill(completion: { (list) in
let response = CreateSkillOther.MDLevelSkill.Response(LevelSkillList: list)
self.presenter?.presentLevelSkill(response: response)
})
}
}
| true
|
c7bcdd3fa8727991b3009fd835b9ef26471671f2
|
Swift
|
mfutami/Diary
|
/Diary/Diary/Model/WebView/WebView.swift
|
UTF-8
| 630
| 2.734375
| 3
|
[] |
no_license
|
//
// WebView.swift
// Diary
//
// Created by futami on 2019/11/21.
// Copyright © 2019年 futami. All rights reserved.
//
import UIKit
struct WebView {
static func presentWebView(_ urlString: String?) -> UIViewController? {
let storyboard = UIStoryboard(name: "WebView", bundle: nil)
guard let webView = storyboard.instantiateInitialViewController() else { return nil }
if let navigation = webView as? UINavigationController,
let webBrowser = navigation.topViewController as? WebViewController {
webBrowser.urlString = urlString
}
return webView
}
}
| true
|
52ef68a2d4b0ffe1722d5bd3a7901031be2f85aa
|
Swift
|
leotaoo/TRSegment
|
/TRSegment/Core/TRSegmentBuilder.swift
|
UTF-8
| 1,317
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// TRSegmentBuilder.swift
// TRSegment
//
// Created by leotao on 2020/9/20.
//
import UIKit
class TRSegmentBuilder {
private var titles: [String] = []
private var config: TRSegment.Config? = nil
private var selectedIndex: UInt = 0
private var childVCs: [UIViewController] = []
private var parentVC: UIViewController?
func set(titles: [String]) -> Self {
self.titles = titles
return self
}
func set(config: TRSegment.Config) -> Self {
self.config = config
return self
}
func set(childVCs: [UIViewController]) -> Self {
self.childVCs = childVCs
return self
}
func set(selectedIndex: UInt) -> Self {
self.selectedIndex = selectedIndex
return self
}
func set(parentVC: UIViewController) -> Self {
self.parentVC = parentVC
return self
}
func build() -> TRSegmentBinder {
let segment = TRSegment(titles: self.titles, selectedIndex: self.selectedIndex, config: self.config)
let content = TRSegmentContentView(parentVC: self.parentVC, childVCs: self.childVCs)
let binder = TRSegmentBinder(segment: segment, content: content)
return binder
}
}
| true
|
500e9506942cb0c2f768c7b231aaae496ed9404f
|
Swift
|
ChristopherStanley14/EFAB
|
/Models/User.swift
|
UTF-8
| 2,396
| 2.796875
| 3
|
[] |
no_license
|
//
// User.swift
// EFAB
//
// Created by TEKYAdmin on 11/2/16.
// Copyright © 2016 EFA. All rights reserved.
//
//
// Test.swift
// EFAB
//
// Created by Terrence Kunstek on 10/31/16.
// Copyright © 2016 EFA. All rights reserved.
//
import Foundation
import Alamofire
import Freddy
// Just a test object to excercise the network stack
class User : NetworkModel {
/*
"username": "string",
"password": "string",
"email": "string"
"token": "string",
"expiration": "2016-11-01T20:58:52.318Z"
*/
var id : Int?
var username : String?
var password : String?
var email : String?
var token : String?
var expiration : String?
// Request Type
enum RequestType {
case login
case register
}
var requestType = RequestType.login
// empty constructor
required init() {}
// create an object from JSON
required init(json: JSON) throws {
token = try? json.getString(at: Constants.BudgetUser.token)
expiration = try? json.getString(at: Constants.BudgetUser.expirationDate)
}
init(username: String, password: String) {
self.username = username
self.password = password
requestType = .login
}
init(username: String, password: String, email: String) {
self.username = username
self.password = password
self.email = email
requestType = .register
}
init(id: Int) {
self.id = id
}
// Always return HTTP.GET
func method() -> Alamofire.HTTPMethod {
return .post
}
// A sample path to a single post
func path() -> String {
switch requestType {
case .login:
return "/auth"
case .register:
return "/register"
}
}
// Demo object isn't being posted to a server, so just return nil
func toDictionary() -> [String: AnyObject]? {
var params: [String: AnyObject] = [:]
params[Constants.BudgetUser.username] = username as AnyObject?
params[Constants.BudgetUser.password] = password as AnyObject?
switch requestType {
case .register:
params[Constants.BudgetUser.email] = email as AnyObject?
default:
break
}
return params
}
}
| true
|
6d10aa54c6e10fa84335f03d1695fdc6ddf902c6
|
Swift
|
Robert174/Uvel
|
/uvel/Audit/sourse/Models/inMemory/Product.swift
|
UTF-8
| 565
| 2.921875
| 3
|
[] |
no_license
|
//
// Product.swift
// uvel
//
// Created by Роберт Райсих on 26/07/2019.
// Copyright © 2019 Роберт Райсих. All rights reserved.
//
import Foundation
class Product: Decodable {
var productName: String?
var opened: Bool = false
var switchOn: Bool = false
enum CodingKeys: String, CodingKey {
case productName
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.productName = try? container.decode(String.self, forKey: .productName)
}
}
| true
|
696335df0a5e344ee5e5298aaa92ffd92e1944e3
|
Swift
|
liamdkane/AC3.2-Unit3FinalAssessment
|
/Unit3FinalAssessment/Unit3FinalAssessment/MuseumObject.swift
|
UTF-8
| 4,213
| 2.59375
| 3
|
[] |
no_license
|
//
// MuseumObject.swift
// Unit3FinalAssessment
//
// Created by C4Q on 11/10/16.
// Copyright © 2016 C4Q. All rights reserved.
//
import Foundation
class MuseumObject {
let title: String
let image: String
let thumbImage: String
let description: String
let subtitle: String
init (title: String, image: String, thumbImage: String, description: String, subtitle: String) {
self.description = description
self.image = image
self.subtitle = subtitle
self.thumbImage = thumbImage
self.title = title
}
/*
"pk": 8757,
"model": "collection.museumobject",
"fields": {
"primary_image_id": "2006AM3589",
"rights": 3,
"year_start": 1595,
"object_number": "O77755",
"artist": "Unknown",
"museum_number": "851-1871",
"object": "Gimmel ring",
"longitude": "10.45424000",
"last_processed": "2016-10-28 19:04:41",
"event_text": "",
"place": "Germany",
"location": "British Galleries, room 58c, case 5",
"last_checked": "2016-10-28 19:04:41",
"museum_number_token": "8511871",
"latitude": "51.09083900",
"title": "",
"date_text": "ca.1600 (made)",
"slug": "gimmel-ring-unknown",
"sys_updated": "2015-03-02 00:00:00",
"collection_code": "MET"
}
*/
convenience init? (record: [String: Any]) {
guard let dict = record["fields"] as? [String: AnyObject] else {
print("dict failed")
return nil
}
guard let subtitle = dict["title"] as? String else {
print("subtitle failed")
return nil
}
guard let imageIDPrimary = dict["primary_image_id"] as? String else {
print("imageID failed")
return nil
}
guard let object = dict["object"] as? String else {
print("object failed")
return nil
}
guard let date = dict["date_text"] as? String else {
print("date failed")
return nil
}
guard let place = dict["place"] as? String else {
print("place failed")
return nil
}
guard let objectNumber = dict["object_number"] as? String else {
print("objectNumber failed")
return nil
}
let description = "http://www.vam.ac.uk/api/json/museumobject/\(objectNumber)"
let title = "\(object) from: \(date) located: \(place)"
var image = ""
var thumbImage = ""
if imageIDPrimary.characters.count > 6 {
let imageIDRange = imageIDPrimary.index(imageIDPrimary.startIndex, offsetBy: 6)..<imageIDPrimary.endIndex
let imageID = imageIDPrimary.replacingCharacters(in: imageIDRange, with: "")
image = "http://media.vam.ac.uk/media/thira/collection_images/\(imageID)/\(imageIDPrimary).jpg"
thumbImage = "http://media.vam.ac.uk/media/thira/collection_images/\(imageID)/\(imageIDPrimary)_jpg_o.jpg"
}
self.init(title: title, image: image, thumbImage: thumbImage, description: description, subtitle: subtitle)
}
static func parseData (data: Data) -> [MuseumObject]? {
var objects = [MuseumObject]()
do {
let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
guard let dict = jsonObject as? [String: AnyObject] else {
print("dict failed")
return nil
}
guard let records = dict["records"] as? [[String:AnyObject]] else {
print("records failed")
return nil
}
for record in records {
guard let object = MuseumObject(record: record) else {
print("object failed")
return nil
}
objects.append(object)
}
}
catch {
print(error)
}
return objects
}
}
| true
|
8026cefd92157d7377f68b4ae32d7cf6dc3c3358
|
Swift
|
wishWinds/googlemapdemo
|
/GoogleMapDemoSwift/UNUserNotificationCenterExt.swift
|
UTF-8
| 599
| 2.53125
| 3
|
[] |
no_license
|
//
// UNUserNotificationCenterExt.swift
// GoogleMapDemoSwift
//
// Created by shupeng on 2020/11/12.
//
import Foundation
import UserNotifications
extension UNUserNotificationCenter {
func pushNotitfication(with title: String, body: String) {
let notiContent = UNMutableNotificationContent()
notiContent.title = title
notiContent.body = body
notiContent.sound = .default
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notiContent, trigger: nil)
add(request, withCompletionHandler: nil)
}
}
| true
|
fc0b634927b7f4b22325da8d54c641dcfc7a3231
|
Swift
|
koromiko/GithubChat
|
/GithubChat/GithubChat/Helper/UIView+Autolayout.swift
|
UTF-8
| 2,022
| 2.84375
| 3
|
[] |
no_license
|
//
// UIView+Autolayout.swift
// GithubChat
//
// Created by Neo on 2019/1/28.
// Copyright © 2019 STH. All rights reserved.
//
import UIKit
import ObjectiveC
extension UIView {
/// generate constraints to superview with given padding setting. Returned constraints are not activated. Given no padding infers to fully snap to superview without padding.
func constraints(snapTo superview: UIView, top: CGFloat? = nil, left: CGFloat? = nil, bottom: CGFloat? = nil, right: CGFloat? = nil) -> [NSLayoutConstraint] {
var constraints: [NSLayoutConstraint] = []
var (topConstant, leftConstant, bottomConstant, rightConstant) = (top, left, bottom, right)
if top == nil && left == nil && bottom == nil && right == nil {
topConstant = 0.0
leftConstant = 0.0
bottomConstant = 0.0
rightConstant = 0.0
}
if let top = topConstant {
constraints.append(self.topAnchor.constraint(equalTo: superview.topAnchor, constant: top))
}
if let left = leftConstant {
constraints.append(self.leftAnchor.constraint(equalTo: superview.leftAnchor, constant: left))
}
if let bottom = bottomConstant {
constraints.append(self.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: -bottom))
}
if let right = rightConstant {
constraints.append(self.rightAnchor.constraint(equalTo: superview.rightAnchor, constant: -right))
}
return constraints
}
/// Return width/height constraints
func constraints(width: CGFloat? = nil, height: CGFloat? = nil) -> [NSLayoutConstraint] {
var constraints: [NSLayoutConstraint] = []
if let width = width {
constraints.append(self.widthAnchor.constraint(equalToConstant: width))
}
if let height = height {
constraints.append(self.heightAnchor.constraint(equalToConstant: height))
}
return constraints
}
}
| true
|
2de528334ad15904b92b1e9610d0f8996902408f
|
Swift
|
maximepeschard/Blues
|
/Sources/Blues/Commands/Alias.swift
|
UTF-8
| 928
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
import SwiftCLI
class SetAliasCommand: Command {
let name = "set"
let shortDescription = "Set an alias for a device"
let alias = Parameter()
let address = Parameter()
func execute() throws {
BluesConfig.shared.setAlias(alias.value, forAddress: address.value)
printMessage("Set alias '\(alias.value)' for device with address \(address.value)", withLevel: Level.SUCCESS)
}
}
class UnsetAliasCommand: Command {
let name = "unset"
let shortDescription = "Unset an alias"
let alias = Parameter()
func execute() throws {
if BluesConfig.shared.unsetAlias(alias.value) != nil {
printMessage("Unset alias '\(alias.value)'", withLevel: Level.SUCCESS)
}
}
}
class AliasGroup: CommandGroup {
let name = "alias"
let shortDescription = "Manage aliases for devices"
let children: [Routable] = [SetAliasCommand(), UnsetAliasCommand()]
}
| true
|
7747090b9b6c1877d268f8162a5cdc108124d1a2
|
Swift
|
abdorahmanmahmoudd/Odiggo
|
/odiggo/Source/Network/API+NetworkRepository.swift
|
UTF-8
| 3,825
| 2.984375
| 3
|
[] |
no_license
|
//
// API+NetworkRepository.swift
// odiggo
//
// Created by Abdelrahman Ali on 01/01/2021.
//
import Foundation
import RxSwift
/// A protocol to group all of our app repositories so we have single and central dependency for network requests across the app.
protocol NetworkRepository {
var authenticationRepository: AuthenticationRepository { get }
}
// MARK: - API shared client
class API: NetworkRepository {
/// Environment types
enum Environment {
case production
}
/// CachePolicy
var cachePolicy: URLRequest.CachePolicy {
return .reloadIgnoringLocalCacheData
}
/// Shared `URLSession`
let sharedSession = URLSession.shared
/// Returns the base URL of the given type
///
/// - Parameter env: the base URL envrionment
/// - Returns: the URL string
func baseUrl(of environment: Environment) -> String {
switch environment {
case .production:
return "https://www.odiggo.com.eg"
}
}
}
// MARK: - API+NetworkRepository
extension API {
var authenticationRepository: AuthenticationRepository {
return AuthenticationAPI()
}
}
// MARK: API+Request
extension API {
/// Helper method to construct the URL Request
func request(fullUrl: String, method: HTTPMethod = .post, parameters: [String: String?] = [:]) -> URLRequest? {
let urlString = fullUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
guard let urlStringUnwrapped = urlString, var urlComponents = URLComponents(string: urlStringUnwrapped) else {
return nil
}
urlComponents.setQueryItems(parameters: parameters)
guard let url = urlComponents.url else {
return nil
}
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
if method == .post {
request.httpBody = urlComponents.percentEncodedQuery?.data(using: .utf8)
}
// if let accessToken = accessToken {
// request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
// }
return request
}
}
// MARK: - API+Response
extension API {
/// Helper method to trigger the API call and parse the response
func response<T>(for request: URLRequest) -> Single<T> where T: Decodable {
return Single<T>.create { (single) -> Disposable in
let task = self.sharedSession.dataTask(with: request) { data, response, error in
/// Validate Response
guard let response = response, let data = data else {
single(.error(error ?? APIError.unknown))
return
}
guard let httpResponse = response as? HTTPURLResponse else {
single(.error(APIError.nonHTTPResponse))
return
}
guard (200 ..< 300) ~= httpResponse.statusCode, error == nil else {
return single(.error(APIError.networkError(httpResponse.statusCode)))
}
/// Decode data into a model
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
do {
let model = try decoder.decode(T.self, from: data)
single(.success(model))
} catch {
single(.error(APIError.decodingError(error)))
}
}
task.resume()
return Disposables.create {
task.cancel()
}
}
}
}
| true
|
63486f03273dbf2a1e69afaf0dbd2122cbdcc065
|
Swift
|
ChristianHurtado29/TeamBite
|
/TeamBite/FirebaseManager/AuthenticationSessions.swift
|
UTF-8
| 1,620
| 2.75
| 3
|
[] |
no_license
|
//
// AuthenticationSessions.swift
// TeamBite
//
// Created by Christian Hurtado on 4/20/20.
// Copyright © 2020 Christian Hurtado. All rights reserved.
//
import UIKit
import FirebaseAuth
class FirebaseAuthManager{
static let shared = FirebaseAuthManager()
private var authRef = Auth.auth()
private init() {}
public func signInWithEmail(_ email: String, _ password: String, completion: @escaping (Result<AuthDataResult,Error>) -> ()){
authRef.signIn(withEmail: email, password: password) { (dataResult, error) in
if let error = error {
completion(.failure(error))
} else if let dataResult = dataResult {
completion(.success(dataResult))
}
}
}
public func createNewAccountWithEmail(_ email: String, _ password: String, completion: @escaping (Result<AuthDataResult,Error>) -> ()){
authRef.createUser(withEmail: email, password: password) { (dataResult, error) in
if let error = error {
completion(.failure(error))
} else if let dataResult = dataResult {
completion(.success(dataResult))
}
}
}
public func signInWith(credential: PhoneAuthCredential, completion: @escaping (Result<AuthDataResult,Error>) -> ()){
authRef.signIn(with: credential) { (authResult, error) in
if let error = error {
completion(.failure(error))
} else if let authResult = authResult {
completion(.success(authResult))
}
}
}
}
| true
|
e486294ae25223a0c442ce4528d2c025e9fc97d7
|
Swift
|
osa212/travelExpenses
|
/travelExpenses/Helpers/Box.swift
|
UTF-8
| 599
| 3.640625
| 4
|
[] |
no_license
|
//
// Box.swift
// report
//
// Created by osa on 18.07.2021.
//
class Box<T> {
typealias Listener = (T) -> Void
var listener: Listener?
//listener захватывает новое значение с типом T при его изменении
var value: T {
didSet {
listener?(value)
}
}
init(_ value: T) {
self.value = value
}
//момент изменения свойства с типом T
func bind(listener: @ escaping Listener) {
self.listener = listener
listener(value)
}
}
| true
|
3a64d9bb0ff816915f27d8227d250340bd9b56fa
|
Swift
|
Cunqi/CXPopupKit
|
/CXPopupKit/Animation/CXPopAnimation.swift
|
UTF-8
| 1,148
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
class CXZoomAnimation: CXBasicAnimation {
override func presenting(_ context: UIViewControllerContextTransitioning) {
guard let toView = context.view(forKey: .to) else {
return
}
let duration = transitionDuration(using: context)
toView.transform = CGAffineTransform.zero
UIView.animate(withDuration: duration, animations: {
toView.transform = CGAffineTransform.identity
}, completion: { finished in
let wasCancelled = context.transitionWasCancelled
context.completeTransition(!wasCancelled)
})
}
override func dismissing(_ context: UIViewControllerContextTransitioning) {
guard let fromView = context.view(forKey: .from) else {
return
}
let duration = transitionDuration(using: context)
UIView.animate(withDuration: duration, animations: {
fromView.transform = CGAffineTransform.zero
}, completion: { finished in
let wasCancelled = context.transitionWasCancelled
context.completeTransition(!wasCancelled)
})
}
}
| true
|
bf56cf1b72dfe584d034a4e394f9d4cf4342ca6b
|
Swift
|
plivesey/JazzMusicGenerator
|
/JazzMusicGenerator/PLMusicRepresentationHelpers/MusicUtil+Scales.swift
|
UTF-8
| 1,245
| 3.046875
| 3
|
[] |
no_license
|
//
// MusicUtil+Scales.swift
// TestAudio
//
// Created by Peter Livesey on 7/14/14.
// Copyright (c) 2014 Peter Livesey. All rights reserved.
//
import Foundation
extension MusicUtil {
// Returns a zero based scale
// Keeps the current order so it will not be always ascending
class func zeroBasedScale(scale: [Int]) -> [Int] {
return scale.map {
note in return note % 12
}
}
class func scaleWithScale(scale: [Int], differentMode mode: Int) -> [Int] {
var newScale: [Int] = []
var currentIndex = mode
var addition = 0
while newScale.count < scale.count {
newScale.append(scale[currentIndex] + addition)
currentIndex++
if currentIndex >= scale.count {
currentIndex = 0
addition = 12
}
}
if newScale[0] >= 12 {
newScale = newScale.map { note in
return note - 12
}
}
return newScale
}
class func transposedScale(scale: [Int], transposition: Int) -> [Int] {
assert(transposition >= 0 && transposition < 12)
var newScale: [Int] = scale.map { note in
return note + transposition
}
if newScale[0] >= 12 {
newScale = newScale.map { note in
return note - 12
}
}
return newScale
}
}
| true
|
b72921dabc9a752747a395527c0f7162d71da90d
|
Swift
|
n1ckl0sk0rtge/WWDC21-Homomorphic-Encryption
|
/HomomorphicEncryption.playground/Pages/Introduction.xcplaygroundpage/Contents.swift
|
UTF-8
| 6,478
| 3.859375
| 4
|
[
"MIT"
] |
permissive
|
//#-hidden-code
import PlaygroundSupport
//#-end-hidden-code
/*:
# Introduction
Hey you and welcome to my playground!😊
On the following pages I will introduce you to the capabilities of **Homomorphic Encryption**. Thereby I will try to simplify the usually used mathematical notations to explanatory texts and figures. I hope that this will give you an easy access to the complexity of homomorphic encryption.😉
Let's start with a liitle bit of an introduction...
## What is Homomorphic Encryption?
The main use of encryption is, to protect your data from others. You may heard about the CIA, no not the agency...😉 CIA stays for **C**onfidentiality, **I**ntegrity, and **A**vailability, which discribes the primary focus of information security. All three components can be secured directly or indirectly through encryption. As long as the data is encrypted, it is stored somewhere and will stay there until you need it. If you want to use the data again, you have to decrypt it. So, as you can see, there are currently two states of the data:
* the data is encrypted and at rest
* the data is in use and decrypted
There is another case, and that is the encryption of data during transmission. This is achieved by using SSL over TLS, but apart from the transfer of data, these are not in use, so we can include this case among the first state.
Homomorphic encryption brings another dimension to the world of encrypted data. In addition to encrypting data at rest and allowing the data to be decrypted for use, the class of homomorphic encryption schemes allows you to work with the encrypted data without losing its meaning. Sounds cool, doesn't it?🤓
**Let's give you a short example with a real use case of homomorphic encryption**
Imagine you work in healthcare. Over time, you will see medical information from dozens of different patients. Wouldn't it be nice to have some kind of AI that is able to determine a patient's disease by analyzing the patient's current and past health data, as well as data from other patients?
Yes, that would be great, BUT there is a good reason why this is not currently done on a large scale. In Europe, for example, we have the GDPR, which helps protect the privacy of every citizen. So if you build an AI that uses people's health data, you will be disregarding their rights.
However, with homorphic encryption, you can do that! By training an AI with the encrypted data, you respect the privacy rights and are able to produce valid results. The big advantage is the ability to calculate a meaningful result with the encrypted data. I know, already this use case birngt you to learn even more about this topic, right? But there is more. With the move to the cloud, you can think of even more use cases for this cool technology. So you will learn something for the future 😜
So let's start with a little theory...🤓
## Lattices
Lattices are a kind of mathematical structuring of algebra. For simplicity, you can think of a grid as shown in the figure below. In slightly more mathematical terms, each point (black) in a 2D grid can be described by its x and y components. For example, the point *(1, 2)* can be a point in a 2D-lattice. Moreover, in mathematics, a point is represented as a vector. This is nothing more than a fancy name for a point, so from now on we'll just call a point a vector.
But because mathematicians always want to think outside the box, they never defined a box for a lattice. This means that the pattern you see in the picture goes on forever and has no limits. So there is an infinite number of vectors in the x-direction and in the y-direction. That means the pattern is what deffinates the lattice. But how do we define the pattern, or rather, how do we write it down?🤔

To do this, we need to open the box of mathtools again and find something called a basis. A basis of a space or dimension describes each point within the space by a finite number of vectors. Sounds like we found the right thing, right? For our grid in the picture above, we can use the basis of *(0, 1)* and *(1, 0)* to describe each point within the grid. A basis for the grid in our image is shown with green arrows.
Let's have a look at an example. How we can define the vector *(4, 2)* with our basis? Simple we multipli *(1, 0)* with 4 and *(0, 1)* with 2. The result is *(4, 2)*, our vector! This is called linear combination of vectores. (In addition, the vectors of a basis should be [linear-independent](https://en.wikipedia.org/wiki/Linear_independence))
Let's have a look at a little bit of code 🧑💻
*/
let v1 = Vector(values: [1, 0])
let v2 = Vector(values: [0, 1])
let basis = Basis(space: 2, vectors: [v1, v2])
let newPoint = /*#-editable-code*/4/*#-end-editable-code*/ * v1 + /*#-editable-code*/2/*#-end-editable-code*/ * v2
/*:
A cool fact about basis' are that there are an infinite number of them that can describe the same space. See the blue arrows in the picture? They describe the same lattice, just in a different way. Mathematics just doesn't like to commit to anything...🙄
The dimension of the vectors is usually not limited to two, with regard to the cryptogtaphic application the dimension of the vectors will be much larger than two. Notice that!
But why is that all important for cryptography, you may ask? Let's see..😉
## Short Vector Problem
The security of crypthographic algorithms is generally based on a problem that is very difficult to solve in a reasonable amount of time. For homorphic encryption, this problem is based on the theory of lattices. Based on what you have just learned, imagine a given lattice but with at least dimension 1000. As we know, the base of a lattice consists of exactly as many vectors as the dimension is large. The Short Vector Problem (SVP) asks you to find a point in the given grid that is as close as possible to the origin point, but not the same. This is easy to solve for our example with dimension 2, but when the dimension is large, the problem is really hard to solve!
**As you might guess, we will not be working directly with vectors in the real implementation. Instead, we will use polynomials for the implementation, but the basis is the same. Polynomials can be traded as vectors and vice versa.**
Okay, that's it for the theory, let's take a look at how homomorphic encryption actually works! 👀
*/
//: [Next](@next)
| true
|
286cd9131a9f42c3efa8228f9857252b78b733dc
|
Swift
|
crisogray/SoFlow
|
/SoFlow/TitleView.swift
|
UTF-8
| 1,100
| 2.75
| 3
|
[] |
no_license
|
//
// TitleView.swift
// EZSwipeController
//
// Created by Ben Gray on 19/11/2015.
// Copyright © 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
import S4PageControl
class TitleView: UIView {
@IBOutlet var label: UILabel!
@IBOutlet var pageControl: S4PageControl!
func setTitle(title: String, index: UInt, total: UInt, dark: Bool) {
self.label.text = title
self.pageControl.numberOfPages = total
self.pageControl.currentPage = index
self.pageControl.indicatorSize = CGSizeMake(5, 5)
self.pageControl.indicatorSpace = 5
if dark {
self.pageControl.currentPageIndicatorTintColor = UIColor.blackColor()
self.label.textColor = UIColor.blackColor()
self.pageControl.pageIndicatorTintColor = UIColor.lightGrayColor()
} else {
self.pageControl.currentPageIndicatorTintColor = UIColor.whiteColor()
self.label.textColor = UIColor.whiteColor()
self.pageControl.pageIndicatorTintColor = UIColor.whiteColor().colorWithAlphaComponent(0.25)
}
}
}
| true
|
fbdaca2063c89731e67b473e9ef91bebf2970965
|
Swift
|
da-manifest/ChatTest
|
/ChatTest/Helpers/UIViewController.swift
|
UTF-8
| 950
| 2.8125
| 3
|
[] |
no_license
|
//
// UIViewController.swift
// ChatTest
//
// Created by Admin on 01.09.2018.
// Copyright © 2018 Maksim Khozyashev. All rights reserved.
//
import UIKit
private struct Constants {
static let alertTitle = "Error"
static let ok = "OK"
}
extension UIViewController {
func showError(_ error: Error) {
let alertMessage = APIError.description(error)
let alertViewController = UIAlertController(title: Constants.alertTitle,
message: alertMessage,
preferredStyle: .alert)
let okAction = UIAlertAction(title: Constants.ok, style: .default) { _ in
alertViewController.dismiss(animated: true)
}
alertViewController.addAction(okAction)
DispatchQueue.main.async { [weak self] in
self?.present(alertViewController, animated: true)
}
}
}
| true
|
e9fe22bca63deaa31f2bc54466588c85f1374944
|
Swift
|
sheshnathiicmr/SceenCast-Demo-App
|
/ScreenCast/ViewController.swift
|
UTF-8
| 3,007
| 2.546875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ScreenCastDemoApp
//
// Created by Sheshnath Kumar on 13/12/18.
// Copyright © 2018 ProMobi Technologies. All rights reserved.
//
import UIKit
import WebRTC
class ViewController: UIViewController {
@IBOutlet weak var signalingStatusLabel: UILabel!
let signalClient = SignalClient()
let webRTCClient = WebRTCClient()
var signalingConnected: Bool = false {
didSet {
DispatchQueue.main.async {
if self.signalingConnected {
self.signalingStatusLabel.text = "Connected"
self.signalingStatusLabel.textColor = UIColor.green
}
else {
self.signalingStatusLabel.text = "Not connected"
self.signalingStatusLabel.textColor = UIColor.red
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.signalingConnected = false
self.signalClient.connect()
self.webRTCClient.delegate = self
self.signalClient.delegate = self
}
@IBAction func buttonConnectPressed(_ sender: Any) {
self.webRTCClient.offer { (sdp) in
//self.hasLocalSdp = true
self.signalClient.send(sdp: sdp)
}
}
@IBAction func buttonRecieveCallPressed(_ sender: Any) {
self.webRTCClient.answer { (localSdp) in
//self.hasLocalSdp = true
self.signalClient.send(sdp: localSdp)
}
}
@IBAction func showvideoPressed(_ sender: Any) {
//let vc = VideoViewController(webRTCClient: self.webRTCClient)
//self.present(vc, animated: true, completion: nil)
self.webRTCClient.startCaptureLocalVideo()
}
}
extension ViewController: SignalClientDelegate {
func signalClientDidConnect(_ signalClient: SignalClient) {
self.signalingConnected = true
}
func signalClientDidDisconnect(_ signalClient: SignalClient) {
self.signalingConnected = false
}
func signalClient(_ signalClient: SignalClient, didReceiveRemoteSdp sdp: RTCSessionDescription) {
print("Received remote sdp")
self.webRTCClient.set(remoteSdp: sdp) { (error) in
//self.hasRemoteSdp = true
}
}
func signalClient(_ signalClient: SignalClient, didReceiveCandidate candidate: RTCIceCandidate) {
print("Received remote candidate")
//self.remoteCandidateCount += 1
self.webRTCClient.set(remoteCandidate: candidate)
}
}
extension ViewController: WebRTCClientDelegate {
func webRTCClient(_ client: WebRTCClient, didDiscoverLocalCandidate candidate: RTCIceCandidate) {
print("discovered local candidate")
//self.localCandidateCount += 1
self.signalClient.send(candidate: candidate)
}
}
| true
|
2024a03b419111bd5a817c5d7b93f3b839b69e0f
|
Swift
|
zhouxueyun/Leetcode.playground
|
/Pages/Problem68.xcplaygroundpage/Contents.swift
|
UTF-8
| 907
| 3.765625
| 4
|
[] |
no_license
|
import Foundation
/**
Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
*/
func mySqrt(_ x: Int) -> Int {
guard x > 1 else {
return x
}
var start = 1, end = x / 2
while start < end {
let mid = start + (end - start) / 2
if x / mid < mid {
end = mid - 1
} else if x / mid > mid {
start = mid + 1
} else {
return mid
}
}
return x/end < end ? end-1 : end
}
mySqrt(5)
mySqrt(4)
mySqrt(8)
mySqrt(32)
mySqrt(100)
| true
|
246d245212c53580ada3929a2318f86095345a2b
|
Swift
|
loicpirez/WeatherApp
|
/WeatherApp/AlertController+Loading.swift
|
UTF-8
| 367
| 2.71875
| 3
|
[] |
no_license
|
import UIKit
extension UIAlertController {
static func loadingAlert() -> UIAlertController {
return UIAlertController(title: "Loading", message: "Please, wait...", preferredStyle: .alert)
}
func presentInViewController(_ viewController: UIViewController) {
viewController.present(self, animated: true, completion: nil)
}
}
| true
|
df5e036572870f7f3790bc9282ed2e8fb78be74b
|
Swift
|
ws00801526/Themeful
|
/Themeful/Classes/Base/UIKit+Extension.swift
|
UTF-8
| 6,588
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
// UIKit+Extension.swift
// Pods
//
// Created by XMFraker on 2019/1/14
// Copyright © XMFraker All rights reserved. (https://github.com/ws00801526)
// @class UIKit_Extension
// @version <#class version#>
// @abstract <#class description#>
import UIKit
internal extension UIColor {
convenience init(_ hex3: UInt16, alpha: CGFloat = 1, displayP3: Bool = false) {
let divisor = CGFloat(15)
let red = CGFloat((hex3 & 0xF00) >> 8) / divisor
let green = CGFloat((hex3 & 0x0F0) >> 4) / divisor
let blue = CGFloat( hex3 & 0x00F ) / divisor
if displayP3, #available(iOS 10, *) {
self.init(displayP3Red: red, green: green, blue: blue, alpha: alpha)
} else {
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
convenience init(_ hex4: UInt16, displayP3: Bool = false) {
let divisor = CGFloat(15)
let red = CGFloat((hex4 & 0xF000) >> 12) / divisor
let green = CGFloat((hex4 & 0x0F00) >> 8) / divisor
let blue = CGFloat((hex4 & 0x00F0) >> 4) / divisor
let alpha = CGFloat( hex4 & 0x000F ) / divisor
if displayP3, #available(iOS 10, *) {
self.init(displayP3Red: red, green: green, blue: blue, alpha: alpha)
} else {
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
convenience init(_ hex6: UInt32, alpha: CGFloat = 1, displayP3: Bool = false) {
let divisor = CGFloat(255)
let red = CGFloat((hex6 & 0xFF0000) >> 16) / divisor
let green = CGFloat((hex6 & 0x00FF00) >> 8) / divisor
let blue = CGFloat( hex6 & 0x0000FF ) / divisor
if displayP3, #available(iOS 10, *) {
self.init(displayP3Red: red, green: green, blue: blue, alpha: alpha)
} else {
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
convenience init(_ hex8: UInt32, displayP3: Bool = false) {
let divisor = CGFloat(255)
let red = CGFloat((hex8 & 0xFF000000) >> 24) / divisor
let green = CGFloat((hex8 & 0x00FF0000) >> 16) / divisor
let blue = CGFloat((hex8 & 0x0000FF00) >> 8) / divisor
let alpha = CGFloat( hex8 & 0x000000FF ) / divisor
if displayP3, #available(iOS 10, *) {
self.init(displayP3Red: red, green: green, blue: blue, alpha: alpha)
} else {
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
convenience init?(_ hex: String, displayP3: Bool = false) {
let str = hex.trimmingCharacters(in: .whitespacesAndNewlines).lowercased().replacingOccurrences(of: "#", with: "").replacingOccurrences(of: "0x", with: "")
let len = str.count
guard [3, 4, 6, 8].contains(len) else { return nil }
let scanner = Scanner(string: str)
var rgba: UInt32 = 0
guard scanner.scanHexInt32(&rgba) else { return nil }
let hasAlpha = (len % 4) == 0
if len < 5 {
let divisor = CGFloat(15)
let red = CGFloat((rgba & (hasAlpha ? 0xF000 : 0xF00)) >> (hasAlpha ? 12 : 8)) / divisor
let green = CGFloat((rgba & (hasAlpha ? 0x0F00 : 0x0F0)) >> (hasAlpha ? 8 : 4)) / divisor
let blue = CGFloat((rgba & (hasAlpha ? 0x00F0 : 0x00F)) >> (hasAlpha ? 4 : 0)) / divisor
let alpha = hasAlpha ? CGFloat(rgba & 0x000F) / divisor : 1.0
if displayP3, #available(iOS 10, *) {
self.init(displayP3Red: red, green: green, blue: blue, alpha: alpha)
} else {
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
} else {
let divisor = CGFloat(255)
let red = CGFloat((rgba & (hasAlpha ? 0xFF000000 : 0xFF0000)) >> (hasAlpha ? 24 : 16)) / divisor
let green = CGFloat((rgba & (hasAlpha ? 0x00FF0000 : 0x00FF00)) >> (hasAlpha ? 16 : 8)) / divisor
let blue = CGFloat((rgba & (hasAlpha ? 0x0000FF00 : 0x0000FF)) >> (hasAlpha ? 8 : 0)) / divisor
let alpha = hasAlpha ? CGFloat(rgba & 0x000000FF) / divisor : 1.0
if displayP3, #available(iOS 10, *) {
self.init(displayP3Red: red, green: green, blue: blue, alpha: alpha)
} else {
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
}
}
internal extension UIImage {
class func image(with color: UIColor, size: CGSize = CGSize(width: 1.0, height: 1.0)) -> UIImage? {
guard size.width > 0, size.height > 0 else { return nil }
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
@available(iOS 8.2, *)
internal extension UIFont.Weight {
init(_ style: String) {
switch style {
case "ultraLight": self.init(rawValue: UIFont.Weight.medium.rawValue)
case "thin": self.init(rawValue: UIFont.Weight.thin.rawValue)
case "light": self.init(rawValue: UIFont.Weight.light.rawValue)
case "medium": self.init(rawValue: UIFont.Weight.medium.rawValue)
case "semibold": self.init(rawValue: UIFont.Weight.semibold.rawValue)
case "bold": self.init(rawValue: UIFont.Weight.bold.rawValue)
case "heavy": self.init(rawValue: UIFont.Weight.heavy.rawValue)
case "black": self.init(rawValue: UIFont.Weight.black.rawValue)
default: self.init(rawValue: UIFont.Weight.regular.rawValue)
}
}
}
internal extension UIFont {
class func font(with string: String) -> UIFont? {
let values = string.split(separator: ".")
guard values.count == 3 else { return nil }
let name = String(values.first ?? "")
let size = CGFloat((String(values[1]) as NSString).floatValue)
if (name.count <= 0 || ["system", "*"].contains(name)) {
if #available(iOS 8.2, *) {
return UIFont.systemFont(ofSize: size, weight: UIFont.Weight(String(values.last ?? "")))
} else {
return UIFont.systemFont(ofSize: size)
}
} else {
return UIFont.init(name: name, size: size)
}
}
}
| true
|
632947e5a0a8fdd068ea22cb741e700d7c54cb25
|
Swift
|
SvetlanaSavenko/firstapp
|
/BeauBody/MainView.swift
|
UTF-8
| 1,369
| 2.859375
| 3
|
[] |
no_license
|
//
// ContentView.swift
// BeauBody
//
// Created by Савенко Светлана Александровна on 08.01.2021.
// Copyright © 2021 Svetlana Savenko. All rights reserved.
//
import SwiftUI
struct MainView: View {
@State private var showCalendarModal = false
@State private var showServiceModal = false
@ObservedObject private var vm: MainViewModel = Container.instance.provideMainViewModel()
var body: some View {
Group {
Button("Выбрать услугу", action:{
self.showServiceModal.toggle()
})
.sheet(isPresented: $showServiceModal) {
ServiceDetail(showServiceModal: self.$showServiceModal)
}
Button("Выбрать время", action:{
self.showCalendarModal.toggle()
})
.sheet(isPresented: $showCalendarModal) {
CalendarDetail(showСalendarModal: self.$showCalendarModal)
}
ForEach(vm.unfinishedAppointment!.services, id: \.self) {
Text("\($0.rawValue)")
}
if let date = vm.unfinishedAppointment?.date {
Text("\(date)")
}
if vm.isAppointmentButtonVisible {
Button("Записаться", action:{
self.vm.saveAppointment()
})
}
if let currentAppointment = vm.currentAppointment {
ForEach(currentAppointment.services, id: \.self) {
Text("Вы записаны: \($0.rawValue)")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
MainView()
}
}
| true
|
939f9c4c10008ebc3d8b9ccc59522397ba35d656
|
Swift
|
stzn/DogCollection
|
/DogCollection/Views/DogImageList/DogImageListView.swift
|
UTF-8
| 1,162
| 2.78125
| 3
|
[] |
no_license
|
//
// DogImageListView.swift
// DogCollection
//
// Created by Shinzan Takata on 2020/02/24.
// Copyright © 2020 shiz. All rights reserved.
//
import SwiftUI
struct DogImageListView: View {
@EnvironmentObject var api: DogWebAPI
@ObservedObject var viewModel: DogImageListViewModel
var body: some View {
VStack(spacing: 0) {
self.content
Spacer()
}.onAppear {
self.viewModel.get(api: self.api)
}
}
private var content: some View {
switch viewModel.state {
case .loading:
return AnyView(LoadingView())
case .loaded:
return AnyView(DogImageCollection(breed: viewModel.breed,
dogImages: viewModel.dogImages))
case .error:
return AnyView(ErrorView(message: self.viewModel.error,
retryAction: { self.viewModel.get(api: self.api) }))
}
}
}
struct DogImageListView_Previews: PreviewProvider {
static var previews: some View {
DogImageListView(viewModel: DogImageListViewModel(breed: Breed.anyBreed.name))
}
}
| true
|
420fd1c8dc1ff5653687de966c58778256fb7beb
|
Swift
|
pusher/pusher-websocket-swift
|
/Tests/Extensions/String+Extensions.swift
|
UTF-8
| 1,747
| 2.875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
import XCTest
extension String {
func removing(_ set: CharacterSet) -> String {
var newString = self
newString.removeAll { char -> Bool in
guard let scalar = char.unicodeScalars.first else { return false }
return set.contains(scalar)
}
return newString
}
var escaped: String {
return self.debugDescription
}
func toJsonData(validate: Bool = true, file: StaticString = #file, line: UInt = #line) -> Data {
do {
let data = try self.toData()
if validate {
// Verify the string is valid JSON (either a dict or an array) before returning
_ = try toJsonAny()
}
return data
} catch {
XCTFail("\(error)", file: file, line: line)
}
return Data()
}
func toJsonDict(file: StaticString = #file, line: UInt = #line) -> [String: Any] {
do {
let json = try toJsonAny()
guard let jsonDict = json as? [String: Any] else {
XCTFail("Not a dictionary", file: file, line: line)
return [:]
}
return jsonDict
} catch {
XCTFail("\(error)", file: file, line: line)
}
return [:]
}
// MARK: - Private methods
private func toJsonAny() throws -> Any {
return try JSONSerialization.jsonObject(with: self.toData(), options: .allowFragments)
}
private func toData() throws -> Data {
guard let data = self.data(using: .utf8) else {
throw JSONError.conversionFailed
}
return data
}
}
// MARK: - Error handling
enum JSONError: Error {
case conversionFailed
}
| true
|
f6920f86a2649e1772c828d435748f23bd98639c
|
Swift
|
lelea2/CMPE297_Project
|
/MyCare/ZombieKit/FoodItem.swift
|
UTF-8
| 749
| 3.390625
| 3
|
[] |
no_license
|
//
// FoodItem.swift
// MyCare
//
// Created by Dao, Khanh on 12/2/16.
//
import Foundation
import UIKit
//Create string view for food items
class FoodItem: NSObject {
private(set) var name: String
private(set) var joules: Double
class func foodItem(name: String, joules: Double) -> FoodItem {
let item: FoodItem = FoodItem(name: name, joules: joules)
return item
}
init(name: String, joules: Double) {
self.name = name
self.joules = joules
super.init()
}
override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? FoodItem else {
return false
}
return (object.joules == self.joules) && (object.name == self.name)
}
}
| true
|
f698f8ce12555239d535cdc85c7c827e0beb871b
|
Swift
|
LambdaDigamma/Bahnhofsfotos
|
/Bahnhofsfotos/API.swift
|
UTF-8
| 2,725
| 3.09375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// API.swift
// Bahnhofsfotos
//
// Created by Miguel Dönicke on 15.01.17.
// Copyright © 2017 MrHaitec. All rights reserved.
//
import Alamofire
import Foundation
import SwiftyJSON
import SwiftyUserDefaults
class API {
enum APIError: Error {
case message(String)
}
static var baseUrl: String {
return Constants.baseUrl
}
// Get all countries
static func getCountries(completionHandler: @escaping ([Country]) -> Void) {
Alamofire.request(API.baseUrl + "/countries.json")
.responseJSON { response in
var countries = [Country]()
guard let json = JSON(response.result.value as Any).array else {
completionHandler(countries)
return
}
do {
countries = try json.map {
guard let country = try Country(json: $0) else { throw APIError.message("JSON of country is invalid.") }
return country
}
} catch {
debugPrint(error)
}
completionHandler(countries)
}
}
// Get all stations (or with/out photo)
static func getStations(withPhoto hasPhoto: Bool?, completionHandler: @escaping ([Station]) -> Void) {
var parameters = Parameters()
parameters["country"] = Defaults[.country].lowercased()
if let hasPhoto = hasPhoto {
parameters["hasPhoto"] = hasPhoto.description
}
Alamofire.request(API.baseUrl + "/stations",
method: .get,
parameters: parameters,
encoding: URLEncoding.default,
headers: nil)
.responseJSON { response in
var stations = [Station]()
guard let json = JSON(response.result.value as Any).array else {
completionHandler(stations)
return
}
do {
stations = try json.map {
guard let station = try Station(json: $0) else { throw APIError.message("JSON of station is invalid.") }
return station
}
} catch {
debugPrint(error)
}
completionHandler(stations)
}
}
// Get all photographers of given country
static func getPhotographers(completionHandler: @escaping ([String: Any]) -> Void) {
Alamofire.request(API.baseUrl + "/photographers",
method: .get,
parameters: ["country": Defaults[.country].lowercased()],
encoding: URLEncoding.default,
headers: nil)
.responseJSON { response in
guard let value = response.result.value, let json = JSON(value).dictionaryObject else {
completionHandler([:])
return
}
completionHandler(json)
}
}
}
| true
|
b78ea8e49a13d4ffde1cab99d2defdfec553b693
|
Swift
|
Smalex911/CheckPlease
|
/CheckPlease/Views/Classes/MainVC/MainPresenter.swift
|
UTF-8
| 434
| 2.515625
| 3
|
[] |
no_license
|
//
// MainPresenter.swift
// CheckPlease
//
// Created by Aleksandr Smorodov on 14.05.2021.
//
import Foundation
protocol MainPresentationLogic: AnyObject {
func updatePositions(_ positions: [Position]?)
}
final class MainPresenter: MainPresentationLogic {
weak var viewController: MainDisplayLogic?
func updatePositions(_ positions: [Position]?) {
viewController?.updatePositions(positions)
}
}
| true
|
20570bb603ba945997ee6f65b5d80d37d2ecb798
|
Swift
|
aoblea/ADiaryApp
|
/A Diary App/Controllers/DetailViewController.swift
|
UTF-8
| 5,562
| 2.59375
| 3
|
[] |
no_license
|
//
// DetailViewController.swift
// A Diary App
//
// Created by Arwin Oblea on 12/15/19.
// Copyright © 2019 Arwin Oblea. All rights reserved.
//
import UIKit
import CoreLocation
import CoreData
// This controller will be used to create entries.
class DetailViewController: UIViewController {
// MARK: - Properties
let dateFormatter = DateFormatter()
let today = Date()
var selectedEmote: UIImage?
let goodEmoteImage = UIImage(named: "icn_happy")
let averageEmoteImage = UIImage(named: "icn_average")
let badEmoteImage = UIImage(named: "icn_bad")
var latitude: String?
var longitude: String?
let locationManager = CLLocationManager()
var selectedPhoto: UIImage?
lazy var photoPickerManager: PhotoPickerManager = {
let manager = PhotoPickerManager(presentingViewController: self)
manager.delegate = self
return manager
}()
var entry: Entry?
var managedObjectContext: NSManagedObjectContext!
// MARK: - IBOutlets
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var contentTextView: UITextView!
@IBOutlet weak var contentLimitLabel: UILabel!
@IBOutlet weak var addPhoto: UIButton!
@IBOutlet weak var goodButton: UIButton! {
didSet {
self.goodButton.isSelected = false
}
}
@IBOutlet weak var averageButton: UIButton! {
didSet {
self.averageButton.isSelected = false
}
}
@IBOutlet weak var badButton: UIButton! {
didSet {
self.badButton.isSelected = false
}
}
@IBOutlet weak var saveButton: UIBarButtonItem!
// MARK: - Viewdidload
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupEmoteButtons()
setupContentTextView()
setupTitle()
setupPhotoPicker()
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
setupLocationManager()
} else {
// request permission again
locationManager.requestWhenInUseAuthorization()
}
// if entry exists, we are in editing mode
if let entry = entry {
self.titleTextField.text = entry.title
self.contentTextView.text = entry.content
self.selectedEmote = entry.emoteImage
self.selectedPhoto = entry.photoImage
self.latitude = entry.latitude
self.longitude = entry.longitude
}
}
// MARK: - Viewdidappear
override func viewDidAppear(_ animated: Bool) {
if CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
}
func setupLocationManager() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
}
func setupPhotoPicker() {
addPhoto.addTarget(self, action: #selector(launchCamera), for: .touchUpInside)
}
@objc func launchCamera() {
photoPickerManager.presentPhotoPicker(animated: true)
}
// this method should take today's date whenever creating a new entry/updating an existing entry
func setupTitle() {
dateFormatter.dateStyle = .medium
let formattedDate = dateFormatter.string(from: today)
title = formattedDate
}
func setupUI() {
view.backgroundColor = UIColor.ThemeColor.russianViolet
contentLimitLabel.textColor = UIColor.ThemeColor.lavendarGray
self.navigationController?.navigationBar.tintColor = UIColor.ThemeColor.verdigris
}
func setupEmoteButtons() {
goodButton.addTarget(self, action: #selector(goodButtonPressed), for: .touchUpInside)
averageButton.addTarget(self, action: #selector(averageButtonPressed), for: .touchUpInside)
badButton.addTarget(self, action: #selector(badButtonPressed), for: .touchUpInside)
}
func setupContentTextView() {
contentTextView.delegate = self
contentTextView.text = "Write more about your day here."
contentTextView.textColor = .lightGray
}
// MARK: - Save bar button method
@IBAction func saveEntry(_ sender: UIBarButtonItem) {
guard let title = titleTextField.text, let content = contentTextView.text else { return }
if title.count >= 20 {
self.presentAlert(error: .exceedsCharacterLimit)
} else if title.isEmpty || content.isEmpty {
self.presentAlert(error: .emptyInformation)
} else {
if let updatedEntry = entry {
// update existing entry
updatedEntry.title = title
updatedEntry.content = content
updatedEntry.creationDate = today
updatedEntry.emotion = selectedEmote?.jpegData(compressionQuality: 1.0)
updatedEntry.photo = selectedPhoto?.jpegData(compressionQuality: 1.0)
updatedEntry.latitude = latitude?.description
updatedEntry.longitude = longitude?.description
managedObjectContext.saveChanges()
locationManager.stopUpdatingLocation()
navigationController?.popToRootViewController(animated: true)
} else {
// creating a new entry
let entry = NSEntityDescription.insertNewObject(forEntityName: "Entry", into: managedObjectContext) as! Entry
entry.title = title
entry.content = content
entry.creationDate = today
entry.emotion = selectedEmote?.jpegData(compressionQuality: 1.0)
entry.photo = selectedPhoto?.jpegData(compressionQuality: 1.0)
entry.latitude = latitude?.description
entry.longitude = longitude?.description
managedObjectContext.saveChanges()
locationManager.stopUpdatingLocation()
navigationController?.popToRootViewController(animated: true)
}
}
}
}
| true
|
49af232928bb843243722a639ca6bab9c87a9d5a
|
Swift
|
laymond1/ios_swift
|
/ios_Swift1&2/Basic/Operator.playground/Contents.swift
|
UTF-8
| 227
| 3.5625
| 4
|
[] |
no_license
|
// 산술 연산자
var weight = 65
weight + 10
weight - 10
weight * 10
weight / 10
weight % 2
// 비교 연산자
let age = 28
let isAdult = age >= 20
let 중1 = age == 14
// 논리 연산자
true && true
true || false
| true
|
4099956005552c0626bfa3d84d596e1c0592392d
|
Swift
|
huangboju/Alpha
|
/Demo/UIKitCatalog/VideoPlayerViewController.swift
|
UTF-8
| 5,591
| 2.765625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates how to present an `AVPlayerViewController` for an `AVPlayerItem` with metadata and timings.
*/
import UIKit
import AVKit
class VideoPlayerViewController: UIViewController, AVPlayerViewControllerDelegate {
// MARK: IB Actions
@IBAction func playVideo(_ sender: AnyObject) {
// Create an AVAsset with for the media's URL.
let mediaURL = URL(string: "http://p.events-delivery.apple.com.edgesuite.net/1509pijnedfvopihbefvpijlkjb/m3u8/hls_vod_mvp.m3u8")!
let asset = AVAsset(url: mediaURL)
/*
Create an `AVPlayerItem` for the `AVAsset` and populate it with information
about the video.
*/
let playerItem = AVPlayerItem(asset: asset)
playerItem.externalMetadata = sampleExternalMetaData()
playerItem.navigationMarkerGroups = [sampleNavigationMarkerGroup()]
playerItem.interstitialTimeRanges = sampleInterstitialTimeRanges()
// Create and present an `AVPlayerViewController`.
let playerViewController = AVPlayerViewController()
playerViewController.delegate = self
let player = AVPlayer(playerItem: playerItem)
playerViewController.player = player
self.present(playerViewController, animated: true) {
/*
Begin playing the media as soon as the controller has
been presented.
*/
player.play()
}
}
// MARK: AVPlayerViewControllerDelegate
func playerViewController(_ playerViewController: AVPlayerViewController, willPresent interstitial: AVInterstitialTimeRange) {
// Prevent the user from skipping intersitials.
playerViewController.requiresLinearPlayback = true
}
func playerViewController(_ playerViewController: AVPlayerViewController, didPresent interstitial: AVInterstitialTimeRange) {
/*
Allow the user to navigate anywhere in the video once an interstitial
has been played.
*/
playerViewController.requiresLinearPlayback = false
}
// MARK: Meta data
func sampleExternalMetaData() -> [AVMetadataItem] {
let titleItem = AVMutableMetadataItem()
titleItem.identifier = AVMetadataCommonIdentifierTitle
titleItem.value = "Apple Special Event, September 2015" as NSString
titleItem.extendedLanguageTag = "und"
let descriptionItem = AVMutableMetadataItem()
descriptionItem.identifier = AVMetadataCommonIdentifierDescription
descriptionItem.value = "Check out iPhone 6s and iPhone 6s Plus, learn about the powerful iPad Pro, take a look at the new features and bands for Apple Watch, and see the premiere of the all-new Apple TV." as NSString
descriptionItem.extendedLanguageTag = "und"
return [titleItem, descriptionItem]
}
func sampleNavigationMarkerGroup() -> AVNavigationMarkersGroup {
let group = AVNavigationMarkersGroup(title: "Announcements", timedNavigationMarkers: [
timedMetaDataGroupWithTitle("Apple Watch", startTime: 90, endTime: 917),
timedMetaDataGroupWithTitle("iPad Pro", startTime: 917, endTime: 1691),
timedMetaDataGroupWithTitle("Apple Pencil", startTime: 1691, endTime: 3105),
timedMetaDataGroupWithTitle("Apple TV", startTime: 3105, endTime: 4968),
timedMetaDataGroupWithTitle("iPhone", startTime: 4968, endTime: 7328)
])
return group
}
func sampleInterstitialTimeRanges() -> [AVInterstitialTimeRange] {
let ranges = [
AVInterstitialTimeRange(timeRange: timeRange(withStartTime: 728, duration: 53)),
AVInterstitialTimeRange(timeRange: timeRange(withStartTime: 1015, duration: 55)),
AVInterstitialTimeRange(timeRange: timeRange(withStartTime: 3305, duration: 759)),
AVInterstitialTimeRange(timeRange: timeRange(withStartTime: 7261, duration: 61))
]
return ranges
}
// MARK: Convenience
func timedMetaDataGroupWithTitle(_ title: String, startTime: TimeInterval, endTime: TimeInterval) -> AVTimedMetadataGroup {
// Create an `AVMetadataItem` for the title.
let titleItem = AVMutableMetadataItem()
titleItem.identifier = AVMetadataCommonIdentifierTitle
titleItem.value = title as NSString
titleItem.extendedLanguageTag = "und"
// Create a `CMTimeRange` from the supplied information.
let range = timeRange(from: startTime, to: endTime)
return AVTimedMetadataGroup(items: [titleItem], timeRange: range)
}
func timeRange(from startTime: TimeInterval, to endTime: TimeInterval) -> CMTimeRange {
let cmStartTime = CMTimeMakeWithSeconds(Float64(startTime), 100)
let cmEndTime = CMTimeMakeWithSeconds(Float64(endTime), 100)
let timeRange = CMTimeRangeFromTimeToTime(cmStartTime, cmEndTime)
return timeRange
}
func timeRange(withStartTime startTime: TimeInterval, duration: TimeInterval) -> CMTimeRange {
let cmStartTime = CMTimeMakeWithSeconds(Float64(startTime), 100)
let cmDuration = CMTimeMakeWithSeconds(Float64(duration), 100)
let timeRange = CMTimeRange(start: cmStartTime, duration: cmDuration)
return timeRange
}
}
| true
|
36f42475077f31541a63b0fb67a6c67411c7a17f
|
Swift
|
ealiaga/ios-movs
|
/Movs/models/Movie.swift
|
UTF-8
| 715
| 2.65625
| 3
|
[] |
no_license
|
//
// Movie.swift
// Movs
//
// Created by Ever Aliaga on 2/7/19.
// Copyright © 2019 Ever. All rights reserved.
//
import ObjectMapper
import RealmSwift
import UIKit
import RealmSwift
class Movie: Object, Mappable {
@objc dynamic var id:Int = 0;
@objc dynamic var title:String = ""
@objc dynamic var overview:String = ""
@objc dynamic var posterPath: String = ""
required convenience init?(map: Map) {
self.init()
}
override static func primaryKey() -> String? {
return "id"
}
func mapping(map: Map) {
id <- map["id"]
title <- map["title"]
overview <- map["overview"]
posterPath <- map["poster_path"]
}
}
| true
|
0ee574f2f95328f39bbbc459046062983d1f3aeb
|
Swift
|
ccal2/Aprendendo_Swift
|
/TodosPrimos/TodosPrimos/main.swift
|
UTF-8
| 969
| 4.3125
| 4
|
[] |
no_license
|
/*
Construa um programa que lê um número N a partir do teclado e calcula todos os números primos entre 2 e
N
*/
var number = 0
// ler e validar a entrada
var valid = false
while !valid {
if let input = readLine(), let innberNumber = Int(input) {
valid = true
number = innberNumber
} else {
print("Entrada inválida")
}
}
// encontrar números primos
var numerosPrimos: [Int] = []
if number > 1 {
for i in 2...number {
// verificar se é primo
var primo = true
if i > 2 {
for j in 2...i-1{
if i%j == 0 {
primo = false
break
}
}
}
// se o número for primo, adicionar ao vetor
if primo {
numerosPrimos.append(i)
}
}
}
print("Números primos entre 2 e \(number): \n\(numerosPrimos)")
| true
|
5b375a4d58be352756003cde9e619680c1fdde7a
|
Swift
|
bluesentinelsec/OWCT
|
/OpenWeatherCT/jfb-libs/CGRect.swift
|
UTF-8
| 15,669
| 3.140625
| 3
|
[] |
no_license
|
//
// CGRect.swift
// __core_sources
//
// Created by verec on 22/08/2015.
// Copyright © 2015 Cantabilabs Ltd. All rights reserved.
//
import CoreGraphics
import UIKit.UIGeometry
enum CGRectPosition {
case Above,Below
}
protocol CGSizeable {
func autoSize() -> CGSize
}
/// Arbitratry positionning & Aligning
extension CGRect {
func edgeAligned(toRect toRect:CGRect, edge: UIRectEdge) -> CGRect {
var rect = self
if [UIRectEdge.Top].contains(edge) {
rect.origin.y = toRect.origin.y
} else if [UIRectEdge.Left].contains(edge) {
rect.origin.x = toRect.origin.x
} else if [UIRectEdge.Bottom].contains(edge) {
rect.origin.y = toRect.maxY - rect.height
} else if [UIRectEdge.Right].contains(edge) {
rect.origin.x = toRect.maxX - rect.width
}
return rect
}
func positionned(intoRect r: CGRect, widthUnitRange wu: CGFloat, heightUnitRange hu: CGFloat) -> CGRect {
let size:CGSize = r.size
let center:CGPoint = CGPoint(x: r.minX + size.width * wu
, y: r.minY + size.height * hu)
var rect = self
rect.origin.x = center.x - (rect.width / 2.0)
rect.origin.y = center.y - (rect.height / 2.0)
return rect
}
}
/// edge operations
extension CGRect {
func edge(edge:UIRectEdge, alignedToRect:CGRect) -> CGRect {
return edgeAligned(toRect: alignedToRect, edge: edge)
}
func edge(edge:UIRectEdge, ofSize: CGFloat) -> CGRect {
return band(edge, size: ofSize)
}
func edge(edge: UIRectEdge, growBy: CGFloat) -> CGRect {
return grow(edge, by: growBy)
}
func edge(edge: UIRectEdge, shrinkBy: CGFloat) -> CGRect {
return shrink(edge, by: shrinkBy)
}
func edge(edge:UIRectEdge, offsetBy: CGFloat) -> CGRect {
return offset(edge, by: offsetBy)
}
func edge(edge:UIRectEdge, abutToRect: CGRect) -> CGRect {
var rect = self
if edge == .Top {
rect.origin.y = abutToRect.maxY
} else if edge == .Left {
rect.origin.x = abutToRect.maxX
} else if edge == .Bottom {
rect.origin.y = abutToRect.minY - abutToRect.height
} else if edge == .Right {
rect.origin.x = abutToRect.minX - abutToRect.width
}
return rect
}
}
/// Centering
extension CGRect {
func centered(intoRect intoRect: CGRect) -> CGRect {
return self.positionned(intoRect: intoRect, widthUnitRange: 0.5, heightUnitRange: 0.5)
}
func centered(witdh: CGFloat, height: CGFloat) -> CGRect {
/// workaround some Swift code gen bug that mistakes self.width &
/// self.height with the width and height parameters ...
var rect = CGRect.zero
rect.size = CGSize(width: witdh, height: height)
var orgn = self.center
orgn.x -= rect.size.width / 2.0
orgn.y -= rect.size.height / 2.0
rect.origin = orgn
return rect
}
func centered(side: CGFloat) -> CGRect {
return self.centered(side, height: side)
}
func centeredPosition(position:CGPoint) -> CGRect {
var rect = self
rect.origin.x = position.x - rect.width / 2.0
rect.origin.y = position.y - rect.height / 2.0
return rect
}
func centeredXPosition(positionX:CGFloat) -> CGRect {
var rect = self
rect.origin.x = positionX - rect.width / 2.0
return rect
}
func centeredYPosition(positionY:CGFloat) -> CGRect {
var rect = self
rect.origin.y = positionY - rect.height / 2.0
return rect
}
func centerAttractor() -> CGRect {
return self.squarest(.Shortest).centered(intoRect: self)
}
}
/// Slicing
extension CGRect {
func band(edge:UIRectEdge, size: CGFloat) -> CGRect {
if [UIRectEdge.Top].contains(edge) {
return self.top(size)
} else if [UIRectEdge.Left].contains(edge) {
return self.left(size)
} else if [UIRectEdge.Bottom].contains(edge) {
return self.bottom(size)
} else if [UIRectEdge.Right].contains(edge) {
return self.right(size)
}
return self
}
func top(offset: CGFloat, size: CGFloat) -> CGRect {
var rect = self
rect.origin.y = offset
rect.size.height = size
return rect
}
func top(size: CGFloat) -> CGRect {
var rect = self
rect.size.height = size
return rect
}
func left(offset: CGFloat, size: CGFloat) -> CGRect {
var rect = self
rect.origin.x = offset
rect.size.width = size
return rect
}
func left(size: CGFloat) -> CGRect {
var rect = self
rect.size.width = size
return rect
}
func bottom(offset: CGFloat, size: CGFloat) -> CGRect {
var rect = self
rect.origin.y = rect.size.height - (offset + size)
rect.size.height = size
return rect
}
func bottom(size: CGFloat) -> CGRect {
var rect = self
rect.origin.y += rect.size.height - size
rect.size.height = size
return rect
}
func right(offset: CGFloat, size: CGFloat) -> CGRect {
var rect = self
rect.origin.x = rect.size.width - (offset + size)
rect.size.width = size
return rect
}
func right(size: CGFloat) -> CGRect {
var rect = self
rect.origin.x += rect.size.width - size
rect.size.width = size
return rect
}
enum Aspect {
case Wide
case Tall
}
func slice(slice slice:Int, outOf:Int, aspect: Aspect) -> CGRect {
var rect = self
switch aspect {
case .Wide: rect.size.height /= CGFloat(outOf)
rect.origin.y += rect.size.height * CGFloat(slice)
case .Tall: rect.size.width /= CGFloat(outOf)
rect.origin.x += rect.size.width * CGFloat(slice)
}
return rect
}
func slices(sliceCount: Int, margin: CGFloat, aspect: Aspect) -> [CGRect] {
var rects = [CGRect]()
var rect = self
let count = CGFloat(sliceCount)
let gapCount = 1.0 + count
let used = margin * gapCount
switch aspect {
case .Wide:
let remain = rect.size.height - used
let size = remain / count
rect.origin.y += margin
rect.size.height = size
for _ in 0 ..< sliceCount {
rects.append(rect)
rect.origin.y += margin + size
}
case .Tall:
let remain = rect.size.width - used
let size = remain / count
rect.origin.x += margin
rect.size.width = size
for _ in 0 ..< sliceCount {
rects.append(rect)
rect.origin.x += margin + size
}
}
return rects
}
}
/// Slicing
extension CGRect {
func russianDolls(dollsCount: Int) -> [CGRect] {
var rects : [CGRect] = [self]
if dollsCount > 0 {
let dollsGapCount = 1.0 + CGFloat(dollsCount)
let (w,h) = (0.5 * self.width / dollsGapCount, 0.5 * self.height / dollsGapCount)
for i in 1 ..< dollsCount {
var rect = self
let wBias = CGFloat(i) * w
rect.origin.x += wBias
rect.size.width -= 2.0 * wBias
let hBias = CGFloat(i) * h
rect.origin.y += hBias
rect.size.height -= 2.0 * hBias
rects.append(rect)
}
}
return rects
}
}
/// Slicing
extension CGRect {
func spread(count:Int, margin: CGFloat, aspect: Aspect) -> [CGRect] {
var rects = [CGRect]()
let marginUsed = margin * CGFloat(1 + count)
if aspect == .Wide {
let remain = self.size.width - marginUsed
let spreadWidth = remain / CGFloat(count)
var sofar = margin
for _ in 0 ..< count {
var rect = self
rect.origin.x = sofar
rect.size.width = spreadWidth
rects.append(rect)
sofar = rect.maxX + margin
}
} else {
let remain = self.size.height - marginUsed
let spreadHeight = remain / CGFloat(count)
var sofar = margin
for _ in 0 ..< count {
var rect = self
rect.origin.y = sofar
rect.size.height = spreadHeight
rects.append(rect)
sofar = rect.maxY + margin
}
}
return rects
}
func spread(sizeables: [CGSizeable], aspect: Aspect) -> [CGRect] {
if sizeables.count < 2 {
return [self]
}
var rects: [CGRect] = sizeables.map {
let size = $0.autoSize()
var rect = self
if aspect == .Wide {
rect.size.height = size.height
} else {
rect.size.width = size.width
}
return rect.withWidth(rect.size.width).withHeight(rect.size.height)
}
let toKeep = rects.reduce(CGFloat(0.0)) {
$0 + (aspect == .Wide ? $1.size.height : $1.size.width)
}
let toFill = aspect == .Wide ? self.height : self.width
let toDist = toFill - toKeep
let toSpread = toDist / (CGFloat(rects.count) - 1.0)
func wideSpread() {
for index in 1 ..< rects.count {
rects[index].origin.y = toSpread + rects[index-1].maxY
}
}
func tallSpread() {
for index in 1 ..< rects.count {
rects[index].origin.x = toSpread + rects[index-1].maxX
}
}
switch aspect {
case .Wide: wideSpread()
case .Tall: tallSpread()
}
return rects
}
func tabStops(stops: [CGFloat]) -> [CGRect] {
return stops.map {
let tab = $0
let w = self.width
let w1 = w * tab
var rect = self
rect.origin.x += w1
rect.size.width -= w1
return rect
}
}
}
/// Sizing
extension CGRect {
func withWidth(forcedWidth:CGFloat) -> CGRect {
var rect = self
rect.size.width = forcedWidth
return rect
}
func withX(forcedX:CGFloat) -> CGRect {
var rect = self
rect.origin.x = forcedX
return rect
}
func withHeight(forcedHeight:CGFloat) -> CGRect {
var rect = self
rect.size.height = forcedHeight
return rect
}
func withY(forcedY:CGFloat) -> CGRect {
var rect = self
rect.origin.y = forcedY
return rect
}
func grow(edge:UIRectEdge, by: CGFloat) -> CGRect {
var rect = self
if edge == .Top {
rect.origin.y -= by
rect.size.height += by
} else if edge == .Left {
rect.origin.x -= by
rect.size.width += by
} else if edge == .Bottom {
rect.size.height += by
} else if edge == .Right {
rect.size.width += by
}
return rect
}
func shrink(edge:UIRectEdge, by: CGFloat) -> CGRect {
return self.grow(edge, by: -1.0 * by)
}
enum Sizest { /// yeah, play with English a bit
case Shortest
case Tallest
}
func squarest(sizest: Sizest) -> CGRect {
var rect = self
let min = rect.width < rect.height ? rect.width : rect.height
let max = rect.width > rect.height ? rect.width : rect.height
let dim = sizest == .Shortest ? min : max
rect.size.width = dim
rect.size.height = dim
return rect
}
func square(side: CGFloat) -> CGRect {
return size(CGSize(width: side, height: side))
}
func size(size: CGSize) -> CGRect {
var rect = self
rect.size = size
return rect
}
}
/// Misc
extension CGRect {
func offset(edge:UIRectEdge, by: CGFloat) -> CGRect {
var rect = self
if edge == .Left {
rect.origin.x -= by
} else if edge == .Right {
rect.origin.x += by
} else if edge == .Bottom {
rect.origin.y -= by
} else if edge == .Top {
rect.origin.y += by
}
return rect
}
func rectByApplyingInsets(insets: UIEdgeInsets) -> CGRect {
var rect = self
rect.origin.x += insets.left
rect.size.width -= insets.left + insets.right
rect.origin.y += insets.top
rect.size.height -= insets.top + insets.bottom
return rect
}
func rowInBetween(other: CGRect) -> CGRect {
var rect = self
rect.size.height = other.minY - rect.maxY
rect.origin.y = self.maxY
return rect
}
var isDefined: Bool {
if self.isEmpty || self.isInfinite || self.isNull {
return false
}
return true
}
func swapOrientation() -> CGRect {
var rect = self
let w = rect.size.width
rect.size.width = rect.size.height
rect.size.height = w
return rect
}
func stack(location:CGRectPosition, toRect:CGRect, offset:CGFloat=0) -> CGRect {
var positioned = self
switch location {
case .Above:
positioned.origin.y = toRect.origin.y - positioned.size.height
positioned = positioned.offset(.Bottom, by: -offset)
case .Below:
positioned.origin.y = toRect.origin.y + toRect.size.height
positioned = positioned.offset(.Top, by: offset)
}
return positioned
}
}
/// Interesting points
extension CGRect {
func north() -> CGPoint { return CGPoint(x:self.midX, y:self.minY) }
func northEast() -> CGPoint { return CGPoint(x:self.maxX, y:self.minY) }
func east() -> CGPoint { return CGPoint(x:self.maxX, y:self.midY) }
func southEast() -> CGPoint { return CGPoint(x:self.maxX, y:self.maxY) }
func south() -> CGPoint { return CGPoint(x:self.midX, y:self.maxY) }
func southWest() -> CGPoint { return CGPoint(x:self.minX, y:self.maxY) }
func west() -> CGPoint { return CGPoint(x:self.minX, y:self.midY) }
func northWest() -> CGPoint { return CGPoint(x:self.minX, y:self.minY) }
var N: CGPoint { return north() }
var NE: CGPoint { return northEast() }
var E: CGPoint { return east() }
var SE: CGPoint { return southEast() }
var S: CGPoint { return south() }
var SW: CGPoint { return southWest() }
var W: CGPoint { return west() }
var NW: CGPoint { return northWest() }
var topLeft:CGPoint { return NW }
var topRight:CGPoint { return NE }
var bottomLeft:CGPoint { return SW }
var bottomRight:CGPoint { return SE }
var home: CGRect {
var rect = self
rect.origin = CGPoint.zero
return rect
}
var center:CGPoint {
return CGPoint(x: self.midX, y:self.midY)
}
}
| true
|
8043e61a88d708cf86b407b0fbb123ded6ddcca6
|
Swift
|
suscabogdan/romat
|
/RoMat/navigationController.swift
|
UTF-8
| 1,017
| 2.59375
| 3
|
[] |
no_license
|
//
// navigationController.swift
// Romana clasa a 8a
//
// Created by Susca Bogdan on 11/05/2019.
// Copyright © 2019 Susca Bogdan. All rights reserved.
//
import Foundation
import UIKit
class navigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
let isLoggedIn = false
if isLoggedIn
{
let homeController = mainRoViewController()
viewControllers = [homeController]
}
else
{
perform(#selector(showLogginController), with: nil, afterDelay: 0.01)
}
}
@objc func showLogginController()
{
let logginController = mainPageViewController()
present(logginController, animated: true, completion: nil)
}
}
//class HomeController: UIViewController {
//
// override func viewDidLoad() {
// super.viewDidLoad()
// view.backgroundColor = .yellow
// }
//
//}
| true
|
f05cceca970039732960e08a3690a67636bef469
|
Swift
|
LuisFcoOrtiz/camarerosSwift
|
/Camareros/Camareros/DataCamarer.swift
|
UTF-8
| 3,380
| 2.640625
| 3
|
[] |
no_license
|
//
// DataCamarer.swift
// Camareros
//
// Created by aleluis burguerMan on 29/1/18.
// Copyright © 2018 aleluis burguerMan. All rights reserved.
//
import Foundation
import UIKit
class DataCamarer: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{
var array = [String]()
var arrayPuestos = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
lee()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return array.count//RETORNO EL NUMERO DE ELEMENTOOOOOOOOS
}
//EN ESTE METODO DE AQUI ABAJO COLOCAS EL TEXTO CORRESPONDIENTE EN LOS ETNOMBRE Y ETPUESTO, SI QUIERES AGREGAR ALGO MAS
//AL DISEÑO DE CADA ITEM HAZLO
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MiCeldaCollectionViewCell
cell.etNombre.text=array[indexPath.row]
cell.etPuesto.text=arrayPuestos[indexPath.row]
return cell
//ese cell entre comillas
//es el nombre que le he puesto yo a cada celda que conforma el collectionView
}
/*leer de mySQL*/
func lee() {
let request = NSMutableURLRequest(url: NSURL(string: "http://192.168.1.139/restabar/querys/swiftCamarero.php")! as URL)
request.httpMethod = "POST"
let postString = ""
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
self.parseJSON(data!)
}
task.resume()
}
/*-------*/
func parseJSON(_ data:Data) {
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
} catch let error as NSError {
print(error)
}
var jsonElement = NSDictionary()
let locations = NSMutableArray()
for i in 0 ..< jsonResult.count{
jsonElement = jsonResult[i] as! NSDictionary
//the following insures none of the JsonElement values are nil through optional binding
if let cnom = jsonElement["cnomcam"] as? String,
let puesto = jsonElement["cpuesto"] as? String{
//rellenar la lista
array.append(cnom)
arrayPuestos.append(puesto)
}
}
// en locations tenemos el resulado de la select
print(locations)
}
/**/
@IBOutlet weak var goBack: UIButton!
@IBAction func goToBack(_ sender: Any) {
}
}//fin de clase
| true
|
d5d4de46141fa342a54bcf19591dc3e8856781b3
|
Swift
|
lcs-earmstrong/waxingGuide
|
/waxingGuide/Views/waxRecomendationWithTool/casual/warmWax1.swift
|
UTF-8
| 1,158
| 3.15625
| 3
|
[] |
no_license
|
//
// warmWax1.swift
// waxingGuide
//
// Created by Evan Armstrong on 2021-03-22.
//
import SwiftUI
//
// warmWax.swift
// waxingGuide
//
// Created by Evan Armstrong on 2021-03-21.
//
import SwiftUI
struct warmWax1: View {
var body: some View {
ScrollView{
Text("""
These conditions can be some of the nicest to ski in but can sometimes be very slow (if it is above 0) for these temperatures I would recomend the swix PS8 or the swix TS8B.
""")
.padding(.horizontal, 15.0)
Spacer()
Spacer()
HStack{
Image("warmWaxCasual")
.resizable()
.frame(width: 125.0)
Image("warmWaxCasual2")
.resizable()
.frame(width: 125.0)
}
Text("Set the iron temp to 130 degrees celsius (266 degrees fahrenheit). Put wax on the ski than let cool for 10 minutes or more and scrape the wax off.")
.padding(.horizontal, 15.0)
}
}
}
struct warmWax1_Previews: PreviewProvider {
static var previews: some View {
warmWax1()
}
}
| true
|
fcae4af14a3bbbcc6a3ee2848b51b481fafeb2ba
|
Swift
|
Ahmedyoussefg5/Home-bride
|
/Home bride/Scenes/Hame Tabs/Provider Only/Galary/GalaryModels.swift
|
UTF-8
| 1,129
| 2.578125
| 3
|
[] |
no_license
|
//
// GalaryModels.swift
// Home bride
//
// Created by Youssef on 4/28/19.
// Copyright © 2019 Youssef. All rights reserved.
//
import Foundation
struct AllGalaryData: BaseCodable {
var status: Int
var msg: String?
let data: GalaryData?
}
struct GalaryData: Codable {
let galleries: Galleries
}
struct Galleries: Codable {
let images: Images
let videos: Videos
}
struct Images: Codable {
let image: [Image]
let count: Int
}
struct Image: Codable {
let id: Int
let type: String
let image: String
}
struct Videos: Codable {
let video: [Video]
let count: Int
}
struct Video: Codable {
let id: Int
let type: String
let video: String
}
// add image model
struct AddImage: BaseCodable {
var status: Int
var msg: String?
let data: ImageAdded?
}
struct ImageAdded: Codable {
let id: Int
let type: String
let image: String
}
// add Vid model
struct AddVideo: BaseCodable {
var status: Int
var msg: String?
let data: VideoAdded?
}
struct VideoAdded: Codable {
let id: Int
let type: String
let video: String
}
| true
|
28ad94fc61595a07a5628b1696ce91382e8f72d2
|
Swift
|
sodascourse/basic-swift
|
/Coding with Swift.playground/Pages/Collections.xcplaygroundpage/Contents.swift
|
UTF-8
| 5,561
| 4.90625
| 5
|
[
"Apache-2.0"
] |
permissive
|
//:
//: # Collection Data Types
//:
//: 
//:
//: Swift provides three primary collections, known as arrays, sets, and dictionaries. Arrays are ordered
//: collections of values. Sets are unordered collections of _unique_ values. Dictionaries are unordered collections of
//: key-value associations.
//:
//: Arrays, sets, and dictionaries in Swift are always clear about the types of values and keys that they can store.
//: They are implemented as **generic collections**.
//:
//:
//: --------------------------------------------------------------------------------------------------------------------
//:
//: ## Array
//:
//: You can treat an array like a sequence of variables which are indexed by continuous numbers.
//:
//: An array could be created via an array literal, which is values separated by commas (`,`) and wrapped by a bracket
//: (`[]`)
//:
[1, 2, 3] // An array with 3 integers
//:
//: The type of a array is written as `[Element]`, where `Element` is the type of values the array is allowed to store.
//:
let arrayOfStrings: [String] = ["Hello", "World"]
let arrayOfIntegers: [Int] = [1, 2, 3]
// NOTE: Try to uncomment the following line to see what happend
//let arrayOfIntegers1: [Int] = [1, 2, 3.1415926]
let emptyArrayOfFloats: [Float] = []
//:
//: ### Access the elements of an array
//:
//: In Swift, we can use **dot operator** (`.`) to access variables and functions associated to a value. We usually
//: call the assocatiated variable as `properties` of a variable, and the associated functions as `methods` of a
//: variable.
//:
//: For example, each arrays has a property named `count`, whose value is the number of elements in this array.
//: Also, there's a property named `isEmpty`, which is a boolean indicating whether this is an empty array or not.
//:
arrayOfStrings.count
arrayOfIntegers.isEmpty
emptyArrayOfFloats.isEmpty
//:
//: You can just use **subscript operator** (`[]`) to access elements in an array with an index.
//: Note that the index is zero-based. (The first number is `0` but not `1`.)
//:
//: Besides using the subscript operator, there are also some _properties_ for accessing elements.
//:
let firstString = arrayOfStrings[0]
let secondInteger = arrayOfIntegers[1]
// NOTE: Try to uncomment this line to see what error message the Xcode yields
//let thirdString = arrayOfStrings[2]
let lastString = arrayOfStrings.last
//:
//: ### Manipulate with the elements of an array
//:
//: There are some _methods_ used to manipulate the array
//:
var arrayOfFruits: [String] = ["Apple"]
// Use `append` method to add elements into an array
arrayOfFruits.append("Banana")
// Arrays are also addable
arrayOfFruits = arrayOfFruits + ["Orange", "Grape", "ラーメン"]
arrayOfFruits.removeAtIndex(4)
print(arrayOfFruits)
//:
//: ### Mutability
//:
//: In Swift, if you declare collections as constant (i.e. using `let`), they would become immutable
//: (i.e. not be able to be modified, like adding or removing elements).
//:
let numberArray1 = [1, 2, 3]
//numberArray1.append(2) // ERROR: Uncomment this line to see which error message you get.
//:
//: --------------------------------------------------------------------------------------------------------------------
//:
//: ## Dictionary
//:
//: You can treat a dictionary like a collection of variables which are labelled by **keys**.
//:
//: Each `value` in a _dictionary_ is associated with `a unique key`, which acts as an identifier for that value within
//: the dictionary. Unlike items in an array, items in a dictionary do not have a specified order. You use a dictionary
//: when you need to look up values based on their identifier, in much the same way that a real-world dictionary is
//: used to look up the definition for a particular word.
//:
//: A dictionary could be created by a dictionary literal. A key-value pair is annotated by _colon_ (`:`) like
//: `key: value`, and each key-value pairs is separated by _commas_ (`,`). The whole literal is wrapped by a _bracket_
//: (`[]`). Note, Swift also uses **bracket** for dictionary literals, unlike most programming languages which
//: use _curly braces_ (`{}`) for dictionaries
//:
[
"Peter": "peter@nccu.edu.tw",
"Angela": "angela@nccu.edu.tw"
]
//:
//: The type of a dictionary is written as `[Key: Value]`, where `Key` is the type of value that can be
//: used as a dictionary key, and `Value` is the type of value that the dictionary stores for those keys.
//:
let namesOfIntegers: [Int: String] = [1: "One", 2: "Two", 3: "Three"]
let contactBook: [String: String] = ["Peter": "Taipei, Taiwan", "Steve": "Palo Alto, CA, USA"]
let emptyDictionary: [String: String] = [:]
//:
//: ### Access the elements of a dictionary
//:
//: You can use **subscript operator** (`[]`) to access elements in a dictionary with its keys.
//:
namesOfIntegers.count
emptyDictionary.isEmpty
let one = namesOfIntegers[1]
let steveHome = contactBook["Steve"]
//:
//: ### Manipulate with the elements of a dictionary
//:
//: Just assign a new value with its key by the subscript operator
//:
var universities: [String: String] = ["NCCU": "政治大學", "NTU": "國立台灣大學"]
universities["NCCU"] = "國立政治大學" // Update
universities["NCKU"] = "國立成功大學" // Insert
print(universities)
// Try to uncomment the following line to see what happend
//namesOfIntegers[4] = "Four"
//: --------------------------------------------------------------------------------------------------------------------
//: [<- previous](@previous) | [next ->](@next)
//:
| true
|
8ef3fd395339e41f268e610371448696c7edd599
|
Swift
|
johndpope/SwiftRewriter
|
/Sources/GrammarModels/PropertySynthesizationList.swift
|
UTF-8
| 1,766
| 3.015625
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
/// Node for a @synthesize/@dynamic declaration in a class implementation.
public class PropertyImplementation: ASTNode, InitializableNode {
/// Returns the kind of this property implementation node.
/// Defaults to `@synthesize`, if it's missing the required keyword nodes.
public var kind: PropertyImplementationKind {
let kws = childrenMatching(type: KeywordNode.self)
if kws.contains(where: { $0.keyword == Keyword.atDynamic }) {
return .dynamic
} else {
return .synthesize
}
}
public var list: PropertySynthesizeList? {
return firstChild()
}
public required init(isInNonnullContext: Bool) {
super.init(isInNonnullContext: isInNonnullContext)
}
public override func addChild(_ node: ASTNode) {
super.addChild(node)
}
}
public enum PropertyImplementationKind {
case synthesize
case dynamic
}
/// List of synthesizes in a @synthesize property implementation.
public class PropertySynthesizeList: ASTNode, InitializableNode {
public var synthesizations: [PropertySynthesizeItem] {
return childrenMatching()
}
public required init(isInNonnullContext: Bool) {
super.init(isInNonnullContext: isInNonnullContext)
}
}
/// Single item of a @synthesize property implementation list.
public class PropertySynthesizeItem: ASTNode, InitializableNode {
public var propertyName: Identifier? {
return firstChild()
}
public var instanceVarName: Identifier? {
return child(atIndex: 1)
}
public var isDynamic: Bool = false
public required init(isInNonnullContext: Bool) {
super.init(isInNonnullContext: isInNonnullContext)
}
}
| true
|
0133dc225267e3270734cf6a9a46efe34a7d46bd
|
Swift
|
lucka3s/teste-beagle
|
/BeagleTest/Renderer/Renderer.swift
|
UTF-8
| 2,113
| 3.03125
| 3
|
[] |
no_license
|
//
// Renderer.swift
// BeagleTest
//
// Created by Lucas Sousa Silva on 17/02/20.
// Copyright © 2020 Zup IT. All rights reserved.
//
import UIKit
class Renderer: NSObject {
var rootItem: BeagleView?
enum ViewType: String {
case button = "BUTTON"
case text = "TEXT"
case input = "INPUT"
case image = "IMAGE"
case container = "CONTAINER"
static func beagleView(widget: [AnyHashable: Any]) -> BeagleView? {
guard let typeString = widget["_type_"] as? String, let type = ViewType(rawValue: typeString) else {
return nil
}
let text = widget["text"] as? String ?? ""
switch type {
case .button:
return Button(text: text)
case .text:
return Text(text: text)
case .input:
let value = widget["value"] as? String ?? ""
return Input(text: text, value: value)
case .image:
let url = widget["value"] as? String ?? ""
return Image(url: url)
case .container:
return containerView(widget: widget)
}
}
static func containerView(widget: [AnyHashable: Any]) -> BeagleView {
var children = [BeagleView]()
let widgetOrientation = widget["orientation"] as? String
let orientation: Container.Orientation = widgetOrientation == "H" ? .horizontal : .vertical
if let widgetChildren = widget["children"] as? [[AnyHashable: Any]] {
for child in widgetChildren {
if let beagleView = beagleView(widget: child) {
children.append(beagleView)
}
}
}
return Container(children: children, orientation: orientation)
}
}
func render(widget: [AnyHashable: Any]) -> UIView {
rootItem = ViewType.beagleView(widget: widget)
return rootItem?.view() ?? UIView()
}
}
| true
|
ee7647320dbb26783c434bf949446156aa865741
|
Swift
|
iX0ness/CoreDataSchool
|
/CoreDataSchool/Domain/Domain+Group.swift
|
UTF-8
| 439
| 2.8125
| 3
|
[] |
no_license
|
//
// Domain+Group.swift
// CoreDataSchool
//
// Created by Mykhaylo Levchuk on 03/01/2021.
//
import Foundation
extension Domain {
struct Group {
let speciality: String
let title: String
let students: [Domain.Student]?
}
}
extension Domain.Group {
static var mock: Domain.Group {
Domain.Group(speciality: "Informatics",
title: "I-A",
students: [])
}
}
| true
|
c86a5a6b73bf0e80d3ecb53807aa0becd07d6412
|
Swift
|
BB9z/iOS-Project-Template
|
/App/General/Extensions/Format/Date+App.swift
|
UTF-8
| 3,055
| 3.53125
| 4
|
[
"MIT"
] |
permissive
|
/*
应用级别的便捷方法
*/
import B9Foundation
extension Date {
/// 判断一个时间是否在最近给定的范围内
static func isRecent(_ date: Date?, range: TimeInterval) -> Bool {
guard let date = date else { return false }
return fabs(date.timeIntervalSinceNow) <= range
}
// @MBDependency:2
/// 一天的起始时间
var dayStart: Date {
(self as NSDate).dayStart
}
// @MBDependency:2
/// 一天的结束时间
var dayEnd: Date {
(self as NSDate).dayEnd
}
/// 后台专用日期格式
var dayIdentifier: MBDateDayIdentifier {
DateFormatter.dayIdentifier.string(from: self) as MBDateDayIdentifier
}
// @MBDependency:2 范例性质,请根据项目需求修改
/**
今天,则“今天”
今年,则本地化的 X月X日
再久,本地化的 X年X月X日
*/
var dayString: String {
if Date.isSame(granularity: .day, self, .current) {
return "今天"
} else if Date.isSame(granularity: .year, self, .current) {
return DateFormatter.localizedMD.string(from: self)
} else {
return DateFormatter.localizedYMD.string(from: self)
}
}
// @MBDependency:2 范例性质,请根据项目需求修改
/// 刚刚、几分钟前、几小时前等样式
var recentString: String {
let diff = -timeIntervalSinceNow
if diff < 3600 * 24 {
if diff < 60 {
return "刚刚"
}
let hour = Int(diff / 3600)
if hour < 1 {
return "\(Int(diff / 60))分钟前"
}
return "\(hour)小时前"
} else if diff < 3600 * 24 * 30 {
let diffDay = NSDate.daysBetweenDate(self, andDate: .current)
return "\(diffDay)天前"
}
return dayString
}
}
extension TimeInterval {
// @MBDependency:3
/// XX:XX 时长显示,超过一小时不显示小时
var mmssString: String {
let value = Int(self.rounded())
return String(format: "%02d:%02d", value / 60, value % 60)
}
// @MBDependency:2
/**
按时长返回时分秒
例
```
print(TimeInterval(12345).durationComponents)
// (hour: 3, minute: 25, second: 45)
```
*/
var durationComponents: (hour: Int, minute: Int, second: Int) {
var second = Int(self.rounded())
let hour = second / 3600
second -= hour * 3600
let minute = second / 60
second -= minute * 60
return (hour, minute, second)
}
}
// MARK: - 时间戳
/* 🔰 如需使用毫秒时间戳,可启用下列代码
/// 应用毫秒时间戳
typealias TimeStamp = Int64
extension Date {
/// 毫秒时间戳
var timestamp: TimeStamp {
TimeStamp(timeIntervalSince1970 * 1000)
}
}
extension TimeStamp {
/// 转为日期对象
var date: Date {
Date(timeIntervalSince1970: Double(self) / 1000.0)
}
}
*/
| true
|
fe595d1decd779533f54bbd26a75c38a4b2ba692
|
Swift
|
DocVaughan/Swift-SpriteKit-Analog-Stick
|
/AnalogStick Empty/AnalogStick Empty/GameScene.swift
|
UTF-8
| 4,256
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// GameScene.swift
//
// Created by Dmitriy Mitrophanskiy on 28.09.14.
// Copyright (c) 2014 Dmitriy Mitrophanskiy. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
var appleNode: SKSpriteNode?
//let toOtherSceneBtn = SKSpriteNode(imageNamed: "gear")
let moveAnalogStick = AnalogJoystick(diameters: (88, 44), colors: (UIColor.darkGrayColor(), UIColor.grayColor()))
let rotateAnalogStick = AnalogJoystick(diameters: (88, 44), colors: (UIColor.darkGrayColor(), UIColor.grayColor()))
override func didMoveToView(view: SKView) {
/* Setup your scene here */
backgroundColor = UIColor.whiteColor()
physicsBody = SKPhysicsBody(edgeLoopFromRect: frame)
moveAnalogStick.position = CGPointMake(moveAnalogStick.radius + 15, moveAnalogStick.radius + 15)
addChild(moveAnalogStick)
rotateAnalogStick.position = CGPointMake(CGRectGetMaxX(self.frame) - rotateAnalogStick.radius - 15, rotateAnalogStick.radius + 15)
addChild(rotateAnalogStick)
//MARK: Handlers begin
moveAnalogStick.startHandler = { [unowned self] in
guard let aN = self.appleNode else { return }
aN.runAction(SKAction.sequence([SKAction.scaleTo(0.5, duration: 0.5), SKAction.scaleTo(1, duration: 0.5)]))
}
moveAnalogStick.trackingHandler = { [unowned self] data in
guard let aN = self.appleNode else { return }
aN.position = CGPointMake(aN.position.x + (data.velocity.x * 0.12), aN.position.y + (data.velocity.y * 0.12))
}
moveAnalogStick.stopHandler = { [unowned self] in
guard let aN = self.appleNode else { return }
aN.runAction(SKAction.sequence([SKAction.scaleTo(1.5, duration: 0.5), SKAction.scaleTo(1, duration: 0.5)]))
}
rotateAnalogStick.trackingHandler = { [unowned self] jData in
self.appleNode?.zRotation = jData.angular
}
rotateAnalogStick.stopHandler = { [unowned self] in
guard let aN = self.appleNode else { return }
aN.runAction(SKAction.rotateByAngle(3.6, duration: 0.5))
}
//MARK: Handlers end
let selfHeight = CGRectGetHeight(frame)
let btnsOffset: CGFloat = 10
// toOtherSceneBtn.position = CGPointMake(CGRectGetMaxX(frame) - CGRectGetWidth(toOtherSceneBtn.frame), CGRectGetMidY(joystickSizeLabel.frame))
// addChild(toOtherSceneBtn)
addApple(CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame)))
view.multipleTouchEnabled = true
}
func addApple(position: CGPoint) {
guard let appleImage = UIImage(named: "apple") else { return }
let texture = SKTexture(image: appleImage)
let apple = SKSpriteNode(texture: texture)
apple.physicsBody = SKPhysicsBody(texture: texture, size: apple.size)
apple.physicsBody!.affectedByGravity = false
insertChild(apple, atIndex: 0)
apple.position = position
appleNode = apple
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
if let touch = touches.first {
let node = nodeAtPoint(touch.locationInNode(self))
switch node {
// case toOtherSceneBtn:
// toOtherScene()
default:
addApple(touch.locationInNode(self))
}
}
}
func toOtherScene() {
let newScene = GameScene()
newScene.scaleMode = .ResizeFill
let transition = SKTransition.moveInWithDirection(SKTransitionDirection.Right, duration: 1)
view?.presentScene(newScene, transition: transition)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
extension UIColor {
static func random() -> UIColor {
return UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1)
}
}
| true
|
3db4f0814888c5fe8f3f5d49c70fc02b93ba3dfc
|
Swift
|
robsoncassol/PhysicsCup
|
/PhysicsCup/GameScene.swift
|
UTF-8
| 1,651
| 2.78125
| 3
|
[] |
no_license
|
//
// GameScene.swift
// PhysicsCup
//
// Created by John Fisher on 12/5/14.
// Copyright (c) 2014 John Fisher. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var sounds = [SKAction.playSoundFileNamed("small-bell-ring-01a.wav", waitForCompletion:true)]
var lastTime = NSTimeInterval()
var canPlaySound = false, shouldPlaySound = false
override func didMoveToView(view: SKView) {
self.physicsWorld.contactDelegate = self
self.physicsWorld.gravity = CGVectorMake(0.0, -4.9)
let sprite = SKSpriteNode(imageNamed: "arrow.png")
sprite.xScale = 0.15
sprite.yScale = 0.15
sprite.name = "arrow"
sprite.position = CGPointMake(self.frame.size.width/8.0, self.frame.size.height/8.0)
self.addChild(sprite)
sprite.runAction(SKAction.rotateByAngle(CGFloat(M_PI_2), duration: 0))
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: AnyObject in touches {
let sprite = StarNode.star(touch.locationInNode(self))
self.addChild(sprite)
}
}
override func update(currentTime: CFTimeInterval) {
self.canPlaySound = currentTime - self.lastTime > 0.1
if (self.canPlaySound && self.shouldPlaySound) {
self.runAction(sounds[0])
self.lastTime = currentTime
self.shouldPlaySound = false
}
}
func didBeginContact(contact: SKPhysicsContact) {
self.shouldPlaySound = (contact.bodyA.node?.name == "star" && contact.bodyB.node?.name == "star")
}
}
| true
|
b82df68826e60d8750923c8d625f6536530e492f
|
Swift
|
sahsubodh/leetcode-swift
|
/1008. Construct Binary Search Tree from Preorder Traversal.playground/Contents.swift
|
UTF-8
| 1,513
| 3.84375
| 4
|
[] |
no_license
|
import UIKit
var str = "Hello, playground"
/*
Return the root node of a binary search tree that matches the given preorder traversal.
(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)
Example 1:
Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]
Note:
1 <= preorder.length <= 100
The values of preorder are distinct.
*/
/**
* Definition for a binary tree node. */
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
class Solution {
var i = 0
func bstFromPreorder(_ preorder: [Int]) -> TreeNode? {
guard preorder.count > 0 else {
return nil
}
return bstFromPreorder(preorder, Int.max)
}
private func bstFromPreorder(_ preorder:[Int],_ bound:Int) -> TreeNode? {
if preorder.count == i || preorder[i] > bound {
return nil
}
var root = TreeNode(preorder[i])
i += 1
root.left = bstFromPreorder(preorder, root.val)
root.right = bstFromPreorder(preorder, bound)
return root
}
}
| true
|
df058f9f5f78e5f98886c9299add9b7496c4fe37
|
Swift
|
SomeRandomiOSDev/CBORCoding
|
/Tests/CBORCodingTests/CBORTests.swift
|
UTF-8
| 22,423
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// CBORTests.swift
// CBORCodingTests
//
// Copyright © 2021 SomeRandomiOSDev. All rights reserved.
//
// swiftlint:disable comma nesting force_try implicitly_unwrapped_optional
@testable import CBORCoding
import XCTest
// MARK: - CBORTests Definition
class CBORTests: XCTestCase {
// MARK: Test Methods
func testIndefiniteLengthDataInitialization() {
let data = Data([UInt8(0), 1, 2, 3, 4, 5, 6, 7, 8, 9])
let ilData1 = CBOR.IndefiniteLengthData(wrapping: [Data(data[0 ..< 6]), Data(data[6...])])
let ilData2 = CBOR.IndefiniteLengthData(wrapping: data, chunkSize: 6)
XCTAssertEqual(ilData1.chunks, ilData2.chunks)
}
func testIndefiniteLengthStringInitialization() {
let string = "CBORCoding"
let ilString1 = CBOR.IndefiniteLengthString(wrapping: ["CBORCod", "ing"])
let ilString2 = CBOR.IndefiniteLengthString(wrapping: string, chunkSize: 7)
XCTAssertEqual(ilString1.chunks, ilString2.chunks)
XCTAssertEqual(ilString1.stringValue, string)
XCTAssertEqual(ilString1.stringValue(as: .utf8), string)
}
func testTagValues() {
XCTAssertEqual(CBOR.Tag.standardDateTime.bits[0], CBOR.MajorType.tag.rawValue | 0)
XCTAssertEqual(CBOR.Tag.epochDateTime.bits[0], CBOR.MajorType.tag.rawValue | 1)
XCTAssertEqual(CBOR.Tag.positiveBignum.bits[0], CBOR.MajorType.tag.rawValue | 2)
XCTAssertEqual(CBOR.Tag.negativeBignum.bits[0], CBOR.MajorType.tag.rawValue | 3)
XCTAssertEqual(CBOR.Tag.decimalFraction.bits[0], CBOR.MajorType.tag.rawValue | 4)
XCTAssertEqual(CBOR.Tag.bigfloat.bits[0], CBOR.MajorType.tag.rawValue | 5)
XCTAssertEqual(CBOR.Tag.base64URLConversion.bits[0], CBOR.MajorType.tag.rawValue | 21)
XCTAssertEqual(CBOR.Tag.base64Conversion.bits[0], CBOR.MajorType.tag.rawValue | 22)
XCTAssertEqual(CBOR.Tag.base16Conversion.bits[0], CBOR.MajorType.tag.rawValue | 23)
XCTAssertEqual(CBOR.Tag.encodedCBORData.bits[0], CBOR.MajorType.tag.rawValue | 24)
XCTAssertEqual(CBOR.Tag.encodedCBORData.bits[1], 24)
XCTAssertEqual(CBOR.Tag.uri.bits[0], CBOR.MajorType.tag.rawValue | 24)
XCTAssertEqual(CBOR.Tag.uri.bits[1], 32)
XCTAssertEqual(CBOR.Tag.base64URL.bits[0], CBOR.MajorType.tag.rawValue | 24)
XCTAssertEqual(CBOR.Tag.base64URL.bits[1], 33)
XCTAssertEqual(CBOR.Tag.base64.bits[0], CBOR.MajorType.tag.rawValue | 24)
XCTAssertEqual(CBOR.Tag.base64.bits[1], 34)
XCTAssertEqual(CBOR.Tag.regularExpression.bits[0], CBOR.MajorType.tag.rawValue | 24)
XCTAssertEqual(CBOR.Tag.regularExpression.bits[1], 35)
XCTAssertEqual(CBOR.Tag.mimeMessage.bits[0], CBOR.MajorType.tag.rawValue | 24)
XCTAssertEqual(CBOR.Tag.mimeMessage.bits[1], 36)
XCTAssertEqual(CBOR.Tag.selfDescribedCBOR.bits[0], CBOR.MajorType.tag.rawValue | 25)
XCTAssertEqual(CBOR.Tag.selfDescribedCBOR.bits[1], 0xD9)
XCTAssertEqual(CBOR.Tag.selfDescribedCBOR.bits[2], 0xF7)
}
func testTagInitialization() {
// Valid Tag Values
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 0]))) // .standardDateTime
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 1]))) // .epochDateTime
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 2]))) // .positiveBignum
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 3]))) // .negativeBignum
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 4]))) // .decimalFraction
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 5]))) // .bigfloat
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 21]))) // .base64URLConversion
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 22]))) // .base64Conversion
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 23]))) // .base16Conversion
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 24, 24]))) // .encodedCBORData
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 24, 32]))) // .uri
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 24, 33]))) // .base64URL
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 24, 34]))) // .base64
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 24, 35]))) // .regularExpression
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 24, 36]))) // .mimeMessage
XCTAssertNotNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 25, 0xD9, 0xF7]))) // .selfDescribedCBOR
// Invalid Tag Values
XCTAssertNil(CBOR.Tag(bits: Data()))
XCTAssertNil(CBOR.Tag(bits: Data([CBOR.MajorType.unsigned.rawValue])))
XCTAssertNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 24])))
XCTAssertNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 25])))
XCTAssertNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 26])))
XCTAssertNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 24, 25])))
XCTAssertNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 25, 25])))
XCTAssertNil(CBOR.Tag(bits: Data([CBOR.MajorType.tag.rawValue | 25, 25, 25])))
}
func testDirectlyEncodeUndefined() {
struct Test: Encodable {
func encode(to encoder: Encoder) throws {
try CBOR.Undefined().encode(to: encoder)
}
}
let encoder = CBOREncoder()
var encoded1 = Data(), encoded2 = Data()
XCTAssertNoThrow(encoded1 = try encoder.encode(Test()))
XCTAssertNoThrow(encoded2 = try encoder.encode(CBOR.Undefined()))
XCTAssertEqual(encoded1, encoded2)
}
func testDirectlyDecodeUndefined() {
struct Test: Decodable {
init(from decoder: Decoder) throws {
_ = try CBOR.Undefined(from: decoder)
}
}
XCTAssertThrowsError(try CBORDecoder().decode(Test.self, from: convertFromHexString("0xF6")))
}
func testEncodeUndefinedWithOtherEncoder() {
// Success
do {
let encoded = try JSONEncoder().encode([CBOR.Undefined()])
_ = try JSONDecoder().decode([CBOR.Undefined].self, from: encoded)
} catch { XCTFail(error.localizedDescription) }
// Failure
let encoded = try! JSONEncoder().encode(["Some random string"])
XCTAssertThrowsError(try JSONDecoder().decode([CBOR.Undefined].self, from: encoded))
}
func testEncodeIndefiniteLengthArrayWithOtherEncoder() {
let array = CBOR.IndefiniteLengthArray(wrapping: [0, 1, 2, 3])
let encoder = JSONEncoder()
var encoded = Data(), encodedIL = Data()
XCTAssertNoThrow(encoded = try encoder.encode(array))
XCTAssertNoThrow(encodedIL = try encoder.encode(array.array))
XCTAssertEqual(encoded, encodedIL)
}
func testDirectlyDecodeIndefiniteLengthArray() {
struct Test: Decodable {
let value: CBOR.IndefiniteLengthArray<Int>
init(from decoder: Decoder) throws {
value = try CBOR.IndefiniteLengthArray(from: decoder)
}
}
var test: Test!
XCTAssertNoThrow(test = try CBORDecoder().decode(Test.self, from: convertFromHexString("0x9F00010203040506070809FF")))
XCTAssertEqual(test.value, CBOR.IndefiniteLengthArray(wrapping: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
}
func testEncodeIndefiniteLengthMapWithOtherEncoder() {
let map = CBOR.IndefiniteLengthMap(wrapping: ["a": 0])
let encoder = JSONEncoder()
var encoded = Data(), encodedIL = Data()
XCTAssertNoThrow(encoded = try encoder.encode(map))
XCTAssertNoThrow(encodedIL = try encoder.encode(map.map))
XCTAssertEqual(encoded, encodedIL)
}
func testDirectlyDecodeIndefiniteLengthMap() {
struct Test: Decodable {
let value: CBOR.IndefiniteLengthMap<String, Int>
init(from decoder: Decoder) throws {
value = try CBOR.IndefiniteLengthMap(from: decoder)
}
}
var test: Test!
XCTAssertNoThrow(test = try CBORDecoder().decode(Test.self, from: convertFromHexString("0xBF616100616201616302616403616504FF")))
XCTAssertEqual(test.value, CBOR.IndefiniteLengthMap(wrapping: ["a": 0, "b": 1, "c": 2, "d": 3, "e": 4]))
}
func testEncodeIndefiniteLengthDataWithOtherEncoder() {
let data = CBOR.IndefiniteLengthData(wrapping: Data([UInt8(0), 1, 2, 3, 4, 5, 6, 7, 8, 9]), chunkSize: 6)
let encoder = JSONEncoder()
var encoded = Data(), encodedIL = Data()
XCTAssertNoThrow(encoded = try encoder.encode(data))
XCTAssertNoThrow(encodedIL = try encoder.encode(data.chunks))
XCTAssertEqual(encoded, encodedIL)
}
func testDecodeIndefiniteLengthDataWithOtherEncoder() {
let value = CBOR.IndefiniteLengthData(wrapping: convertFromHexString("0x00010203040506070809"), chunkSize: 5)
do {
let encoded = try JSONEncoder().encode(value)
let decoded = try JSONDecoder().decode(CBOR.IndefiniteLengthData.self, from: encoded)
XCTAssertEqual(value, decoded)
} catch { XCTFail(error.localizedDescription) }
}
func testEncodeIndefiniteLengthStringWithOtherEncoder() {
let string = CBOR.IndefiniteLengthString(wrapping: "CBORCoding", chunkSize: 6)
let encoder = JSONEncoder()
var encoded = Data(), encodedIL = Data()
XCTAssertNoThrow(encoded = try encoder.encode(string))
XCTAssertNoThrow(encodedIL = try encoder.encode(string.chunks))
XCTAssertEqual(encoded, encodedIL)
}
func testDecodeIndefiniteLengthStringWithOtherEncoder() {
let value = CBOR.IndefiniteLengthString(wrapping: "CBORCoding", chunkSize: 5)
do {
let encoded = try JSONEncoder().encode(value)
let decoded = try JSONDecoder().decode(CBOR.IndefiniteLengthString.self, from: encoded)
XCTAssertEqual(value, decoded)
} catch { XCTFail(error.localizedDescription) }
}
func testDirectlyEncodeIndefiniteLengthData() {
struct Test: Encodable {
static let data = CBOR.IndefiniteLengthData(wrapping: Data([UInt8(0), 1, 2, 3, 4, 5, 6, 7, 8, 9]), chunkSize: 6)
func encode(to encoder: Encoder) throws {
try Test.data.encode(to: encoder)
}
}
let encoder = CBOREncoder()
var encoded1 = Data(), encoded2 = Data()
XCTAssertNoThrow(encoded1 = try encoder.encode(Test()))
XCTAssertNoThrow(encoded2 = try encoder.encode(Test.data))
XCTAssertEqual(encoded1, encoded2)
}
func testDirectlyDecodeIndefiniteLengthData() {
struct Test: Decodable {
let data: CBOR.IndefiniteLengthData
init(from decoder: Decoder) throws {
data = try CBOR.IndefiniteLengthData(from: decoder)
}
}
var test: Test!
XCTAssertNoThrow(test = try CBORDecoder().decode(Test.self, from: convertFromHexString("0x5F460001020304054406070809FF")))
XCTAssertEqual(test.data.chunks, [convertFromHexString("0x000102030405"), convertFromHexString("0x06070809")])
}
func testDirectlyEncodeIndefiniteLengthString() {
struct Test: Encodable {
static let string = CBOR.IndefiniteLengthString(wrapping: "CBORCoding", chunkSize: 6)
func encode(to encoder: Encoder) throws {
try Test.string.encode(to: encoder)
}
}
let encoder = CBOREncoder()
var encoded1 = Data(), encoded2 = Data()
XCTAssertNoThrow(encoded1 = try encoder.encode(Test()))
XCTAssertNoThrow(encoded2 = try encoder.encode(Test.string))
XCTAssertEqual(encoded1, encoded2)
}
func testDirectlyDecodeIndefiniteLengthString() {
struct Test: Decodable {
let string: CBOR.IndefiniteLengthString
init(from decoder: Decoder) throws {
string = try CBOR.IndefiniteLengthString(from: decoder)
}
}
var test: Test!
XCTAssertNoThrow(test = try CBORDecoder().decode(Test.self, from: convertFromHexString("0x7F6643424F52436F6464696E67FF")))
XCTAssertEqual(test.string.chunks, [convertFromHexString("0x43424F52436F"), convertFromHexString("0x64696E67")])
XCTAssertEqual(test.string.stringValue, "CBORCoding")
XCTAssertEqual(test.string.stringValue(as: .utf8), "CBORCoding")
}
func testEncodeNegativeUInt64WithOtherEncoder() {
let value = CBOR.NegativeUInt64(rawValue: 0xFF)
let encoder = JSONEncoder()
var encoded = Data(), encodedIL = Data()
XCTAssertNoThrow(encoded = try encoder.encode([value.rawValue]))
XCTAssertNoThrow(encodedIL = try encoder.encode([value]))
XCTAssertEqual(encoded, encodedIL)
}
func testDirectlyEncodeNegativeUInt64() {
struct Test: Encodable {
static let value = CBOR.NegativeUInt64(rawValue: 0x100)
func encode(to encoder: Encoder) throws {
try Test.value.encode(to: encoder)
}
}
let encoder = CBOREncoder()
var encoded1 = Data(), encoded2 = Data()
XCTAssertNoThrow(encoded1 = try encoder.encode(Test()))
XCTAssertNoThrow(encoded2 = try encoder.encode(Test.value))
XCTAssertEqual(encoded1, encoded2)
}
func testDecodeNegativeUInt64WithOtherEncoder() {
let value = CBOR.NegativeUInt64(rawValue: 0xFF)
do {
let encoded = try JSONEncoder().encode([value])
let decoded = try JSONDecoder().decode([CBOR.NegativeUInt64].self, from: encoded)
XCTAssertEqual([value], decoded)
} catch { XCTFail(error.localizedDescription) }
}
func testDirectlyDecodeNegativeUInt64() {
struct Test: Decodable {
let value: CBOR.NegativeUInt64
init(from decoder: Decoder) throws {
value = try CBOR.NegativeUInt64(from: decoder)
}
}
var test: Test!
XCTAssertNoThrow(test = try CBORDecoder().decode(Test.self, from: convertFromHexString("0x38FF")))
XCTAssertEqual(test.value.rawValue, 0xFF)
}
func testEncodeSimpleValueWithOtherEncoder() {
let simple = CBOR.SimpleValue(rawValue: 0x6E)
let encoder = JSONEncoder()
var encoded1 = Data(), encoded2 = Data()
XCTAssertNoThrow(encoded1 = try encoder.encode([simple]))
XCTAssertNoThrow(encoded2 = try encoder.encode([simple.rawValue]))
XCTAssertEqual(encoded1, encoded2)
}
func testDirectlyDecodeSimpleValue() {
struct Test: Decodable {
let value: CBOR.SimpleValue
init(from decoder: Decoder) throws {
value = try CBOR.SimpleValue(from: decoder)
}
}
var test: Test!
XCTAssertNoThrow(test = try CBORDecoder().decode(Test.self, from: convertFromHexString("0xF818")))
XCTAssertEqual(test.value.rawValue, 24)
}
func testDecodeSimpleValueWithOtherEncoder() {
let value = CBOR.SimpleValue(rawValue: 0x7F)
do {
let encoded = try JSONEncoder().encode([value])
let decoded = try JSONDecoder().decode([CBOR.SimpleValue].self, from: encoded)
XCTAssertEqual([value], decoded)
} catch { XCTFail(error.localizedDescription) }
}
func testEncodeBignumWithOtherEncoder() {
struct Test: Encodable {
private enum CodingKeys: String, CodingKey {
case isPositive
case content
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(true, forKey: .isPositive)
try container.encode(Data([UInt8(0x00), 0x01, 0x02, 0x03]), forKey: .content)
}
}
let bignum = CBOR.Bignum(isPositive: true, content: Data([UInt8(0x00), 0x01, 0x02, 0x03]))
let encoder = JSONEncoder()
var encoded1 = Data(), encoded2 = Data()
XCTAssertNoThrow(encoded1 = try encoder.encode(bignum))
XCTAssertNoThrow(encoded2 = try encoder.encode(Test()))
XCTAssertEqual(encoded1, encoded2)
}
func testDecodeBignumWithOtherEncoder() {
let value = CBOR.Bignum(isPositive: true , content: convertFromHexString("0x010000000000000000"))
do {
let encoded = try JSONEncoder().encode(value)
let decoded = try JSONDecoder().decode(CBOR.Bignum.self, from: encoded)
XCTAssertEqual(value, decoded)
} catch { XCTFail(error.localizedDescription) }
}
func testDirectlyDecodeBignum() {
struct Test: Decodable {
let value: CBOR.Bignum
init(from decoder: Decoder) throws {
value = try CBOR.Bignum(from: decoder)
}
}
var test: Test!
XCTAssertNoThrow(test = try CBORDecoder().decode(Test.self, from: convertFromHexString("0xC249010000000000000000")))
XCTAssertTrue(test.value.isPositive)
XCTAssertEqual(test.value.content, convertFromHexString("0x010000000000000000"))
}
func testEncodeDecimalFractionWithOtherEncoder() {
let decimal = CBOR.DecimalFraction<Int, Int>(exponent: 9, mantissa: -3)
let encoder = JSONEncoder()
var encoded1 = Data(), encoded2 = Data()
XCTAssertNoThrow(encoded1 = try encoder.encode(decimal))
XCTAssertNoThrow(encoded2 = try encoder.encode([decimal.exponent, decimal.mantissa]))
XCTAssertEqual(encoded1, encoded2)
}
func testDecodeDecimalFractionWithOtherEncoder() {
let value = CBOR.DecimalFraction(exponent: 1, mantissa: 15)
do {
let encoded = try JSONEncoder().encode(value)
let decoded = try JSONDecoder().decode(CBOR.DecimalFraction<Int, Int>.self, from: encoded)
XCTAssertEqual(value, decoded)
} catch { XCTFail(error.localizedDescription) }
}
func testEncodeBigfloatWithOtherEncoder() {
let float = CBOR.Bigfloat<Int, Int>(exponent: 9, mantissa: -3)
let encoder = JSONEncoder()
var encoded1 = Data(), encoded2 = Data()
XCTAssertNoThrow(encoded1 = try encoder.encode(float))
XCTAssertNoThrow(encoded2 = try encoder.encode([float.exponent, float.mantissa]))
XCTAssertEqual(encoded1, encoded2)
}
func testDecodeBigfloatWithOtherEncoder() {
let value = CBOR.Bigfloat(exponent: 1, mantissa: 15)
do {
let encoded = try JSONEncoder().encode(value)
let decoded = try JSONDecoder().decode(CBOR.Bigfloat<Int, Int>.self, from: encoded)
XCTAssertEqual(value, decoded)
} catch { XCTFail(error.localizedDescription) }
}
func testCBOREncoded() {
let encoder = CBOREncoder()
var data = Data(), encodedData = Data()
XCTAssertNoThrow(data = try encoder.encode("CBOR"))
XCTAssertNoThrow(encodedData = try encoder.encode(CBOR.CBOREncoded(encodedData: data)))
XCTAssertEqual(data, encodedData)
}
func testEncodeCBOREncodedWithOtherEncoder() {
let encoder = JSONEncoder()
let dataToEncode = Data("CBOR".utf8)
var encoded1 = Data(), encoded2 = Data()
XCTAssertNoThrow(encoded1 = try encoder.encode([dataToEncode]))
XCTAssertNoThrow(encoded2 = try encoder.encode([CBOR.CBOREncoded(encodedData: dataToEncode)]))
XCTAssertEqual(encoded1, encoded2)
}
func testDirectlyEncodeCBOREncoded() {
struct Test: Encodable {
static var value: Data = {
try! CBOREncoder().encode("CBOR")
}()
func encode(to encoder: Encoder) throws {
try CBOR.CBOREncoded(encodedData: Test.value).encode(to: encoder)
}
}
let encoder = CBOREncoder()
var data = Data()
XCTAssertNoThrow(data = try encoder.encode(Test()))
XCTAssertEqual(data, Test.value)
}
// MARK: Private Methods
private func convertFromHexString(_ string: String) -> Data {
var hex = string.starts(with: "0x") ? String(string.dropFirst(2)) : string
if (hex.count % 2) == 1 { // odd number of hex characters
hex.insert(contentsOf: "0", at: hex.startIndex)
}
var data = Data(capacity: hex.count / 2)
for i in stride(from: 0, to: hex.count, by: 2) {
let map = { (character: Character) -> UInt8 in
switch character {
case "0": return 0x00
case "1": return 0x01
case "2": return 0x02
case "3": return 0x03
case "4": return 0x04
case "5": return 0x05
case "6": return 0x06
case "7": return 0x07
case "8": return 0x08
case "9": return 0x09
case "A": return 0x0A
case "B": return 0x0B
case "C": return 0x0C
case "D": return 0x0D
case "E": return 0x0E
case "F": return 0x0F
default: preconditionFailure("Invalid hex character: \(character)")
}
}
data.append(map(hex[hex.index(hex.startIndex, offsetBy: i)]) << 4 |
map(hex[hex.index(hex.startIndex, offsetBy: i + 1)]))
}
return data
}
}
| true
|
978086b1cb54f998039691794d050e89891e4985
|
Swift
|
NickMoignard/movieAPP
|
/MovieAPP/LoginSwipeableCardViewController.swift
|
UTF-8
| 2,866
| 2.734375
| 3
|
[] |
no_license
|
/*
LoginSwipeableCardViewController.swift
MovieAPP
Created by Nicholas Moignard on 12/8/16.
Synopsis:
Data Members:
Mehtods:
Developer Notes:
~ When user logs in, need to call a delegate method in the
MasterViewController that removes the card from the screen
*/
import UIKit
import Firebase
class LoginSwipeableCardViewController: SwipeViewController, FBSDKLoginButtonDelegate {
var cardOrigin: CGPoint? = nil,
delegate: LoginMasterSwipeViewControllerDelegate? = nil
let firebase = FirebaseService()
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Overlay View
override func addOverlayView(origin: CGPoint) {
// ...
print("adding overlay view from loginVC")
}
// MARK: - Facebook Login Button and Delegate Methods
func addFBLoginButton() {
// Adjust SubView Center
var center = self.view.center
if let cardOrigin = self.cardOrigin {
center.x -= cardOrigin.x
center.y -= cardOrigin.y
}
let loginView: FBSDKLoginButton = FBSDKLoginButton()
self.view.addSubview(loginView)
loginView.center = center
loginView.readPermissions = ["public_profile", "email"]
loginView.delegate = self
}
func returnUserData() {
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil) {
// Process error
print("Error: \(error)")
} else {
print("fetched user: \(result)")
let userName : NSString = result.valueForKey("name") as! NSString
print("User Name is: \(userName)")
let userEmail : NSString = result.valueForKey("email") as! NSString
print("User Email is: \(userEmail)")
}
})
}
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
// DELEGATE METHOD
if error != nil {
print("there was an error logging in with facebook!")
}
else if result.isCancelled {
print("user cancelled logging in with facebook")
} else {
// Swap facebook credentials with firebase credentials, then login to firebase
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)
FIRAuth.auth()?.signInWithCredential(credential) {
(user, error) in
if error != nil {
print("There was an error logging in to firebase after getting facebook credentials")
}
self.delegate?.userLoggedIn()
}
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
print("User Logged Out")
try! FIRAuth.auth()?.signOut()
self.delegate?.userLoggedOut()
}
}
| true
|
e4b80ae6e3746e65cf8acc9d23cdb6edbf860071
|
Swift
|
bharatsesham/InstaAuction
|
/CameraKitDemo/CameraKitDemo/CKFSession.swift
|
UTF-8
| 2,925
| 3.015625
| 3
|
[] |
permissive
|
//
// This file initiates the AVCaptureSession and returns the camera device input. It is also responsible for start and stop of the
// session
//
// Created by Avinash Parasurampuram on 09/03/2020.
//
import AVFoundation
public extension UIDeviceOrientation {
var videoOrientation: AVCaptureVideoOrientation {
switch UIDevice.current.orientation {
case .portraitUpsideDown:
return .portrait
case .landscapeLeft:
return .portrait
case .landscapeRight:
return .portrait
default:
return .portrait
}
}
}
private extension CKFSession.DeviceType {
var captureDeviceType: AVCaptureDevice.DeviceType {
switch self {
case .frontCamera, .backCamera:
return .builtInWideAngleCamera
case .microphone:
return .builtInMicrophone
}
}
var captureMediaType: AVMediaType {
switch self {
case .frontCamera, .backCamera:
return .video
case .microphone:
return .audio
}
}
var capturePosition: AVCaptureDevice.Position {
switch self {
case .frontCamera:
return .front
case .backCamera:
return .back
case .microphone:
return .unspecified
}
}
}
extension CKFSession.CameraPosition {
var deviceType: CKFSession.DeviceType {
switch self {
case .back:
return .backCamera
case .front:
return .frontCamera
}
}
}
@objc public protocol CKFSessionDelegate: class {
@objc func didChangeValue(session: CKFSession, value: Any, key: String)
}
@objc public class CKFSession: NSObject {
@objc public enum DeviceType: UInt {
case frontCamera, backCamera, microphone
}
@objc public enum CameraPosition: UInt {
case front, back
}
@objc public let session: AVCaptureSession
@objc public var previewLayer: AVCaptureVideoPreviewLayer?
@objc public var overlayView: UIView?
@objc public var zoom = 1.0
@objc public weak var delegate: CKFSessionDelegate?
@objc override init() {
self.session = AVCaptureSession()
}
@objc deinit {
self.session.stopRunning()
}
@objc public func start() {
self.session.startRunning()
}
@objc public func stop() {
self.session.stopRunning()
}
//Captures the AVCaptureDeviceInput of the camera. In this case - BuiltInDualCamera
@objc public static func captureDeviceInput(type: DeviceType) throws -> AVCaptureDeviceInput {
guard let captureDevice = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back) else {
fatalError("No depth video camera available")
}
let cameraInput = try AVCaptureDeviceInput(device: captureDevice)
return cameraInput
}
}
| true
|
fedf89fa2eb684fc995d51bccdc3d3393fe18898
|
Swift
|
brenopolanski/calculate-bmi-app
|
/CalculateIMC/CalculateIMC/TelaResultadosViewController.swift
|
UTF-8
| 1,467
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// TelaResultadosViewController.swift
// CalculateIMC
//
// Created by user140218 on 5/26/18.
// Copyright © 2018 user140218. All rights reserved.
//
import UIKit
class TelaResultadosViewController: UIViewController {
var valorImc : Float?
var nomeCompleto: String?
var idade : Float?
@IBOutlet weak var labelNomeCompleto: UILabel!
@IBOutlet weak var labelValorIdade: UILabel!
@IBOutlet weak var labelResultado: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let sValorImg = NSString(format: "%.2f", valorImc!)
let sIdade = NSString(format: "%.0f", idade!)
self.labelNomeCompleto.text = "Olá \(nomeCompleto!)"
self.labelValorIdade.text = "\(sIdade) anos"
self.labelResultado.text = "\(sValorImg)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func voltar(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
603ddb9daea52f6e5e039d7c0ea23e0c6a7e3bcf
|
Swift
|
S-TooManyQuestions-S/FINTECH
|
/TinkoffChat/TinkoffChat/CoreLayer/Handlers/CoreDataStackHandler/ObjectsExtensions.swift
|
UTF-8
| 1,721
| 2.734375
| 3
|
[] |
no_license
|
//
// ObjectsExtensions.swift
// TinkoffChat
//
// Created by Андрей Самаренко on 31.03.2021.
//
import UIKit
import CoreData
extension Channel {
func about() -> String {
return "Channel Id: \(identifier_db ?? "no id")\n\t"
+ "Name: \(name_db ?? "Unnamed channel")\n\t"
+ "Last message: \(lastMessage_db ?? "No last message")\t\n"
+ "Last activity: \(lastActivity_db ?? Date())\n\n"
+ "Messages of the chanel: \(messages?.count ?? 0)\n"
}
convenience init(with channelDataModel: ConversationCellDataModel,
in context: NSManagedObjectContext) {
self.init(context: context)
self.identifier_db = channelDataModel.identifier
self.name_db = channelDataModel.name
self.lastMessage_db = channelDataModel.lastMessage
self.lastActivity_db = channelDataModel.lastActivity
}
}
extension Message {
func about() -> String {
return
"MessageId: \(messageId_db ?? "unknown id")\n\t"
+ "Content: \(content_db ?? "no content")\n\t"
+ "Created: \(created_db ?? Date())\n\t"
+ "SenderId: \(senderId_db ?? "no sender ID")\n\t"
+ "SenderName: \(senderName_db ?? "unknownuser")\n"
}
convenience init(with messageDataModel: MessageCellDataModel,
in context: NSManagedObjectContext) {
self.init(context: context)
self.messageId_db = messageDataModel.messageId
self.created_db = messageDataModel.created
self.content_db = messageDataModel.content
self.senderName_db = messageDataModel.senderName
self.senderId_db = messageDataModel.senderId
}
}
| true
|
567e900e61d397f1328e853b741f7e25ab652e42
|
Swift
|
dmitryamiller/CoinWatcher
|
/CoinWatch/AddWalletViewController.swift
|
UTF-8
| 7,013
| 2.53125
| 3
|
[] |
no_license
|
//
// AddWalletViewController.swift
// CoinWatch
//
// Created by Dmitry Miller on 8/26/17.
// Copyright © 2017 Dmitry Miller. All rights reserved.
//
import UIKit
import PromiseKit
class AddWalletViewController: UIViewController {
private var coinType: CoinType?
private var address: String?
private var addressEntry: AddressEntryViewController?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let addressEntry = segue.destination as? AddressEntryViewController {
self.addressEntry = addressEntry
addressEntry.didGetAddressWithCoinType = { [weak self] address, coinType in
guard let unwrappedSelf = self else { return }
unwrappedSelf.coinType = coinType
unwrappedSelf.address = address
if let coinType = unwrappedSelf.coinType {
unwrappedSelf.validateAndSaveCoin(withType: coinType, address: address)
} else {
unwrappedSelf.performSegue(withIdentifier: "coinType", sender: self)
}
}
} else if let coinTypeSelection = segue.destination as? CoinTypeViewController {
coinTypeSelection.coinType = self.coinType
coinTypeSelection.didSelectCointype = { [weak self] coinType in
guard let address = self?.address else { return }
coinTypeSelection.navigationController?.popViewController(animated: true)
self?.validateAndSaveCoin(withType: coinType, address: address)
}
}
}
@IBAction func handleEntryTypeChange(_ sender: UISegmentedControl) {
guard let addressEntry = self.addressEntry else { sender.selectedSegmentIndex = 0; return }
switch addressEntry.entryType {
case .qr:
addressEntry.entryType = .manual
case .manual:
addressEntry.entryType = .qr
}
}
private func validateAndSaveCoin(withType coinType: CoinType, address: String) {
if !coinType.validate(address: address) {
let alert = UIAlertController(title: "Invalid Address", message: "Address apperas to be in invalid format", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { [weak self] _ in
if self?.addressEntry?.entryType == .manual {
self?.navigationController?.popViewController(animated: true)
}
self?.addressEntry?.restartIfApplicable()
}))
self.present(alert, animated: true, completion: nil)
return
}
// check if we already have this wallet
if Wallet.exists(with: address, coinType: coinType) {
let alert = UIAlertController(title: "Wallet Exists", message: "Looks like a wallet with this address already exists", preferredStyle: .alert)
let dismissAction = UIAlertAction(title: "Dismiss", style: .default) { [weak self] _ in
if self?.addressEntry?.entryType == .manual {
self?.navigationController?.popViewController(animated: true)
} else {
self?.addressEntry?.restartIfApplicable()
}
}
alert.addAction(dismissAction)
self.present(alert, animated: true, completion: nil)
return
}
let address = try! coinType.normalize(address: address)
BusyIndicatorManager.instance.show()
self.fetchNativeBalance(for: address, coinType)
.then { [weak self] nativeBalance in
_ = Wallet.create(coinType: coinType, address: address, name: Wallet.defaultName(for: coinType), nativeBalance: nativeBalance)
self?.dismiss(animated: true, completion: nil)
return AnyPromise(Promise<Void>())
}
.catch {[weak self] error in
let alert = UIAlertController(title: "Validation Failed", message: "Failed to validate this address. Would you like to try again?", preferredStyle: .alert)
let tryAgainAction = UIAlertAction(title: "Try Again", style: .default) { _ in
self?.validateAndSaveCoin(withType: coinType, address: address)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
self?.addressEntry?.restartIfApplicable()
}
alert.addAction(tryAgainAction)
alert.addAction(cancelAction)
self?.present(alert, animated: true, completion: nil)
}.always {
BusyIndicatorManager.instance.hide()
}
}
private func fetchNativeBalance(for address: String, _ coinType: CoinType) -> Promise<Double> {
switch coinType {
case .bitcoin:
return BitcoinManager.instance.fetchBalances(for: [address]).then { balances in
if let balance = balances[address] {
return Promise<Double>(value: balance)
} else {
return Promise<Double>(error: CoinBalanceError.notFound)
}
}
case .bitcoinCash:
return BitcoinCashManager.instance.fetchBalances(for: [address]).then { balances in
if let balance = balances[address] {
return Promise<Double>(value: balance)
} else {
return Promise<Double>(error: CoinBalanceError.notFound)
}
}
case .etherium:
return EtheriumManager.instance.fetchBalances(for: [address]).then { balances in
if let balance = balances[address] {
return Promise<Double>(value: balance)
} else {
return Promise<Double>(error: CoinBalanceError.notFound)
}
}
case .dash:
return DashManager.instance.fetchBalances(for: [address]).then { balances in
if let balance = balances[address] {
return Promise(value: balance)
} else {
return Promise(error: CoinBalanceError.notFound)
}
}
case .litecoin:
return LitecoinManager.instance.fetchBalances(for: [address]).then { balances in
if let balance = balances[address] {
return Promise<Double>(value: balance)
} else {
return Promise<Double>(error: CoinBalanceError.notFound)
}
}
}
}
}
extension AddWalletViewController {
enum CoinBalanceError : Error {
case notFound
}
}
| true
|
eda2836032aa4acb99e3183e0894eea74c7835ac
|
Swift
|
dweiner13/cypress
|
/Cypress/Repository list/View/RepositoryViewModel.swift
|
UTF-8
| 912
| 2.921875
| 3
|
[] |
no_license
|
//
// RepositoryViewModel.swift
// Cypress
//
// Created by Daniel A. Weiner on 11/18/15.
// Copyright © 2015 Daniel Weiner. All rights reserved.
//
import Foundation
import RxSwift
struct RepositoryViewModel: Equatable {
enum RepoStatus {
case Available
case InProgress
}
let name: String
let url: NSURL
var cloningProgress: Observable<RepositoryCloningDelegate.CloningEvent>? = nil
init(url: NSURL) {
self.url = url
if let name = url.lastPathComponent {
self.name = name
}
else {
errorStream.value = NSError(domain: "URL had no last path component", code: 0, userInfo: nil)
self.name = "[error]"
}
}
func selectAsActive() {
activeRepositoryStream.value = url
}
}
func ==(lhs: RepositoryViewModel, rhs:RepositoryViewModel) -> Bool {
return lhs.url == rhs.url
}
| true
|
90575b88e725b6b5b6866947de53a9f2d7dc31ff
|
Swift
|
leafarmd/shuffleSongs
|
/ShuffleSongs/Features/SongsList/Cell/SongsListTableViewCell.swift
|
UTF-8
| 776
| 2.5625
| 3
|
[] |
no_license
|
import UIKit
typealias SongsListCellConfig = TableCellConfigurator<SongsListTableViewCell, SongModel>
class SongsListTableViewCell: UITableViewCell, ConfigurableCell {
@IBOutlet weak var imageViewAlbum: UIImageView!
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelArtistName: UILabel!
func configure(data: SongModel) {
imageViewAlbum.layer.cornerRadius = 10
imageViewAlbum.loadImageFromURL(data.artworkURL)
labelTitle.text = data.trackName ?? "--"
let primaryGenreName = data.primaryGenreName ?? ""
labelArtistName.text = "\(data.artistName)(\(primaryGenreName))"
}
override func prepareForReuse() {
super.prepareForReuse()
self.imageViewAlbum.image = nil
}
}
| true
|
5833b585fa4c306a09ee37f12d60c1c281609ea4
|
Swift
|
ilijapuaca/OpenCombine
|
/Sources/OpenCombine/Publishers/Publishers.Optional.swift
|
UTF-8
| 13,679
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
//
// Publishers.Optional.swift
//
//
// Created by Sergej Jaskiewicz on 17.06.2019.
//
extension Publishers {
/// A publisher that publishes an optional value to each subscriber exactly once, if
/// the optional has a value.
///
/// If `result` is `.success`, and the value is non-nil, then `Optional` waits until
/// receiving a request for at least 1 value before sending the output. If `result` is
/// `.failure`, then `Optional` sends the failure immediately upon subscription.
/// If `result` is `.success` and the value is nil, then `Optional` sends `.finished`
/// immediately upon subscription.
///
/// In contrast with `Just`, an `Optional` publisher can send an error.
/// In contrast with `Once`, an `Optional` publisher can send zero values and finish
/// normally, or send zero values and fail with an error.
public struct Optional<Output, Failure: Error>: Publisher {
// swiftlint:disable:previous syntactic_sugar
/// The result to deliver to each subscriber.
public let result: Result<Output?, Failure>
/// Creates a publisher to emit the optional value of a successful result, or fail
/// with an error.
///
/// - Parameter result: The result to deliver to each subscriber.
public init(_ result: Result<Output?, Failure>) {
self.result = result
}
public init(_ output: Output?) {
self.init(.success(output))
}
public init(_ failure: Failure) {
self.init(.failure(failure))
}
public func receive<SubscriberType: Subscriber>(subscriber: SubscriberType)
where Output == SubscriberType.Input, Failure == SubscriberType.Failure
{
switch result {
case .success(let value?):
subscriber.receive(subscription: Inner(value: value,
downstream: subscriber))
case .success(nil):
subscriber.receive(subscription: Subscriptions.empty)
subscriber.receive(completion: .finished)
case .failure(let failure):
subscriber.receive(subscription: Subscriptions.empty)
subscriber.receive(completion: .failure(failure))
}
}
}
}
private final class Inner<SubscriberType: Subscriber>: Subscription,
CustomStringConvertible,
CustomReflectable
{
private let _output: SubscriberType.Input
private var _downstream: SubscriberType?
init(value: SubscriberType.Input, downstream: SubscriberType) {
_output = value
_downstream = downstream
}
func request(_ demand: Subscribers.Demand) {
if let downstream = _downstream, demand > 0 {
_ = downstream.receive(_output)
downstream.receive(completion: .finished)
_downstream = nil
}
}
func cancel() {
_downstream = nil
}
var description: String { return "Optional" }
var customMirror: Mirror {
return Mirror(self, unlabeledChildren: CollectionOfOne(_output))
}
}
extension Publishers.Optional: Equatable where Output: Equatable, Failure: Equatable {}
extension Publishers.Optional where Output: Equatable {
public func contains(_ output: Output) -> Publishers.Optional<Bool, Failure> {
return Publishers.Optional(result.map { $0 == output })
}
public func removeDuplicates() -> Publishers.Optional<Output, Failure> {
return self
}
}
extension Publishers.Optional where Output: Comparable {
public func min() -> Publishers.Optional<Output, Failure> {
return self
}
public func max() -> Publishers.Optional<Output, Failure> {
return self
}
}
extension Publishers.Optional {
public func allSatisfy(
_ predicate: (Output) -> Bool
) -> Publishers.Optional<Bool, Failure> {
return Publishers.Optional(result.map { $0.map(predicate) })
}
public func tryAllSatisfy(
_ predicate: (Output) throws -> Bool
) -> Publishers.Optional<Bool, Error> {
return Publishers.Optional(result.tryMap { try $0.map(predicate) })
}
public func collect() -> Publishers.Optional<[Output], Failure> {
return Publishers.Optional(result.map { $0.map { [$0] } })
}
public func compactMap<ElementOfResult>(
_ transform: (Output) -> ElementOfResult?
) -> Publishers.Optional<ElementOfResult, Failure> {
return Publishers.Optional(result.map { $0.flatMap(transform) })
}
public func tryCompactMap<ElementOfResult>(
_ transform: (Output) throws -> ElementOfResult?
) -> Publishers.Optional<ElementOfResult, Error> {
return Publishers.Optional(result.tryMap { try $0.flatMap(transform) })
}
public func min(
by areInIncreasingOrder: (Output, Output) -> Bool
) -> Publishers.Optional<Output, Failure> {
return self
}
public func tryMin(
by areInIncreasingOrder: (Output, Output) throws -> Bool
) -> Publishers.Optional<Output, Failure> {
return self
}
public func max(
by areInIncreasingOrder: (Output, Output) -> Bool
) -> Publishers.Optional<Output, Failure> {
return self
}
public func tryMax(
by areInIncreasingOrder: (Output, Output) throws -> Bool
) -> Publishers.Optional<Output, Failure> {
return self
}
public func contains(
where predicate: (Output) -> Bool
) -> Publishers.Optional<Bool, Failure> {
return Publishers.Optional(result.map { $0.map(predicate) })
}
public func tryContains(
where predicate: (Output) throws -> Bool
) -> Publishers.Optional<Bool, Error> {
return Publishers.Optional(result.tryMap { try $0.map(predicate) })
}
public func count() -> Publishers.Optional<Int, Failure> {
return Publishers.Optional(result.map { _ in 1 })
}
public func dropFirst(_ count: Int = 1) -> Publishers.Optional<Output, Failure> {
precondition(count >= 0, "count must not be negative")
return Publishers.Optional(try? result.get().flatMap { count == 0 ? $0 : nil })
}
public func drop(
while predicate: (Output) -> Bool
) -> Publishers.Optional<Output, Failure> {
return Publishers.Optional(result.map { $0.flatMap { predicate($0) ? nil : $0 } })
}
public func tryDrop(
while predicate: (Output) throws -> Bool
) -> Publishers.Optional<Output, Error> {
return Publishers.Optional(
result.tryMap { try $0.flatMap { try predicate($0) ? nil : $0 } }
)
}
public func first() -> Publishers.Optional<Output, Failure> {
return self
}
public func first(
where predicate: (Output) -> Bool
) -> Publishers.Optional<Output, Failure> {
return Publishers.Optional(result.map { $0.flatMap { predicate($0) ? $0 : nil } })
}
public func tryFirst(
where predicate: (Output) throws -> Bool
) -> Publishers.Optional<Output, Error> {
return Publishers.Optional(
result.tryMap { try $0.flatMap { try predicate($0) ? $0 : nil } }
)
}
public func last() -> Publishers.Optional<Output, Failure> {
return self
}
public func last(
where predicate: (Output) -> Bool
) -> Publishers.Optional<Output, Failure> {
return Publishers.Optional(result.map { $0.flatMap { predicate($0) ? $0 : nil } })
}
public func tryLast(
where predicate: (Output) throws -> Bool
) -> Publishers.Optional<Output, Error> {
return Publishers.Optional(
result.tryMap { try $0.flatMap { try predicate($0) ? $0 : nil } }
)
}
public func filter(
_ isIncluded: (Output) -> Bool
) -> Publishers.Optional<Output, Failure> {
return Publishers.Optional(
result.map { $0.flatMap { isIncluded($0) ? $0 : nil } }
)
}
public func tryFilter(
_ isIncluded: (Output) throws -> Bool
) -> Publishers.Optional<Output, Error> {
return Publishers.Optional(
result.tryMap { try $0.flatMap { try isIncluded($0) ? $0 : nil } }
)
}
public func ignoreOutput() -> Publishers.Empty<Output, Failure> {
return Publishers.Empty()
}
public func map<ElementOfResult>(
_ transform: (Output) -> ElementOfResult
) -> Publishers.Optional<ElementOfResult, Failure> {
return Publishers.Optional(result.map { $0.map(transform) })
}
public func tryMap<ElementOfResult>(
_ transform: (Output) throws -> ElementOfResult
) -> Publishers.Optional<ElementOfResult, Error> {
return Publishers.Optional(result.tryMap { try $0.map(transform) })
}
public func mapError<TransformedFailure: Error>(
_ transform: (Failure) -> TransformedFailure
) -> Publishers.Optional<Output, TransformedFailure> {
return Publishers.Optional(result.mapError(transform))
}
public func output(at index: Int) -> Publishers.Optional<Output, Failure> {
precondition(index >= 0, "index must not be negative")
return Publishers.Optional(result.map { $0.flatMap { index == 0 ? $0 : nil } })
}
public func output<RangeExpr: RangeExpression>(
in range: RangeExpr
) -> Publishers.Optional<Output, Failure> where RangeExpr.Bound == Int {
// TODO: Broken in Apple's Combine? (FB6169621)
// Empty range should result in a nil
let range = range.relative(to: 0..<Int.max)
return Publishers.Optional(
result.map { $0.flatMap { range.lowerBound == 0 ? $0 : nil } }
)
// The above implementation is used for compatibility.
//
// It actually probably should be just this:
// return Publishers.Optional(
// result.map { $0.flatMap { range.contains(0) ? $0 : nil } }
// )
}
public func prefix(_ maxLength: Int) -> Publishers.Optional<Output, Failure> {
precondition(maxLength >= 0, "maxLength must not be negative")
// TODO: Seems broken in Apple's Combine (FB6168300)
return Publishers.Optional(
result.map { $0.flatMap { maxLength == 0 ? $0 : nil } }
)
// The above implementation is used for compatibility.
//
// It actually should be the following:
// return Publishers.Optional(
// result.map { $0.flatMap { maxLength > 0 ? $0 : nil } }
// )
}
public func prefix(
while predicate: (Output) -> Bool
) -> Publishers.Optional<Output, Failure> {
return Publishers.Optional(
result.map { $0.flatMap { predicate($0) ? $0 : nil } }
)
}
public func tryPrefix(
while predicate: (Output) throws -> Bool
) -> Publishers.Optional<Output, Error> {
return Publishers.Optional(
result.tryMap { try $0.flatMap { try predicate($0) ? $0 : nil } }
)
}
public func reduce<Accumulator>(
_ initialResult: Accumulator,
_ nextPartialResult: (Accumulator, Output) -> Accumulator
) -> Publishers.Optional<Accumulator, Failure> {
return Publishers.Optional(
result.map { $0.map { nextPartialResult(initialResult, $0) } }
)
}
public func tryReduce<Accumulator>(
_ initialResult: Accumulator,
_ nextPartialResult: (Accumulator, Output) throws -> Accumulator
) -> Publishers.Optional<Accumulator, Error> {
return Publishers.Optional(
result.tryMap { try $0.map { try nextPartialResult(initialResult, $0) } }
)
}
public func scan<ElementOfResult>(
_ initialResult: ElementOfResult,
_ nextPartialResult: (ElementOfResult, Output) -> ElementOfResult
) -> Publishers.Optional<ElementOfResult, Failure> {
return Publishers.Optional(
result.map { $0.map { nextPartialResult(initialResult, $0) } }
)
}
public func tryScan<ElementOfResult>(
_ initialResult: ElementOfResult,
_ nextPartialResult: (ElementOfResult, Output) throws -> ElementOfResult
) -> Publishers.Optional<ElementOfResult, Error> {
return Publishers.Optional(
result.tryMap { try $0.map { try nextPartialResult(initialResult, $0) } }
)
}
public func removeDuplicates(
by predicate: (Output, Output) -> Bool
) -> Publishers.Optional<Output, Failure> {
return self
}
public func tryRemoveDuplicates(
by predicate: (Output, Output) throws -> Bool
) -> Publishers.Optional<Output, Error> {
return Publishers.Optional(result.mapError { $0 })
}
public func replaceError(with output: Output) -> Publishers.Optional<Output, Never> {
return Publishers.Optional(.success(result.unwrapOr(output)))
}
public func replaceEmpty(
with output: Output
) -> Publishers.Optional<Output, Failure> {
return self
}
public func retry(_ times: Int) -> Publishers.Optional<Output, Failure> {
return self
}
public func retry() -> Publishers.Optional<Output, Failure> {
return self
}
}
extension Publishers.Optional where Failure == Never {
public func setFailureType<Failure: Error>(
to failureType: Failure.Type
) -> Publishers.Optional<Output, Failure> {
return Publishers.Optional(result.success)
}
}
| true
|
8a601215a81cc10b2b41a93503fef174e2ba54d9
|
Swift
|
Wainow/MyDiary
|
/MyDiary/domain/entity/Note.swift
|
UTF-8
| 1,087
| 3.1875
| 3
|
[] |
no_license
|
//
// Note.swift
// MyDiary
//
// Created by Алексей Черепанов on 04.07.2021.
//
import Foundation
class Note: Identifiable{
init(
id: Int = CurrentDateHelper.getIdFromCurrentDate(),
title: String = "New Day",
date: String = CurrentDateHelper.getCurrentDate(),
evaluate: Int = 0,
tags: [String] = [],
isLocked: Bool = false,
story: String = ""
) {
self.id = id
self.date = date
self.title = title
self.evaluate = evaluate
self.tags = tags
self.isLocked = isLocked
self.story = story
}
var id: Int
var title: String
var date: String
var evaluate: Int
var tags: [String]
var isLocked: Bool
var story: String
}
extension String {
func deleteIncorrectSpacers() -> String {
self.replacingOccurrences(
of: "\\s*(\\p{Po}\\s?)\\s*",
with: "$1",
options: [.regularExpression])
}
func deleteAllSpacers() -> String {
self.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
| true
|
b6a77f522ca936dfaa5432f6b1e9099cccc1e122
|
Swift
|
hollylowe/Drill-Alert
|
/DrillAlert/WellboreTableViewCell.swift
|
UTF-8
| 736
| 2.546875
| 3
|
[] |
no_license
|
//
// WellboreTableViewCell.swift
// DrillAlert
//
// Created by Lucas David on 11/29/14.
// Copyright (c) 2014 Drillionaires. All rights reserved.
//
import Foundation
import UIKit
class WellboreTableViewCell: UITableViewCell {
@IBOutlet weak var wellboreNameLabel: UILabel!
@IBOutlet weak var wellNameLabel: UILabel!
class func getCellIdentifier() -> String! {
return "WellboreTableViewCell"
}
func setupWithWellbore(wellbore: Wellbore!) {
self.wellboreNameLabel.text = wellbore.name
self.wellNameLabel.text = wellbore.well.name + ", " + wellbore.well.location
self.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
self.selectionStyle = .None
}
}
| true
|
0b3658ec2be4ca252d6a6c385cdee7ef8d55220a
|
Swift
|
gzkiwiinc/SuperCodable
|
/SuperCodable/IntegerType+Codable.swift
|
UTF-8
| 501
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
//
// Integer+Codable.swift
// SuperCodable
//
// Created by 卓同学 on 2018/8/7.
// Copyright © 2018年 kiwi. All rights reserved.
//
import Foundation
extension SingleValueEncodingContainer {
public mutating func encode(_ value: IntegerType) throws {
if let int64 = value.int64 {
try encode(int64)
} else if let uint64 = value.uint64 {
try encode(uint64)
} else {
assertionFailure("unexpected integer")
}
}
}
| true
|
2b3b358f4142cf098aba631e8c1a81110fe9cfcc
|
Swift
|
XianxianChen/AsyncTesting
|
/AsyncTesting/MovieView.swift
|
UTF-8
| 1,479
| 2.515625
| 3
|
[] |
no_license
|
//
// MovieView.swift
// AsyncTesting
//
// Created by C4Q on 4/25/18.
// Copyright © 2018 C4Q. All rights reserved.
//
import UIKit
class MovieView: UIView {
lazy var tableView: UITableView = {
let tv = UITableView(frame: UIScreen.main.bounds)
tv.register(UITableViewCell.self, forCellReuseIdentifier: "movieCell")
return tv
}()
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override init(frame: CGRect) {
super.init(frame: UIScreen.main.bounds)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
setupViews()
}
private func setupViews() {
self.backgroundColor = .green
addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.centerXAnchor.constraint(equalTo: safeAreaLayoutGuide.centerXAnchor).isActive = true
tableView.centerYAnchor.constraint(equalTo: safeAreaLayoutGuide.centerYAnchor).isActive = true
tableView.widthAnchor.constraint(equalTo: safeAreaLayoutGuide.widthAnchor).isActive = true
tableView.heightAnchor.constraint(equalTo: safeAreaLayoutGuide.heightAnchor).isActive = true
}
}
| true
|
79a908ecf0ff385671d6475fc86282566d10cdf0
|
Swift
|
andremvb/BigShows
|
/BigShows/Modules/Episodes/EpisodesViewModel.swift
|
UTF-8
| 2,518
| 3.015625
| 3
|
[] |
no_license
|
//
// EpisodesViewModel.swift
// BigShows
//
// Created by Andre Valdivia on 9/1/20.
// Copyright © 2020 Andre Valdivia. All rights reserved.
//
import Foundation
protocol EpisodesServiceProtocol{
func fetchsEpisodes(showID: Int, completion: @escaping (Result<[Episode],Error>) -> ())
}
class EpisodesViewModel{
var episodesViewModel: [EpisodeCellViewModel] = []
var seasonsViewModel: [Int] = []
///Called when fetched new seasons
var onUpdateSeasons: (() -> ())?
///Called when fetched new episodes
var onUpdateEpisodes: (() -> ())?
private let showID: Int
private let service: EpisodesServiceProtocol
private var seasons: [Season] = []
init(service: EpisodesServiceProtocol, showID: Int){
self.service = service
self.showID = showID
}
func fetchSeasons(){
service.fetchsEpisodes(showID: showID) { (result) in
switch result{
case .success(let episodes):
self.seasons = self.createSeasons(episodes: episodes)
self.updateSeasonsViewModel()
if self.seasons.count > 0{
self.updateEpisodes(index: 0)
}
case .failure(let error):
print(error)
}
}
}
func updateEpisodes(index: Int){
episodesViewModel = seasons[index].episodes.map{EpisodeCellViewModel($0)}
DispatchQueue.main.async {
self.onUpdateEpisodes?()
}
}
private func updateSeasonsViewModel(){
seasonsViewModel = seasons.map{$0.number}
DispatchQueue.main.async {
self.onUpdateSeasons?()
}
}
private func createSeasons(episodes: [Episode]) -> [Season]{
var seasonsDict: [Int:Season] = [:]
episodes.forEach { (episode) in
if seasonsDict[episode.season] != nil{
seasonsDict[episode.season]!.episodes.append(episode)
}else{
var season = Season(number: episode.season)
season.episodes.append(episode)
seasonsDict[episode.season] = season
}
}
var seasons: [Season] = []
//Sort Episodes
for (_,var season) in seasonsDict{
season.episodes.sort{$0.number < $1.number}
seasons.append(season)
}
//Sort seasons
seasons.sort{$0.number < $1.number}
return seasons
}
}
| true
|
098332060af3dacecc18adb9bd8adbd1b35a8d18
|
Swift
|
xxpenghao1-ios/pointSingleThatIsTo
|
/pointSingleThatIsTo/Vendors/SKScNavBarController/SKController/SKScNavViewController.swift
|
UTF-8
| 7,000
| 2.5625
| 3
|
[] |
no_license
|
//
// SKScNavViewController.swift
// SCNavController
//
// Created by Sukun on 15/9/29.
// Copyright © 2015年 Sukun. All rights reserved.
//
import UIKit
class SKScNavViewController: UIViewController, SKScNavBarDelegate, UIScrollViewDelegate {
//MARK:必须设置的一些属性
/**
* @param scNaBarColor
* @param showArrowButton
* @param lineColor
*/
//MARK: -- 公共设置属性
/**
* 是否显示扩展按钮
*/
var showArrowButton:Bool! // 默认值是true
/**
* 导航栏的颜色
*/
var scNavBarColor:UIColor! //默认值clearColor
/**
* 扩展按钮上的图片
*/
var scNavBarArrowImage:UIImage!
/**
* 包含所有子视图控制器的数组
*/
var subViewControllers:NSArray!
/**
* 线的颜色
*/
var lineColor:UIColor! //默认值redColor
/**
* 扩展菜单栏的高度
*/
var launchMenuHeight:CGFloat!
//MARK: -- 私有属性
fileprivate var currentIndex:Int! //当前显示的页面的下标
fileprivate var titles:NSMutableArray! //子视图控制器的title数组
fileprivate var scNavBar:SKScNavBar! //导航栏视图
fileprivate var mainView:UIScrollView! //主页面的ScrollView
//MARK: ----- 方法 -----
//MARK: -- 外界接口
/**
* 初始化withShowArrowButton
* @param showArrowButton 显示扩展菜单按钮
*/
init(show:Bool){
super.init(nibName: nil, bundle: nil)
self.showArrowButton = show
}
/**
* 初始化withSubViewControllers
* @param subViewControllers 子视图控制器数组
*/
init(subViewControllers:NSArray) {
super.init(nibName: nil, bundle: nil)
self.subViewControllers = subViewControllers
}
/**
* 初始化withParentViewController
* @param parentViewController 父视图控制器
*/
init(parentViewController:UIViewController) {
super.init(nibName: nil, bundle: nil)
self.addParentController(parentViewController)
}
/**
* 初始化SKScNavBarController
* @param subViewControllers 子视图控制器
* @param parentViewController 父视图控制器
* @param show 是否显示展开扩展菜单栏按钮
*/
init(subViewControllers:NSArray, parentViewController:UIViewController, show:Bool) {
super.init(nibName: nil, bundle: nil)
self.subViewControllers = subViewControllers
self.showArrowButton = show
self.addParentController(parentViewController)
}
/**
* 添加父视图控制器的方法
* @param viewController 父视图控制器
*/
func addParentController(_ viewcontroller:UIViewController) {
if viewcontroller.responds(to: #selector(getter: UIViewController.edgesForExtendedLayout)) {
viewcontroller.edgesForExtendedLayout = UIRectEdge()
}
viewcontroller.addChildViewController(self)
viewcontroller.view.addSubview(self.view)
}
override func viewDidLoad() {
super.viewDidLoad()
//调用初始化属性的方法
initParamConfig()
//调用初始化、配置视图的方法
viewParamConfig()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: -- 私有方法
//初始化一些属性
fileprivate func initParamConfig() {
//初始化一些变量
currentIndex = 1
scNavBarColor = scNavBarColor != nil ? scNavBarColor : kNavColor
if scNavBarArrowImage == nil {
scNavBarArrowImage = UIImage(named: "arrow")
}
if showArrowButton == nil {
showArrowButton = true
}
if lineColor == nil {
lineColor = UIColor.applicationMainColor()
}
//获取所有子视图控制器上的title
titles = NSMutableArray(capacity: subViewControllers.count)
for vc in subViewControllers {
titles.add((vc as AnyObject).navigationItem.title!)
}
}
//初始化视图
fileprivate func initWithScNavBarAndMainView() {
scNavBar = SKScNavBar(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScNavBarHeight), show: showArrowButton, image: scNavBarArrowImage)
scNavBar.delegate = self
scNavBar.backgroundColor = scNavBarColor
scNavBar.itemsTitles = titles
scNavBar.lineColor = lineColor
scNavBar.setItemsData()
mainView = UIScrollView(frame: CGRect(x: 0, y: scNavBar.frame.origin.y + scNavBar.frame.size.height, width: kScreenWidth, height: kScreenHeight - scNavBar.frame.origin.y - scNavBar.frame.size.height))
mainView.delegate = self
mainView.isPagingEnabled = true
mainView.bounces = false
mainView.showsHorizontalScrollIndicator = false
mainView.contentSize = CGSize(width: kScreenWidth * CGFloat(subViewControllers.count), height: 0)
view.addSubview(mainView)
view.addSubview(scNavBar)
}
//配置视图参数
fileprivate func viewParamConfig() {
initWithScNavBarAndMainView()
//将子视图控制器的view添加到mainView上
subViewControllers.enumerateObjects { (_, index:Int, _) -> Void in
let vc = self.subViewControllers[index] as! UIViewController
vc.view.frame = CGRect(x: CGFloat(index) * kScreenWidth, y: 0, width: kScreenWidth, height: self.mainView.frame.size.height)
self.mainView.addSubview(vc.view)
self.mainView.backgroundColor = UIColor.cyan
self.addChildViewController(vc)
}
}
//MARK: -- ScrollView Delegate 方法
func scrollViewDidScroll(_ scrollView: UIScrollView) {
currentIndex = Int(scrollView.contentOffset.x / kScreenWidth)
scNavBar.setViewWithItemIndex = currentIndex
}
//MARK: -- SKScNavBarDelegate 中的方法
func didSelectedWithIndex(_ index: Int) {
mainView.setContentOffset(CGPoint(x: CGFloat(index) * kScreenWidth, y: 0), animated: true)
}
func isShowScNavBarItemMenu(_ show: Bool, height: CGFloat) {
if show {
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.scNavBar.frame = CGRect(x: self.scNavBar.frame.origin.x, y: self.scNavBar.frame.origin.y, width: kScreenWidth, height: height)
})
}else{
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.scNavBar.frame = CGRect(x: self.scNavBar.frame.origin.x, y: self.scNavBar.frame.origin.y, width: kScreenWidth, height: kScNavBarHeight)
})
}
scNavBar.refreshAll()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.