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
1eb89d9c2f7243ed894abe90f74e29f25557e2ca
Swift
ekaterinaivanova/sensors
/Sensors/AccountTableViewCell.swift
UTF-8
2,032
2.65625
3
[]
no_license
// // AccountTableViewCell.swift // SensorDataSend // // Created by Ekaterina Ivanova on 25/01/16. // Copyright © 2016 Ekaterina Ivanova. All rights reserved. // import UIKit protocol AccountTableViewCellDelegete { func textfieldTextWasChanged(_ newText: String, parentCell: AccountTableViewCell) func buttonWasTapped(_ parentCell: AccountTableViewCell) } class AccountTableViewCell: UITableViewCell, UITextFieldDelegate { @IBOutlet weak var accountButton: UIButton! @IBOutlet weak var label: UILabel! @IBOutlet weak var textField: UITextField! let bigFont = Styles.bigFont let smallFont = Styles.smallFont let primaryColor = Styles.blackColor let secondaryColor = Styles.grayColor var delegate: AccountTableViewCellDelegete! override func awakeFromNib() { super.awakeFromNib() // Initialization code if label != nil { label.font = bigFont label.textColor = primaryColor } if textField != nil { textField.font = bigFont textField.textColor = primaryColor textField.delegate = self } if accountButton != nil{ accountButton.titleLabel?.font = bigFont accountButton.backgroundColor = UIColor.red accountButton.setTitleColor(UIColor.white, for: UIControl.State()) } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func buttonTapped(_ sender: AnyObject) { if delegate != nil { delegate.buttonWasTapped(self) } } // MARK: UITextFieldDelegate Function func textFieldDidBeginEditing(_ textField: UITextField) { if delegate != nil { delegate.textfieldTextWasChanged(textField.text!, parentCell: self) } } }
true
0c07094682d07d714a398b734c401349e53f8bb0
Swift
ferryngu/yisai
/yisai/YISAI/YSCustomDatePickerViewController.swift
UTF-8
2,232
2.71875
3
[]
no_license
// // YSCustomDatePickerViewController.swift // YISAI // // Created by Yufate on 15/8/1. // Copyright (c) 2015年 Shenzhen Jianbo Information Technology Co., Ltd. All rights reserved. // import UIKit protocol YSCustomDatePickerDelegate: NSObjectProtocol { // 隐藏DatePickerView func changeDateString(dateString: String) } class YSCustomDatePickerViewController: UIViewController { @IBOutlet weak var datePicker: UIDatePicker! private var dateString: String! var dateFormatter = NSDateFormatter() var isConfirm: Bool = false var delegate: YSCustomDatePickerDelegate! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. dateFormatter.dateFormat = "YYYY-MM-dd" dateString = dateFormatter.stringFromDate(NSDate()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func showPicker() { UIView.animateWithDuration(0.5, animations: { [weak self] () -> Void in if self == nil { return } self!.view.alpha = 1 }) } private func hidePicker() { UIView.animateWithDuration(0.5, animations: { [weak self] () -> Void in if self == nil { return } self!.view.alpha = 0 }) } @IBAction func confirm(sender: AnyObject) { isConfirm = true if (self.delegate != nil) && (self.delegate.respondsToSelector("changeDateString:")) { self.delegate.changeDateString(self.dateString) } hidePicker() } @IBAction func cancel(sender: AnyObject) { isConfirm = false hidePicker() } @IBAction func datePickerEditingDidBegin(sender: UIDatePicker) { dateString = dateFormatter.stringFromDate(datePicker.date) } @IBAction func datePickerEditingChanged(sender: UIDatePicker) { dateString = dateFormatter.stringFromDate(datePicker.date) } }
true
6b1ec233f855cfc0b261fee6734f4ad844a9b28b
Swift
eggswift/CoreNetwork
/CoreNetwork/CoreNetwork/Network/HTTPRequestManager.swift
UTF-8
5,663
2.546875
3
[]
no_license
// HTTPRequestManager.swift // // Copyright (c) 2015 Egg swift. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the “Software”), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit import Alamofire import SwiftyJSON public enum HTTPRequestError: ErrorType { case None case SystemError(error: NSError?) case NetworkError case BusinessError(description: String) } public typealias HTTPRequestHandler = (responseObject: AnyObject?, error: HTTPRequestError?) -> Void public typealias HTTPRequestJSONHandler = (responseObject: JSON?, error: HTTPRequestError?) -> Void public class HTTPRequestManager { public enum Method : String { case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT var alamofireMethod: Alamofire.Method { var results = Alamofire.Method.GET switch self { case .GET: results = Alamofire.Method.GET case .POST: results = Alamofire.Method.POST case .HEAD: results = Alamofire.Method.HEAD case .OPTIONS: results = Alamofire.Method.OPTIONS case .PUT: results = Alamofire.Method.PUT case .PATCH: results = Alamofire.Method.POST case .DELETE: results = Alamofire.Method.DELETE case .TRACE: results = Alamofire.Method.TRACE case .CONNECT: results = Alamofire.Method.CONNECT } return results } } /** data请求 - parameter m: 方法类型 - parameter url: URL - parameter param: 参数 - parameter complectionHandler: 回调 - returns: 当前request */ public func dataRequest(method m: Method, urlString url: URLStringConvertible, parameter param: [String : AnyObject]?, complectionHandler: HTTPRequestHandler?) -> Request{ /* public func request(method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request */ let req = Alamofire.request(m.alamofireMethod, url, parameters: param, encoding: .URL, headers: nil) req.responseJSON { (resp) -> Void in if resp.result.isSuccess { if let handler = complectionHandler { handler(responseObject: resp.result.value, error: nil) } } else { if let handler = complectionHandler { handler(responseObject: nil, error: HTTPRequestError.SystemError(error: resp.result.error)) } } } return req } /** 上传任务 - parameter data: 上传的数据 - parameter urlStr: URL - parameter completionHandle: 回调 */ public func uploadRequest(data: NSData, urlStr: URLStringConvertible, completionHandler: HTTPRequestHandler?){ } } extension HTTPRequestManager { public func dataRequest(requestParams param: HTTPRequestParameters, completionHandler: HTTPRequestHandler?) { let req = HTTPRequest(requestParams: param) let now = NSDate().timeIntervalSince1970 //已经设置了缓存 if let _ = req.cacheIdentifier { //是否过期 if let t = req.cacheOverdueTimeInterval where now - t < 0 { if let handler = completionHandler, data = req.loadCacheData(){ //存在缓存并没有过期,返回缓存中的数据 handler(responseObject: data, error: nil) } return } } //开始请求数据 dataRequest(method: req.method, urlString: req.URLString, parameter: req.parameters) { (responseObject, error) -> Void in if error == nil { // 成功后,根据业务解析数据 //缓存 req.dataProcess.saveData(responseObject!) req.cacheOverdueTimeInterval = now if let handler = completionHandler { handler(responseObject: req.loadCacheData(), error: nil) } }else { //失败情况 if let handler = completionHandler { handler(responseObject: nil, error: error) } } } } }
true
8034f73f521f07c90cec45ecd43e6d9a98e4f570
Swift
HeQiang-IOS/swiftStudy
/10-结构体和类.playground/Contents.swift
UTF-8
3,117
4.0625
4
[]
no_license
import UIKit /** Swift中结构体和类有很多共同点, 两者都可以: 1、定义属性用于存储值 2、定义方法用于提供功能 3、定义下标操作用于通过下标语法访问它们的值 4、定义构造器用于设置初始值 5、通过扩展以增加默认实现之外的功能 6、遵循协议以提供某种标准功能 与结构体相比, 类还有如下的功能: 1、继承,允许一个类继承另一个类的特征 2、类型转换允许在运行时检查和解释一个类实例的类型 3、析构器允许一个类实例释放任何其所被分配的资源 4、引用计数允许对一个类的多次引用 类支持的附加功能是以增加复杂性为代价的,作为一般准则,优先使用结构体,因为它们更容易理解,仅在适当或必要时才使用类。 所有结构体都有一个自动生成的成员逐一构造器。用于初始化新结构体实例中成员的属性。与结构体不同,类实例没有默认的成员逐一构造器 结构体和枚举是值类型 值类型是这样一种类型,当它被赋值给一个变量、常量或者被传递给一个函数的时候,其值会被拷贝。 标准库定义的集合,例如数组、字典和字符串。都对复制进行了优化以降低性能成本。新集合不会立即复制,而是跟原集合共享同一份内存,共享同样的元素。在集合的某个副本要被修改前,才会复制a它的元素,而你在代码中看起来就像是立即发生了复制 类是引用类型 与值类型不同,引用类型在被赋予到一个变量、常量或者被传递到一个函数时,其值不会被拷贝。以此,使用的是已存在实例的引用,而不是其拷贝 恒等运算符 ===-(相同) ==(等于), ”相同“表示两个类类型的常量或者变量引用同一个类实例, ”等于“表示两个实例的值相等或等价 */ struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? } let someResolution = Resolution() let someVideoMode = VideoMode() print("The width of someResolution is \(someResolution.height)") someVideoMode.resolution.width = 1280 let vge = Resolution(width: 640, height: 480) let hd = Resolution(width: 1920, height: 1080) var cinema = hd cinema.width = 2048 print(cinema.width) enum CompassPoint { case north, south, east, west mutating func turnNorth(){ self = .north } } var currentDirection = CompassPoint.west let rememberedDirection = currentDirection currentDirection.turnNorth() print(currentDirection) print(rememberedDirection) let tenEighty = VideoMode() tenEighty.resolution = hd tenEighty.interlaced = true tenEighty.name = "1080i" tenEighty.frameRate = 25.0 let alsoTenEighty = tenEighty alsoTenEighty.frameRate = 30.0 print(tenEighty.frameRate) print(alsoTenEighty.frameRate) if tenEighty === alsoTenEighty { print("tenEighty and alsoTenEighty refer to the same VideoMode instance. ") }
true
d34343836351af0da7ba8793f7978bfcab38cd5a
Swift
detector-m/SwiftToolLibCollection
/SwiftToolLibCollection/SwiftToolLibCollection/ExcuteDuration/ExcuteDuration.swift
UTF-8
6,780
3.390625
3
[]
no_license
// // ExcuteDuration.swift // SwiftToolLibCollection // // Created by Riven on 16/4/7. // Copyright © 2016年 Riven. All rights reserved. // /* Duration.measure("Tough Math", block: yourToughMathStuff) In all cases (by default) you will get the output (assuming it took 243 milliseconds) Tough Math took: 243ms If measurements are nested, they will be appropriately indented in the output, for example if yourToughMath() made a measurement of part of its code you would see Measuring Tough Math: Part 1 took: 100ms Part 2 took: 143ms Tough Math took: 243ms Understanding Performance Deviations In order to better understand how your code is impacted by other things the system is doing you can get average times and standard deviations for block based measurements by supplying a number of iterations for the block, so Duration.measure("Tough Math", iterations: 10, forBlock:myToughMath) Would run the block 10 times, taking and reporting the 10 individual measurements and then the average time taken for the block, together with the standard deviation Measuring Tough Math Iteration 1 took: 243ms Iteration 2 took: 242ms ... Iteration 10 took: 243ms Tough Math Average: 243ms Tough Math STD Dev.: 1ms Stopping Report Generation Because you may want to stop reporting of measurements in release builds, you can set the logStyle variable in order to control the logging behavior Duration.logStyle = .None Will disable measurement logging. In the future I will extend this library to support logging to a data-structure for subsequent analysis, but at this point there are two valid values .None and .Print If you are using Duration within a Package of your own that you are distributing, rather than just over-writing the log style, you can push your desired style, then pop it to restore it to what a consuming package would want. For example public func myMethod(){ //Because this is a release of your package //don't log measurements pushLogStyle(.None) // Do stuff that is instrumented //Restore the logging style to whatever it was //before popLogStyle() } */ import Foundation public enum MeasurementLogStyle { case None case Print } public class ExcuteDuration { public typealias MeasuredBlock = () -> () public static func push(logStyle: MeasurementLogStyle) { logStyleStack.append(self.logStyle) self.logStyle = logStyle } public static func pop() { logStyle = logStyleStack.removeLast() } /// ensures that if any parent measurement boundaries have not yet resulted // in output that their headers are displayed private static func reportContaining() { if logStyle != .None && depth > 0 { if logStyle == .Print { for stackPointer in 0..<timingStack.count { let containingMeasurement = timingStack[stackPointer] if !containingMeasurement.reported { print(String(count: stackPointer, repeatedValue: "\t" as Character) + "Measuring \(containingMeasurement):") timingStack[stackPointer] = (containingMeasurement.startTime, containingMeasurement.name, true) } } } } } public static func startMeasurement(name: String) { if logStyle == .None { return } reportContaining() timingStack.append((now, name, false)) depth++ } public static func stopMeasurement() -> Double { if logStyle == .None { return 0.0 } return stopMeasurement(nil) } public static func stopMeasurement(executionDetails: String?) -> Double { if logStyle == .None { return 0.0 } let endTime = now precondition(depth > 0, "Attempt to stop a measurement when none has been started") let beginning = timingStack.removeLast() depth -= 1 let took = endTime - beginning.startTime print("\(depthIndent)\(beginning.name) took: \(took.milliSeconds)" + (executionDetails == nil ? "" : "(\(executionDetails!))")) return took } public static func log(message: String, includeTimeStamp: Bool = false) { // if logStyle == .None { // return // } guard logStyle != .None else { return } reportContaining() if includeTimeStamp { let currentTime = now let timeStamp = currentTime - timingStack[timingStack.count - 1].startTime return print("\(depthIndent)\(message) \(timeStamp.milliSeconds)ms") } else { return print("\(depthIndent)\(message)") } } public static func measure(name: String, block: MeasuredBlock) -> Double { if logStyle == .None { block() return 0 } startMeasurement(name) block() return stopMeasurement() } public static func measure(name: String, iterations: Int = 10, forBlock block: MeasuredBlock) -> Double { guard logStyle != .None else { return 0 } precondition(iterations > 0, "Iterations must be a positive integer") var total: Double = 0 var samples = [Double]() print("\(depthIndent)Measuring \(name)") for i in 0..<iterations { let took = measure("Iteration \(i+1)", block: block) samples.append(took) total += took } let mean = total / Double(iterations) var deviation = 0.0 for result in samples { let difference = result - mean deviation += difference * difference } let variance = deviation / Double(iterations) print("\(depthIndent)\(name) Average", mean.milliSeconds) print("\(depthIndent)\(name) STD Dev.", variance.milliSeconds) return mean } private static var depth = 0 private static var depthIndent: String { return String(count: depth, repeatedValue: "\t" as Character) } private static var now: Double { return NSDate().timeIntervalSinceReferenceDate } private static var timingStack = [(startTime: Double, name: String, reported: Bool)]() private static var logStyleStack = [MeasurementLogStyle]() private static var logStyle = MeasurementLogStyle.Print } private extension Double { var milliSeconds: String { return String(format: "%03.2fms", self * 1000) } }
true
a8c5ee6039834fbc93c8a28edce186d4b6588f62
Swift
JuseobJang/iOS-project-fastcampus
/projects/MyAssets/MyAssets/AssetSectionHeaderView.swift
UTF-8
689
2.828125
3
[]
no_license
// // AssetSectionHeaderView.swift // MyAssets // // Created by seob_jj on 2021/10/29. // import SwiftUI struct AssetSectionHeaderView: View { let title: String var body: some View { VStack(alignment: .leading){ Text(title) .font(.system(size: 20, weight: .bold)) .foregroundColor(.accentColor) Divider() .frame(height: 2) .background(Color.primary) .foregroundColor(.accentColor) } } } struct AssetSectionHeaderView_Previews: PreviewProvider { static var previews: some View { AssetSectionHeaderView(title: "은행") } }
true
1139e067b1cfceddd272196035273db04a67930d
Swift
uts-ios-dev/project3-group-52
/Insist/Insist/RecordController.swift
UTF-8
2,400
2.625
3
[]
no_license
// // RecordController.swift // Insist // // Created by Shiwei Lin on 26/5/18. // Copyright © 2018 Shiwei Lin. All rights reserved. // import Firebase import FirebaseFirestore import FacebookCore import UIKit class RecordController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() if Auth.auth().currentUser != nil || AccessToken.current != nil { showRecord() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } var recordsString = Array<String>() //get the record from Firebase cloud and order them by distance func showRecord() { let settings = db.settings settings.areTimestampsInSnapshotsEnabled = true db.settings = settings db.collection("users").document("\(user.email)").collection("records").order(by: "distance", descending: true).getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") } else { for document in querySnapshot!.documents { print("\(document.documentID) => \(document.data())") let userRecords = document.data() let latestTime = userRecords["time"] as? String ?? "" let latestDistance = userRecords["distance"] as? String ?? "" let latestDate = userRecords["date"] as? String ?? "" let recordString = "🗓 " + latestDate + " ⏱ " + latestTime + " 🏃🏻 " + latestDistance self.recordsString.append(recordString) self.tableView.reloadData() } } } } override func numberOfSections(in tableView: UITableView) -> Int{ return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return recordsString.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel?.text = recordsString[indexPath.row] return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
true
b57c69bdefa73ead73df137b23b6124631b47bce
Swift
dan-zheng/swift
/test/attr/accessibility_proto.swift
UTF-8
5,720
2.640625
3
[ "Apache-2.0", "Swift-exception" ]
permissive
// RUN: %target-typecheck-verify-swift // RUN: %target-swift-frontend -typecheck -disable-access-control %s public protocol ProtoWithReqs { associatedtype Assoc func foo() } public struct Adopter<T> : ProtoWithReqs {} // expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} // expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} extension Adopter { typealias Assoc = Int // expected-note@-1 {{mark the type alias as 'public' to satisfy the requirement}} {{3-3=public }} func foo() {} // expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }} } public struct Adopter2<T> : ProtoWithReqs {} // expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} // expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} public extension Adopter2 { internal typealias Assoc = Int // expected-note@-1 {{mark the type alias as 'public' to satisfy the requirement}} {{3-12=}} fileprivate func foo() {} // expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-15=}} } public struct Adopter3<T> : ProtoWithReqs {} // expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} // expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} internal extension Adopter3 { typealias Assoc = Int // expected-note@-1 {{move the type alias to another extension where it can be declared 'public' to satisfy the requirement}} {{none}} func foo() {} // expected-note@-1 {{move the instance method to another extension where it can be declared 'public' to satisfy the requirement}} {{none}} } public class AnotherAdopterBase { typealias Assoc = Int // expected-note@-1 {{mark the type alias as 'public' to satisfy the requirement}} {{3-3=public }} func foo() {} // expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }} } public class AnotherAdopterSub : AnotherAdopterBase, ProtoWithReqs {} // expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} // expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} public class AnotherAdopterBase2 {} public extension AnotherAdopterBase2 { internal typealias Assoc = Int // expected-note@-1 {{mark the type alias as 'public' to satisfy the requirement}} {{3-12=}} fileprivate func foo() {} // expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-15=}} } public class AnotherAdopterSub2 : AnotherAdopterBase2, ProtoWithReqs {} // expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} // expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} public class AnotherAdopterBase3 {} internal extension AnotherAdopterBase3 { typealias Assoc = Int // expected-note@-1 {{move the type alias to another extension where it can be declared 'public' to satisfy the requirement}} {{none}} func foo() {} // expected-note@-1 {{move the instance method to another extension where it can be declared 'public' to satisfy the requirement}} {{none}} } public class AnotherAdopterSub3 : AnotherAdopterBase3, ProtoWithReqs {} // expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} // expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} public protocol ReqProvider {} extension ReqProvider { func foo() {} // expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }} } public struct AdoptViaProtocol : ProtoWithReqs, ReqProvider { // expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} public typealias Assoc = Int } public protocol ReqProvider2 {} extension ProtoWithReqs where Self : ReqProvider2 { func foo() {} // expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }} } public struct AdoptViaCombinedProtocol : ProtoWithReqs, ReqProvider2 { // expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}} public typealias Assoc = Int } public protocol PublicInitProto { var value: Int { get } init(value: Int) } public struct NonPublicInitStruct: PublicInitProto { public var value: Int init(value: Int) { // expected-error@-1 {{initializer 'init(value:)' must be declared public because it matches a requirement in public protocol 'PublicInitProto'}} // expected-note@-2 {{mark the initializer as 'public' to satisfy the requirement}} self.value = value } } public struct NonPublicMemberwiseInitStruct: PublicInitProto { // expected-error@-1 {{initializer 'init(value:)' must be declared public because it matches a requirement in public protocol 'PublicInitProto'}} public var value: Int }
true
4fd8451d56220c4ae7452366cc3ad9e2e302e57f
Swift
m-alani/contests
/hackerrank/JumpingOnTheClouds.swift
UTF-8
601
3.390625
3
[ "MIT" ]
permissive
// // JumpingOnTheClouds.swift // // Contest solution - Marwan Alani - 2021 // // Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/jumping-on-the-clouds // Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code // func jumpingOnClouds(c: [Int]) -> Int { var jumps = 0 var index = 0 while (index < c.count - 1) { if (index + 2 < c.count && c[index+2] == 0) { index += 2 } else { index += 1 } jumps += 1 } return jumps }
true
d15f7dccc27daf735d87852a1b0652e8c9d08750
Swift
emfigura/AwwRedditFeed
/AwwRedditFeed/AwwUITableViewCell.swift
UTF-8
953
2.8125
3
[]
no_license
// // AwwUITableViewCell.swift // AwwRedditFeed // // Created by Eric on 10/20/15. // Copyright © 2015 Eric Figura. All rights reserved. // import UIKit class AwwUITableViewCell: UITableViewCell { @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var authorLabel: UILabel! @IBOutlet private weak var timeLabel: UILabel! @IBOutlet private weak var scoreLabel: UILabel! var cellIndex: Int! func configureCell(title: String, author: String, time: Double, score: Int, index: Int) { titleLabel.text = title authorLabel.text = author let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" let date = NSDate(timeIntervalSince1970: time) let timeAsString = dateFormatter.stringFromDate(date) timeLabel.text = timeAsString scoreLabel.text = String(score) cellIndex = index } }
true
417995e252150161441795f85921c789481df483
Swift
wblt/Aolanya
/Meimeila/Classes/Home/MyCollection/Model/MMLMyCollectionListModel.swift
UTF-8
786
2.71875
3
[]
no_license
// // MMLMyCollectionListModel.swift // // Create by 家仟 黄 on 21/10/2017 // Copyright © 2017. All rights reserved. // Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation import SwiftyJSON class MMLMyCollectionListModel{ var code : String! var data : [MMLMyCollectionListData]! var message : String! /** * Instantiate the instance using the passed json values to set the properties values */ init(fromJson json: JSON!){ if json.isEmpty{ return } code = json["code"].stringValue data = [MMLMyCollectionListData]() let dataArray = json["data"].arrayValue for dataJson in dataArray{ let value = MMLMyCollectionListData(fromJson: dataJson) data.append(value) } message = json["message"].stringValue } }
true
2ab7a889a7cc6979eaadd4861f9c7b09bd408144
Swift
Alvazz/CamPrefs
/Cam Prefs/Utils/UVCDevice.swift
UTF-8
12,341
2.71875
3
[]
no_license
// // UVCDevice.swift // Cam Prefs // // Created by scchn on 2021/6/29. // import Foundation extension UVCDevice { enum ValueType { case min, max case def, cur fileprivate var request: uvc_req_code { switch self { case .min: return UVC_GET_MIN case .max: return UVC_GET_MAX case .def: return UVC_GET_DEF case .cur: return UVC_GET_CUR } } } enum StateType { case def, cur fileprivate var request: uvc_req_code { switch self { case .def: return UVC_GET_DEF case .cur: return UVC_GET_CUR } } } enum AutoExposureMode: UInt8, CaseIterable { case manual = 1 case auto = 2 case shutterPriority = 4 case aperturePriority = 8 } } class UVCDevice { private let device: OpaquePointer private let device_handle: OpaquePointer private var device_descriptor_pointer: UnsafeMutablePointer<uvc_device_descriptor_t>? private var device_descriptor: uvc_device_descriptor_t? { device_descriptor_pointer?.pointee } var productName: String? { guard let cName = device_descriptor?.product else { return nil } return String(cString: cName) } deinit { if let descriptor = device_descriptor_pointer { uvc_free_device_descriptor(descriptor) } uvc_unref_device(device) } init?(device: OpaquePointer) { var device_handle: OpaquePointer? let ret = uvc_open(device, &device_handle) print("[UVCDevice] Open: \(String(cString: libusb_error_name(ret.rawValue)))") if ret == UVC_SUCCESS, let device_handle = device_handle { self.device = device self.device_handle = device_handle uvc_get_device_descriptor(device, &device_descriptor_pointer) } else { return nil } } // MARK: - Brightness func getBrightness(type: ValueType) -> Int? { var value: Int16 = 0 return uvc_get_brightness(device_handle, &value, type.request) == UVC_SUCCESS ? Int(value) : nil } @discardableResult func setBrightness(_ value: Int) -> Bool { uvc_set_brightness(device_handle, Int16(value)) == UVC_SUCCESS } // MARK: - Contrast func getAutoContrast(type: StateType) -> Bool? { var value: UInt8 = 0 return uvc_get_contrast_auto(device_handle, &value, type.request) == UVC_SUCCESS ? value != 0 : nil } @discardableResult func setAutoContrast(_ state: Bool) -> Bool { uvc_set_contrast_auto(device_handle, state ? 1 : 0) == UVC_SUCCESS } func getContrast(type: ValueType) -> Int? { var value: UInt16 = 0 return uvc_get_contrast(device_handle, &value, type.request) == UVC_SUCCESS ? Int(value) : nil } @discardableResult func setContrast(_ value: Int) -> Bool { uvc_set_contrast(device_handle, UInt16(value)) == UVC_SUCCESS } // MARK: - Sharpness func getSharpness(type: ValueType) -> Int? { var value: UInt16 = 0 return uvc_get_sharpness(device_handle, &value, type.request) == UVC_SUCCESS ? Int(value) : nil } @discardableResult func setSharpness(_ value: Int) -> Bool { uvc_set_sharpness(device_handle, UInt16(value)) == UVC_SUCCESS } // MARK: - Saturation func getSaturation(type: ValueType) -> Int? { var value: UInt16 = 0 return uvc_get_saturation(device_handle, &value, type.request) == UVC_SUCCESS ? Int(value) : nil } @discardableResult func setSaturation(_ value: Int) -> Bool { uvc_set_saturation(device_handle, UInt16(value)) == UVC_SUCCESS } // MARK: - Gamma func getGamma(type: ValueType) -> Int? { var value: UInt16 = 0 return uvc_get_gamma(device_handle, &value, type.request) == UVC_SUCCESS ? Int(value) : nil } @discardableResult func setGamma(_ value: Int) -> Bool { uvc_set_gamma(device_handle, UInt16(value)) == UVC_SUCCESS } // MARK: - HUE func getAutoHue(type: StateType) -> Bool? { var state: UInt8 = 0 return uvc_get_hue_auto(device_handle, &state, type.request) == UVC_SUCCESS ? state != 0 : nil } @discardableResult func setAutoHue(_ state: Bool) -> Bool { uvc_set_hue_auto(device_handle, state ? 1 : 0) == UVC_SUCCESS } func getHue(type: ValueType) -> Int? { var value: Int16 = 0 return uvc_get_hue(device_handle, &value, type.request) == UVC_SUCCESS ? Int(value) : nil } @discardableResult func setHue(_ value: Int) -> Bool { uvc_set_hue(device_handle, Int16(value)) == UVC_SUCCESS } // MARK: - Exposure func getAutoExposureMode(type: StateType) -> AutoExposureMode? { var value: UInt8 = 0 return uvc_get_ae_mode(device_handle, &value, type.request) == UVC_SUCCESS ? AutoExposureMode(rawValue: value) : nil } @discardableResult func setAutoExposureMode(_ mode: AutoExposureMode) -> Bool { uvc_set_ae_mode(device_handle, mode.rawValue) == UVC_SUCCESS } func getAutoExposureModeIndex(type: ValueType) -> Int? { switch type { case .min: return 0 case .max: return 3 case .def: guard let mode = getAutoExposureMode(type: .def) else { return nil } return AutoExposureMode.allCases.firstIndex(of: mode) case .cur: guard let mode = getAutoExposureMode(type: .cur) else { return nil } return AutoExposureMode.allCases.firstIndex(of: mode) } } func setAutoExposureModeWithIndex(_ index: Int) -> Bool { guard (0..<AutoExposureMode.allCases.count).contains(index) else { return false } let mode = AutoExposureMode.allCases[index] return setAutoExposureMode(mode) } func getExposureAbs(type: ValueType) -> Int? { var value: UInt32 = 0 return uvc_get_exposure_abs(device_handle, &value, type.request) == UVC_SUCCESS ? Int(value) : nil } @discardableResult func setExposureAbs(_ value: Int) -> Bool { uvc_set_exposure_abs(device_handle, UInt32(value)) == UVC_SUCCESS } // MARK: - Gain func getGain(type: ValueType) -> Int? { var value: UInt16 = 0 return uvc_get_gain(device_handle, &value, type.request) == UVC_SUCCESS ? Int(value) : nil } @discardableResult func setGain(_ value: Int) -> Bool { uvc_set_gain(device_handle, UInt16(value)) == UVC_SUCCESS } // MARK: - White Balance func getAutoWhiteBalanceTemp(type: StateType) -> Bool? { var value: UInt8 = 0 return uvc_get_white_balance_temperature_auto(device_handle, &value, type.request) == UVC_SUCCESS ? value != 0 : nil } @discardableResult func setAutoWhiteBalanceTemp(_ state: Bool) -> Bool { uvc_set_white_balance_temperature_auto(device_handle, state ? 1 : 0) == UVC_SUCCESS } func getWhiteBalanceTemp(type: ValueType) -> Int? { var value: UInt16 = 0 return uvc_get_white_balance_temperature(device_handle, &value, type.request) == UVC_SUCCESS ? Int(value) : nil } @discardableResult func setWhiteBalanceTemp(_ value: Int) -> Bool { uvc_set_white_balance_temperature(device_handle, UInt16(value)) == UVC_SUCCESS } // MARK: - Focus func getAutoFocus(type: StateType) -> Bool? { var value: UInt8 = 0 return uvc_get_focus_auto(device_handle, &value, type.request) == UVC_SUCCESS ? value != 0 : nil } @discardableResult func setAutoFocus(_ state: Bool) -> Bool { uvc_set_focus_auto(device_handle, state ? 1 : 0) == UVC_SUCCESS } func getFocusAbs(type: ValueType) -> Int? { var value: UInt16 = 0 return uvc_get_focus_abs(device_handle, &value, type.request) == UVC_SUCCESS ? Int(value) : nil } @discardableResult func setFocusAbs(_ value: Int) -> Bool { uvc_set_focus_abs(device_handle, UInt16(value)) == UVC_SUCCESS } // MARK: - Zoom func getZoomAbs(type: ValueType) -> Int? { var value: UInt16 = 0 return uvc_get_zoom_abs(device_handle, &value, type.request) == UVC_SUCCESS ? Int(value) : nil } @discardableResult func setZoomAbs(_ value: Int) -> Bool { uvc_set_zoom_abs(device_handle, UInt16(value)) == UVC_SUCCESS } // MARK: - Pan & Tilt func getPanTilt(type: ValueType) -> (pan: Int, tilt: Int)? { var pan: Int32 = 0 var tilt: Int32 = 0 return uvc_get_pantilt_abs(device_handle, &pan, &tilt, type.request) == UVC_SUCCESS ? (Int(pan), Int(tilt)) : nil } @discardableResult func setPanTilt(_ pan: Int, _ tilt: Int) -> Bool { uvc_set_pantilt_abs(device_handle, Int32(pan), Int32(tilt)) == UVC_SUCCESS } func getPan(type: ValueType) -> Int? { getPanTilt(type: type)?.pan } @discardableResult func setPan(_ value: Int) -> Bool { guard let (_, tilt) = getPanTilt(type: .cur) else { return false } return setPanTilt(value, tilt) } func getTilt(type: ValueType) -> Int? { getPanTilt(type: type)?.tilt } @discardableResult func setTilt(_ value: Int) -> Bool { guard let (pan, _) = getPanTilt(type: .cur) else { return false } return setPanTilt(pan, value) } // MARK: - Backlight Compensation func getBacklightCompensation(type: ValueType) -> Int? { var value: UInt16 = 0 return uvc_get_backlight_compensation(device_handle, &value, type.request) == UVC_SUCCESS ? Int(value) : nil } @discardableResult func setBacklightCompensation(_ value: Int) -> Bool { uvc_set_backlight_compensation(device_handle, UInt16(value)) == UVC_SUCCESS } // MARK: - Power-Line Frequency func getPowerLineFrequency(type: ValueType) -> Int? { var value: UInt8 = 0 return uvc_get_power_line_frequency(device_handle, &value, type.request) == UVC_SUCCESS ? Int(value) : nil } @discardableResult func setPowerLineFrequency(_ value: Int) -> Bool { uvc_set_power_line_frequency(device_handle, UInt8(value)) == UVC_SUCCESS } // MARK: - Reset func resetAll() { if let value = getBrightness(type: .def) { setBrightness(value) } if let value = getContrast(type: .def) { setContrast(value) } if let value = getSharpness(type: .def) { setSharpness(value) } if let value = getSaturation(type: .def) { setSaturation(value) } if let value = getGamma(type: .def) { setGamma(value) } if let value = getHue(type: .def) { setHue(value) } if let value = getExposureAbs(type: .def) { setExposureAbs(value) } if let value = getGain(type: .def) { setGain(value) } if let value = getWhiteBalanceTemp(type: .def) { setWhiteBalanceTemp(value) } if let value = getFocusAbs(type: .def) { setFocusAbs(value) } if let value = getBacklightCompensation(type: .def) { setBacklightCompensation(value) } if let value = getPowerLineFrequency(type: .def) { setPowerLineFrequency(value) } if let value = getZoomAbs(type: .def) { setZoomAbs(value) } if let value = getPanTilt(type: .def) { setPanTilt(value.pan, value.tilt) } if let value = getAutoContrast(type: .def) { setAutoContrast(value) } if let value = getAutoHue(type: .def) { setAutoHue(value) } if let value = getAutoExposureMode(type: .def) { setAutoExposureMode(value) } if let value = getAutoWhiteBalanceTemp(type: .def) { setAutoWhiteBalanceTemp(value) } if let value = getAutoFocus(type: .def) { setAutoFocus(value) } } }
true
0d100016fd4b71e53bdcc045c297dfb1a1da4dcf
Swift
peterparker007/tfiws
/Swift 3 Demo/CollectionDemo Good/Demo App For Buckeython Data Download/KidsCollectionViewCell.swift
UTF-8
1,755
3.484375
3
[]
no_license
// // KidsCollectionViewCell.swift // Demo App For Buckeython Data Download // // Created by Taha Topiwala on 10/31/16. // Copyright © 2016 Taha Topiwala. All rights reserved. // import UIKit struct Kid { var name : String! var friendly : String! var image : String! var birthday : String! init(data : Dictionary<String, String>) { if let name = data["name"] { self.name = name } if let friendly = data["friendly"] { self.friendly = friendly } if let image = data["image"] { self.image = image } if let birthday = data["birthday"] { self.birthday = birthday } } } class KidsCollectionViewCell: UICollectionViewCell { @IBOutlet weak var kidImage : UIImageView! @IBOutlet weak var name : UILabel! func configureCell(kid : Kid) { self.name.text = kid.name if let url = URL(string : kid.image) { self.kidImage.contentMode = .scaleAspectFit self.downloadImage(url: url) } } // Get data from the Image url func getDataFromURL(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) { URLSession.shared.dataTask(with: url) { (data, response, error) in completion(data, response, error) }.resume() } // Download the image func downloadImage(url: URL) { getDataFromURL(url: url) { (data, response, error) in guard let data = data, error == nil else { return } DispatchQueue.main.async() { () -> Void in self.kidImage.image = UIImage(data: data) } } } }
true
9a533b552f43bca14b8ead82fa2faf600e774146
Swift
enthuCoder/LeetCode-Solutions
/LeetCode-Solutions/Arrays/Medium/15. 3Sum.swift
UTF-8
2,338
3.5
4
[]
no_license
// // 15. 3Sum.swift // LeetCode-Solutions // // Created by Dilgir Siddiqui on 12/30/20. // import Foundation /* 15. 3Sum Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Notice that the solution set must not contain duplicate triplets. Example 1: Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Example 2: Input: nums = [] Output: [] Example 3: Input: nums = [0] Output: [] */ class Input_15 { func executeInput() { let nums = [-2,0,0,2,2]//[-1,0,1,2,-1,-4]//[-3, 0, 1, 2, -1, 1, -2] // output = [[-1,-1,2],[-1,0,1]] //[-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1] print(threeSum(nums)) } } extension Input_15 { func threeSum(_ nums: [Int]) -> [[Int]] { var result = [[Int] : Int]() if nums.count < 3 { return [] } var numArray = nums numArray.sort(by: { $0 < $1 }) for i in 0..<nums.count-1 { if i > 0 && numArray[i] == numArray[i - 1] { continue } twoSum(i + 1, nums.count - 1, numArray, -numArray[i], &result) } var answer = [[Int]]() result.forEach { answer.append($0.key) } return answer } func twoSum(_ start: Int, _ end: Int, _ nums: [Int], _ target: Int, _ res: inout [[Int] : Int]) { var firstIdx = start var secondIdx = end for _ in firstIdx...secondIdx where secondIdx > firstIdx { if nums[firstIdx] + nums[secondIdx] == target { var key = [Int]() if target == 0 { key = [0] + [nums[firstIdx], nums[secondIdx]] } else { key = [-target] + [nums[firstIdx], nums[secondIdx]] } res[key, default:0] += 1 firstIdx += 1 secondIdx -= 1 } else if nums[firstIdx] + nums[secondIdx] < target { // As sum is lesser than target, increment firstIdx firstIdx += 1 } else if nums[firstIdx] + nums[secondIdx] > target { // As sum is greater than target, decrement secondIdx secondIdx -= 1 } } } }
true
cfd408c54ba01693977d763f9fffe760d2584de9
Swift
tgreener/Tarnish
/Tarnish/ItemsGraphicsFactory.swift
UTF-8
1,812
3.03125
3
[]
no_license
// // ItemsGraphicsFactory.swift // Tarnish // // Created by Todd Greener on 1/24/15. // Copyright (c) 2015 Todd Greener. All rights reserved. // import SpriteKit enum ItemTextureType { case Cheese case Bread case Apple } class ItemGraphicsFactory { let itemRects : [ItemTextureType : CGRect] var itemTextures : [ItemTextureType : SKTexture] = [ItemTextureType : SKTexture](minimumCapacity: 3) let itemAtlas : SKTexture let atlasHeight : UInt = 16 let atlasWidth : UInt = 48 let itemTextureDimension : UInt = 16 init() { itemAtlas = SKTexture(imageNamed: "items.png") let cheeseRect : CGRect = spriteSheetRect(0, y: 0, dimension: itemTextureDimension, sheetWidth: atlasWidth, sheetHeight: atlasHeight) let breadRect : CGRect = spriteSheetRect(1, y: 0, dimension: itemTextureDimension, sheetWidth: atlasWidth, sheetHeight: atlasHeight) let appleRect : CGRect = spriteSheetRect(2, y: 0, dimension: itemTextureDimension, sheetWidth: atlasWidth, sheetHeight: atlasHeight) itemRects = [ ItemTextureType.Cheese : cheeseRect, ItemTextureType.Bread : breadRect, ItemTextureType.Apple : appleRect ] } func loadItems() { for (type, rect) in itemRects { let texture = SKTexture(rect: rect, inTexture: itemAtlas) itemTextures[type] = texture texture.filteringMode = SKTextureFilteringMode.Nearest } } func createItemGraphic(type: ItemTextureType) -> GraphicsComponent { let tex = itemTextures[type] let result = GraphicNode(texture: tex) result.anchorPoint = CGPointZero result.setScale(0.5) result.zPosition = 0.5 return result } }
true
b7cde2175e3b896415961bcf01d37f8fa8ddf2e3
Swift
Ronaldoh1/AdvancedSwift
/DynamicProgramming.playground/Contents.swift
UTF-8
726
3.953125
4
[]
no_license
// This is a simple implemtation for Coin Change Problem //given value n, if we can make n into change for N cents, and we have infinite supply of each S = { S1, S2, S3 } how many ways can we have to make the change. // steps // To count total number of solutions, we can devide all set solutions in two sets. //1. Solutions do not contain mth coin or (Sm) //2. Solutions that contains at least one Sm // The method below computes the same subproblems again and again. Since same problems are called again and again, this problem has overlapping subproblems property. So the coin change problem has both properties of a dynamic programming problem. func count(coins: [Int], dollarAmount: Int) -> Int { return 0 }
true
f7d744f0beb93d1d5ecce6a4f112e132e2c469e8
Swift
ImSajalKaushik/30-Days-iOS
/FireBaseDemo/SignupViewController.swift
UTF-8
1,519
2.875
3
[]
no_license
// // SignupViewController.swift // FireBaseDemo // // Created by Sajal Kaushik on 26/05/20. // Copyright © 2020 Sajal Kaushik. All rights reserved. // import UIKit import Firebase import FirebaseAuth class SignupViewController: UIViewController { @IBOutlet weak var email: UITextField! @IBOutlet weak var password: UITextField! var emailAddress: String? = nil var pass: String? = nil override func viewDidLoad() { super.viewDidLoad() setupView() } func setupView() { email.delegate = self password.delegate = self } @IBAction func signUp(_ sender: UIButton) { if emailAddress != nil, pass != nil { Auth.auth().createUser(withEmail: emailAddress!, password: pass!) { (result, err) in if err != nil { print("error in sign up:", err!.localizedDescription) } else { let uid = result?.user.uid print("Success", result?.credential) } } } self.dismiss(animated: true, completion: nil) } } extension SignupViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == email { password.becomeFirstResponder() emailAddress = email.text } else { pass = password.text textField.resignFirstResponder() } return true } }
true
e62f1daf2f1827c6399c1884a6ef644c383276bd
Swift
GillianY/SWIFT
/Day03/CH07Enum/CH07Enum/main.swift
UTF-8
341
2.71875
3
[]
no_license
// // main.swift // CH07Enum // // Created by ucom Apple 13 on 2016/11/10. // Copyright © 2016年 ucom Apple root. All rights reserved. // import Foundation //print("Hello, World!") print(Gender.Male) getGenger(Gender.Male) print(Planet.Monday.rawValue) let possiblePlanet = Planet(rawValue:5) print(possiblePlanet ?? Planet.Monday)
true
6c7950521dcec2134066f52015c2ee7cdc145638
Swift
Jen-Vu/InstagramClone
/InstagramClone/NewsFeed/PostDetailViewController.swift
UTF-8
1,900
2.71875
3
[ "MIT" ]
permissive
// // PostDetailViewController.swift // InstagramClone // // Created by Juan Francisco Dorado Torres on 04/01/20. // Copyright © 2020 Juan Francisco Dorado Torres. All rights reserved. // import UIKit import Firebase class PostDetailViewController: UITableViewController { // MARK: - Properties var post: Post? var currentUser: User? var comments = [Comment]() // MARK: - View cycle override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Photo" tableView.allowsSelection = false fetchComments() } // MARK: - Methods private func fetchComments() { guard let post = self.post else { fatalError("Could not get the post in \(#file)") } post.docRef?.collection("comments").addSnapshotListener({ (documentSnapshot, error) in guard let documents = documentSnapshot?.documents else { print("Error fetching documents: \(error!)") return } documents .map { Comment(dictionary: $0.data()) } .forEach { self.comments.insert($0, at: 0) DispatchQueue.main.async { self.tableView.reloadData() } } print("**** COMMENTS: \(self.comments)") }) } } // MARK: - Table view delegates extension PostDetailViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return comments.count + 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "CommentTableViewCell", for: indexPath) as? CommentTableViewCell else { fatalError("Could not dequeue tableview cell in \(#file)") } if indexPath.row == 0 { // post caption cell.post = self.post } else { // comment cell.comment = self.comments[indexPath.row - 1] } return cell } }
true
b1f56a2417bc9bd068b6c968f53e3bf902b5bb52
Swift
ufuk-trkz/ios-cocoa-design-pattern
/Tasks-master/Tasks/TaskCell.swift
UTF-8
1,365
2.9375
3
[]
no_license
// // TaskCell.swift // Tasks // // Created by Ben Gohlke on 2/25/20. // Copyright © 2020 Lambda School. All rights reserved. // import UIKit class TaskCell: UITableViewCell { // MARK: - Properties var task: Task? { didSet { updateViews() } } // MARK: - Outlets @IBOutlet weak var taskTitleLabel: UILabel! @IBOutlet weak var completedButton: UIButton! // MARK: - Actions @IBAction func toggleComplete(_ sender: UIButton) { // This changes it from true to false or vice versa task?.completed.toggle() guard let task = task else { return } // Sets the button image to the correct SF Symbol (either checked or empty) completedButton.setImage(task.completed ? UIImage(systemName: "checkmark.circle.fill") : UIImage(systemName: "circle"), for: .normal) do { try CoreDataStack.shared.save() } catch { NSLog("Error saving managed object context: \(error)") } } // MARK: - Private private func updateViews() { guard let task = task else { return } taskTitleLabel.text = task.name completedButton.setImage(task.completed ? UIImage(systemName: "checkmark.circle.fill") : UIImage(systemName: "circle"), for: .normal) } }
true
95b376c4d7b9440a510ee53c6dad62ab8d4b69ae
Swift
mddrill/WallAppiOS
/WallAppiOS/ViewControllers/EditPostViewController.swift
UTF-8
1,369
2.75
3
[]
no_license
// // EditPostViewController.swift // WallAppiOS // // Created by Matthew Drill on 6/30/17. // Copyright © 2017 Matthew Drill. All rights reserved. // import UIKit class EditPostViewController: BaseViewController { // Used for setting the post's current text var postText: String! var postId: Int! override func viewDidLoad(){ super.viewDidLoad() if postText != nil { textView.text = postText postText = nil } } @IBOutlet weak var textView: UITextView! @IBAction func confirmEdit(_ sender: UIButton) { guard self.validate(textView: textView) else { popUpError(withTitle: "Empty Post", withMessage: "You can't send an empty post!") return } // If this throws an error, it means the user was able to get to this view without logging, in. // Something is wrong, app needs to crash try! self.postClient.edit(postWithId: self.postId!, withNewText: textView.text!, onSuccess: {_ in self.performSegue(withIdentifier: "EditToWallSegue", sender: self)}, onError: { error in self.handleError(error: error) }) } }
true
6df83b59c1b455f51eb27f911304be4efef3c523
Swift
dennisvera/RIckyAndMorty
/RickyAndMorty/Models/CharacterModel.swift
UTF-8
2,331
3.03125
3
[]
no_license
// // CharacterModel.swift // RMUIChallenge // // Copyright © 2020 com.adt.myadtmobileenterprise. All rights reserved. // import Foundation enum CharacterStatus: String { // MARK: - Cases case alive case dead case unknown } enum CharacterGender: String { // MARK: - Cases case female case male case genderless case unknown } struct CharactersResponse: Decodable { // MARK: - Properties var info: CharactersInfo? var results: [CharacterModel]? } struct CharactersInfo: Decodable { // MARK: - Properties var count: Int? var pages: Int? var next: String? var prev: String? } struct CharacterModel: Decodable, Hashable { // MARK: - Properties let id: Int? let name: String? let status: CharacterStatus? let species: String? let type: String? let gender: CharacterGender? let origin: String? let location: String? let image: URL? let episodes: [URL]? enum CodingKeys: String, CodingKey { // MARK: - Cases case id, name, status, species, type, gender, origin, location, image case episodes = "episode" } // MARK: - Initializer init(from decoder: Decoder) throws { let container = try? decoder.container(keyedBy: CodingKeys.self) self.id = try? container?.decode(Int.self, forKey: .id) self.name = try? container?.decode(String.self, forKey: .name) self.species = try? container?.decode(String.self, forKey: .species) self.type = try? container?.decode(String.self, forKey: .type) self.origin = try? container?.decode(String.self, forKey: .origin) self.location = try? container?.decode(String.self, forKey: .location) let statusStr = try? container?.decode(String.self, forKey: .status) let genderStr = try? container?.decode(String.self, forKey: .gender) self.status = Helper.set(with: statusStr) self.gender = Helper.set(with: genderStr) if let imgURLStr = try? container?.decode(String.self, forKey: .image), let imgURL = URL(string: imgURLStr) { self.image = imgURL } else { self.image = nil } if let epStrings = try? container?.decode([String].self, forKey: .episodes) { let epURLs = epStrings.compactMap { URL(string: $0) } self.episodes = epURLs } else { self.episodes = nil } } }
true
5d427bb1b866cfba4d8c960011f1b3c379ee11c1
Swift
PrashantGaikwad-iOS/Autofill-Password
/Password Autofill/ViewController.swift
UTF-8
1,349
2.703125
3
[]
no_license
// // ViewController.swift // Password Autofill // // Created by Prashant G on 7/7/18. // Copyright © 2018 MyOrg. All rights reserved. // import UIKit // Passcode autofill // If you want to use Passcode Autofill from Message app then // set the content type of your password textfield to One time Code. // This is available from ios 12 // Strong Passwprd suggestion // To provide your user with strong password suggestion while signing up // you have to just set your password textfields content type to New Password // Again this is available from ios 12 class ViewController: UIViewController { @IBOutlet private weak var username: UITextField! @IBOutlet private weak var password: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "detailView" { } } @IBAction func logInAction(_ sender: Any) { performSegue(withIdentifier: "detailView", sender: self) } }
true
cd39c743b2343b5b725b0bd56e68deea0d50c867
Swift
224apps/LBTAAPPS
/MapsDirectionsLBTA/MapsDirectionsLBTA/Main/MainController.swift
UTF-8
1,458
2.828125
3
[]
no_license
// // MainController.swift // MapsDirectionsLBTA // // Created by Abdoulaye Diallo on 12/22/19. // Copyright © 2019 Abdoulaye Diallo. All rights reserved. // import UIKit import MapKit import LBTATools import SwiftUI class MainController: UIViewController{ let mapView = MKMapView() override func viewDidLoad() { super.viewDidLoad() view.addSubview(mapView) view.backgroundColor = .white mapView.fillSuperview() mapView.mapType = .standard setupRegionForMap() } fileprivate func setupRegionForMap(){ let center = CLLocationCoordinate2D(latitude: 37.7666, longitude: -122.427290) let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1) let region = MKCoordinateRegion(center: center, span: span) mapView.setRegion(region, animated: true) } } // SwiftUI Preview struct MainPreview: PreviewProvider { static var previews: some View { ContainerView() } struct ContainerView:UIViewControllerRepresentable { typealias UIViewControllerType = MainController func makeUIViewController(context: UIViewControllerRepresentableContext<MainPreview.ContainerView>) -> MainController { return MainController() } func updateUIViewController(_ uiViewController: MainController, context: UIViewControllerRepresentableContext<MainPreview.ContainerView>) { } } }
true
f898b10026c3584dd6706724c176ef022ce4cf66
Swift
JonesCxy/SwiftyMath
/Sources/SwiftyHomology/Tools/ExactSequenceSolver.swift
UTF-8
9,160
2.6875
3
[ "CC0-1.0" ]
permissive
// // ExactSequence.swift // SwiftyMath // // Created by Taketo Sano on 2017/12/14. // Copyright © 2017年 Taketo Sano. All rights reserved. // import Foundation import SwiftyMath public extension LogFlag { public static var exactSequence: LogFlag { return LogFlag(id: "Homology.ExactSequence", label: "exSeq") } } public final class ExactSequenceSolver<R: EuclideanRing>: CustomStringConvertible { public typealias Object = ModuleObject<AbstractBasisElement, R> public typealias Map = FreeModuleHom<AbstractBasisElement, AbstractBasisElement, R> public var objects : Grid1<Object> public var maps : Grid1<Map> internal var matrices: Grid1<Matrix<R>> public init(objects: [Object?], maps: [Map?]) { self.objects = Grid1(data: objects.toDictionary()) self.maps = Grid1(data: maps.toDictionary()) self.matrices = Grid1.empty } public convenience init() { self.init(objects: [], maps: []) } public subscript(i: Int) -> Object? { get { return objects[i] } set { log("set \(i) = \(newValue.map{ "\($0)" } ?? "nil")") objects[i] = newValue } } public var length: Int { return objects.isEmpty ? 0 : objects.topIndex - objects.bottomIndex + 1 } public var range: [Int] { return objects.isEmpty ? [] : (objects.bottomIndex ... objects.topIndex).toArray() } public func matrix(_ i: Int) -> Matrix<R>? { if let A = matrices[i] { return A } let A = _matrix(i) matrices[i] = A return A } private func _matrix(_ i: Int) -> Matrix<R>? { guard let from = self[i], let to = self[i + 1], let map = maps[i] else { return nil } let comps = from.generators.enumerated().flatMap { (j, z) -> [MatrixComponent<R>] in let w = map.applied(to: z) let vec = to.factorize(w) return vec.enumerated().map{ (i, a) in MatrixComponent(i, j, a) } } return Matrix(rows: to.generators.count, cols: from.generators.count, components: comps) } public func isZero(_ i: Int) -> Bool { return self[i]?.isZero ?? false } public func isNonZero(_ i: Int) -> Bool { return self[i].map{ !$0.isZero } ?? false } public func isZeroMap(_ i1: Int) -> Bool { if _isZeroMap(i1) { let i2 = i1 + 1 if matrices[i1] == nil, let M1 = self[i1], let M2 = self[i2] { log("\(i1) -> \(i2): zeroMap") matrices[i1] = .zero(rows: M2.generators.count, cols: M1.generators.count) } return true } else { return false } } private func _isZeroMap(_ i1: Int) -> Bool { if let A = matrices[i1], A.isZero { return true } // The following are equivalent: // // f0 [f1] f2 // M0 ---> M1 ----> M2 ---> M3 // // // 1) f1 = 0 // 2) f2: injective ( Ker(f2) = Im(f1) = 0 ) // 3) f0: surjective ( M1 = Ker(f1) = Im(f0) ) // let (i0, i2, i3) = (i1 - 1, i1 + 1, i1 + 2) if let M1 = self[i1], M1.isZero { return true } if let M2 = self[i2], M2.isZero { return true } if let A1 = matrix(i1), A1.isZero { return true } if let M2 = self[i2], M2.isFree, let M3 = self[i3], M3.isFree, let A2 = matrix(i2), A2.elimination().isInjective { return true } if let M0 = self[i0], M0.isFree, let M1 = self[i1], M1.isFree, let A0 = matrix(i0), A0.elimination().isSurjective { return true } return false } public func isInjective(_ i: Int) -> Bool { return isZeroMap(i - 1) } public func isSurjective(_ i: Int) -> Bool { return isZeroMap(i + 1) } public func isIsomorphic(_ i: Int) -> Bool { return isInjective(i) && isSurjective(i) } public func solve() { return range.forEach{ i in if objects[i] == nil { solve(i) } } } @discardableResult public func solve(_ i: Int) -> Object? { if let o = self[i] { return o } if let o = _solve(i) { self[i] = o return o } else { return nil } } private func _solve(_ i2: Int) -> Object? { // Aim: [M2] // // f0 f1 f2 f3 // M0 ---> M1 ---> [M2] ---> M3 ---> M4 (exact) // let (i0, i1, i3) = (i2 - 2, i2 - 1, i2 + 1) // Case 1. // // 0 0 // M1 ---> [M2] ---> M3 ==> M2 = Ker(0) = Im(0) = 0 if isZeroMap(i1), isZeroMap(i2) { log("\(i2): trivial.") return Object.zeroModule } // Case 2. // // 0 f1 0 // M0 ---> M1 ---> [M2] ---> M3 ==> f1: isom if let M1 = self[i1], isZeroMap(i0), isZeroMap(i2) { log("\(i2): isom to \(i1).") maps[i1] = .identity return M1 } // Case 3. // // 0 f2 0 // M1 ---> [M2] ---> M3 ---> M4 ==> f2: isom if let M3 = self[i3], isZeroMap(i1), isZeroMap(i3) { log("\(i2): isom to \(i3).") maps[i2] = .identity return M3 } // General Case. // // f0 f1 f2 f3 // M0 ---> M1 ---> [M2] ---> M3 ---> M4 (exact) // // ==> // f2 // 0 -> Ker(f2) ⊂ [M2] -->> Im(f2) -> 0 (exact) // = Im(f1) = Ker(f3) // ~= Coker(f0) if let M1 = self[i1], M1.isFree, // TODO concider non-free case let M3 = self[i3], M3.isFree, let A0 = matrix(i0), let A3 = matrix(i3) { let (r, k) = (M1.rank, A3.elimination().nullity) let generators = AbstractBasisElement.generateBasis(r + k) let B = A0 + Matrix<R>.zero(rows: k, cols: k) let M2 = Object(generators: generators, relationMatrix: B) log("\(i2): \(M2)") return M2 } log("\(i2): unsolvable.") return nil } public func describe(_ i0: Int) { if let s = self[i0] { print("\(i0): ", terminator: "") s.describe() } else { print("\(i0): ?") } } public func describeMap(_ i0: Int) { let i1 = i0 + 1 print("\(i0): \(objectDescription(i0)) \(arrowDescription(i0)) \(objectDescription(i1))") if let A = self.matrix(i0) { print(A.detailDescription, "\n") } } public func assertExactness(at i1: Int, debug: Bool = false) { // f0 f1 // M0 ---> [M1] ---> M2 let (i0, i2) = (i1 - 1, i1 + 1) guard let M0 = self[i0], let M1 = self[i1], let M2 = self[i2], let f0 = maps[i0], let f1 = maps[i1] else { return } if M1.isZero { return } // Im ⊂ Ker for x in M0.generators { let y = f0.applied(to: x) let z = f1.applied(to: y) assert(M2.elementIsZero(z)) } // Im ⊃ Ker // TODO } public func assertExactness(debug: Bool = false) { for i in range { assertExactness(at: i, debug: debug) } } internal func objectDescription(_ i: Int) -> String { return self[i]?.description ?? "?" } internal func arrowDescription(_ i: Int) -> String { return isNonZero(i) && isNonZero(i + 1) ? (isZeroMap(i) ? "-ͦ>" : isIsomorphic(i) ? "-̃>" : isInjective(i) ? "-ͫ>" : isSurjective(i) ? "-ͤ>" : "->") : "->" } public var description: String { if objects.isEmpty { return "ExSeq<\(R.symbol)>: empty" } else { let (i0, i1) = (objects.bottomIndex, objects.topIndex) return "ExSeq<\(R.symbol)>: " + (i0 ..< i1).map { i in "\(objectDescription(i)) \(arrowDescription(i)) " }.joined() + objectDescription(i1) } } private func log(_ msg: @autoclosure () -> String) { Logger.write(.exactSequence, msg) } }
true
903789526581e8f7823245465f5d5c695e6d416a
Swift
YAPP-16th/Study_DesignPattern
/iOS/Dayeon/ViperPractice/Worker/MainWorker.swift
UTF-8
486
2.75
3
[]
no_license
// // MainWorker.swift // ViperPractice // // Created by 성다연 on 21/02/2020. // Copyright © 2020 성다연. All rights reserved. // import Foundation protocol APIStoreWorkerProtocol { func fetchCandyStore(callBack: (StoreEntity) -> Void) } class StoreAPIWorker : APIStoreWorkerProtocol { func fetchCandyStore(callBack: (StoreEntity) -> Void) { let Entity = StoreEntity(StoreName: "Candy Store", StoreImage: "candystoreimg") callBack(Entity) } }
true
ad002a7151fd87902e09846fcc9cd8fc9ec06b6d
Swift
5oya/PracticeIGListKit
/PracticeIGListKit/User.swift
UTF-8
524
2.9375
3
[]
no_license
import Foundation import IGListKit class User { let id: Int let nickname: String init(id: Int, nickname: String) { self.id = id self.nickname = nickname } } // MARK: IGListDiffable extension User: IGListDiffable { func diffIdentifier() -> NSObjectProtocol { return id as NSObjectProtocol } func isEqual(toDiffableObject object: IGListDiffable?) -> Bool { guard let user = object as? User else { return false } return id == user.id } }
true
9c97030d0d7da6364e6ea0d7a7faa8bd0b4512f7
Swift
darioalessandro/FunctionalProgrammingSwift3
/FPSwift3/Dictionary + filter.swift
UTF-8
718
3.265625
3
[]
no_license
// // Dictionary + filter.swift // FPSwift3 // // Created by Dario on 10/11/16. // Copyright © 2016 BlackFireApps. All rights reserved. // import Foundation extension Dictionary { public func filterCopy(_ isIncluded: (Key, Value) throws -> Bool) rethrows -> [Key : Value] { var newDict = [Key : Value]() try self.forEach {if try isIncluded($0,$1) {newDict[$0] = $1}} return newDict } public mutating func filterInPlace(_ isIncluded: (Key, Value) throws -> Bool) rethrows -> [Key : Value] { try self.forEach { (key: Key, value: Value) in if try !isIncluded(key,value) {self.removeValue(forKey: key)} } return self } }
true
7620850d7e2cde788b6a68e5273198cfd1688c48
Swift
yangheetae86/showHide
/showHide/ContentView.swift
UTF-8
1,030
3.21875
3
[]
no_license
// // ContentView.swift // showHide // // Created by HEE TAE YANG on 2020/06/11. // Copyright © 2020 yht. All rights reserved. // import SwiftUI struct ContentView: View { @State var truefalse = false var body: some View { VStack { if self.truefalse { Text("메디콜 공중전화1") } else { Text("메디콜 공중전화1").hidden() } if self.truefalse { Text("메디콜 공중전화2").hidden() } else { Text("메디콜 공중전화2") } ShowHidden(truefalse: $truefalse) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } struct ShowHidden: View { @Binding var truefalse: Bool var body: some View { Button(action: { self.truefalse = !self.truefalse }){ Text("버튼") } } }
true
e4c5fd0d6af766dbd97f9517186798ba20886327
Swift
atorresruiz8/resortFeedback
/ResortFeedback/Logging In/SignUpViewController.swift
UTF-8
1,672
2.6875
3
[]
no_license
// // SignUpViewController.swift // ResortFeedback // // Created by Antonio Torres-Ruiz on 4/19/21. // import UIKit class SignUpViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var userT: UITextField! @IBOutlet weak var passT: UITextField! @IBOutlet weak var createAcc: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. userT.delegate = self passT.delegate = self // these following lines are used to create a rounded button effect, with a border width of 4 pixels, corner radius of 10 pixels, continuous corner curve and a default border color of black createAcc.layer.borderWidth = 4 createAcc.layer.cornerRadius = 10.0 createAcc.layer.cornerCurve = .continuous } @IBAction func createNewUser(_ sender: Any) { let dic = ["username" : userT.text, "password" : passT.text] DBHelper.inst.addData(object: dic as! [String:String]) userT.text = "" // reset the text fields to empty so the user can create another new user if they wish passT.text = "" } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
true
2bb8076af1271ae63c2de099db02464221098fd9
Swift
wfarley16/WFarley-HW04
/To Do List/DetailViewController.swift
UTF-8
2,447
2.671875
3
[]
no_license
// // DetailViewController.swift // To Do List // // Created by William Farley on 2/13/17. // Copyright © 2017 William Farley. All rights reserved. // import UIKit class DetailViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var toDoField: UITextField! @IBOutlet weak var toDoNoteView: UITextView! @IBOutlet weak var saveBarButton: UIBarButtonItem! var toDoItem: String? var toDoNote: String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. toDoField.text = toDoItem toDoNoteView.text = toDoNote toDoField.delegate = self toDoField.becomeFirstResponder() if toDoItem?.characters.count == 0 || toDoItem == nil { saveBarButton.isEnabled = false } else { saveBarButton.isEnabled = true navigationItem.title = "To Do Item" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK:- UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField == toDoField { let oldString = textField.text! as NSString let newString = oldString.replacingCharacters(in: range, with: string) as NSString if newString.length == 0 { saveBarButton.isEnabled = false } else { saveBarButton.isEnabled = true } } return true } //MARK:- Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if saveBarButton == sender as! UIBarButtonItem { toDoItem = toDoField.text toDoNote = toDoNoteView.text } } @IBAction func cancelPressed(_ sender: UIBarButtonItem) { let isPresentingInAddMode = presentingViewController is UINavigationController if isPresentingInAddMode { dismiss(animated: true, completion: nil) } else { navigationController!.popViewController(animated: true) } } }
true
0782a288627a5641a545c1f9e8288013d4b29423
Swift
Hideyuki-Machida/iOSGraphicsLibs
/iOSGraphicsLibs/Animation/Easing/Circ.swift
UTF-8
1,790
3.140625
3
[]
no_license
// Reference resource: // http://www.robertpenner.com/easing/ // // License: // http://www.robertpenner.com/easing_terms_of_use.html import Foundation extension EasingFunc { /** :param: t current time :param: b begInnIng value :param: c change In value :param: d duration :returns: current value */ public static func easeInCirc (t: Float, b: Float, c: Float, d: Float) -> Float { var t = t t = t / d return (-c * (sqrt( 1 - pow(t, 2)) - 1) + b) } /** :param: t current time :param: b begInnIng value :param: c change In value :param: d duration :returns: current value */ public static func easeOutCirc (t: Float, b: Float, c: Float, d: Float) -> Float { var t = t t = t / d - 1 return (c * sqrt(1 - pow(t, 2)) + b) } /** :param: t current time :param: b begInnIng value :param: c change In value :param: d duration :returns: current value */ public static func easeInOutCirc (t: Float, b: Float, c: Float, d: Float) -> Float { var t = t t = t / d * 2 if t < 1 { return -c / 2 * (sqrt( 1 - t * t) - 1) + b } else { t = t - 2 return c / 2 * (sqrt( 1 - t * t) + 1) + b } } /** :param: t current time :param: b begInnIng value :param: c change In value :param: d duration :returns: current value */ public static func easeOutInCirc (t: Float, b: Float, c: Float, d: Float) -> Float { if t < d / 2 { return easeOutCirc(t: t * 2, b: b, c: c / 2, d: d) } else { return easeInCirc(t: ( t * 2 ) - d, b: b + c / 2, c: c / 2, d: d) } } }
true
5a203e402846b1b9dff557ded4af75c6635fbd50
Swift
vadyma18/Go
/Sources/SideBar/CellForPassengerMessage.swift
UTF-8
970
2.5625
3
[]
no_license
import UIKit class CellForPassengerMessage: UITableViewCell { @IBOutlet private weak var _nickNameLabel: UILabel! @IBOutlet private weak var _dateLabel: UILabel! @IBOutlet private weak var _textView: UITextView! @IBOutlet private weak var _avatarImageView: UIImageView! var avatarImageView: UIImageView { get { return _avatarImageView } } var nickName: NSString? { get { return nil } set { _nickNameLabel.text = newValue } } var date: NSDate? { get { return nil } set { _dateLabel.text = NSDate.routeDateFormater.stringFromDate(newValue!) } } var textForMessage: NSString? { get { return nil } set { _textView.text = newValue } } }
true
4535f1b67915cf2fcdadc87d9aa5f14bf539cf43
Swift
Marcus-Mosley/ICS4U-Swift-Lesson-4
/Lesson 4 Challenge/Shared/ContentView.swift
UTF-8
977
2.96875
3
[]
no_license
// // ContentView.swift // Lesson 4 Challenge // // Created by Marcus A. Mosley on 2021-01-19 // import SwiftUI import UIKit let toronto: UIImage = #imageLiteral(resourceName: "toronto.jpg") struct ContentView: View { var body: some View { ZStack() { Image(uiImage: toronto) .resizable() .aspectRatio(contentMode: .fit) .cornerRadius(10) VStack() { Text("CN Tower") .font(.largeTitle) .padding([.top, .leading, .trailing]) Text("Toronto") .font(.caption) .padding([.leading, .bottom, .trailing]) } .background(Color.black) .opacity(0.8) .cornerRadius(10) .foregroundColor(Color.white) }.padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
true
dfa94240f2ff8a7dfb3e564e7916b11426b0f319
Swift
incanus/Hands-On-AR
/iOS Visualizer/Hand Control/Hand.swift
UTF-8
5,961
2.9375
3
[]
no_license
import UIKit import SceneKit class Hand: SCNNode { private var lastFingerRotationX: [CGFloat] = [0, 0, 0, 0, 0] private var lastHandRotation = SCNVector3(0, 0, 0) private var lastPosition = SCNVector3(0, 0, 0) override init() { super.init() self.name = "hand" self.opacity = 0.75 let colorMaterial = SCNMaterial() colorMaterial.diffuse.contents = UIColor.blue let darkMaterial = SCNMaterial() darkMaterial.diffuse.contents = UIColor.darkGray let palm = SCNTube(innerRadius: 0.35, outerRadius: 0.5, height: 0.1) palm.materials = [darkMaterial, darkMaterial, colorMaterial, colorMaterial] let palmNode = SCNNode(geometry: palm) palmNode.name = "palm" palmNode.position = SCNVector3(0, 0, 0) palmNode.transform = SCNMatrix4MakeRotation(.pi / 2, 1, 0, 0) self.addChildNode(palmNode) let ls: [CGFloat] = [0.6, 0.75, 0.65, 0.5] let rs: [Float] = [.pi / 6, .pi / 11, -.pi / 11, -.pi / 6, .pi / 3] let xs: [Float] = [-0.35, -0.1, 0.1, 0.35, -0.35] let ys: [Float] = [0.35, 0.5, 0.5, 0.35, 0] for f in 1...4 { let finger = SCNCylinder(radius: 0.1, height: ls[f - 1]) finger.materials = [colorMaterial, darkMaterial, darkMaterial] let fingerNode = SCNNode(geometry: finger) fingerNode.name = "finger.\(f)" fingerNode.position = SCNVector3(0, 0, 0) fingerNode.pivot = SCNMatrix4MakeTranslation(0, -0.5, 0) fingerNode.transform = SCNMatrix4MakeRotation(rs[f - 1], 0, 0, 1) fingerNode.transform = SCNMatrix4Translate(fingerNode.transform, xs[f - 1], ys[f - 1], 0) self.addChildNode(fingerNode) } let thumb = SCNCylinder(radius: 0.1, height: 0.4) thumb.materials = [colorMaterial, darkMaterial, darkMaterial] let thumbNode = SCNNode(geometry: thumb) thumbNode.name = "finger.0" thumbNode.position = SCNVector3(0, 0, 0) thumbNode.pivot = SCNMatrix4MakeTranslation(0, -0.5, 0) thumbNode.transform = SCNMatrix4MakeRotation(rs[4], 0, 0, 1) thumbNode.transform = SCNMatrix4Translate(thumbNode.transform, xs[4], ys[4], 0) self.addChildNode(thumbNode) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func wiggleFingers() { for f in 0...4 { if let finger = self.childNode(withName: "finger.\(f)", recursively: true) { let bend = SCNAction.rotateBy(x: -.pi / 3, y: 0, z: 0, duration: 0.25) let wait = SCNAction.wait(duration: TimeInterval(f) * 0.25) let sequence = SCNAction.sequence([wait, bend, bend.reversed()]) sequence.timingMode = .easeInEaseOut finger.runAction(sequence) } } } func wave() { let moveLeft = SCNAction.moveBy(x: -0.25, y: 0, z: 0, duration: 0.1) let moveRight = SCNAction.moveBy(x: 0.25, y: 0, z: 0, duration: 0.1) let rotateLeft = SCNAction.rotateBy(x: 0, y: 0, z: .pi / 10, duration: 0.1) let rotateRight = SCNAction.rotateBy(x: 0, y: 0, z: -.pi / 10, duration: 0.1) let left = SCNAction.group([moveLeft, rotateLeft]) let right = SCNAction.group([moveRight, rotateRight]) let reset = SCNAction.group([SCNAction.move(to: SCNVector3(0, 0, 0), duration: 0.1), SCNAction.rotateTo(x: 0, y: 0, z: 0, duration: 0.1)]) let wave = SCNAction.sequence([left, reset, right, reset]) self.runAction(SCNAction.repeat(wave, count: 3)) } func makeFist() { for f in 0...4 { if let finger = self.childNode(withName: "finger.\(f)", recursively: true) { let fist = SCNAction.rotateBy(x: -.pi * 0.6, y: 0, z: 0, duration: 0.25) let wait = SCNAction.wait(duration: 1) let sequence = SCNAction.sequence([fist, wait, fist.reversed()]) sequence.timingMode = .easeInEaseOut finger.runAction(sequence) } } } func setFingers(_ values: [UInt]) { for f in 0...4 { if let finger = self.childNode(withName: "finger.\(f)", recursively: true) { finger.runAction(SCNAction.rotateBy(x: -lastFingerRotationX[f], y: 0, z: 0, duration: 0)) let factor = CGFloat(Float(values[f]) / 10 * -.pi * 0.6) finger.runAction(SCNAction.rotateBy(x: factor, y: 0, z: 0, duration: 0)) lastFingerRotationX[f] = factor } } } func setTilt(_ values: [UInt]) { self.runAction(SCNAction.rotateBy(x: CGFloat(-lastHandRotation.x), y: CGFloat(-lastHandRotation.y), z: CGFloat(-lastHandRotation.z), duration: 0)) let xFactor = (CGFloat(Float(values[0]) - 180) / 360) * 2 * -.pi let yFactor = (CGFloat(Float(values[1]) - 180) / 360) * 2 * -.pi let zFactor = CGFloat(0) self.runAction(SCNAction.rotateBy(x: xFactor, y: yFactor, z: zFactor, duration: 0)) lastHandRotation = SCNVector3(xFactor, yFactor, zFactor) } func setPosition(x: Float, y: Float, dropped: Bool) { self.runAction(SCNAction.moveBy(x: CGFloat(-lastPosition.x), y: CGFloat(-lastPosition.y), z: CGFloat(-lastPosition.z), duration: 0)) let xFactor = CGFloat(x * 1) let yFactor = CGFloat(y * 1) let zFactor = (dropped ? 0 : CGFloat(1)) self.runAction(SCNAction.moveBy(x: xFactor, y: yFactor, z: zFactor, duration: 0)) lastPosition = SCNVector3(xFactor, yFactor, zFactor) } }
true
d5f20ba300dcf54fa1d6bd78902a4427ea4e775c
Swift
demchenkoalex/tumblr-viewer
/Tumblr/Scenes/RegularPostDetailsViewController/RegularPostDetailsViewController.swift
UTF-8
2,013
2.71875
3
[ "MIT" ]
permissive
// // RegularPostDetailsViewController.swift // Tumblr // // Created by Alex Demchenko on 30/01/2018. // Copyright © 2018 Alex Demchenko. All rights reserved. // import UIKit class RegularPostDetailsViewController: UIViewController { private let titleLabel = UILabel().then { $0.font = .avenirBold(ofSize: 20) $0.numberOfLines = 0 } private let bodyTextView = UITextView().then { $0.font = .avenirRegular(ofSize: 16) $0.backgroundColor = .clear $0.showsVerticalScrollIndicator = false } // MARK: Initialization init(title: String?, body: String?) { titleLabel.text = title bodyTextView.text = body super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .background view.addSubview(titleLabel) view.addSubview(bodyTextView) setupConstraints() } // MARK: Helpers override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Fix `UITextView` offset when view controller is presented bodyTextView.setContentOffset(.zero, animated: false) } // MARK: UI private func setupConstraints() { titleLabel.snp.makeConstraints { make in make.left.equalToSuperview().offset(16) make.right.equalToSuperview().offset(-16) make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(16) } let isTitleAvailable = titleLabel.text != nil && !titleLabel.text!.isEmpty bodyTextView.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(isTitleAvailable ? 8 : 0) make.left.equalTo(titleLabel) make.right.equalTo(titleLabel) make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom) } } }
true
7f5fde464370f57b816c4925bb6a89703e4bf5fd
Swift
Serhii-Blinov/CoreDataManager
/Extensions/NSObject+Extensions.swift
UTF-8
363
2.703125
3
[]
no_license
// Repos // // Created by Sergey on 6/10/18. // Copyright © 2018 Sergey Blinov. All rights reserved. // import Foundation public extension NSObject { var className: String { return NSStringFromClass(type(of: self)) } class var className: String { return NSStringFromClass(self).components(separatedBy: ".").last ?? "" } }
true
5f888c1a6a33d84eb1eb95cfe16292c7411baa09
Swift
dfesslerZynga/RottenTomatoes
/RottenTomatoes/ViewController.swift
UTF-8
3,256
2.53125
3
[]
no_license
// // ViewController.swift // RottenTomatoes // // Created by Dan Fessler on 2/4/15. // Copyright (c) 2015 CodePath. All rights reserved. // import UIKit class ViewController: UITableViewController { var moviesArray: NSArray? var networkError: Bool = false override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) loadMovieData() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let array = moviesArray { return array.count } else { return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let movie = self.moviesArray![indexPath.row] as NSDictionary let cell = tableView.dequeueReusableCellWithIdentifier("com.codepath.mycell") as MovieTableViewCell cell.movieTitleLabel.text = movie["title"] as NSString if let posters: AnyObject = movie["posters"] { if let thumbnail: AnyObject? = posters["thumbnail"] { //println(thumbnail) let url = NSURL(string: thumbnail as String); cell.movieThumbnail.setImageWithURL(url); } } //cell.movieThumbnail.SetImageWithURL(ThumbnailURL!) return cell } override func viewDidLoad() { self.refreshControl?.addTarget(self, action: "onRefresh:", forControlEvents: UIControlEvents.ValueChanged) } func onRefresh(sender:AnyObject) { loadMovieData() } func loadMovieData() { SVProgressHUD.show() let RottenTomatoesURLString = "http://api.rottentomatoes.com/api/public/v1.0/lists/dvds/top_rentals.json?apikey=67jux3kv24atd6nu52ugk4dq" let request = NSMutableURLRequest(URL: NSURL(string: RottenTomatoesURLString)!) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ (response, data, error) in var errorValue: NSError? = nil if errorValue == nil { self.networkError = false let dictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &errorValue) as NSDictionary self.moviesArray = dictionary["movies"] as? NSArray self.tableView.reloadData() SVProgressHUD.dismiss() println("REFRESH") self.refreshControl?.endRefreshing() } else { self.networkError = true } }) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let movie = self.moviesArray![indexPath.row] as NSDictionary let detailsView : MovieDetailsViewController! = self.storyboard?.instantiateViewControllerWithIdentifier("shapoopy") as MovieDetailsViewController detailsView.movieDictionary = movie self.showViewController(detailsView, sender: detailsView) } }
true
01bafe5a1c61387826fa9b2e04380ce1704296e9
Swift
danielcolnaghi/TheMovie
/DCTheMovie/DCTheMovie/View/MyMoviesViewController.swift
UTF-8
3,055
2.5625
3
[]
no_license
// // MyMoviesViewController.swift // DCTheMovie // // Created by Daniel Colnaghi on 30/11/17. // Copyright © 2017 Cold Mass Digital Entertainment. All rights reserved. // import UIKit class MyMoviesViewController: UIViewController { var myMoviesVM = MyMoviesViewModel() @IBOutlet weak var tblMovies: UITableView! override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11.0, *) { self.navigationController?.navigationBar.prefersLargeTitles = true } } override func viewWillAppear(_ animated: Bool) { myMoviesVM.reloadData() tblMovies.reloadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? MovieDetailsViewController { if let sender = sender as? Movie { vc.movieDetailVM = MovieDetailViewModel(movie: sender) } } } } extension MyMoviesViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return myMoviesVM.countMovies } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "moviecell") as? MyMovieCell else { return UITableViewCell() } cell.loadCellWithMovie(myMoviesVM.movieAtIndex(indexPath.row)!) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let data = myMoviesVM.movieAtIndex(indexPath.row) performSegue(withIdentifier: "segueMyMovies", sender: data) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let act1 = UITableViewRowAction(style: .normal, title: "Watched") { (rowAction, index) in if let movie = self.myMoviesVM.movieAtIndex(indexPath.row) { // Add movie to watched list self.myMoviesVM.moveToWatchedList(Movie: movie) self.myMoviesVM.removeMovie(movie) tableView.deleteRows(at: [indexPath], with: .automatic) } } act1.backgroundColor = UIColor.blue let act2 = UITableViewRowAction(style: .destructive, title: "Delete") { (rowAction, index) in if let movie = self.myMoviesVM.movieAtIndex(indexPath.row) { // Remove movie from must watch list self.myMoviesVM.removeMovie(movie) tableView.deleteRows(at: [indexPath], with: .automatic) } } // Set Watched and Delete action return [act2, act1] } }
true
feb1bfb0c5fc4f8b92b53feca074b870bfba8c84
Swift
MIR013/Today-I-Learned
/IOS/swift/swiftPractice07.playground/Contents.swift
UTF-8
5,564
4.65625
5
[]
no_license
// chapter8. Class import Cocoa //2. 클래스와 프로퍼티 /* 프로퍼티 - 클래스 내의 변수를 뜻한다 클래스 파일에 따로 정의 할 경우 탑 레벨에 실행 코드를 작성할 수 없다!!! main.swift에는 탑 레벨에 실행 코드를 작성할 수 있다. */ //저장 프로퍼티 - 값을 저장하기 위한 용도, 객체 생성시 초기화해야한다. class myClass{ var intProperty=0 var floatProperty:Float? //옵셔널의 경우 초기값을 입력 안하면 자동으로 nil이 들어감 //var strProperty:String //초기화 해야한다 아니면 에러 } var obj = myClass() obj.intProperty=10 obj.floatProperty=3.1 //옵셔널 타입이 nil을 사용 할 수 있다지 값을 대입할때 언래핑하고 값넣고 다시 래핑할 필요는 없음 아마 지들이 알아서 하는 듯 let val = obj.floatProperty type(of:val) //val은 옵셔널 타입 type(of:val!) //계산 프로퍼티 - 값을 저장하지 않음, 값을 얻거나 설정 //읽고 쓰기가 모두 가능하면 set/get 모두 작성, 읽기만 하려면 get생략 가능, set전용은 없음 class person{ //저장 프로퍼티 let thisYear=2019 var birthYear:Int=0 // 계산 프로퍼티 -> 따로 저장 안하고 그때 그때 값에 따라 계산 var age:Int{//type생략하면 안됨 get{//외부에서 콜할때 나옴 return thisYear-birthYear//반드시 return문으로 끝내기 } set{ //들어오는 값을 newValue란 이름을 사용 할 거라면 (생략가능) //다른 이름을 사용할 거라면 set(otherName)으로 지정해 줘야 한다. birthYear=thisYear-newValue } } } var obj2=person() obj2.age obj2.birthYear=1995 obj2.age //3. 메소드 class Counter{ var count=0 func increment(){ count+=1 } func increment(amount:Int){ count+=amount } func increment(amt amount:Int,times:Int){ count+=amount*times } func setCount(count:Int){ self.count = count //프로퍼티 이름이 겹칠때 이를 구분하기 위한 객체 자신을 참조하는 self } } let counter = Counter() //객체 생성 후 counter.increment() counter.count counter.increment(amount: 5) //하나만 있으면 내부==외부 란 뜻 counter.count counter.increment(amt: 3, times: 5) //외부파라미터 이름 사용 counter.count //4. 타입 메소드, 타입 프로퍼티 //인스턴스 메소드 - 객체를 생성하여 사용,인스턴스 멤버(메소드,프로퍼티) 접근 가능, 타입멤버는 접근 불가 // 원래 자바나 씨쁠쁠은 타입멤버 접근가능한디.. 여긴 안됨 //타입 메소드 - 객체 생성 안함, 인스턴스 멤버 접근 불가, 타입 멤버 접근 가능, static class fourClass{ var property=0 static var staticProperty = 0 static func typeMethod(){ //property=2 //static method에서 인스턴스 변수 사용 불가 staticProperty=2 print("type method work") } func instanceMethod(){ property=1 //staticProperty=1 //인스턴스 메소드에서 타입 변수 사용 불가 print("instance method work") } } var obj3 = fourClass() obj3.instanceMethod() //obj3.typeMethod()//이렇게는 타입 메소드를 부를 수 없다. fourClass.typeMethod() //fourClass.instanceMethod() //객체 생성 없이 인스턴스를 부를 수는 없다 //타입 프로퍼티 - 저장,계산 프로퍼티 가능, 객체 생성 없이 사용 class rectangle{ var width:Int=0 static var name:String{ return "사각형" } static var edge=4 } var obj4 = rectangle() obj4.width = 10 //obj4.name //인스턴스 타입에는 타입 프로퍼티 사용 불가! rectangle.edge=3 //그냥 객 체 전체적으로 바꾸려고 할때 사용한다. rectangle.edge rectangle.name //프로퍼티 변경 감시 /* 프로퍼티 변경 전(호출 전에 처리): willSet 프로퍼티 변경 후(호출 후에 처리): didSet 단, initializer의 초기화때는 동작하지 않는다. */ class square{ var height:Int=0{ //저장 프로퍼티 willSet{ //여기도 newValue 이름 그대로 사용할 거면 생략 가능 아니면 생략 불가 print("사각형 높이 변경 예정: \(newValue)") } didSet{// oldValue 이름 그대로 사용할 거면 생략 가능 아니면 생략 불가 print("사각형 높이 변경 완료. 이전값: \(oldValue)") } } } var obj5 = square() obj5.height=100 //값 병경시 willSet,didSet이 바로 불린다. // 프로퍼티 늦은 초기화 - 저장 프로퍼티는 반드시 초기화를 해야 하는데 경우에 따라 못할 경우가 생긴다.(예를 들어 나중에 불리는 객체가 생성 될때, 이걸 미리 초기화 하면 메모리에 좋지 않음) 그래서 나중에사용할대 초기화를 한다. class people{ lazy var phone = Phone() //lazy를 이용하여 늦은 초기화 명시(메모리를 최대한 효율적으로 사용하기 위함) } class Phone{ var number:String init(){ print("phone 객체 생성") number="010-123-123" //여기서 초기화 해줘도 됨 어차피 객체 생성 될 때, init부터 불리니까 } } let obj7 = people() //아직 Phone이 불려서 초기화 되지 않음 obj7.phone //이 lazy 변수를 사용 할 때, 초기화가 진행 된다.
true
1ea709eb02346f5cf63da273ced9882106963bf2
Swift
mrsn5/MEOW
/MEOW/ViewModels/BreedCellViewModel.swift
UTF-8
1,219
2.546875
3
[]
no_license
// // BreedCellViewModel.swift // MEOW // // Created by San Byn Nguyen on 23.05.2020. // Copyright © 2020 San Byn Nguyen. All rights reserved. // import UIKit class BreedDetailsViewModel: ImageViewModel<FileStorage> { private var service = CatImageService(dataService: CodableService(cache: FileStorage.shared, policy: .loadCacheElseLoad)) private(set) var catImage: CatImage? init() { super.init(service: ImageService(cache: FileStorage.shared, policy: .loadCacheElseLoad)) } func fetch(breed: Breed, handler: @escaping (UIImage?) -> ()) { service.fetch(count: 1, breedId: breed.id, order: "ASC") { [weak self] res in if case .success(let catImages) = res { guard let catImages = catImages, catImages.count > 0 else { return } self?.catImage = catImages[0] self?.load(string: catImages[0].url, handler: handler) } else { handler(nil) } } } func cancel(breed: Breed) { service.cancel(count: 1, breedId: breed.id, order: "ASC", handler: nil) if let catImage = catImage { self.cancel(string: catImage.url) } } }
true
5a732b954efb829a41df7e8f1ad136806caa5f8c
Swift
CodeNationDev/KVTUIKit
/Sources/KVTUIKit/Label/KVTLabel.swift
UTF-8
583
2.609375
3
[ "MIT" ]
permissive
// import Foundation import UIKit public class KVTLabel: UILabel { public var size: CGFloat { get { return font.pointSize } set { font = .kidSans(size: newValue) } } override public init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } private func setupView() { textColor = theme.primaryColor?.color() font = .boldSystemFont(ofSize: size) } }
true
10abf1a9bf90738d35d9863dbd493183844f0194
Swift
TerryHuangHD/LeetCode-Swift
/Array/TwoSum.swift
UTF-8
536
3.53125
4
[ "MIT" ]
permissive
/** * Question Link: https://leetcode.com/problems/two-sum/ * Primary idea: Traverse the array and store target - nums[i] in a dict * * Time Complexity: O(n), Space Complexity: O(n) */ class TwoSum { func twoSum(_ nums: [Int], _ target: Int) -> [Int] { var dict = [Int: Int]() for (i, num) in nums.enumerated() { if let lastIndex = dict[target - num] { return [lastIndex, i] } dict[num] = i } fatalError("No valid outputs") } }
true
a422aae351c5d13183324329e7e4e32496df0def
Swift
sagayathri/iOSChatApp
/ChatApp/View/HelperClass.swift
UTF-8
505
2.9375
3
[]
no_license
// // HelperClass.swift // ChatApp // // import Foundation import UIKit extension UIColor { static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor { return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1.0) } static func primaryColour() -> UIColor { return UIColor(red:0.96, green:0.25, blue:0.41, alpha:1.0) } static func fadeOut() -> UIColor { return UIColor(red:0.96, green:0.25, blue:0.41, alpha:0.8) } }
true
865733eee1b54e4260aa495722f95e7907d2f571
Swift
antonselyanin/pwsafe
/Tests/PwsafeSwiftTests/PwsafeParsingInternalTest.swift
UTF-8
2,768
2.578125
3
[ "MIT" ]
permissive
// // PwsafeParsingInternalTest.swift // PwsafeSwift // // Created by Anton Selyanin on 18/10/15. // Copyright © 2015 Anton Selyanin. All rights reserved. // import Foundation import Quick import Nimble @testable import PwsafeSwift class PwsafeParsingInternalTest: QuickSpec { //todo: add test for failures! override func spec() { describe("RawField parser") { it("parses RawField") { // Given let writer = BlockWriter() writer.write(UInt32(5)) writer.write(UInt8(1)) // When let result = RawField.parser.parse(Data(writer.data)) // Then expect(result.value).to(beNil()) } it("fails if not enough data") { let fieldData: [UInt8] = [1, 2, 3, 4] let writer = BlockWriter() writer.write(UInt32(fieldData.count)) writer.write(UInt8(1)) writer.write(fieldData) var data = Data(writer.data) data.append(5) data.append(6) data.append(7) let parsed = RawField.parser.parse(data).value! expect(parsed.remainder) == Data([5, 6, 7]) expect(parsed.value) == RawField(typeCode: 1, bytes: [1, 2, 3, 4]) } } describe("parseRawPwsafeRecords") { it ("parses multiple records") { // Given let writer = BlockWriter() try! writer.writeRawField(type: 1, data: [1, 2, 3, 4]) try! writer.writeRawField(type: 2, data: [5, 6, 7]) try! writer.writeRawField(type: 0xff) try! writer.writeRawField(type: 1, data: [1, 2, 3, 4]) try! writer.writeRawField(type: 5) try! writer.writeRawField(type: 5) try! writer.writeRawField(type: 0xff) // When let rawRecords = try! parseRawPwsafeRecords(writer.data) // Then expect(rawRecords.count) == 2 expect(rawRecords[0]) == [ RawField(typeCode: 1, bytes: [1, 2, 3, 4]), RawField(typeCode: 2, bytes: [5, 6, 7]) ] expect(rawRecords[1]) == [ RawField(typeCode: 1, bytes: [1, 2, 3, 4]), RawField(typeCode: 5, bytes: []), RawField(typeCode: 5, bytes: []) ] } } } }
true
c48a4a65cb82151e9885a3bac3acd9f08d41e233
Swift
wesleysfavarin/SwiftUI-Combine-MVVM-Clean
/SwiftUIMVVM/Modules/ActorDetail/View/ActorMovieItem.swift
UTF-8
557
2.59375
3
[]
no_license
// // ActorMovieItem.swift // SwiftUIMVVM // // Created by GandhiMena on 30/10/19. // Copyright © 2019 gandhi. All rights reserved. // import Foundation import SwiftUI struct ActorMovieItem: View { var cast: CastMovie var body: some View { VStack { ActorMovieItemImage(urlString: cast.poster_path) Text(cast.title) .foregroundColor(Color.white) .frame(width: 120) .font(.system(size: 14, weight: .medium, design: .default) ) } } }
true
909d3ccb14575da29e9d11c75798b14dd539b781
Swift
AV8R-/Hyped-Books
/BooksService/BooksService.swift
UTF-8
973
2.859375
3
[]
no_license
// // BooksService.swift // BooksService // // Created by Богдан Маншилин on 02/10/2017. // Copyright © 2017 BManshilin. All rights reserved. // import Foundation import Result import Model import APIService public enum BookError: APIServiceError { public init(apiError: APIError) { self = .nested(api: apiError) } case nested(api: APIError) case noPersistanteStorage public var title: String { switch self { case .noPersistanteStorage: return "Failed to fetch local books" case .nested(let error): return error.title } } public var description: String { return "Contant support" } } public protocol BooksService { func fetchList( page: Int, completion: @escaping (Result<[Book], BookError>) -> Void ) func fetchBook( byUUID uuid: String, completion: @escaping (Result<Book, BookError>) -> Void ) func cancelAll() }
true
570be8ba4e69ce4066af4068a41de7797e5c86e6
Swift
OmarTarek32-zz/free-now-task
/FreeNow/Module/Drivers/Shared/DriverCardView.swift
UTF-8
673
2.59375
3
[]
no_license
// // DriverCardView.swift // FreeNow // // Created by Omar Tarek on 3/30/21. // import UIKit class DriverCardView: UIView, NibLoadable { @IBOutlet weak var driverCodeLabel: UILabel! @IBOutlet weak var carTypeLabel: UILabel! @IBOutlet weak var driverStateLabel: UILabel! // MARK: - Life Cycle Functions override func awakeFromNib() { super.awakeFromNib() loadNibContent() } // MARK: - Public Functions func configure(viewModel: DriverViewModel){ driverCodeLabel.text = "\(viewModel.id)" carTypeLabel.text = viewModel.type driverStateLabel.text = viewModel.state } }
true
348b6b0e89f96c73845bebbf5f727b4c4dda8f61
Swift
DenisSemerych/SwiftyCompanion
/SwiftyCompanion/Model/Achivment.swift
UTF-8
479
2.75
3
[]
no_license
// // Achivment.swift // SwiftyCompanion // // Created by Denis SEMERYCH on 6/27/19. // Copyright © 2019 Denis SEMERYCH. All rights reserved. // import Foundation class Achievement: Item { var name: String var id: Int var description: String var stringURL: String init(name: String, id: Int, description: String, stringURL: String) { self.name = name self.id = id self.description = description self.stringURL = stringURL } }
true
8f73a3ea702b93848d2734fbd6f486342c340957
Swift
hidekiohnuma/test
/swift_sample/ch1/HelloWorld/HelloWorld/HelloWorld.swift
UTF-8
382
3.0625
3
[]
no_license
import UIKit //HelloWorld class HelloWorld: UIView { //(4) //描画時に呼ばれる override func drawRect(rect: CGRect) { //文字列の描画 let attrs = [NSFontAttributeName: UIFont.systemFontOfSize(24)] let str = "Hello, World!" let nsstr = str as NSString nsstr.drawAtPoint(CGPointMake(0, 20), withAttributes: attrs) } }
true
5465084c273c1f967724e9d9c5540281c6c38711
Swift
zhangyu1993/testAnimation
/testAnimation/systomTran/ZYSystomTranViewController.swift
UTF-8
2,291
2.65625
3
[]
no_license
// // ZYSystomTranViewController.swift // testAnimation // // Created by zhangyu on 2018/8/20. // Copyright © 2018年 zhangyu. All rights reserved. // import UIKit class ZYSystomTranViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.orange let btn = UIButton(type: .custom) btn.frame = CGRect(x: 100, y: 200, width: 50, height: 50) btn.backgroundColor = .red btn.addTarget(self, action: #selector(btnClick), for: UIControlEvents.touchUpInside) self.view.addSubview(btn) } @objc func btnClick() { let vc = ZYSystomViewController1() self.navigationController?.view.layer.add(pushAnimation(), forKey: nil) self.navigationController?.pushViewController(vc, animated: true) } func pushAnimation() -> CATransition { /*私有API cube 立方体效果 pageCurl 向上翻一页 pageUnCurl 向下翻一页 rippleEffect 水滴波动效果 suckEffect 变成小布块飞走的感觉 oglFlip 上下翻转 cameraIrisHollowClose 相机镜头关闭效果 cameraIrisHollowOpen 相机镜头打开效果 */ //下面四个是系统公有的API //kCATransitionMoveIn, kCATransitionPush, kCATransitionReveal, kCATransitionFade let caTran = CATransition.init() caTran.duration = 3 caTran.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionDefault) caTran.type = "cube" // caTran.subtype = kCATransitionFromRight return caTran } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
a6d18c742c54b9ccdfa37a7c65d5189b7cc00633
Swift
ahmedhawas/swift_voicetweek
/VoiceTweak/ViewController.swift
UTF-8
3,722
2.625
3
[]
no_license
// // ViewController.swift // VoiceTweak // // Created by Ahmed Hawas on 2015-11-08. // Copyright © 2015 Ahmed Hawas. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController, AVAudioPlayerDelegate { var audioRecorder : AVAudioRecorder? var audioPlayer : AVAudioPlayer? var rate : Float = 1.0 var audioURL : NSURL? @IBOutlet weak var speedLabel: UILabel! @IBOutlet weak var loopSwitch: UISwitch! @IBOutlet weak var playButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. setUpAudioRecorder() } func setUpAudioRecorder() { do { let basePath : String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first! let pathComponenets = [basePath, "theAudio.m4a"] self.audioURL = NSURL.fileURLWithPathComponents(pathComponenets) let session = AVAudioSession.sharedInstance() try session.setCategory(AVAudioSessionCategoryPlayAndRecord) try session.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker) try session.setActive(true) var recordSettings = [String : AnyObject]() recordSettings[AVFormatIDKey] = Int(kAudioFormatMPEG4AAC) recordSettings[AVSampleRateKey] = 44100.0 recordSettings[AVNumberOfChannelsKey] = 2 self.audioRecorder = try AVAudioRecorder(URL: self.audioURL!, settings: recordSettings) self.audioRecorder!.meteringEnabled = true self.audioRecorder!.prepareToRecord() } catch {} } @IBAction func recordTapped(button: UIButton) { if self.audioRecorder!.recording { self.audioRecorder!.stop() button.setTitle("RECORD", forState: UIControlState.Normal) } else { do { try AVAudioSession.sharedInstance().setActive(true) self.audioRecorder!.record() button.setTitle("STOP", forState: UIControlState.Normal) } catch {} } } @IBAction func playTapped(sender: UIButton) { if self.audioPlayer == nil { setUpAndPlay() } else { if self.audioPlayer!.playing { self.audioPlayer!.stop() self.playButton.setTitle("PLAY", forState: UIControlState.Normal) } else { setUpAndPlay() } } } func setUpAndPlay() { do { self.audioPlayer = try AVAudioPlayer(contentsOfURL: self.audioURL!) self.audioPlayer!.enableRate = true self.audioPlayer!.rate = self.rate if self.loopSwitch.on { self.audioPlayer!.numberOfLoops = -1 } self.audioPlayer!.delegate = self self.audioPlayer!.play() self.playButton.setTitle("STOP", forState: UIControlState.Normal) } catch {} } func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) { self.playButton.setTitle("PLAY", forState: UIControlState.Normal) } @IBAction func sliderMoved(slider: UISlider) { self.rate = 0.2 self.rate += (slider.value * 3.8) let prettyRate = String(format: "%.1f", self.rate) self.speedLabel.text = "Speed \(prettyRate)x" if self.audioPlayer != nil { self.audioPlayer!.rate = self.rate } } }
true
653afeb023d628f770e30301ec2660deca8d6f4e
Swift
shobitgoel/AsurionCode
/AsurionCodeExercise/AsurionCodeExercise/View/Controller/PetDetailsViewController.swift
UTF-8
827
2.5625
3
[]
no_license
// // PetDetailsViewController.swift // AsurionCodeExercise // // Created by Goel, Shobit on 02/10/20. // Copyright © 2020 Goel, Shobit. All rights reserved. // import UIKit import WebKit class PetDetailsViewController: UIViewController, WKUIDelegate { var webView: WKWebView! var petContentURL: String? override func loadView() { let webConfiguration = WKWebViewConfiguration() webView = WKWebView(frame: .zero, configuration: webConfiguration) webView.uiDelegate = self view = webView } override func viewDidLoad() { super.viewDidLoad() guard let petContentURL = petContentURL, let url = URL(string: petContentURL) else { return } let urlRequest = URLRequest(url: url) webView.load(urlRequest) } }
true
1d3c5ddfb0a9990bb8afc2dbab9b41a42d925980
Swift
jpjesus/pruebaIosGrability
/PruebaIOS/CustomAnimation.swift
UTF-8
1,624
2.703125
3
[]
no_license
// // CustomAnimation.swift // PruebaIOS // // Created by Jesus Alberto on 22/7/16. // Copyright © 2016 Jesus Alberto. All rights reserved. // import Foundation class CustimAnimation : NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.45 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView: UIView = transitionContext.containerView()! let originatingVC: UIViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let destinationVC: UIViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! containerView.addSubview(destinationVC.view!) destinationVC.view.transform = CGAffineTransformMakeScale(0.01, 0.01) let duration: NSTimeInterval = self.transitionDuration(transitionContext) UIView.animateWithDuration(duration, animations: {() -> Void in destinationVC.view.transform = CGAffineTransformIdentity originatingVC.view.transform = self.transformForVC(originatingVC) }, completion: {(finished: Bool) -> Void in transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) }) } func transformForVC(VC: UIViewController) -> CGAffineTransform { if (VC is ViewController) { let scale: CGAffineTransform = CGAffineTransformMakeScale(0.1, 0.1) return CGAffineTransformRotate(scale, 2 * 1) } else { return CGAffineTransformMakeScale(0.1, 0.1) } } }
true
75164562b8a61bad875fc9f49c12589aea4f1002
Swift
Kuniwak/MirrorDiffKit
/Sources/PrettyPrinter.swift
UTF-8
176
2.84375
3
[ "MIT" ]
permissive
enum PrettyPrinter { static func print(fromLines lines: [PrettyLine]) -> String { return lines.map { $0.description } .joined(separator: "\n") } }
true
398147336301c831e1bd23afbcf6518ff438254f
Swift
leodegeus7/Silverline
/CustomerApp/CustomerApp/ViewController.swift
UTF-8
4,106
2.78125
3
[]
no_license
// // ViewController.swift // CustomerApp // // Created by Leonardo Geus on 22/02/19. // Copyright © 2019 Leonardo Geus. All rights reserved. // import UIKit import FirebaseFirestore class ViewController: UIViewController { @IBOutlet weak var textField: UITextField! @IBOutlet weak var tagsCollectionView: UICollectionView! var db : Firestore! var areas = [Area]() var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.purple, UIColor.green, UIColor.orange, UIColor.magenta] override func viewDidLoad() { super.viewDidLoad() db = Firestore.firestore() tagsCollectionView.delegate = self tagsCollectionView.dataSource = self let layout = tagsCollectionView.collectionViewLayout as? UICollectionViewFlowLayout layout?.estimatedItemSize = CGSize(width: 200, height: 80) // Do any additional setup after loading the view, typically from a nib. getAreas { (areas) in self.areas = areas self.areas.removeAll(where: {$0.name == "all"}) self.tagsCollectionView.reloadData() } } func getAreas(completion: @escaping (_ result: [Area]) -> Void) { db.collection("areas").addSnapshotListener { (querySnapshot, error) in if let err = error { print("Error getting documents: \(err)") } else { var areas = [Area]() var strings = [String]() for document in querySnapshot!.documents { strings.append((document.data()["name"] as? String)!) } strings = strings.sorted(by: {$0 < $1}) strings.append("all") var count = 0 for string in strings { areas.append(Area.init(name: string, color: self.colors[count])) count = count + 1 } completion(areas) } } } } extension ViewController:UICollectionViewDataSource,UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return areas.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCell", for: indexPath) as? TagCollectionViewCell cell?.label.text = areas[indexPath.row].name cell?.label.textColor = UIColor.white cell?.label.layer.cornerRadius = (cell?.label.frame.height)!/2 cell?.label.layer.masksToBounds = true if areas[indexPath.row].isActive == true { cell?.label.backgroundColor = areas[indexPath.row].color } else { cell?.label.backgroundColor = UIColor.gray } return cell! } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if textField.text != "" { perfomedCustomer(name: textField.text!, area: areas[indexPath.row].name!) } else { let alert = UIAlertController(title: "Alert", message: "Insira um nome", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)) self.present(alert, animated: true, completion: nil) } tagsCollectionView.reloadData() } func perfomedCustomer(name:String,area:String) { let url = URL(string: "https://us-central1-silverline-c3342.cloudfunctions.net/addCustomer?name=\(name)&area=\(area)")! let task = URLSession.shared.dataTask(with: url) {(data, response, error) in guard let data = data else { return } print(String(data: data, encoding: .utf8)!) } textField.text = "" task.resume() } }
true
2cfe13429e3e410caa65fb796f99d7fba678e6ad
Swift
gituxedo/UBookIt
/UBookIt/Models/Listing.swift
UTF-8
2,626
2.8125
3
[]
no_license
// // Listing.swift // UBookIt // // Created by apple on 7/12/17. // Copyright © 2017 Sylvia Jin. All rights reserved. // import Foundation import UIKit import FirebaseDatabase.FIRDataSnapshot protocol UKeyed { var key:String? {get set} } class Listing:UKeyed { var key: String? let creationDate: Date let poster: User let title: String let author: String let condition: String let edition: String let price: Double let imgURL: String var extra: String var dictValue: [String : Any] { let createdAgo = creationDate.timeIntervalSince1970 let userDict = ["uid" : poster.uid, "zip" : poster.zip, "name": poster.name] return ["title" : title, "author" : author, "condition" : condition, "edition" : edition, "price" : price, "extra" : extra, "imageURL" : imgURL, "created_at" : createdAgo, "poster" : userDict] } init(title:String, author:String, condition:String, edition:String, price:Double, imageURL:String, extra: String) { self.title = title self.author = author self.condition = condition self.edition = edition self.price = price self.poster = User.current self.imgURL = imageURL self.extra = extra self.creationDate = Date() } init?(snapshot:DataSnapshot) { guard let dict = snapshot.value as? [String:Any], let title = dict["title"] as? String, let author = dict["author"] as? String, let condition = dict["condition"] as? String, let edition = dict["edition"] as? String, let price = dict["price"] as? Double, let imageURL = dict["imageURL"] as? String, let createdAgo = dict["created_at"] as? TimeInterval, let userDict = dict["poster"] as? [String:Any], let uid = userDict["uid"] as? String, let zip = userDict["zip"] as? String, let name = userDict["name"] as? String, let extra = dict["extra"] as? String else {return nil} self.key = snapshot.key self.title = title self.author = author self.condition = condition self.edition = edition self.imgURL = imageURL self.price = price self.creationDate = Date(timeIntervalSince1970: createdAgo) self.poster = User(uid: uid, zip: zip, name: name) self.extra = extra } }
true
7dfa825c83f8afde9275702c5731c00a484d25c5
Swift
ricardoAntolin/demo
/Network/Repositories/AlbumNetworkRepository.swift
UTF-8
548
2.609375
3
[]
no_license
// // AlbumNetworkRepository.swift // network // // Created by Ricardo Antolin on 31/01/2019. // Copyright © 2019 Square1. All rights reserved. // import Alamofire public protocol AlbumsNetworkRepository: class { var baseUrl: String { get set } } extension AlbumsNetworkRepository { public func getAlbums(completion: @escaping (Result<[NWAlbumEntity]>)->Void){ AF.request("\(baseUrl)/albums") .responseDecodable { (response: DataResponse<[NWAlbumEntity]>) in completion(response.result) } } }
true
292225c1e18d311aa6c0c75a1944e603bbc28652
Swift
hajunho/SpeechDictationDemo
/SpeechDictationDemo/TrafficLightIndicator.swift
UTF-8
1,006
3.046875
3
[]
no_license
// // TrafficLightIndicator.swift // SpeechDictationDemo // // Created by Russell Archer on 07/10/2019. // Copyright © 2019 Russell Archer. All rights reserved. // import UIKit public class TrafficLightIndicator: UIView { public enum State { case red, green, amber } public var state = State.amber { didSet { switch state { case .red: backgroundColor = UIColor.red case .green: backgroundColor = UIColor.green case .amber: backgroundColor = UIColor.orange } } } /// Draw ourselves as a circular object override public func draw(_ rect: CGRect) { let width = bounds.width < bounds.height ? bounds.width : bounds.height let mask = CAShapeLayer() mask.path = UIBezierPath(ovalIn: CGRect( x: bounds.midX - width / 2, y: bounds.midY - width / 2, width: width, height: width)).cgPath layer.mask = mask } }
true
f9f155fcfa06931f25639c9c50301b5fbee169c4
Swift
jdkauffman11/AutoBuddy
/AutoBuddy/AutoBuddy/WebVC.swift
UTF-8
1,671
2.65625
3
[]
no_license
// // WebVC.swift // AutoBuddy // // Created by Jordan Kauffman on 3/20/17. // Copyright © 2017 Jordan Kauffman. All rights reserved. // import UIKit class WebVC: UIViewController { @IBOutlet var navBar: UINavigationBar! @IBOutlet var navItem: UINavigationItem! @IBOutlet var webView: UIWebView! @IBOutlet var navigationBar: UINavigationBar! var car = "" override func viewDidLoad() { super.viewDidLoad() navBar.backgroundColor = UIColor.white navItem.leftBarButtonItem = UIBarButtonItem(title: "< Back", style: .plain, target: self, action: #selector(backAction)) if car.contains(" ") { car = car.replacingOccurrences(of: " ", with: "%20") } if let url = URL(string: "https://www.google.com/search?q=\(car)%20for%20sale") { let request = URLRequest(url: url) webView.loadRequest(request) } } func backAction() { dismiss(animated: true, completion: nil) } @IBAction func backButton(_ sender: Any) { _ = navigationController?.popViewController(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
17072e473516afc480cfe976f448a01835f51b9b
Swift
joseBenavides/Todoey
/Todoey/model/Item.swift
UTF-8
292
2.796875
3
[]
no_license
// // Item.swift // Todoey // // Created by Jose on 6/6/18. // Copyright © 2018 Benavides, Jose. All rights reserved. // import Foundation //adding the codable type allows the Method to be saved and loaded locally class Item : Codable{ var title : String = "" var done : Bool = false }
true
39c7e411fdf0a7e7bc13fc9b8ac10d5523cd70f6
Swift
HTWDD/HTWDresden-iOS
/HTWDD/Components/Settings/Main/WKWebViewController.swift
UTF-8
2,106
2.703125
3
[ "MIT" ]
permissive
// // WebViewController.swift // HTWDD // // Created by Mustafa Karademir on 11.08.19. // Copyright © 2019 HTW Dresden. All rights reserved. // import UIKit class WKWebViewController: UIViewController { // MARK: - Properties private var filename: String? private var url: URL? private lazy var wkWebView: WKWebView = { let js = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);" return WKWebView(frame: .zero, configuration: WKWebViewConfiguration().also { configuration in configuration.userContentController = WKUserContentController().also { controller in controller.addUserScript(WKUserScript(source: js, injectionTime: .atDocumentEnd, forMainFrameOnly: true)) } }) }() // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setup() } func show(title: String, filename: String) { self.title = title self.filename = filename } func show(title: String, url: URL) { self.title = title self.url = url } } // MARK: - Setup extension WKWebViewController { private func setup() { if #available(iOS 11.0, *) { navigationItem.largeTitleDisplayMode = .never } view.apply { v in v.backgroundColor = UIColor.htw.veryLightGrey v.add(wkWebView.also { wkV in wkV.frame = v.frame }) } if let filename = filename { guard let path = Bundle.main.path(forResource: filename, ofType: nil) else { return } do { wkWebView.loadHTMLString(try String(contentsOfFile: path), baseURL: nil) } catch let error { Log.error(error) } } if let url = url { wkWebView.load(URLRequest(url: url)) } } }
true
a88cce9f033efb0779197cf86cf02e1ce33b56a1
Swift
tkmrCF/SecondKadaiApp
/SecondKadaiApp01/ViewController.swift
UTF-8
1,418
2.546875
3
[]
no_license
// // ViewController.swift // SecondKadaiApp01 // // Created by 株式会社コアファイン on 2016/02/17. // Copyright © 2016年 eiichi.takamura. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var YourNname: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){ // segueから遷移先のResultViewControllerを取得する let resultViewController:ResultViewController = segue.destinationViewController as! ResultViewController // 遷移先のResultViewControllerで宣言しているx, yに値を代入して渡す resultViewController.x = 1 resultViewController.y = 1 //resultViewController.NameYours = "hello Men" resultViewController.NameYours = YourNname.text! //????? !をつけるのか? } // レビューにより追加 @IBAction func unwind(segue: UIStoryboardSegue) { // 他の画面から segue を使って戻ってきた時に呼ばれる } }
true
3d9b1815dad12224241506899b1bf9eb4aae0470
Swift
Sivaty/DesignPattern
/8-外观模式/8-外观模式/Facade.swift
UTF-8
699
3.109375
3
[]
no_license
// // Facade.swift // 8-外观模式 // // Created by sengshuaibin on 2021/3/29. // import Cocoa class Facade { let systemA = SubSystemA() let systemB = SubSystemB() let systemC = SubSystemC() let systemD = SubSystemD() func methodA() { systemA.method() systemB.method() } func methodB() { systemC.method() systemD.method() } } class SubSystemA { func method() { print(#function) } } class SubSystemB { func method() { print(#function) } } class SubSystemC { func method() { print(#function) } } class SubSystemD { func method() { print(#function) } }
true
7ac5bcea3fc9351f65ebe3fc6c42b4f07a4f4e9a
Swift
Penjat/StartTwins
/BlueStarRedStar/Menus/MenuTitleView.swift
UTF-8
3,241
2.546875
3
[]
no_license
import UIKit class MenuTitleView: UIView , Menu{ @IBOutlet var contentView: UIView! @IBOutlet weak var titleView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var highScoresButton: UIButton! var delegate : MenuDelegate? override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit(){ Bundle.main.loadNibNamed("MenuTitle", owner: self, options: nil) addSubview(contentView) contentView.frame = self.bounds contentView.autoresizingMask = [.flexibleWidth , .flexibleHeight] let gradient = CAGradientLayer() // gradient colors in order which they will visually appear gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor,UIColor.red.cgColor, UIColor.blue.cgColor] // Gradient from left to right gradient.startPoint = CGPoint(x: 0.0, y: 1) gradient.endPoint = CGPoint(x: 0.5, y: 0.5) gradient.locations = [-2,-1,0,1] // set the gradient layer to the same size as the view gradient.frame = titleView.bounds // add the gradient layer to the views layer for rendering titleView.layer.addSublayer(gradient) titleView.mask = titleLabel let fromAnimation = CABasicAnimation(keyPath: "locations") fromAnimation.duration = 5.0 fromAnimation.toValue = [0,1,2,3] fromAnimation.fillMode = CAMediaTimingFillMode.forwards fromAnimation.isRemovedOnCompletion = false fromAnimation.repeatCount = HUGE //fromAnimation.autoreverses = true gradient.add(fromAnimation, forKey: "locationChange") //startFadeIn() } @IBAction func pressedPlay(_ sender: Any) { if let delegate = delegate{ delegate.toStartGame() }else{ print("no delegate set") } } @IBAction func pressedHighScores(_ sender: Any) { if let delegate = delegate{ delegate.toHighScores() }else{ print("no delegate set") } } func startFadeIn(){ titleView.alpha = 0.0 playButton.alpha = 0.0 highScoresButton.alpha = 0.0 UIView.animateKeyframes(withDuration: 10.0, delay: 0.0, options: [], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations: { self.titleView.alpha = 1.0 }) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.25, animations: { self.playButton.alpha = 1.0 }) UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.5, animations: { self.highScoresButton.alpha = 1.0 }) }, completion: {_ in}) } func clear(menuCommand: MenuCommand) { switch menuCommand{ case .StartGame: //startgame animation self.isUserInteractionEnabled = false UIView.animate(withDuration: 2.0, delay: 0.0, options: [], animations: { self.contentView.alpha = 0.0 self.transform = CGAffineTransform(translationX: 0, y: 100.0) }, completion: {_ in self.removeFromSuperview() }) break default: removeFromSuperview() } } }
true
a2e19e9994a31721bffa5e900370f25f0e477d1a
Swift
kaikaka/StudySwift
/StudySwift/SwiftBase/RxBase/UIViewController+Rx.swift
UTF-8
2,238
2.578125
3
[]
no_license
// // UIViewController+Rx.swift // Foowwphone // // Created by Yoon on 2020/10/30. // Copyright © 2020 Fooww. All rights reserved. // import RxSwift import RxCocoa import Toast_Swift public extension Reactive where Base: UIViewController { func push(_ viewController: @escaping @autoclosure () -> UIViewController, animated: Bool = true) -> Binder<Void> { return Binder(base) { this, _ in this.navigationController?.pushViewController(viewController(), animated: animated) } } func pop(animated: Bool = true) -> Binder<Void> { return Binder(base) { this, _ in this.navigationController?.popViewController(animated: animated) } } func popToRoot(animated: Bool = true) -> Binder<Void> { return Binder(base) { this, _ in this.navigationController?.popToRootViewController(animated: animated) } } func present(_ viewController: @escaping @autoclosure () -> UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) -> Binder<Void> { return Binder(base) { this, _ in this.present(viewController(), animated: animated, completion: completion) } } func dismiss(animated: Bool = true) -> Binder<Void> { return Binder(base) { this, _ in this.dismiss(animated: animated, completion: nil) } } var showError: Binder<Error> { return Binder(base) { this , _ in /* this, error in 获取请求code 可用来处理不同请求状态 let moyaError: MoyaError? = error as? MoyaError let response : Response? = moyaError?.response log.info(response?.statusCode) */ this.view.makeToast("网络错误,请稍后再试~") } } } public extension UIViewController { ///延迟执行 /// - Parameters: /// - delay: 延迟时间(秒) /// - closure: 延迟执行的闭包 func delay(_ delay: Double, closure: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { closure() } } }
true
b1d00aa112a3cacda8abc7c8118b93603c3d55e4
Swift
doulos76/GooMinHoi_iOS_School6
/Practice/SubViewMakeTest/SubViewMakeTest/MySubView.swift
UTF-8
3,019
2.703125
3
[]
no_license
// // MySubView.swift // SubViewMakeTest // // Created by 구민회 on 2018. 2. 7.. // Copyright © 2018년 mobileandsmile. All rights reserved. // import UIKit class MySubView: UIView { //MARK: - Custom UI View용 Private Property 선언. private var backgroundImageView: UIImageView? private var mainTitleLabel: UILabel? private var subTitleLabel: UILabel? private var actionButton: UIButton? //MARK: - Custom UI view 용 property observer 선언 var index: Int = 0 { didSet { actionButton?.tag = index } } //MARK: - Custom UI View용 Computed Property 선언. var image: UIImage? { get { return backgroundImageView?.image } set { backgroundImageView?.image = newValue } } var mainTitleText: String? { get { return mainTitleLabel?.text } set { mainTitleLabel?.text = newValue } } var subTitleText: String? { get { return subTitleLabel?.text } set { subTitleLabel?.text = newValue } } //Mark: - Initializer override init(frame: CGRect) { super.init(frame: frame) createView() updateLayout() } convenience init() { self.init(frame: CGRect.zero) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - Private Method func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents) { actionButton?.addTarget(target, action: action, for: controlEvents) } private func createView() { backgroundImageView = UIImageView() self.addSubview(backgroundImageView!) mainTitleLabel = UILabel() mainTitleLabel!.font = UIFont.systemFont(ofSize: 22) mainTitleLabel!.textColor = UIColor.white mainTitleLabel!.textAlignment = NSTextAlignment.center self.addSubview(mainTitleLabel!) subTitleLabel = UILabel() subTitleLabel!.font = UIFont.systemFont(ofSize: 15) subTitleLabel!.textColor = UIColor.blue subTitleLabel!.textAlignment = NSTextAlignment.right self.addSubview(subTitleLabel!) actionButton = UIButton(type: UIButtonType.custom) self.addSubview(actionButton!) } private func updateLayout() { let frameWidth = self.frame.size.width let frameHeight = self.frame.size.height backgroundImageView?.frame = CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight) mainTitleLabel?.frame = CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight * 2/3) subTitleLabel?.frame = CGRect(x: 0, y: frameHeight * 2/3, width: frameWidth, height: frameHeight * 1/3) actionButton?.frame = CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight) } }
true
6bc339ed946071acda0ce237fee8ebd17d0a4301
Swift
jonathanlu98/JLSptfy
/JLSptfy/Extension/Fetch/JLLibraryFetchManagement.swift
UTF-8
5,462
2.546875
3
[]
no_license
// // JLLibraryFetchManagement.swift // JLSptfy // // Created by Jonathan Lu on 2020/2/25. // Copyright © 2020 Jonathan Lu. All rights reserved. // import UIKit import Alamofire class JLLibraryFetchManagement: NSObject { /** 每次搜索限制的个数。 */ public var limit:Int = 50 /** 在该搜索结果下的索引值。配合limit可实现翻页效果 */ private(set) var offset:Int = 0 /** 搜索类型。 */ private(set) var type:JLLibraryContentType? /** 拉取的次数,用于搜索单类的时候下拉定位offset */ private(set) var pulls:Int = 0 /** 用于Library的artist获取,他与其他的get请求的参数不相同 */ private(set) var lastFollowedArtistID:String? typealias JLLibraryCompletionBlock = (JLLibraryQuickJSON?, Int, Error?) -> Void override init() { super.init() } init(limit:Int, type:JLLibraryContentType) { super.init() self.limit = limit self.type = type } /** 用于spotify获取Library的方法 - Parameter type: 搜索类型 - Parameter isReload: 是否重载,用于上拉刷新 - Parameter completed: 完成返回Block,返回json,offset,error */ func fetchMyLibrary(type: JLLibraryContentType, isReload: Bool, completed completedBlock: JLLibraryCompletionBlock?) { self.type = type let oldOffset = self.offset let oldLastFollowedArtistID = self.lastFollowedArtistID if isReload == true { self.lastFollowedArtistID = nil self.offset = 0 } else { self.offset = pulls*limit } var urlString = "" var paras:[String:String] = [:] let headers: HTTPHeaders = ["Authorization":"Bearer " + (UserDefaults.standard.string(forKey: "accessToken") ?? "")] if type == .Artists { if self.lastFollowedArtistID != nil { urlString = "https://api.spotify.com/v1/me/following" paras = ["type":"artist","limit":String(self.limit),"after":self.lastFollowedArtistID!] } else { urlString = "https://api.spotify.com/v1/me/following" paras = ["type":"artist","limit":String(self.limit)] } } else { urlString = "https://api.spotify.com/v1/me/"+type.description() paras = ["limit":String(self.limit),"offset":String(self.offset)] } Alamofire.request(urlString, method: .get, parameters: paras, encoding: URLEncoding.default, headers: headers).responseData { (response) in guard let data = response.data else { if (completedBlock != nil) { self.offset = oldOffset self.lastFollowedArtistID = oldLastFollowedArtistID completedBlock?(nil, self.offset, response.error) } return } do { var json: JLLibraryQuickJSON! switch type { case .Playlists: json = .Playlists(item: try .init(data: data)) case .Artists: json = .Artists(item: try .init(data: data)) case .Albums: json = .Albums(item: try .init(data: data)) case .Tracks: json = .Songs(item: try .init(data: data)) } if (completedBlock != nil) { if isReload == true { self.pulls = 1 self.lastFollowedArtistID = json.getLastFollowingID() completedBlock!(json, self.offset, nil) } else { self.pulls += 1 self.lastFollowedArtistID = json.getLastFollowingID() completedBlock!(json, self.offset, nil) } } } catch { if (completedBlock != nil) { self.offset = oldOffset self.lastFollowedArtistID = oldLastFollowedArtistID completedBlock!(nil, self.offset, error) } } } } func fetchList() { let urlString = "https://api.spotify.com/v1/me/track" let paras = ["limit":String(self.limit),"offset":String(self.offset)] let headers: HTTPHeaders = ["Authorization":"Bearer " + (UserDefaults.standard.string(forKey: "accessToken") ?? "")] Alamofire.request(urlString, method: .get, parameters: paras, encoding: URLEncoding.default, headers: headers).responseData { (response) in } } private func fetchSubList(url:String) { } // private func request(_ url:String) -> Library_PagingTracks { // // let headers: HTTPHeaders = ["Authorization":"Bearer " + (UserDefaults.standard.string(forKey: "accessToken") ?? "")] // // Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).responseData { (response) in // guard let data = response.data else { // // } // // } // } }
true
5822c631846a60060e44e373c4c349c65b6fbe58
Swift
msalah104/Fly365-MS
/Fly365-MS/Network/AlamofireRequestExtensions.swift
UTF-8
3,449
2.65625
3
[]
no_license
// // TripViewModel.swift // Fly365-MS // // Created by Mohammed Salah on 4/19/19. // Copyright © 2019 Mohammed Salah. All rights reserved. // import UIKit import Alamofire import SwiftyBeaver typealias Log = SwiftyBeaver public extension Alamofire.Request { /// Prints the log for the request @discardableResult func debug() -> Self { guard Configurations.mode == .development else {return self} Log.info(self.debugDescription) return self } } public extension Alamofire.DataRequest { @discardableResult func validateErrors() -> Self { return validate { [weak self] (request, response, data) -> Alamofire.Request.ValidationResult in // get status code from server let code = response.statusCode // check the request url let requestURL = String(describing: request?.url?.absoluteString ?? "NO URL") // check if response is empty guard let data = data, let jsonData = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: Any], let json = jsonData else { self?.log(code: code, url: requestURL, message: "Empty response" as AnyObject, isError: false, request: request) return .success } var result: Alamofire.Request.ValidationResult = .success // check if response is html if (response.allHeaderFields["Content-Type"] as? String)?.contains("text/html") == true { self?.log(code: code, url: requestURL, message: json as AnyObject, isError: true, request: request) let error = NSError(domain: "html", code: -999, userInfo: ["html": data, NSLocalizedDescriptionKey: "somethingWentWrong"]) result = .failure(error) } else if let message = (json["message"] as? String ?? json["status_code"] as? String) { //create the error object let domain = json["statusCode"] as? String ?? "error" if domain == "0000" { let error = FlyError(code: domain, message: message) //log error self?.log(code: code, url: requestURL, message: json as AnyObject, isError: true, request: request) //return failure result = .failure(error) } } else { self?.log(code: code, url: requestURL, message: json as AnyObject, isError: false, request: request) result = .success } return result } // validate for request errors .validate() // log request .debug() } private func log(code: Int, url: String, message: AnyObject, isError: Bool, request: URLRequest?) { guard Configurations.mode == .development else {return} if isError { Log.error("FAILED") } Log.info("Status Code >> \(code)") Log.info("URL >> \(url)") Log.info("Request >> \(String(describing: request?.allHTTPHeaderFields))") Log.info("Response >> \(message)") } }
true
529da5999f58f9feb59fdc5a02be7b7cd1b3884d
Swift
dogo/AKSideMenu
/AKSideMenuExamples/Simple/AKSideMenuSimple/AppDelegate/AppDelegate.swift
UTF-8
2,704
2.53125
3
[ "MIT" ]
permissive
// // AppDelegate.swift // AKSideMenu // // Created by Diogo Autilio on 6/3/16. // Copyright © 2016 AnyKey Entertainment. All rights reserved. // import UIKit import AKSideMenu @UIApplicationMain final class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = buildController() self.window?.makeKeyAndVisible() return true } private func buildController() -> UIViewController { // Create content and menu controllers let navigationController = UINavigationController(rootViewController: FirstViewController()) let leftMenuViewController = LeftMenuViewController() let rightMenuViewController = RightMenuViewController() // Create sideMenuController let sideMenuViewController = AKSideMenu(contentViewController: navigationController, leftMenuViewController: leftMenuViewController, rightMenuViewController: rightMenuViewController) // Configure sideMenuController sideMenuViewController.backgroundImage = UIImage(named: "Stars") sideMenuViewController.menuPreferredStatusBarStyle = .lightContent sideMenuViewController.delegate = self sideMenuViewController.contentViewShadowColor = .black sideMenuViewController.contentViewShadowOffset = .zero sideMenuViewController.contentViewShadowOpacity = 0.6 sideMenuViewController.contentViewShadowRadius = 12 sideMenuViewController.contentViewShadowEnabled = true return sideMenuViewController } } extension AppDelegate: AKSideMenuDelegate { public func sideMenu(_ sideMenu: AKSideMenu, willShowMenuViewController menuViewController: UIViewController) { debugPrint("willShowMenuViewController", menuViewController) } public func sideMenu(_ sideMenu: AKSideMenu, didShowMenuViewController menuViewController: UIViewController) { debugPrint("didShowMenuViewController", menuViewController) } public func sideMenu(_ sideMenu: AKSideMenu, willHideMenuViewController menuViewController: UIViewController) { debugPrint("willHideMenuViewController ", menuViewController) } public func sideMenu(_ sideMenu: AKSideMenu, didHideMenuViewController menuViewController: UIViewController) { debugPrint("didHideMenuViewController", menuViewController) } }
true
f3f580fa76b8c98933cfce7ce16e94a1e089d21a
Swift
DataDog/dd-sdk-ios
/DatadogInternal/Sources/Codable/AnyEncoder.swift
UTF-8
24,122
3.140625
3
[ "Apache-2.0", "MIT" ]
permissive
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2019-Present Datadog, Inc. */ import Foundation /// An object that encodes instances of an `Encodable` type as `Any?`. /// /// The example below shows how to encode an instance of a simple `GroceryProduct` /// type to `Any` object. The type adopts `Codable` so that it's encodable as `Any` /// using a `AnyEncoder` instance. /// /// struct GroceryProduct: Codable { /// var name: String /// var points: Int /// var description: String? /// } /// /// let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear.") /// /// let encoder = AnyEncoder() /// /// let object = try encoder.encode(pear) /// print(object as! NSDictionary) /// /// /* Prints: /// { /// description = "A ripe pear."; /// name = Pear; /// points = 250; /// } /// */ open class AnyEncoder { /// Initializes `self`. public init() { } /// Encodes the given top-level value and returns its Any representation. /// /// Depending on the value and its `Encodable` implementation the returned /// encoded value can be `Any`, `[Any?]`, `[String: Any?]`, or `nil`. /// /// - parameter value: The value to encode. /// - returns: An `Any` object containing the value. /// - throws: An error if any value throws an error during encoding. open func encode<T>(_ value: T) throws -> Any? where T: Encodable { let encoder = _AnyEncoder() try value.encode(to: encoder) return encoder.any } } /// A type that can encode values into a native format for external /// representation. private class _AnyEncoder: Encoder { typealias AnyEncodingStorage = (Any?) -> Void /// The path of coding keys taken to get to this point in encoding. let codingPath: [CodingKey] /// Any contextual information set by the user for encoding. let userInfo: [CodingUserInfoKey: Any] = [:] /// The encoded value. var any: Any? init(path: [CodingKey] = []) { codingPath = path } /// Returns an encoding container appropriate for holding multiple values /// keyed by the given key type. /// /// You must use only one kind of top-level encoding container. This method /// must not be called after a call to `unkeyedContainer()` or after /// encoding a value through a call to `singleValueContainer()` /// /// - parameter type: The key type to use for the container. /// - returns: A new keyed encoding container. func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey { let container = KeyedContainer<Key>( store: { self.any = $0 }, dictionary: any as? [String: Any?], path: codingPath ) self.any = container.dictionary return KeyedEncodingContainer(container) } /// Returns an encoding container appropriate for holding multiple unkeyed /// values. /// /// You must use only one kind of top-level encoding container. This method /// must not be called after a call to `container(keyedBy:)` or after /// encoding a value through a call to `singleValueContainer()` /// /// - returns: A new empty unkeyed container. func unkeyedContainer() -> UnkeyedEncodingContainer { let container = UnkeyedContainer( store: { self.any = $0 }, array: any as? [Any?], path: codingPath ) self.any = container.array return container } /// Returns an encoding container appropriate for holding a single primitive /// value. /// /// You must use only one kind of top-level encoding container. This method /// must not be called after a call to `unkeyedContainer()` or /// `container(keyedBy:)`, or after encoding a value through a call to /// `singleValueContainer()` /// /// - returns: A new empty single value container. func singleValueContainer() -> SingleValueEncodingContainer { SingleValueContainer( store: { self.any = $0 }, path: codingPath ) } /// A concrete container that provides a view into an encoder's storage, making /// the encoded properties of an encodable type accessible by keys. class KeyedContainer<Key>: KeyedEncodingContainerProtocol where Key: CodingKey { /// The path of coding keys taken to get to this point in encoding. var codingPath: [CodingKey] /// The dictionary of encoded value. var dictionary: [String: Any?] /// The storage closure to call with encoded value. let store: AnyEncodingStorage /// Creates a keyed container for encoding an `Encodable` object to /// a dictionary of `[String: Any?]`. /// /// - Parameters: /// - store: The storage closure to call with encoded value. /// - dictionary: An existing dictionary of any. /// - path: The path of coding keys taken to get to this point in encoding. init( store: @escaping AnyEncodingStorage, dictionary: [String: Any?]? = nil, path: [CodingKey] = [] ) { self.store = store self.dictionary = dictionary ?? [:] self.codingPath = path } /// Encodes a null value for the given key. /// /// - parameter key: The key to associate the value with. func encodeNil(forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encodeNil() } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: Bool, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: String, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: Double, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: Float, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: Int, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: Int8, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: Int16, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: Int32, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: Int64, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: UInt, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: UInt8, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: UInt16, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: UInt32, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode(_ value: UInt64, forKey key: Key) throws { try nestedSingleValueContainer(forKey: key).encode(value) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable { try nestedSingleValueContainer(forKey: key).encode(value) } /// Stores a keyed encoding container for the given key and returns it. /// /// - parameter keyType: The key type to use for the container. /// - parameter key: The key to encode the container for. /// - returns: A new keyed encoding container. func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { let container = KeyedContainer<NestedKey>( store: { self.set($0, forKey: key) }, path: codingPath + [key] ) return KeyedEncodingContainer(container) } /// Stores an unkeyed encoding container for the given key and returns it. /// /// - parameter key: The key to encode the container for. /// - returns: A new unkeyed encoding container. func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { UnkeyedContainer( store: { self.set($0, forKey: key) }, path: codingPath + [key] ) } /// Stores an single value encoding container for the given key and returns it. /// /// - parameter key: The key to encode the container for. /// - returns: A new unkeyed encoding container. func nestedSingleValueContainer(forKey key: Key) -> SingleValueContainer { SingleValueContainer( store: { self.set($0, forKey: key) }, path: codingPath + [key] ) } /// Set the encoded value at the given key. /// /// - Parameters: /// - any: The encoded value. /// - key: The key to encode the value for. private func set(_ any: Any?, forKey key: Key) { dictionary[key.stringValue] = any store(dictionary) } /// Stores a new nested container for the default `super` key and returns a /// new encoder instance for encoding `super` into that container. /// /// Equivalent to calling `superEncoder(forKey:)` with /// `Key(stringValue: "super", intValue: 0)`. /// /// - returns: A new encoder to pass to `super.encode(to:)`. func superEncoder() -> Encoder { _AnyEncoder(path: codingPath) } /// Stores a new nested container for the given key and returns a new encoder /// instance for encoding `super` into that container. /// /// - parameter key: The key to encode `super` for. /// - returns: A new encoder to pass to `super.encode(to:)`. func superEncoder(forKey key: Key) -> Encoder { _AnyEncoder(path: codingPath + [key]) } } /// A type that provides a view into an encoder's storage and is used to hold /// the encoded properties of an encodable type sequentially, without keys. class UnkeyedContainer: UnkeyedEncodingContainer { /// The path of coding keys taken to get to this point in encoding. let codingPath: [CodingKey] /// The number of elements encoded into the container. var count: Int { array.count } /// The array of encoded value. var array: [Any?] /// The storage closure to call with encoded value. let store: AnyEncodingStorage /// Creates a unkeyed container for encoding an `Encodable` object to /// an array of `[Any?]`. /// /// - Parameters: /// - store: The storage closure to call with encoded value. /// - array: An existing array of any. /// - path: The path of coding keys taken to get to this point in encoding. init( store: @escaping AnyEncodingStorage, array: [Any?]? = nil, path: [CodingKey] = [] ) { self.store = store self.array = array ?? [] self.codingPath = path } /// Encodes a null value. func encodeNil() throws { try nestedSingleValueContainer().encodeNil() } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode(_ value: Bool) throws { try nestedSingleValueContainer().encode(value) } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode(_ value: String) throws { try nestedSingleValueContainer().encode(value) } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode(_ value: Double) throws { try nestedSingleValueContainer().encode(value) } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode(_ value: Float) throws { try nestedSingleValueContainer().encode(value) } func encode(_ value: Int) throws { try nestedSingleValueContainer().encode(value) } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode(_ value: Int8) throws { try nestedSingleValueContainer().encode(value) } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode(_ value: Int16) throws { try nestedSingleValueContainer().encode(value) } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode(_ value: Int32) throws { try nestedSingleValueContainer().encode(value) } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode(_ value: Int64) throws { try nestedSingleValueContainer().encode(value) } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode(_ value: UInt) throws { try nestedSingleValueContainer().encode(value) } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode(_ value: UInt8) throws { try nestedSingleValueContainer().encode(value) } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode(_ value: UInt16) throws { try nestedSingleValueContainer().encode(value) } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode(_ value: UInt32) throws { try nestedSingleValueContainer().encode(value) } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode(_ value: UInt64) throws { try nestedSingleValueContainer().encode(value) } /// Encodes the given value. /// /// - parameter value: The value to encode. func encode<T>(_ value: T) throws where T: Encodable { try nestedSingleValueContainer().encode(value) } /// Encodes a nested container keyed by the given type and returns it. /// /// - parameter keyType: The key type to use for the container. /// - returns: A new keyed encoding container. func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { let container = KeyedContainer<NestedKey>(store: append, path: codingPath) return KeyedEncodingContainer(container) } /// Encodes an unkeyed encoding container and returns it. /// /// - returns: A new unkeyed encoding container. func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { UnkeyedContainer(store: append, path: codingPath) } /// Encodes an single value encoding container and returns it. /// /// - returns: A new unkeyed encoding container. func nestedSingleValueContainer() -> SingleValueContainer { SingleValueContainer(store: append, path: codingPath) } /// Encodes a nested container and returns an `Encoder` instance for encoding /// `super` into that container. /// /// - returns: A new encoder to pass to `super.encode(to:)`. func superEncoder() -> Encoder { _AnyEncoder(path: codingPath) } private func append(_ any: Any?) { array.append(any) store(array) } } /// A container that can support the storage and direct encoding of a single /// non-keyed value. struct SingleValueContainer: SingleValueEncodingContainer { /// The path of coding keys taken to get to this point in encoding. let codingPath: [CodingKey] /// The storage closure to call with encoded value. let store: AnyEncodingStorage /// Creates a single value container for encoding an `Encodable` object to /// `Any?`. /// /// - Parameters: /// - store: The storage closure to call with encoded value. /// - path: The path of coding keys taken to get to this point in encoding. init( store: @escaping AnyEncodingStorage, path: [CodingKey] = [] ) { self.store = store self.codingPath = path } /// Encodes a null value. func encodeNil() throws { store(nil) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: Bool) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: String) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: Double) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: Float) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: Int) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: Int8) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: Int16) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: Int32) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: Int64) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: UInt) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: UInt8) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: UInt16) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: UInt32) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode(_ value: UInt64) throws { store(value) } /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. func encode<T>(_ value: T) throws where T: Encodable { if value is DictionaryEncodable { store(value) } else { let encoder = _AnyEncoder(path: codingPath) try value.encode(to: encoder) store(encoder.any) } } } } /// A shared encodable object will skip encoding when using the `AnyEncoder`. /// /// Making an `Encodable` as shared allow to bypass encoding when the type is /// known by multiple parties. public protocol DictionaryEncodable { } extension URL: DictionaryEncodable { } extension Date: DictionaryEncodable { } extension UUID: DictionaryEncodable { } extension Data: DictionaryEncodable { }
true
ec0649e6722500819c6ae882599f87a07e7f9370
Swift
niekang/WeiBo
/WeiBo/Login/Presenter.swift
UTF-8
846
3.078125
3
[ "Apache-2.0" ]
permissive
// // Presenter.swift // WeiBo // // Created by 聂康 on 2020/7/29. // Copyright © 2020 com.nk. All rights reserved. // import Foundation protocol ViewType: NSObjectProtocol { func loginStateChange(enable: Bool) } protocol UserLoginProtocol: NSObjectProtocol { func textDidChange(usename: String, password: String) func login(username: String, password: String) } class Presenter: NSObject { weak var view: ViewType? init(_ view: ViewType) { self.view = view } } extension Presenter: UserLoginProtocol { func textDidChange(usename: String, password: String) { let can = usename.count >= 6 && password.count >= 6 print(can) self.view?.loginStateChange(enable: can) } func login(username: String, password: String) { print("登录") } }
true
4c788bef3995fa2212360317ffef25bc9b5360ae
Swift
iAmericanBoy/TDWidgets
/TDWidgets/Oauth/OAuthManager.swift
UTF-8
3,137
2.8125
3
[]
no_license
// // OAuthManager.swift // TDWidgets // // Created by Dominic Lanzillotta on 11/5/20. // import AuthenticationServices import SafariServices import UIKit enum OAuthError: Error { case noToken case sessionError(error: Error) } /** Manages / Abstracts out OAuth. */ public protocol OAuthManagerProtocol { // MARK: - Members /// In an authorized state. Valid token, can call services var isAuthorized: Bool { get } // MARK: - Methods /** Attempt to authenticate. - viewController: ViewController to host embedded Safari - completion: Called result of the authenticate call */ func signIn(context: ASWebAuthenticationPresentationContextProviding, completion: @escaping (Result<Void, Error>) -> Void) /** Sign out. Require successful sign in before services can be called again. */ func signOut(viewController: UIViewController, completion: @escaping (Result<Void, Error>) -> Void) } public final class OAuthManager: NSObject, OAuthManagerProtocol { // MARK: - Members // MARK: - Auth Token private let authTokenKey = AppSecrets.clientID private let clientID = "" private let callbackUrlScheme = "tdWidgets://auth" override public init() {} public var isAuthorized: Bool { return false } public func signIn(context: ASWebAuthenticationPresentationContextProviding, completion: @escaping (Result<Void, Error>) -> Void) { var urlComponents = URLComponents(url: URL(string: "https://auth.tdameritrade.com/auth")!, resolvingAgainstBaseURL: true) urlComponents?.queryItems = [URLQueryItem(name: "response_type", value: "code"), URLQueryItem(name: "redirect_uri", value: callbackUrlScheme), URLQueryItem(name: "client_id", value: authTokenKey + "@AMER.OAUTHAP")] guard let url = urlComponents?.url else { return } let webAuthSession = ASWebAuthenticationSession(url: url, callbackURLScheme: "auth") { [weak self] authSessionURL, error in guard error == nil, let successURL = authSessionURL else { completion(.failure(OAuthError.sessionError(error: error!))) return } let successURLComponents = URLComponents(url: successURL, resolvingAgainstBaseURL: true) let token = successURLComponents?.queryItems?.first(where: { $0.name == "code" }) guard let refreshToken = token?.value else { completion(.failure(OAuthError.noToken)) return } self?.storeToken(refreshToken) completion(.success(())) } webAuthSession.presentationContextProvider = context webAuthSession.prefersEphemeralWebBrowserSession = true webAuthSession.start() } public func signOut(viewController: UIViewController, completion: @escaping (Result<Void, Error>) -> Void) {} private func storeToken(_ token: String) { UserDefaults.standard.set(token, forKey: "OAuthManager.code") } }
true
51c687fef993c132ed4c7926998c3d7c581b572c
Swift
codesworth/QuotesMaker
/QuotesMaker/Models/ImageModel.swift
UTF-8
1,559
3.09375
3
[]
no_license
// // ImageModel.swift // QuotesMaker // // Created by Shadrach Mensah on 08/03/2019. // Copyright © 2019 Shadrach Mensah. All rights reserved. // import UIKit struct ImageLayerModel:LayerModel { enum ContentMode:String,CaseIterable,Codable{ case fill, fit, contain, center } var layerFrame:LayerFrame? mutating func layerFrame(_ frame: LayerFrame) { self.layerFrame = frame } var imageSrc:String? var style:Style = Style() var mode:ContentMode = .fill init() { } init(from decoder: Decoder) throws{ let container = try decoder.container(keyedBy: CodingKeys.self) imageSrc = try container.decodeIfPresent(String.self, forKey: .imageSrc) ?? nil layerFrame = try container.decodeIfPresent(LayerFrame.self, forKey: .layerFrame) ?? nil layerIndex = try container.decodeIfPresent(CGFloat.self, forKey: .layerIndex) ?? 0 style = try container.decodeIfPresent(Style.self, forKey: .style) ?? Style() mode = try container.decodeIfPresent(ContentMode.self, forKey: .mode) ?? .fill updateTime = try container.decodeIfPresent(TimeInterval.self, forKey: .updateTime) ?? Date().timeIntervalSinceReferenceDate } var type: ModelType{ return .image } var updateTime: TimeInterval = Date().timeIntervalSinceReferenceDate mutating func update(){ updateTime = Date().timeIntervalSinceReferenceDate } var layerIndex: CGFloat = 0 } extension ImageLayerModel:Codable{}
true
f9a9e70bd102bb628a91d718c6aa1cbcb2d214d5
Swift
jpsim/Yams
/Sources/Yams/YamlError.swift
UTF-8
7,399
2.65625
3
[ "MIT" ]
permissive
// // YamlError.swift // Yams // // Created by JP Simard on 2016-11-19. // Copyright (c) 2016 Yams. All rights reserved. // #if SWIFT_PACKAGE @_implementationOnly import CYaml #endif import Foundation /// Errors thrown by Yams APIs. public enum YamlError: Error { // Used in `yaml_emitter_t` and `yaml_parser_t` /// `YAML_NO_ERROR`. No error is produced. case no /// `YAML_MEMORY_ERROR`. Cannot allocate or reallocate a block of memory. case memory // Used in `yaml_parser_t` /// `YAML_READER_ERROR`. Cannot read or decode the input stream. /// /// - parameter problem: Error description. /// - parameter offset: The offset from `yaml.startIndex` at which the problem occured. /// - parameter value: The problematic value (-1 is none). /// - parameter yaml: YAML String which the problem occured while reading. case reader(problem: String, offset: Int?, value: Int32, yaml: String) // line and column start from 1, column is counted by unicodeScalars /// `YAML_SCANNER_ERROR`. Cannot scan the input stream. /// /// - parameter context: Error context. /// - parameter problem: Error description. /// - parameter mark: Problem position. /// - parameter yaml: YAML String which the problem occured while scanning. case scanner(context: Context?, problem: String, Mark, yaml: String) /// `YAML_PARSER_ERROR`. Cannot parse the input stream. /// /// - parameter context: Error context. /// - parameter problem: Error description. /// - parameter mark: Problem position. /// - parameter yaml: YAML String which the problem occured while parsing. case parser(context: Context?, problem: String, Mark, yaml: String) /// `YAML_COMPOSER_ERROR`. Cannot compose a YAML document. /// /// - parameter context: Error context. /// - parameter problem: Error description. /// - parameter mark: Problem position. /// - parameter yaml: YAML String which the problem occured while composing. case composer(context: Context?, problem: String, Mark, yaml: String) // Used in `yaml_emitter_t` /// `YAML_WRITER_ERROR`. Cannot write to the output stream. /// /// - parameter problem: Error description. case writer(problem: String) /// `YAML_EMITTER_ERROR`. Cannot emit a YAML stream. /// /// - parameter problem: Error description. case emitter(problem: String) /// Used in `NodeRepresentable`. /// /// - parameter problem: Error description. case representer(problem: String) /// String data could not be decoded with the specified encoding. /// /// - parameter encoding: The string encoding used to decode the string data. case dataCouldNotBeDecoded(encoding: String.Encoding) /// The error context. public struct Context: CustomStringConvertible { /// Context text. public let text: String /// Context position. public let mark: Mark /// A textual representation of this instance. public var description: String { return text + " in line \(mark.line), column \(mark.column)\n" } } } extension YamlError { init(from parser: yaml_parser_t, with yaml: String) { func context(from parser: yaml_parser_t) -> Context? { guard let context = parser.context else { return nil } return Context( text: String(cString: context), mark: Mark(line: parser.context_mark.line + 1, column: parser.context_mark.column + 1) ) } func problemMark(from parser: yaml_parser_t) -> Mark { return Mark(line: parser.problem_mark.line + 1, column: parser.problem_mark.column + 1) } switch parser.error { case YAML_MEMORY_ERROR: self = .memory case YAML_READER_ERROR: let index: String.Index? if parser.encoding == YAML_UTF8_ENCODING { index = yaml.utf8 .index(yaml.utf8.startIndex, offsetBy: parser.problem_offset, limitedBy: yaml.utf8.endIndex)? .samePosition(in: yaml) } else { index = yaml.utf16 .index(yaml.utf16.startIndex, offsetBy: parser.problem_offset / 2, limitedBy: yaml.utf16.endIndex)? .samePosition(in: yaml) } let offset = index.map { yaml.distance(from: yaml.startIndex, to: $0) } self = .reader(problem: String(cString: parser.problem), offset: offset, value: parser.problem_value, yaml: yaml) case YAML_SCANNER_ERROR: self = .scanner(context: context(from: parser), problem: String(cString: parser.problem), problemMark(from: parser), yaml: yaml) case YAML_PARSER_ERROR: self = .parser(context: context(from: parser), problem: String(cString: parser.problem), problemMark(from: parser), yaml: yaml) case YAML_COMPOSER_ERROR: self = .composer(context: context(from: parser), problem: String(cString: parser.problem), problemMark(from: parser), yaml: yaml) default: fatalError("Parser has unknown error: \(parser.error)!") } } init(from emitter: yaml_emitter_t) { switch emitter.error { case YAML_MEMORY_ERROR: self = .memory case YAML_EMITTER_ERROR: self = .emitter(problem: String(cString: emitter.problem)) default: fatalError("Emitter has unknown error: \(emitter.error)!") } } } extension YamlError: CustomStringConvertible { /// A textual representation of this instance. public var description: String { switch self { case .no: return "No error is produced" case .memory: return "Memory error" case let .reader(problem, offset, value, yaml): guard let (line, column, contents) = offset.flatMap(yaml.lineNumberColumnAndContents(at:)) else { return "\(problem) at offset: \(String(describing: offset)), value: \(value)" } let mark = Mark(line: line + 1, column: column + 1) return "\(mark): error: reader: \(problem):\n" + contents.endingWithNewLine + String(repeating: " ", count: column) + "^" case let .scanner(context, problem, mark, yaml): return "\(mark): error: scanner: \(context?.description ?? "")\(problem):\n" + mark.snippet(from: yaml) case let .parser(context, problem, mark, yaml): return "\(mark): error: parser: \(context?.description ?? "")\(problem):\n" + mark.snippet(from: yaml) case let .composer(context, problem, mark, yaml): return "\(mark): error: composer: \(context?.description ?? "")\(problem):\n" + mark.snippet(from: yaml) case let .writer(problem), let .emitter(problem), let .representer(problem): return problem case .dataCouldNotBeDecoded(encoding: let encoding): return "String could not be decoded from data using '\(encoding)' encoding" } } }
true
571f536d6802a902789a61ac24650bdfb9132638
Swift
jazzhong1/swift_dev
/grammar/ClosureExpressions.playground/Contents.swift
UTF-8
15,429
4.53125
5
[]
no_license
import Foundation /* Closures 코드블럭으로 C, Objcetive-C의 블럭(Blocks)과, 람다 언어랑 비슷. 비동기?? 코드..비슷.. 어떤 let, var의 참조를 캡처(Capture)해 저장 할 수있다.. Swift는 이 캡쳐와 관련한 모든 메모리를 알아서 관리.. 전역 함수(global functions) : 이름이 있고 어떤 값도 캡쳐하지 않는 클로저 중첩 함수(nested function) : 이름이 있고, 관련한 함수로 부터 값을 캡쳐 할 수 있는 클로져 클로저 표현 : 경량화 된 문법으로 쓰여지고 관련된 문맥(context)로 부터 값을 캡쳐 할 수 있는 이름이 없는 클로저 swift 최적화의 내용. 1. 문맥(context)에서 인자 타입(parameter type)과 반환타입(retun type)의 추론. 2. 단일 표현 클로저에서 암시적 반환. 3. 축약된 인자 이름. 4. 후위 클로저 문법. */ /* 클로저 표현 (Closure Expressions) 인라인 클로저를 명확하게 표현하는 방법으로 문법에 초점이 맞춰저 있음. 클로저의 표현은 코드의 명확성, 의도를 읺지 않으면서 문법을 축약해 사용할 수 있는 다양한 문법의 최적화 제공. */ /* 정렬 메소드(The Sorted Method) Swift 표준 라이브러리에 sorted(by:)라는 타입의 배열값을 정렬하는 메소드를 제공. by 에 어떤 방법으로 정렬을 수행할건지에 대해 기술한 클로저를 넣으면 그 방법대로 정렬된 배열을 얻을 수 있다. sorted(by : )메소드는 원본 배열은 변경하지 않는다 ex.... names배열을 sorted(by : )메소드와 클로저를 이용하여 정렬.. */ var names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] //sorted(by : ) 메소드는 배열의 콘텐츠와 같은 타입을 갖고 두개의 인자를 같은 클로저 인자로 사용해얗안다. //name의 콘텐츠는 String 타입이므로 (String, String )->Bool타입의 클로저를 사용해야함 //클로저를 제공하는 일반적인 방법은 함수를 하나 만드는것. var count : Int = 0; func backward(_ s1 : String, _ s2 : String ) -> Bool{ count += 1 print("check count \(count)") print("check s1 \(s1)") print("check s2 \(s2)") return s1 > s2 } print("before sorted \(names)") var reversedNames = names.sorted(by: backward) print("after sorted \(reversedNames)") /* 클로저 표현 문법(Clsure Expression Syntax) 클로저 표현 문법은 일발적으로 .. { (parameters) -> retun type in statements } 인자로 넣을 parameters, 인자 값으로 처리할 내용을 기술하는 statements 그리고 return type. 앞의 backwrard 클로저를 이용해 배열을 정렬하는 코드는 클로저 표현을 이용해 바꿀수 있음 */ let reversedNames2 = names.sorted { (_ s1 :String, _ s2 : String) -> Bool in return s1 < s2 } print("inline closure \(reversedNames2)") /* 인자로 들어가있는 형태의 클로저를 인라인 클로저라고 부른다. body는 in 키워드 다음에 시작한다. 사용할 인자 값과(parameters), 반환타입(return type)을 알앙ㅆ으니 그것들을 적절히 처리해 넘겨 줄 수 있다는 뜻. //한줄로도 사용가능. ex) 가독성 떨어짐... let reversedNames2 = names.sorted { (_ s1 :String, _ s2 : String) ->Bool in return s1 < s2} */ /* 문맥에서 타입추론 (Inferring Type From Context) String 배열에서 sorted(by : ) 메소드의 인자로 사용된다. sorted(by:)의 메소드에서 이미 (String, String) -> Bool 타입의 인자가 들어와야 하는지 알기 때문에 클로저에서 이 타입이 생략 될 수 있다. ex) 가독성 떨어짐... let reversedNames = names.sorted(by : { s1, s2 in return s1 > s2}) */ /* 단일 표현 클로저에서의 암시적 반환(Implicit Returns From Single-Express closures) 단일 표현 클로저에서 반환 키워드 생략 가능. let reversedName3 = names.sorted(by: {s1,s2 in s1 > s2}) 두 값을 인자로 받아 결과 반환 */ /* 인자 이름 축약(Shorthand Argumentes Names) Swift 인라인 클로저에서 자동으로 축약 인자이름을 제공. 이 인자를 사용하면 값을 순서대로 $0, $1, $2 등으로 사용할 수 있다. 축약 인자 이름을 사용하면 인자값과 그 인자를 처리할 떄 사용하는 인자가 같다는걸 안다. 인자를 입력받는 부분과, in키워드를 생락 할 수 있으며 축약 가능함... 가독성 떨어짐. let reversedName4 = names.sorted(by: {$0 > $1}) 축약은 되었지만 논리를 표현하는데 지장이 없음. 인라인 클로저에 생략된 내용을 포함해 설명하면 $0, $1 인자 두개를 받아서 $0이 $1 보다 큰지 비교하고 Bool을 반환해라 ... */ /* 연산자 메소드 (Operator Methods) Swift의 String타입 연산자에는 String끼리 비교할 수 있는 비교연산자 (>)를 구현함. 그냥 이 연산자를 사용하면 끝..? let reversedNames5 = names.sorted(by: >) .... */ /* 후위 클로저 (Trailing Closures) 함수의 마지막 인자로 클로저를 넣고, 클로저가 길다면 후위 클로저를 사용 할 수있다. 이런 형태의 함수 클로저가 있으면 .. */ func someFunctionThatTakesAClosure(closure : () -> Void){ // function body goes here } //위 클로저의 인자 값 입력 부분과 반환 형 부분을 생략해 다음과 표현 가능. someFunctionThatTakesAClosure(closure: { }) //후위 클로저로 표현하면 함수를 대괄호 ({,})로 묶어 그 안에 처리할 내용을 적으면 가능 //모르고 사용할 경우 전역함수 형태가 사실 클로저로 사용하고 있었음. someFunctionThatTakesAClosure { //....전역함수? } //정렬 예제를 후위 클로저를 이용해 표현하면 var reversedName6 = names.sorted(){ $0 > $1} //만약 함수의 마지막 인자가 클로저이고, 후위 클로저를 사용하면 괄호() 생략 가능 reversedName6 = names.sorted{ $0 > $1} //후위 클로저를 이용해 Int, String으로 매핑 하는 예제. let digitNames = [ 0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine" ] let numbers = [16, 58, 510] let strings = numbers.map{ (number) -> String in var number = number var output = "" repeat{ output = digitNames[number % 10 ]! + output //dictionary 의 subScript는 옵셔널 이기 떄문에 key값이 있을수도 , 없을 수도 있음.... number /= 10 }while number > 0 return output } print("check strings \(strings)") /* 값 캡쳐 (Capturing Values) 클로저는 특정 문맥의 상수, 변수의 값을캡쳐 할 수 있따. 원본 값이 사라져도 클로져의 body안에 그 값을 활용 할 수있다. Swift에서 값을 캡처하는 가장 단순한 형태는 중첩 함수(nested function) 중첩함수는 함수의 body에서 다른 함수를 다시 호출한 형태로 된 함수. */ func makeIncremeter(forIncrement amount : Int) -> () -> Int { var runningTotal = 0 print("check amout \(amount)") func incremeter () -> Int{ print("check runningTotal \(runningTotal)") runningTotal += amount print("check runningTotal + amount \(runningTotal)") return runningTotal } /* runningTotal 과 amount도 없음. 하지만 돌아감 runnningTotal, amout가 캡처링 되서 돌아가는 형태임 최적화 이유로 Swift는 만약 더이상 클로저에 의해 값이 사용되지 않는 경우 그 값을 복사해 저장하거나, 캡처링 하지 않음, Swift는 또 특정 변수가 더이상 필요하지 않을 경우 ARC에 의해 제거하겠지.... */ return incremeter } /* makeIncremeter 함수 안에서 incremeter함수를 호출하는 형태로 중첩 함수이다. 클로저의 인자와 반환값이 보통의 경우 달라 ....보이나 쪼개어 본다... 인자와 반환값 (forIncrement amout : Int) -> () -> 중 처음 ->를 기준으로 앞의 (forIncrement amout : Int) = 인자. 뒤 () -> Int 반환 값. 즉 반환값이 클로저인 형태. () -> Int 파라메터가 없고, Int를 반환하는 function pointer.. */ //중첩 함수 실행, makeIncremeter 함수를 실행하는 메소드를 반환함. let incrementByTen = makeIncremeter(forIncrement: 10) var myTenValue : Int! = incrementByTen() //10 반환 myTenValue += incrementByTen() //20 반환 myTenValue += incrementByTen() //30 반환 //함수가 각기 실행되지만 실제로는 변수 runningTotal, amount가 캡처링 되서 그 변수를 //공유하기 떄문에 계산이 누적된 결과를 갖는다. print("check my TenValue \(String(describing: myTenValue))") //새로운 클로저를 생성해도 마찬가지. let incrementBySeven = makeIncremeter(forIncrement: 7) incrementBySeven() //7 리턴. /* 클로저를 어떤 클래스 인스턴스의 프로퍼티를 할당하고, 그 클로저가 인스턴스를 캡처링하면 강한 순환참조에 빠지게 된다, 즉 인스턴스의 사용이 끝나도 메모리 해제를 하지 못하는 상황임 그래서 swift는 이 문제를 다루기 위해 캡처 리스트(capture list)를 사용한다 */ /* 클로저는 참조타입(Closure Are Referenc Types) incrementBySeven 과 invrementByTen은 상수이다. runningTotal변수를 계속 증가 시킬까 ReferenceType이기 때문에 가능하다. 함수와 클로저를 상수나 변수에 할당할떄 실제로는 상수와 변수에 해당함수나 클로즈이 참조가 할당됨 그래서 만약 한 클로저를 두 상수나 변수에 할당하면 두 상수나 변수는 같은 클로저를 참조하고 있다. C, C++에서 함수포인터를 저장한다고 볼 수 있다. */ /* 이스케이핑 클로저(Escaping Clousre) 클로저를 함수의 파라메터로 넣을수 있는데, 함수 밖(함수가 끝나고 실행되는 클로저) ex)비동기, completionHanlder로 사용되는 클로저는 파라미터 타입앞에 @escaping 이라는 키워드를 명시해야한다. */ var completionHandlers : [() -> Void] = [] //함수포인터 배열. func someFunctionWithEscapingClosure(completionHandler : @escaping() -> Void){ completionHandlers.append(completionHandler) } /* 위 함수에서 인자로 전달된 completionhandler는 someFunctionWithEscapingClosure 함수가 끝나고 나중에 처리된다. 만약 함수가 끝나고 실행되는 클로저는 @escaping 키워드를 붙이지 않으면 컴파일시 오류가 발생 @escaping을 사용하는 클로저는 self를 명시적으로 언급해야한다. */ //ex) func someFunctionWithNonescapingClosure(closure : () -> Void){ closure() } class someClass{ var x = 10 func doSomething(){ someFunctionWithEscapingClosure { print("someFunctionWithEscapingClosuer") self.x = 100 } someFunctionWithNonescapingClosure { print("someFunctionWithNonescapingClosure") x = 200 } } } let instance = someClass() instance.doSomething() instance.doSomething() //someFunctionWithNonescapingClouser 배열안으로 들어간다. print("check completionHandler count \(completionHandlers.count)") print("check insstance \(instance.x)") /*print(instance.x) completionHandlers.first?() print(instance.x) */ /* 자동클로저 (AutoClouser) 자동클로저는 인자값이 없으며 특정표현을 감싸서 다른 함수에 전달 인자로 사용하는 클로저. 자동클로저는 클로저를 실행하기 전까지 실제 실행되지 않는다. 계산이 복잡한연산을 하는데 유용하다. 실제 계산이 필요할때 호출되기 떄문. //지연호출...어떨때 사용가능할ㄲ? */ //ex) var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] print("check customerInLine count \(customersInLine.count)") let customerProvider = { customersInLine.remove(at: 0)} //AutoClouser... print("check customerInLine count \(customersInLine.count)") print("Now serving \(customerProvider())!") //첫번쨰 인덱스 제거 후 출력. print("check customerInLine count \(customersInLine.count)") //size = 4 /* let customerProvider = { customerInLine.remove(at : 0)} 이 클로저 코드를 지났어도 cusotmerInLine.count는 변함없이 5 인것을 확인. 클로저를 실행시킨 print("Now serving \(customerProvider())!") 이후에야 배열 값이 하나 제거되어 배열의 원소개수가 4로 줄어든것 확인. 이렇듯 자동클로저는 적혀진 라인 순서대로 바로 실행되지 않고 실제 사용될때 지연호출..... */ //자동 클로저를 함수의 인자값으로 넣는 예제. func serve(customer customerProvider: () -> String){ print("now serving \(customerProvider())!") } serve(customer: {customersInLine.remove(at: 0)}) func serve(customer customerProvider: @autoclosure () -> String){ print("Now serving \(customerProvider())!") } serve(customer: customersInLine.remove(at: 0)) /* serve 함수는 인자로 () -> String 형, 즉 인자가 없고, String 을 반환하는 클로저를 받는 함수. 이 함수를 실행할떄는 serve(customer: { customerInLine.remove(at : 0)}) 이와같이 클로저를 명시적으로 직접 넣을 수 있다. autoclouser 키워드를 이용하여 보다 간결할게 사용 가능하다. 자동으로 클로저로 변환되나. 함수의 인자 값을 넣을 떄 클로저가 아니라 클로저가 반환하는 값과 일치하는 형의 함수를 인자로 넣을수 있따. server(customer : { customersInLine.remove(at : 0)}) 이런 코드를 @autoclosuer 키워드를 사용했기 떄문에 server(custom: customerInLine.remove(at : 0))이 {} 없이 사용 가능하다. 즉 @autoclouse 를 선언하면 함수가 이미 클로저 인것을 알기 떄문에 리턴값 타입과 같은 값을 넣어 줄 수 있다. NOTE 자동 클로저를 남발하면 코드 가독성이 떨어짐, 문맥과 함수 이름이 autoClosure를 사용하기에 분명 해야함. */ //자동클로저는 @autoclosure는 이스케이프 @escaping와 같이 사용 할 수 있다. //ex) @autoclosuer, @escaping 혼용 print("check customerInLine \(customersInLine)") //["Barry", "Daniella"] var customerProviders : [() -> String] = [] //클로저 저장하는 배열. func collectCustomerProviders(_ customerProvider : @autoclosure @escaping () -> String){ customerProviders.append(customerProvider) } collectCustomerProviders(customersInLine.remove(at: 0)) collectCustomerProviders(customersInLine.remove(at: 0)) print("Collected \(customerProviders.count) closures.") //excpect 2 for customerProvider in customerProviders { print("Now serving \(customerProvider())") } print("check customersInLine coutn \(customersInLine.count)") /* collectCustomerProviders 함수의 인자 customerProvider 는 @autoclouser이면서, @escaping으로 선언 되어 있다. @autoclosuer로 선언됐기 때문에 함수 인자로 리턴 값 String만 만족하는 customersInLine.remove(at : 0)형태로 함수 인자에 넣을 수 있고, 이 클로저는 collectCustomerProviders 함수가 종료된 후에 실행되는 클로저 이기 때문에 앞에 @escaping 키워드를 붙여줌.... */
true
54aabc67b0f276542f8732e8460448258a0cef7c
Swift
LikhovidVladislav/Films
/FIlmsTest/Library/Extentions/ShowAlert + UIViewController.swift
UTF-8
516
2.515625
3
[]
no_license
// // ShowAlert + UIViewController.swift // FIlmsTest // // Created by Влад Лиховид on 17.06.2020. // Copyright © 2020 Влад Лиховид. All rights reserved. // import UIKit extension UIViewController { func showAlert(alertText: String, alertMessage: String) { let alert = UIAlertController(title: alertText, message: alertMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } }
true
099b064211c8ce5a10d4407f9937a6d469277538
Swift
newboadki/RSDataStructures
/RSDataStructures/Sources/RSDataStructures/PriorityQueues/BoundedHeightPriorityQueue.swift
UTF-8
4,065
3.265625
3
[]
no_license
// // BoundedHeightPriorityQueue.swift // Algorithmia // // Created by Borja Arias Drake on 07/11/2016. // Copyright © 2016 Borja Arias Drake. All rights reserved. // import Foundation public struct BoundedHeightPriorityQueue<Element: KeyValuePair> : PriorityQueue { /// Item is defined in the PriorityQueue protocol. public typealias Item = Element /// Valid Indexes go from private (set) var maximumKey : Int = 10000 private var topIndex : Int? private var array : Array<Array<Element>?> private var topPriorityQueue : BasicBinarySearchTree<IntegerPair>? // MARK : PriorityQueue Protocol public var type : PriorityQueueType public init(type: PriorityQueueType) { self.init(type : type, maximumKey: 1000) } public mutating func enqueue(item: Item) throws { let key = item.key as! Int guard (key >= 0 && key<=self.maximumKey) else { throw PriorityQueueError.invalidOperationForType } if var arrayForKey = self.array[Int(key)] { // append it to the existing array arrayForKey.append(item) self.array[Int(key)] = arrayForKey } else { // need to create an array of items for that key self.array[key] = [item] self.addElementToTopQueue(element: key) } // Update the top index if necessary if let top = self.topIndex { if key < top { self.topIndex = key } } else { self.topIndex = key } } public func getFirst() -> Item? { if let top = self.topIndex { return self.array[Int(top)]?.first } else { return nil } } public mutating func dequeue() -> Item? { var result : Item guard self.topIndex != nil else { // There are no element in the queue return nil } if var arrayForTop = self.array[self.topIndex!] { // append it to the existing array result = arrayForTop.removeFirst() let key = result.key as! Int self.array[key] = arrayForTop if arrayForTop.isEmpty { // release the array self.array[key] = nil // we need to find a new top _ = self.removeElementToTopQueue(element: key) if let min = self.minimumElementFromTopQueue() { self.topIndex = min } else { self.topIndex = nil } } return result } else { // Should not happen, throw exception return nil } } // MARK : Public API public init(type: PriorityQueueType, maximumKey: Int) { self.type = type self.maximumKey = maximumKey self.array = Array<Array<Element>?>(repeating: nil, count: Int(maximumKey + 1)) } // MARK: Top priority queue private mutating func addElementToTopQueue(element : Int) { let treeNode = BasicBinarySearchTree<IntegerPair>(parent: nil, leftChild: nil, rightChild: nil, value: IntegerPair(key: element, value: 0)) if let topQueue = self.topPriorityQueue { topQueue.insert(newElement: treeNode) } else { self.topPriorityQueue = treeNode } } private func removeElementToTopQueue(element : Int) { _ = self.topPriorityQueue?.delete(elementWithKey: element) } private func minimumElementFromTopQueue() -> Int? { if let result = self.topPriorityQueue?.minimum() { return result.item?.key } return nil } }
true
a6e3095dee7f5e98292afae80cfb154573571419
Swift
WalletConnect/WalletConnectSwift
/Sources/Internal/UpdateSessionHandler.swift
UTF-8
1,157
2.640625
3
[ "MIT" ]
permissive
// // Copyright © 2019 Gnosis Ltd. All rights reserved. // import Foundation protocol UpdateSessionHandlerDelegate: AnyObject { func handler(_ handler: UpdateSessionHandler, didUpdateSessionByURL: WCURL, sessionInfo: SessionInfo) } class UpdateSessionHandler: RequestHandler { private weak var delegate: UpdateSessionHandlerDelegate? init(delegate: UpdateSessionHandlerDelegate) { self.delegate = delegate } func canHandle(request: Request) -> Bool { return request.method == "wc_sessionUpdate" } func handle(request: Request) { do { let sessionInfo = try request.parameter(of: SessionInfo.self, at: 0) delegate?.handler(self, didUpdateSessionByURL: request.url, sessionInfo: sessionInfo) } catch { LogService.shared.error("WC: wrong format of wc_sessionUpdate request: \(error)") // TODO: send error response } } } /// https://docs.walletconnect.org/tech-spec#session-update struct SessionInfo: Decodable { var approved: Bool var accounts: [String]? var chainId: Int? } enum ChainID { static let mainnet = 1 }
true
0486fa833737d177280dfccb0003a070e8f132d0
Swift
rgex/UBIC-Wallet-for-iOS
/UBIC Wallet/Utils/ChallengeParser.swift
UTF-8
1,238
3
3
[]
no_license
// // ChallengeParser.swift // UBIC Wallet // // Created by Jan Moritz on 29.12.19. // Copyright © 2019 Bondi. All rights reserved. // import Foundation class ChallengeParser { private var challenge: String = "" // example: 3-utopia.org/kyc/challenge=123456789 init(newChallenge: String) { self.challenge = newChallenge } func validateChallenge() -> Bool { if self.challenge.count < 5 { // too short return false } let firstChar = Tools.substr(string: challenge, from: 0, size: 1) let secondChar = Tools.substr(string: challenge, from: 1, size: 1) if firstChar != "0" || firstChar != "1" || firstChar != "2" || firstChar != "3" { return false } if secondChar != "-" { return false } return true } func getAuthenticationMode() -> Int { if self.validateChallenge() { return Int(Tools.substr(string: challenge, from: 0, size: 1)) ?? 0 } return 0 } func getUrl() -> String { return "http://" + Tools.substr(string: challenge, from: 2, size: self.challenge.count) } func getDomain() -> String { return "" } }
true
06e2f567368bcc94e0bc038f309103925d97d436
Swift
marzelwidmer/SwiftWeatherApp
/WeatherApp/view/WeatherView.swift
UTF-8
836
3.015625
3
[]
no_license
// // WeatherView.swift // WeatherApp // // Created by morpheus on 16.10.21. // import SwiftUI struct WeatherView: View { @StateObject var viewModel = WeatherViewModle() var body: some View { NavigationView { VStack { Text((viewModel.timezone)) .font(.system(size: 32)) Text(viewModel.temp) .font(.system(size: 44)) Text(viewModel.title) .font(.system(size: 24)) Text(viewModel.descriptionText) .font(.system(size: 24)) }.navigationTitle("Weather MVVM") } } } struct WeatherView_Previews: PreviewProvider { static var previews: some View { WeatherView() .preferredColorScheme(.dark) } }
true
d9c08bfbf65ab2fcfd92c46deedf7348e40bc920
Swift
eBardX/XestiNetwork
/Sources/XestiNetwork/ParameterName.swift
UTF-8
526
2.96875
3
[ "MIT" ]
permissive
// © 2018–2022 J. G. Pusey (see LICENSE.md) public struct ParameterName: Equatable, Hashable, RawRepresentable { // MARK: Public Initializers public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } // MARK: Public Instance Properties public var rawValue: String } // MARK: - CustomStringConvertible extension ParameterName: CustomStringConvertible { public var description: String { rawValue } }
true
36c925ebe97773761636ba625ae3886df8696f1e
Swift
Noonight/AboutMe
/AboutMe/Views/ChangeUserInfoModalView.swift
UTF-8
1,632
2.84375
3
[]
no_license
// // ChangeUserInfoModelView.swift // AboutMe // // Created by Aiur on 03.09.2020. // Copyright © 2020 Aiur. All rights reserved. // import SwiftUI struct ChangeUserInfoModalView: View { @Binding var isPresented: Bool @ObservedObject var userField: UserObj.UserObjField var body: some View { VStack(alignment: .leading) { Divider() Text(userField.title) TextField("Title", text: Binding(get: { return self.userField.value }, set: { (newValue) in self.userField.value = newValue })) .textFieldStyle(RoundedBorderTextFieldStyle()) Spacer() HStack { Spacer() Button(action: { self.isPresented = false }) { Text("OK") } .frame(width: 90, height: 40) .background(LinearGradient(gradient: Gradient(colors: [.red, .black]), startPoint: .leading, endPoint: .trailing)) .accentColor(Color.white) .cornerRadius(10) Spacer() } // Spacer() } .edgesIgnoringSafeArea(.top) .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity) .padding() // .background(Color.green) } } struct ChangeUserInfoModalView_Previews: PreviewProvider { static var previews: some View { ChangeUserInfoModalView(isPresented: Binding<Bool>.constant(true), userField: UserObj().fields.first!) } }
true
a53325dd9ba520b5092728fc4d04ddc73165f8ff
Swift
ghojeong/baseball
/ios/baseball/baseball/Domain/Entity/Innings.swift
UTF-8
196
2.53125
3
[]
no_license
// // Innings.swift // baseball // // Created by 이다훈 on 2021/05/07. // import Foundation struct Innings: Codable { private (set) var home: [Int] private (set) var away: [Int] }
true
20fea35ba4d57a70e39f224f61ddb76185c7453c
Swift
nunojfg/Checkmate
/Checkmate/Core Data/Delete.swift
UTF-8
1,653
2.859375
3
[]
no_license
// // Delete.swift // Checkmate // // Created by Paul Scott on 12/7/20. // import Foundation import CoreData struct Delete { static let viewContext = PersistenceController.shared.container.viewContext static func gameSave(_ gameSave: GameSave) { for piece in Array(gameSave.pieces) { viewContext.delete(piece) } viewContext.delete(gameSave) } static func allGameSaves() { let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "GameSave") do { let results = try viewContext.fetch(fetchRequest) for gameSave in results { Delete.gameSave(gameSave as! GameSave) } } catch let error as NSError { print(error) } } static func piece(_ piece: Piece) { viewContext.delete(piece) } static func allPiecesFor(gameSave: GameSave) { for piece in gameSave.pieces { Delete.piece(piece) } } static func player(_ player: Player) { for gameSave in Array(player.isPlayer1ForGame) + Array(player.isPlayer2ForGame) { viewContext.delete(gameSave) } viewContext.delete(player) } static func allPlayers() { let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Player") do { let results = try viewContext.fetch(fetchRequest) for player in results { Delete.player(player as! Player) } } catch let error as NSError { print(error) } } }
true
3fad9b133e4363316105f438f7347fbaf61e15cb
Swift
huri000/QuickLayout
/Example/QuickLayout/Utils/FocusableButton.swift
UTF-8
705
2.59375
3
[ "MIT" ]
permissive
// // FocusableButton.swift // QuickLayout // // Created by Daniel Huri on 5/12/18. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit class FocusableButton: UIButton { override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { coordinator.addCoordinatedAnimations({ self.setFocusState() }, completion: nil) } private func setFocusState() { isFocused ? setupFocus() : setupUnfocused() } private func setupFocus() { backgroundColor = QLColor.BlueGray.c100 } private func setupUnfocused() { backgroundColor = QLColor.BlueGray.c400 } }
true
e46fcff7b11394b31bb85c08f853077454658cec
Swift
nancijf/BeverageListTimer
/Coffee Timer/AppDelegate.swift
UTF-8
2,351
2.609375
3
[]
no_license
// // AppDelegate.swift // Coffee Timer // // Created by Nanci Frank on 8/6/15. // Copyright (c) 2015 Wildcat Productions. All rights reserved. // import UIKit import CoreData func appDelegate() -> AppDelegate { return UIApplication.sharedApplication().delegate as! AppDelegate } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var coreDataStack: CoreDataStack = { return CoreDataStack( modelName: "CoffeeTimer", storeName: "CoffeeTimer", options: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]) }() func saveCoreData() { let error = NSErrorPointer() do { try coreDataStack.managedObjectContext.save() } catch let error1 as NSError { error.memory = error1 print("Error saving context: \(error)") } } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { coreDataStack.loadDefaultDataIfFirstLaunch() window?.tintColor = UIColor(red:0.95, green:0.53, blue:0.27, alpha:1) return true } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { let alertController = UIAlertController(title: notification.alertTitle, message: notification.alertBody, preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(okAction) window!.rootViewController!.presentViewController(alertController, animated: true, completion: nil) } func applicationWillResignActive(application: UIApplication) { self.saveCoreData() } func applicationDidEnterBackground(application: UIApplication) { print("Application has entered background.") } func applicationWillEnterForeground(application: UIApplication) { print("Application has entered foreground.") } func applicationDidBecomeActive(application: UIApplication) { print("Application has become active.") } func applicationWillTerminate(application: UIApplication) { print("Application will terminate.") } }
true
38f543cd3f3bf9f5188edf921df8989b25fe6d0f
Swift
SunsetWan/social-distancing-ios
/ExposureNotification/Utilities/Notified.swift
UTF-8
912
2.609375
3
[]
no_license
// // Notified.swift // ExposureNotification // // Created by Shiva Huang on 2021/3/17. // Copyright © 2021 AI Labs. All rights reserved. // import Foundation @propertyWrapper class Notified<Value: Equatable> { let notificationName: Notification.Name var wrappedValue: Value { didSet { if oldValue != wrappedValue { NotificationCenter.default.post(name: notificationName, object: nil) } } } var projectedValue: Notified<Value> { self } init(wrappedValue: Value, notificationName: Notification.Name) { self.wrappedValue = wrappedValue self.notificationName = notificationName } func callAsFunction(using block: @escaping () -> Void) -> NSObjectProtocol { NotificationCenter.default.addObserver(forName: notificationName, object: nil, queue: nil) { _ in block() } } }
true
87ba1e9a4ad1b83168ea5207a3e433d8622916c8
Swift
hyosang813/TotoRan_Architecture
/Infra/Mapper/TotoRateMapper.swift
UTF-8
3,373
2.78125
3
[]
no_license
// // TotoRateMapper.swift // TotoRan // Toto支持率情報のパース処理 // // Created by kosou.tei on 2021/05/13. // import Kanna import Domain class TotoRateMapper { static func parseTotoRate(html: String, heldNumber: Int) -> ([Frame], [Rate])? { // TODO: try?に失敗した場合のエラー処理を区別したいね if let doc = try? HTML(html: html, encoding: .utf8) { var teamNames: [String] = [] for link in doc.css("td") { if link["rowspan"] == "2" { guard let trimData = link.content?.trimmingCharacters(in: .whitespacesAndNewlines) else { return nil } if let teamName = filterTeamName(data: trimData) { teamNames.append(teamName) } } } var arrangeRates: [Double] = [] for link in doc.css("td") { if link["class"] == "pernum" { guard let trimData = link.content?.trimmingCharacters(in: .whitespacesAndNewlines) else { return nil } if let arrangeRate = arrangeRateData(target: trimData) { arrangeRates.append(arrangeRate) } } } // 正常にデータ取得できてるかどうか if teamNames.count != 26 || arrangeRates.count != 39 { return nil } var frames: [Frame] = [] var rates: [Rate] = [] for i in 1...13 { let tmpTeamNames = teamNames[0...1] let tmpArrangeRates = arrangeRates[0...2] frames.append(Frame(id: i, heldNumber: heldNumber, homeTeamName: tmpTeamNames[0], awayTeamName: tmpTeamNames[1])) rates.append(Rate(id: i, heldNumber: heldNumber, homeWinRate: tmpArrangeRates[0], awayWinRate: tmpArrangeRates[2], drawRate: tmpArrangeRates[1])) teamNames.removeFirst(2) arrangeRates.removeFirst(3) } return (frames, rates) } return nil } private static func filterTeamName(data: String) -> String? { if data == "データ" || Int(String(data.first ?? "0")) != nil { return nil } else { return data } } private static func arrangeRateData(target: String) -> Double? { let pattern = "(?<=\\().+?(?=\\))" let regex = try! NSRegularExpression(pattern: pattern, options: []) let result = regex.firstMatch(in: target, options: [], range: NSRange(0..<target.count))! for i in 0..<result.numberOfRanges { let start = target.index(target.startIndex, offsetBy: result.range(at: i).location) let end = target.index(start, offsetBy: result.range(at: i).length - 1) return Double(target[start..<end]) } return nil } }
true
80f9aa7e65b7d1af15d5993088e33f83a62459c3
Swift
carabina/XEasyMotion
/XEasyMotion/GradView.swift
UTF-8
2,944
2.890625
3
[]
no_license
// // GradView.swift // keynav // // Created by h2ero on 5/27/16. // Copyright © 2016 h2ero. All rights reserved. // import Cocoa import Foundation class GradView: NSView{ override func drawRect(dirtyRect: NSRect) { // 设置透明 // NSColor.clearColor().set() drawGrad() } func drawPoint(){ let s = bounds.size let rect = NSMakeRect(0.5 * s.width - 1, 0.5 * s.height - 1, 5, 5); let circlePath = NSBezierPath() circlePath.appendBezierPathWithOvalInRect(rect) NSColor.grayColor().setFill() circlePath.fill() } func drawGrad() { if Constents.mode == Constents.modeHintChars { drawHorizLine(1/3.0) drawHorizLine(2/3.0) drawVertLine(1/3.0) drawVertLine(2/3.0) // draw chars let xAxis:[CGFloat] = [ bounds.size.width / 6, bounds.size.width / 6 * 3, bounds.size.width / 6 * 5 ] let yAxis:[CGFloat] = [ bounds.size.height / 6 * 5, bounds.size.height / 6 * 3, bounds.size.height / 6 ] for (y, row) in Constents.hintChars.enumerate(){ for(x, hintChar) in row.enumerate(){ drawChar(hintChar, x: xAxis[x] - (getHintCharFontSize()/2), y: yAxis[y] - (getHintCharFontSize() / 2)) } } } else { drawHorizLine(0) drawHorizLine(1/2.0) drawHorizLine(1.0) drawVertLine(0) drawVertLine(1/2.0) drawVertLine(1.0) } drawPoint() } func drawLine(p1:CGPoint ,p2 :CGPoint){ NSColor.redColor().set() NSBezierPath.setDefaultLineWidth(1.0) NSBezierPath.strokeLineFromPoint(p1, toPoint: p2) } func drawHorizLine(frac:CGFloat){ let x = frac * bounds.size.width drawLine(NSMakePoint(x, 0),p2: NSMakePoint(x,bounds.size.height)) } func drawVertLine(frac:CGFloat){ let y = frac * bounds.size.height drawLine(NSMakePoint(0, y),p2: NSMakePoint(bounds.size.width,y)) } func drawChar(text:NSString,x:CGFloat, y:CGFloat) { let p = NSMakePoint(x, y) let font = NSFont.systemFontOfSize(getHintCharFontSize()) let paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle let fontColor = NSColor.greenColor() let attrs = [ NSFontAttributeName: font, NSParagraphStyleAttributeName: paraStyle, NSForegroundColorAttributeName: fontColor ] text.drawAtPoint(p, withAttributes: attrs) } func getHintCharFontSize() -> CGFloat { return max(Constents.hitCharBaseFontSize * bounds.size.width / 1000 , Constents.hitCharMinFontSize); } }
true
30faf8b23c63e7dece47d922516df8586a50d04b
Swift
itsji10dra/FireCache
/FireCache/Classes/FireDownloader.swift
UTF-8
5,457
2.59375
3
[ "MIT" ]
permissive
// // FireDownloader.swift // FireCache // // Created by Jitendra Gandhi on 16/11/2018. // import UIKit import Foundation public class FireDownloader<T: Cacheable>: NSObject, URLSessionDataDelegate { // MARK: - Alias public typealias DownloadHandler = ((_ object: T?, _ error: Error?) -> Void) // MARK: - Data class ObjectFetchLoad { var handlers = [DownloadHandler?]() var responseData = NSMutableData() var downloadTaskCount = 0 var downloadTask: FireDownloadTask<T>? } private var session: URLSession! private var fetchLoads: [URL:ObjectFetchLoad] = [:] public var cachePolicy: URLRequest.CachePolicy = FireConfiguration.requestCachePolicy public var requestTimeout: TimeInterval = FireConfiguration.requestTimeoutSeconds public var httpMaximumConnectionsPerHost: Int = FireConfiguration.httpMaximumConnectionsPerHost { didSet { session.configuration.httpMaximumConnectionsPerHost = httpMaximumConnectionsPerHost } } // MARK: - Initializer override public init() { super.init() let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = requestTimeout configuration.httpMaximumConnectionsPerHost = httpMaximumConnectionsPerHost configuration.requestCachePolicy = cachePolicy self.session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) } // MARK: - DeInitializer deinit { session.invalidateAndCancel() } // MARK: - Public Methods public func downloadObject(with url: URL, completionHandler: DownloadHandler? = nil) -> FireDownloadTask<T>? { let loadObjectForURL = fetchLoads[url] ?? ObjectFetchLoad() let index = loadObjectForURL.handlers.count loadObjectForURL.handlers.append(completionHandler) func createNewDownloadTask(from url: URL) -> FireDownloadTask<T> { let request = URLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: requestTimeout) let dataTask = session.dataTask(with: request) let fireDownloadTask = FireDownloadTask<T>(dataTask: dataTask, downloader: self, handlerIndex: index) dataTask.resume() return fireDownloadTask } if loadObjectForURL.downloadTask == nil { let downloadTask = createNewDownloadTask(from: url) loadObjectForURL.downloadTask = downloadTask } else { loadObjectForURL.downloadTask?.handlerIndex = index } loadObjectForURL.downloadTaskCount += 1 fetchLoads[url] = loadObjectForURL return loadObjectForURL.downloadTask } public func removeAllLoads() { session.invalidateAndCancel() fetchLoads.removeAll() } // MARK: - Internal Methods internal func cancel(_ task: FireDownloadTask<T>) { guard let url = task.url, let fetchLoad = fetchLoads[url] else { return } fetchLoad.downloadTaskCount -= 1 let handler = fetchLoad.handlers.remove(at: task.handlerIndex) let error = NSError(domain: "Cancelled", code: NSURLErrorCancelled, userInfo: nil) handler?(nil, error as Error) if fetchLoad.downloadTaskCount == 0 { task.dataTask.cancel() } } // MARK: - Private Methods private func processObject(for url: URL) { guard let fetchLoad = fetchLoads[url] else { return } let data = fetchLoad.responseData let key = url.absoluteString var objectCache: [String:T] = [:] for handler in fetchLoad.handlers { var object: T? = objectCache[key] var error: Error? = nil if object == nil && error == nil { do { if let newObject = try T.convertFromData(data as Data) as? T { objectCache[key] = newObject object = newObject } } catch let fireError { error = fireError } } handler?(object, error) } fetchLoads.removeValue(forKey: url) } // MARK: - URLSessionDataDelegate public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { guard let url = dataTask.originalRequest?.url, let fetchLoad = fetchLoads[url] else { return } fetchLoad.responseData.append(data) } public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { guard let url = task.originalRequest?.url else { return } guard error == nil else { //Server Error, notify everyone. let load = fetchLoads.removeValue(forKey: url) load?.handlers.forEach({ handler in handler?(nil, error) }) return } processObject(for: url) //Download Finish, create object and notify. } }
true
120a1c9d1a8571f53f4f3818d70caf8d91b4d39d
Swift
chmziaurrehman/ios-E-commerce-app
/Qareeb/Model/AddressMode.swift
UTF-8
2,530
2.578125
3
[]
no_license
// // AddressMode.swift // Qareeb // // Created by M Zia Ur Rehman Ch. on 26/02/2019. // Copyright © 2019 Qareeb. All rights reserved. // import Foundation import ObjectMapper import SwiftKVC class AddressModel : NSObject ,Mappable{ var msg : String? var slot : String? var error : String? var address_id : Int? var result : [AddressResults]? var slots : [Slots]? var timeSlots : [String]? var timeSlotsWithDats : [String]? required init?(map: Map){ } func mapping(map: Map) { msg <- map["msg"] slot <- map["timeSlot"] error <- map["error"] address_id <- map["address_id"] result <- map["result"] // Days slots slots <- map["slots"] timeSlots <- map["times"] timeSlotsWithDats <- map["slots"] } } class AddressResults : NSObject ,Mappable{ // Area and city keye var address_id : String? var firstname : String? var lastname : String? var company : String? var address_1 : String? var address_2 : String? var postcode : String? var city : String? var zone_id : String? var zone : String? var zone_code : String? var country_id : String? var country : String? var iso_code_2 : String? var iso_code_3 : String? var address_format : String? var custom_field : Bool? required init?(map: Map){ } func mapping(map: Map) { address_id <- map["address_id"] firstname <- map["firstname"] lastname <- map["lastname"] company <- map["company"] address_1 <- map["address_1"] address_2 <- map["address_2"] postcode <- map["postcode"] city <- map["city"] zone_id <- map["zone_id"] zone <- map["zone"] zone_code <- map["zone_code"] country_id <- map["country_id"] country <- map["country"] iso_code_2 <- map["iso_code_2"] iso_code_3 <- map["iso_code_3"] address_format <- map["address_format"] custom_field <- map["custom_field"] } } class Slots : NSObject ,Mappable{ var value : String? var name : String? var date : String? required init?(map: Map){ } func mapping(map: Map) { value <- map["value"] name <- map["name"] date <- map["date"] } }
true
4b42bb8feeda911f3c149ff5f3111fee4817c85c
Swift
andreskwan/i-rw-avf
/QuickPlay/ViewController.swift
UTF-8
4,826
2.609375
3
[]
no_license
// // ViewController.swift // QuickPlay // // Created by Michael Briscoe on 1/5/16. // Copyright © 2016 Razeware LLC. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { @IBOutlet weak var videoTable: UITableView! var imagePicker: UIImagePickerController! var videoURLs = [URL]() var currentTableIndex = -1 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func addVideoClip(_ sender: AnyObject) { imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary imagePicker.allowsEditing = false imagePicker.mediaTypes = ["public.movie"] present(imagePicker, animated: true, completion: nil) } @IBAction func addRemoteStream(_ sender: AnyObject) { let theAlert = UIAlertController(title: "Add Remote Stream", message: "Enter URL for remote stream.", preferredStyle: UIAlertControllerStyle.alert) theAlert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil)) theAlert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.default, handler: { action in let theTextField = theAlert.textFields![0] as UITextField self.addVideoURL(URL(string: theTextField.text!)!) })) theAlert.addTextField(configurationHandler: { textField in textField.text = "https://devimages.apple.com.edgekey.net/streaming/examples/bipbop_16x9/bipbop_16x9_variant.m3u8" }) present(theAlert, animated: true, completion:nil) } func addVideoURL(_ url: URL) { videoURLs.append(url) videoTable.reloadData() } @IBAction func deleteVideoClip(_ sender: AnyObject) { if currentTableIndex != -1 { let theAlert = UIAlertController(title: "Remove Clip", message: "Are you sure you want to remove this video clip from playlist?", preferredStyle: UIAlertControllerStyle.alert) theAlert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.cancel, handler: nil)) theAlert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.destructive, handler: { action in self.videoURLs.remove(at: self.currentTableIndex) self.videoTable.reloadData() self.currentTableIndex = -1 })) present(theAlert, animated: true, completion:nil) } } @IBAction func playVideoClip(_ sender: AnyObject) { } @IBAction func playAllVideoClips(_ sender: AnyObject) { } // MARK: - Helpers func previewImageFromVideo(_ url: URL) -> UIImage? { let asset = AVAsset(url: url) let imageGenerator = AVAssetImageGenerator(asset: asset) imageGenerator.appliesPreferredTrackTransform = true var time = asset.duration time.value = min(time.value, 2) do { let imageRef = try imageGenerator.copyCGImage(at: time, actualTime: nil) return UIImage(cgImage: imageRef) } catch { return nil } } } // MARK: - UIImagePickerControllerDelegate extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let theImagePath: URL = info["UIImagePickerControllerReferenceURL"] as! URL addVideoURL(theImagePath) imagePicker.dismiss(animated: true, completion: nil) imagePicker = nil } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { imagePicker.dismiss(animated: true, completion: nil) imagePicker = nil } } // MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return videoURLs.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } } // MARK: - UITableViewDelegate extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "VideoClipCell") as! VideoTableViewCell cell.clipName.text = "Video Clip \(indexPath.row + 1)" if let previewImage = previewImageFromVideo(videoURLs[indexPath.row]) { cell.clipThumbnail.image = previewImage } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { currentTableIndex = indexPath.row } }
true
550c1b0a349e5cd13a2119c61ea805eb8de6ebd4
Swift
ngsison/lalanate
/lalanateTests/Extensions/UIViewExtensionTests.swift
UTF-8
1,041
2.703125
3
[]
no_license
// // UIViewExtensionTests.swift // lalanateTests // // Created by Nathaniel Brion Sison on 12/14/20. // import XCTest @testable import lalanate class UIViewExtensionTests: XCTestCase { func testSetCornerRadius() { // arrange let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) // act imageView.setCornerRadius(20) // assert XCTAssertTrue(imageView.clipsToBounds) XCTAssertEqual(imageView.layer.cornerRadius, 20) } func testSetSelectedCornerRadius() { // arrange let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) let corners: CACornerMask = [.layerMinXMinYCorner, .layerMaxXMinYCorner] let radius: CGFloat = 20 // act imageView.setSelectedCornerRadius(corners: corners, radius: radius) // assert XCTAssertTrue(imageView.clipsToBounds) XCTAssertEqual(imageView.layer.cornerRadius, radius) XCTAssertEqual(imageView.layer.maskedCorners, corners) } }
true
1d7a5adfc393504fac0a6988127db3ae2db20ac9
Swift
aadabi/Cruzer
/Hyphenate-Demo-Swift-master/Hyphenate-Demo-Swift/Code/Controllers/Chats/Views/ChatCell/EMChatBaseBubbleView.swift
UTF-8
2,184
2.71875
3
[ "MIT" ]
permissive
// // EMChatBaseBubbleView.swift // Hyphenate-Demo-Swift // // Created by dujiepeng on 2017/6/22. // Copyright © 2017 dujiepeng. All rights reserved. // import UIKit import Hyphenate @objc protocol EMChatBaseBubbleViewDelegate { @objc optional func didBubbleViewPressed(model: EMMessageModel) func didBubbleViewLongPressed() } class EMChatBaseBubbleView: UIView { var _backImageView: UIImageView? var _model: EMMessageModel? weak var delegate: EMChatBaseBubbleViewDelegate? public func heightForBubble(withMessageModel model: EMMessageModel) -> CGFloat{ return 100 } override init(frame: CGRect) { super.init(frame: frame) _backImageView = UIImageView() _backImageView?.isUserInteractionEnabled = true _backImageView?.isMultipleTouchEnabled = true _backImageView?.autoresizingMask = [.flexibleHeight, .flexibleWidth] addSubview(_backImageView!) _backImageView?.backgroundColor = PaleGrayColor _backImageView?.layer.cornerRadius = 10 backgroundColor = UIColor.clear let tap = UITapGestureRecognizer(target: self, action: #selector(bubbleViewPressed(sender:))) addGestureRecognizer(tap) let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(bubbleViewLongPressed(sender:))) lpgr.minimumPressDuration = 0.5 addGestureRecognizer(lpgr) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func set(model: EMMessageModel) { _model = model _backImageView?.backgroundColor = _model!.message!.direction == EMMessageDirectionSend ? KermitGreenTwoColor : PaleGrayColor } // MARK: - Actions func bubbleViewPressed(sender: UITapGestureRecognizer) { if delegate != nil { delegate!.didBubbleViewPressed!(model: _model!) } } func bubbleViewLongPressed(sender: UILongPressGestureRecognizer) { if delegate != nil && sender.state == UIGestureRecognizerState.began{ delegate!.didBubbleViewLongPressed() } } }
true
d9e56f031461fe4e1491c560a06bca886feb024d
Swift
twof/SwiftDataStructures
/Sources/DataStructures/BST.swift
UTF-8
1,713
3.671875
4
[]
no_license
fileprivate class Node<T: Comparable> { let data: T var left: Node<T>? var right: Node<T>? init(data: T, left: Node<T>? = nil, right: Node<T>? = nil) { self.data = data self.left = left self.right = right } } public class BinarySearchTree<T: Comparable> { fileprivate var root: Node<T>? public init() {} public func insert(_ value: T) { guard let root = self.root else { self.root = Node(data: value) return } insertTraversal(value: value, node: root) } public func toArray() -> [T] { var accumulator: [T] = [] self.inOrderTraversal { accumulator.append($0) } return accumulator } public func inOrderTraversal(_ action: (T) -> ()) { traverse(self.root, action: action) } fileprivate func traverse(_ node: Node<T>?, action: (T) -> ()) { if let left = node?.left { traverse(left, action: action) } action(node!.data) if let right = node?.right { traverse(right, action: action) } } fileprivate func insertTraversal(value: T, node: Node<T>) { if value <= node.data { guard let left = node.left else { node.left = Node(data: value) return } insertTraversal(value: value, node: left) } if value > node.data { guard let right = node.right else { node.right = Node(data: value) return } insertTraversal(value: value, node: right) } } }
true
e01e31127c42b3fecc3bb87cc2901326731137f3
Swift
yehao-j/JSPictureViewer
/JSPictureViewer/JSPictureConfig.swift
UTF-8
409
2.671875
3
[ "MIT" ]
permissive
// // JSPictureConfig.swift // PictureBrowser // // Created by jesse on 2017/8/16. // Copyright © 2017年 jesse. All rights reserved. // import UIKit public struct JSPictureConfig { public var url: String? public var image: UIImage? /// url和image是互斥的 public init(url: String? = nil, image: UIImage? = nil) { self.url = url self.image = image } }
true
f8a231f885236d6dab8dbebb0dd91614ccecb519
Swift
levi6y/OurSpace
/OurSpace/View/Dashboard/Space/Anniversary/AnniversaryCreate.swift
UTF-8
4,130
2.8125
3
[]
no_license
// // AnniversaryCreate.swift // OurSpace // // Created by levi6y on 2021/3/18. // import SwiftUI struct AnniversaryCreate: View { @EnvironmentObject var googleDelegate: GoogleDelegate var edges = UIApplication.shared.windows.first?.safeAreaInsets @Binding var newAnniversary: Bool @State var anniversaryDescription: String = "" @State var anniversaryDate: Date = Date() var body: some View { VStack{ HStack{ Text(googleDelegate.selectedSpace.name + " (New Anniversary)") .font(.title) .fontWeight(.heavy) .foregroundColor(.white) Spacer(minLength: 0) } .padding() .padding(.top,edges!.top) // Top Shadow Effect... .background(Color("c2")) .shadow(color: Color.white.opacity(0.06), radius: 5, x: 0, y: 5) VStack{ HStack{ TextField("Description", text: $anniversaryDescription) .foregroundColor(Color("c3")) .lineLimit(1) DatePicker("", selection: $anniversaryDate, in: ...Date(), displayedComponents: .date) .environment(\.timeZone, TimeZone(abbreviation: "GMT-4")!) }.padding(.vertical) .padding(.horizontal,20) .background(Color.white) .cornerRadius(10) .shadow(radius: 5) }.padding() .padding(.top,30) Spacer() HStack{ backButton(newAnniversay: $newAnniversary) createButton(newAnniversary: $newAnniversary,anniversaryDescription: $anniversaryDescription,anniversaryDate: $anniversaryDate) }.padding(.bottom,100) }.onTapGesture { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } } struct backButton: View { @EnvironmentObject var googleDelegate: GoogleDelegate @Binding var newAnniversay: Bool var body: some View { Button(action: { withAnimation(){ newAnniversay = false } }){ Text("Back") .foregroundColor(Color("c3")) .fontWeight(.bold) .padding(.vertical,10) .frame(width: (UIScreen.main.bounds.width - 50) / 2) }.background(Color.white) .clipShape(Capsule()) .shadow(radius: 5) } } struct createButton: View { @EnvironmentObject var googleDelegate: GoogleDelegate @Binding var newAnniversary:Bool @Binding var anniversaryDescription: String @Binding var anniversaryDate: Date var body: some View { Button(action: { var _ = googleDelegate.createAnniversary(anniversaryDescription: anniversaryDescription, anniversaryDate: anniversaryDate) .done{ r in if r { googleDelegate.getAnniversaries() anniversaryDescription = "" anniversaryDate = Date() withAnimation(){ newAnniversary = false } } } }){ Text("Create") .foregroundColor(Color("c3")) .fontWeight(.bold) .padding(.vertical,10) .frame(width: (UIScreen.main.bounds.width - 50) / 2) }.background(Color.white) .clipShape(Capsule()) .shadow(radius: 5) } } }
true
b50bd8a57ed0373ec43c28f631fb1eabb4a7905a
Swift
fatemahzhr/OnTheMap
/PostNewLocation.swift
UTF-8
2,808
2.84375
3
[]
no_license
// PostNewLocation.swift // OnTheMap Project // // Created by Fatimah Abdulraheem on 28/01/2019. // import UIKit import CoreLocation class PostNewLocation: UIViewController { //set the outlet: @IBOutlet weak var locationTextField: UITextField! @IBOutlet weak var mediaLinkTextField: UITextField! @IBOutlet weak var postBtn: UIButton! override func viewDidAppear(_ animated: Bool) { super.viewDidLoad() //Add "Cancel" button to the UIView UserInterfacePrepare() } @IBAction func findLocationBtn(_ sender: Any) { guard let addr = locationTextField.text, let websit = mediaLinkTextField.text, //check that user had added two values successfully addr != "", websit != "" else { self.WarningMsg(title: "Incomplete!", message: "The two fields are required, please fill them then try again") return } let studentLocation = SLocation(mapString: addr, mediaURL: websit) //call placeCordinatesOnMap function to save the data from the map to be used later placeCordinatesOnMap(studentLocation) } private func placeCordinatesOnMap(_ studentLocation: SLocation) { let x = self.ActivityCircle() //call CLGeocoder function to convert between cordinates //https://developer.apple.com/documentation/corelocation/clgeocoder CLGeocoder().geocodeAddressString(studentLocation.mapString!) { (placeMarks, err) in x.stopAnimating() guard let loc = placeMarks?.first?.location else { self.WarningMsg(title: "Error", message: "Error Found: Please post the correct coordinates!") return } //save the location to be sending in the Segue to the next mapview var addr = studentLocation addr.latitude = loc.coordinate.latitude addr.longitude = loc.coordinate.longitude self.performSegue(withIdentifier: "mapSegue", sender: addr) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "mapSegue", let viewContr = segue.destination as? CheckPostedLocation { viewContr.location = (sender as! SLocation) } } private func UserInterfacePrepare() { navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(self.dismissFun(_:))) setupX() } func setupX(){ mediaLinkTextField.delegate = self locationTextField.delegate = self }//end of setupX //Cancel button job: @objc private func dismissFun(_ sender: Any) { self.dismiss(animated: true, completion: nil) } }//end of PostNewLocation class
true
029442592a9d2623a2d76817bd9fc82186ad9e5c
Swift
crelies/RemoteImage
/Sources/RemoteImage/private/Models/RemoteImageServiceError.swift
UTF-8
390
2.53125
3
[ "MIT" ]
permissive
// // RemoteImageServiceError.swift // RemoteImage // // Created by Christian Elies on 11.08.19. // Copyright © 2019 Christian Elies. All rights reserved. // import Foundation enum RemoteImageServiceError: Error { case couldNotCreateImage } extension RemoteImageServiceError: LocalizedError { var errorDescription: String? { return "Could not create image from received data" } }
true