hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
6940cd54c9488c298ec8fc30c77b7dfb51cb98a5
1,128
// swift-tools-version:5.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "LeanCloud", platforms: [ .iOS(.v10), .macOS(.v10_12), .tvOS(.v10), .watchOS(.v3) ], products: [ .library(name: "LeanCloud", targets: ["LeanCloud"]), ], dependencies: [ .package(url: "https://github.com.cnpmjs.org/Alamofire/Alamofire.git", .upToNextMajor(from: "5.3.0")), .package(url: "https://github.com.cnpmjs.org/apple/swift-protobuf.git", .upToNextMajor(from: "1.13.0")), .package(url: "https://github.com.cnpmjs.org/apple/swift-nio-zlib-support.git", from: "1.0.0"), .package(url: "https://github.com.cnpmjs.org/groue/GRDB.swift.git", .upToNextMajor(from: "4.14.0")) ], targets: [ .target( name: "LeanCloud", dependencies: [ "Alamofire", "SwiftProtobuf", "GRDB" ], path: "Sources" ) ], swiftLanguageVersions: [.v5] )
31.333333
112
0.562057
46baa4c8ce7818b810295f9fe6f92971d9ee1438
5,621
import XCTest @testable import PhoenixKitsuReactions class MediaReactionVoteTests: XCTestCase { let decoder = JSONDecoder() let fullyFilledJSON: [String : Any] = [ "id": "4", "type": "mediaReactionVotes", "links": [ "self": "https://kitsu.io/api/edge/media-reaction-votes/4" ], "attributes": [ "createdAt": "2017-08-08T12:39:19.217Z", "updatedAt": "2017-08-08T12:39:19.217Z" ] ] // let validMissingDataJSON: [String : Any] = [ // "id": "4", // "type": "mediaReactionVotes", // "links": [ // "self": "https://kitsu.io/api/edge/media-reaction-votes/4" // ], // "attributes": [ // "createdAt": "2017-08-08T12:39:19.217Z", // "updatedAt": "2017-08-08T12:39:19.217Z" // ] // ] // // let validNilDataJSON: [String : Any] = [ // "id": "4", // "type": "mediaReactionVotes", // "links": [ // "self": "https://kitsu.io/api/edge/media-reaction-votes/4" // ], // "attributes": [ // "createdAt": "2017-08-08T12:39:19.217Z", // "updatedAt": "2017-08-08T12:39:19.217Z" // ] // ] let invalidMissingDataJSON: [String : Any] = [ "id": "1", "type": "mediaReactionVotes", "links": [ "self": "https://kitsu.io/api/edge/media-reaction-votes/4" ], "attributes": [ "updatedAt": "" ] ] let invalidNilDataJSON: [String : Any?] = [ "id": "1", "type": "mediaReactionVotes", "links": [ "self": "https://kitsu.io/api/edge/media-reaction-votes/4" ], "attributes": [ "createdAt": "", "updatedAt": nil ] ] var mediaReactionVote: MediaReactionVote? var mediaReactionVoteAttributes: MediaReactionVoteAttributes? override func tearDown() { mediaReactionVote = nil mediaReactionVoteAttributes = nil super.tearDown() } func testMediaReactionVoteFullyFilled() { let json = fullyFilledJSON if JSONSerialization.isValidJSONObject(json as Any) { let data = try? JSONSerialization.data(withJSONObject: json as Any) mediaReactionVote = try? decoder.decode(MediaReactionVote.self, from: data!) } else { mediaReactionVote = nil } mediaReactionVoteAttributes = mediaReactionVote?.attributes XCTAssertNotNil(mediaReactionVote) XCTAssertEqual(mediaReactionVote?.objectID, "4") XCTAssertEqual(mediaReactionVote?.type, "mediaReactionVotes") XCTAssertNotNil(mediaReactionVoteAttributes) XCTAssertEqual(mediaReactionVoteAttributes?.createdAt, "2017-08-08T12:39:19.217Z") XCTAssertEqual(mediaReactionVoteAttributes?.updatedAt, "2017-08-08T12:39:19.217Z") } // func testMediaReactionVoteValidMissingData() { // let json = validMissingDataJSON // // if JSONSerialization.isValidJSONObject(json as Any) { // let data = try? JSONSerialization.data(withJSONObject: json as Any) // mediaReactionVote = try? decoder.decode(MediaReactionVote.self, from: data!) // } else { // mediaReactionVote = nil // } // mediaReactionVoteAttributes = mediaReactionVote?.attributes // // XCTAssertNotNil(mediaReactionVote) // // XCTAssertEqual(mediaReactionVote?.objectID, "4") // XCTAssertEqual(mediaReactionVote?.type, "mediaReactionVotes") // // XCTAssertNotNil(mediaReactionVoteAttributes) // // XCTAssertEqual(mediaReactionVoteAttributes?.createdAt, "2017-08-08T12:39:19.217Z") // XCTAssertEqual(mediaReactionVoteAttributes?.updatedAt, "2017-08-08T12:39:19.217Z") // } // // func testMediaReactionVoteValidNilData() { // let json = validNilDataJSON // // if JSONSerialization.isValidJSONObject(json as Any) { // let data = try? JSONSerialization.data(withJSONObject: json as Any) // mediaReactionVote = try? decoder.decode(MediaReactionVote.self, from: data!) // } else { // mediaReactionVote = nil // } // mediaReactionVoteAttributes = mediaReactionVote?.attributes // // XCTAssertNotNil(mediaReactionVote) // // XCTAssertEqual(mediaReactionVote?.objectID, "4") // XCTAssertEqual(mediaReactionVote?.type, "mediaReactionVotes") // // XCTAssertNotNil(mediaReactionVoteAttributes) // // XCTAssertEqual(mediaReactionVoteAttributes?.createdAt, "2017-08-08T12:39:19.217Z") // XCTAssertEqual(mediaReactionVoteAttributes?.updatedAt, "2017-08-08T12:39:19.217Z") // } func testMediaReactionVoteInvalidMissingData() { let json = invalidMissingDataJSON if JSONSerialization.isValidJSONObject(json as Any) { let data = try? JSONSerialization.data(withJSONObject: json as Any) mediaReactionVote = try? decoder.decode(MediaReactionVote.self, from: data!) } else { mediaReactionVote = nil } mediaReactionVoteAttributes = mediaReactionVote?.attributes XCTAssertNotNil(mediaReactionVote) XCTAssertEqual(mediaReactionVote?.objectID, "1") XCTAssertEqual(mediaReactionVote?.type, "mediaReactionVotes") XCTAssertNil(mediaReactionVoteAttributes) } func testMediaReactionVoteInvalidNilData() { let json = invalidNilDataJSON if JSONSerialization.isValidJSONObject(json as Any) { let data = try? JSONSerialization.data(withJSONObject: json as Any) mediaReactionVote = try? decoder.decode(MediaReactionVote.self, from: data!) } else { mediaReactionVote = nil } mediaReactionVoteAttributes = mediaReactionVote?.attributes XCTAssertNotNil(mediaReactionVote) XCTAssertEqual(mediaReactionVote?.objectID, "1") XCTAssertEqual(mediaReactionVote?.type, "mediaReactionVotes") XCTAssertNil(mediaReactionVoteAttributes) } }
31.227778
88
0.676214
7a97f58f69a5e741681ad2764b17b637e0812e87
3,199
// // Glider // Fast, Lightweight yet powerful logging system for Swift. // // Created by Daniele Margutti // Email: [email protected] // Web: http://www.danielemargutti.com // // Copyright ©2021 Daniele Margutti. All rights reserved. // Licensed under MIT License. // import Foundation import CommonCrypto // MARK: - PrivacyMode public enum PrivacyMode { case `public` case `private` case privateWith(PrivacyMode.HashType) } internal extension String { func redact(_ privacy: PrivacyMode) -> String { switch privacy { case .public: return self case .private: return "<\(self.hashed(.md5) ?? "")>" case .privateWith(let type): return "<\(self.hashed(type) ?? "")>" } } } // MARK: - HashType extension PrivacyMode { /// Defines types of hash algorithms available public enum HashType { case md5 case sha1 case sha224 case sha256 case sha384 case sha512 var length: Int32 { switch self { case .md5: return CC_MD5_DIGEST_LENGTH case .sha1: return CC_SHA1_DIGEST_LENGTH case .sha224: return CC_SHA224_DIGEST_LENGTH case .sha256: return CC_SHA256_DIGEST_LENGTH case .sha384: return CC_SHA384_DIGEST_LENGTH case .sha512: return CC_SHA512_DIGEST_LENGTH } } } } // MARK: - String Data Extension internal extension String { /// Hashing algorithm for hashing a string instance. /// /// - Parameter type: The type of hash to use. /// - Returns: The requested hash output or nil if failure. func hashed(_ type: PrivacyMode.HashType) -> String? { // convert string to utf8 encoded data guard let message = data(using: .utf8) else { return nil } return message.hashed(type) } } // MARK: - Hash Data Extension fileprivate extension Data { /// Hashing algorithm for hashing a Data instance. /// /// - Parameter type: The type of hash to use. /// - Returns: The requested hash output or nil if failure. func hashed(_ type: PrivacyMode.HashType) -> String? { // setup data variable to hold hashed value var digest = Data(count: Int(type.length)) _ = digest.withUnsafeMutableBytes{ digestBytes -> UInt8 in self.withUnsafeBytes { messageBytes -> UInt8 in if let mb = messageBytes.baseAddress, let db = digestBytes.bindMemory(to: UInt8.self).baseAddress { let length = CC_LONG(self.count) switch type { case .md5: CC_MD5(mb, length, db) case .sha1: CC_SHA1(mb, length, db) case .sha224: CC_SHA224(mb, length, db) case .sha256: CC_SHA256(mb, length, db) case .sha384: CC_SHA384(mb, length, db) case .sha512: CC_SHA512(mb, length, db) } } return 0 } } return digest.map { String(format: "%02hhx", $0) }.joined() } }
28.309735
115
0.576743
0332c9c88c05a3cf04a5e9c750c930227306335d
153
// // UserData.swift // SwiftUISample // // Created by sohee on 2019/06/06. // Copyright © 2019 daybreak. All rights reserved. // import Foundation
15.3
51
0.679739
56dc96a49d64b702f55dd4d4c489f3dd9a4972c7
2,213
// // PokemonTests.swift // iOSBootcampChallengeTests // // Created by Jorge Benavides on 10/11/21. // import XCTest @testable import iOSBootcampChallenge class PokemonTests: XCTestCase { var pokemon: Pokemon! let decoder = JSONDecoder() override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. let expected = Pokemon(id: 132, name: "ditto", image: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/132.png", types: ["normal"], abilities: ["Limber", "Imposter"], weight: 40.0, baseExperience: 101) let notExpected = Pokemon(id: 1, name: "bulbasaur", image: "", types: [], abilities: [], weight: 30, baseExperience: 3) let filepath = Bundle(for: self.classForCoder).path(forResource: "pokemon_raw", ofType: "json")! let json: String = try String(contentsOfFile: filepath) let data = Data(json.utf8) pokemon = try self.decoder.decode(Pokemon.self, from: data) XCTAssertEqual(pokemon, expected) XCTAssertNotEqual(pokemon, notExpected) } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. pokemon = nil } func testPerformanceExample() throws { // This is an example of a performance test case. let options = XCTMeasureOptions.default options.iterationCount = 10 var string: String! self.measure(options: options) { string = pokemon.formattedNumber() } // Use XCTAssert and related functions to verify your tests produce the correct results. XCTAssertEqual(string, "#132", "inccorrect number format") } }
33.530303
144
0.561229
ebe5dcf7634a03e938bf8324b399d22018ce6d2d
6,016
import UIKit.UIViewController import RxSwift import RxCocoa class PublicPipelinesViewController: UIViewController { @IBOutlet weak var pipelinesTableView: UITableView? @IBOutlet weak var gearBarButtonItem: UIBarButtonItem? @IBOutlet weak var loadingIndicator: UIActivityIndicatorView? var publicPipelinesTableViewDataSource = PublicPipelinesTableViewDataSource() var publicPipelinesDataStreamProducer = PublicPipelinesDataStreamProducer() var concourseURLString: String? var pipelines: [Pipeline]? var disposeBag = DisposeBag() class var storyboardIdentifier: String { get { return "PublicPipelines" } } class var showTeamsSegueId: String { get { return "ShowTeams" } } class var showJobsSegueId: String { get { return "ShowJobs" } } class var setConcourseEntryAsRootPageSegueId: String { get { return "SetConcourseEntryAsRootPage" } } override func viewDidLoad() { super.viewDidLoad() guard let concourseURLString = concourseURLString else { return } title = "Pipelines" navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) navigationController?.navigationBar.tintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) setUpCellSelect() setUpCellPopulation(withConcourseURL: concourseURLString) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == PublicPipelinesViewController.showTeamsSegueId { guard let teamsViewController = segue.destination as? TeamsViewController else { return } guard let concourseURLString = concourseURLString else { return } teamsViewController.concourseURLString = concourseURLString } else if segue.identifier == PublicPipelinesViewController.showJobsSegueId { guard let jobsViewController = segue.destination as? JobsViewController else { return } guard let pipeline = sender as? Pipeline else { return } guard let concourseURLString = concourseURLString else { return } jobsViewController.pipeline = pipeline jobsViewController.dataStream = PublicJobsDataStream(concourseURL: concourseURLString) jobsViewController.target = nil } } private func setUpCellSelect() { guard let pipelinesTableView = pipelinesTableView else { return } pipelinesTableView .rx .itemSelected .subscribe(onNext: { indexPath in DispatchQueue.main.async { self.pipelinesTableView?.deselectRow(at: indexPath, animated: true) } }) .disposed(by: disposeBag) pipelinesTableView .rx .modelSelected(Pipeline.self) .subscribe(onNext: { pipeline in DispatchQueue.main.async { self.performSegue(withIdentifier: PublicPipelinesViewController.showJobsSegueId, sender: pipeline) } }) .disposed(by: disposeBag) } private func setUpCellPopulation(withConcourseURL concourseURL: String) { guard let pipelinesTableView = pipelinesTableView else { return } pipelinesTableView.separatorStyle = .none loadingIndicator?.startAnimating() publicPipelinesTableViewDataSource.setUp() publicPipelinesDataStreamProducer.openStream(forConcourseWithURL: concourseURL) .do(onNext: self.onNext(), onError: self.onError() ) .bind(to: pipelinesTableView.rx.items(dataSource: publicPipelinesTableViewDataSource)) .disposed(by: disposeBag) pipelinesTableView.rx.setDelegate(publicPipelinesTableViewDataSource) .disposed(by: disposeBag) } private func onNext() -> ([PipelineGroupSection]) -> () { return { _ in DispatchQueue.main.async { self.pipelinesTableView?.separatorStyle = .singleLine self.loadingIndicator?.stopAnimating() } } } private func onError() -> (Error) -> () { return { _ in let alert = UIAlertController( title: "Error", message: "An unexpected error has occurred. Please try again.", preferredStyle: .alert ) alert.addAction( UIAlertAction( title: "OK", style: .default, handler: nil ) ) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) self.pipelinesTableView?.separatorStyle = .singleLine self.loadingIndicator?.stopAnimating() } } } @IBAction func gearTapped() { let optionsActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) optionsActionSheet.addAction( UIAlertAction( title: "Log Into a Team", style: .default, handler: { _ in self.performSegue(withIdentifier: PublicPipelinesViewController.showTeamsSegueId, sender: nil) } ) ) optionsActionSheet.addAction( UIAlertAction( title: "Select a Concourse", style: .default, handler: { _ in self.performSegue(withIdentifier: PublicPipelinesViewController.setConcourseEntryAsRootPageSegueId, sender: nil) } ) ) optionsActionSheet.addAction( UIAlertAction( title: "Cancel", style: .default, handler: nil ) ) DispatchQueue.main.async { self.present(optionsActionSheet, animated: true, completion: nil) } } }
37.6
132
0.619348
8f582fdfe5c9ea2747c5d1280c7f455bed7ce593
745
// // PlayerContentView.swift // RotationSample // // Created by king on 2021/7/15. // import UIKit class PlayerContentView: UIView { lazy var fullScreenButton: UIButton = { let button = UIButton(type: .custom) button.setTitle("切换全屏", for: .normal) return button }() override init(frame: CGRect) { super.init(frame: frame) addSubview(fullScreenButton) fullScreenButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ fullScreenButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20), fullScreenButton.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -20), ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
23.28125
86
0.74094
67393cca5d57cf0138b0becff34181f70b9ba768
2,221
// // RecipIngredientsView.swift // zhangchu // // Created by 苏宁 on 2016/11/1. // Copyright © 2016年 suning. All rights reserved. // import UIKit class RecipIngredientsView: UIView { var clickClosure:RecipClickClosure? //数据 var model:RecipIngredientsModel?{ didSet{ //set方法调用之后会调用这里的方法 if model != nil { tableView?.reloadData() } } } // private var tableView :UITableView? override init(frame: CGRect) { super.init(frame: frame) tableView = UITableView(frame: CGRectZero, style: .Plain) tableView?.delegate = self tableView?.dataSource = self addSubview(tableView!) tableView?.snp_makeConstraints(closure: { [weak self](make) in make.edges.equalTo(self!) }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension RecipIngredientsView:UITableViewDataSource,UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var row = 0 if model?.data?.data?.count > 0 { row = (model?.data?.data?.count)! } return row } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let tmpModel = model!.data?.data![indexPath.row] return RecipIngredientsCell.heightForCellWithModel(tmpModel!) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellID = "recipIngredientsCellID" var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? RecipIngredientsCell if cell == nil { cell = RecipIngredientsCell(style: .Default, reuseIdentifier: cellID) } cell!.cellModel = model?.data?.data![indexPath.row] // cell?.clickClosure = clickClosure cell?.selectionStyle = .None return cell! // return UITableViewCell() } }
26.129412
109
0.593877
11d0bf1d78ac6020e2cdb0a81ee56e445d8301cd
1,922
// // StatusLabel.swift // CleanflightMobile // // Created by Alex on 14-04-16. // Copyright © 2016 Hangar42. All rights reserved. // import UIKit @IBDesignable final class GlassLabel: UIView { enum Background: Int { case red, green, dark } // MARK: - Variables fileprivate var label: UILabel! var background: Background! { didSet { switch background! { case .red: backgroundColor = UIColor.clear case .green: backgroundColor = UIColor(hex: 0x417505).withAlphaComponent(0.4) case .dark: backgroundColor = UIColor.black.withAlphaComponent(0.18) } } } @IBInspectable dynamic var text: String { get { return label.text ?? "" } set { label.text = newValue } } @IBInspectable dynamic var backgroundOption: Int { get { return background.rawValue } set { background = Background(rawValue: newValue > 2 ? 0 : newValue) } } // MARK: - Functions override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setup() } func setup() { label = UILabel(frame: bounds) label.frame.origin.y += 1 label.autoresizingMask = [.flexibleHeight, .flexibleWidth] label.font = UIFont.systemFont(ofSize: 13) label.textColor = UIColor.white label.textAlignment = .center addSubview(label) layer.cornerRadius = frame.height/2 background = .dark } func adjustToTextSize() { frame.size.width = label.intrinsicContentSize.width + 20 } }
24.025
80
0.57076
6986a5f2ff5af73b59d619f1e21a175fad783520
9,427
// // ViewController.swift // Project8 // // Created by Denis Andreev on 3/26/19. // Copyright © 2019 felarmir. All rights reserved. // import UIKit class ViewController: UIViewController { var cluesLabel: UILabel! var answerLabel: UILabel! var scoreLabel: UILabel! var currentAnswer: UITextField! var letterButtons = [UIButton]() var activetedButtons = [UIButton]() var solutions = [String]() var score = 0 { didSet { scoreLabel.text = "Score: \(score)" } } var totalAnswers = 0 var level = 1 override func loadView() { view = UIView() view.backgroundColor = .white scoreLabel = UILabel() scoreLabel.translatesAutoresizingMaskIntoConstraints = false scoreLabel.textAlignment = .right scoreLabel.text = "Score: 0" view.addSubview(scoreLabel) cluesLabel = UILabel() cluesLabel.translatesAutoresizingMaskIntoConstraints = false cluesLabel.font = UIFont.systemFont(ofSize: 24) cluesLabel.text = "CLUES" cluesLabel.numberOfLines = 0 cluesLabel.setContentHuggingPriority(UILayoutPriority(1), for: .vertical) view.addSubview(cluesLabel) answerLabel = UILabel() answerLabel.translatesAutoresizingMaskIntoConstraints = false answerLabel.font = UIFont.systemFont(ofSize: 24) answerLabel.text = "ANSWER" answerLabel.textAlignment = .right answerLabel.numberOfLines = 0 answerLabel.setContentHuggingPriority(UILayoutPriority(1), for: .vertical) view.addSubview(answerLabel) currentAnswer = UITextField() currentAnswer.translatesAutoresizingMaskIntoConstraints = false currentAnswer.placeholder = "Tap letters to guess" currentAnswer.textAlignment = .center currentAnswer.font = UIFont.systemFont(ofSize: 44) currentAnswer.isUserInteractionEnabled = false view.addSubview(currentAnswer) let submit = UIButton(type: .system) submit.translatesAutoresizingMaskIntoConstraints = false submit.setTitle("SUBMIT", for: .normal) submit.addTarget(self, action: #selector(submitTapAction), for: .touchUpInside) view.addSubview(submit) let clear = UIButton(type: .system) clear.translatesAutoresizingMaskIntoConstraints = false clear.setTitle("CLEAR", for: .normal) clear.addTarget(self, action: #selector(clearTapAction), for: .touchUpInside) view.addSubview(clear) let buttonsView = UIView() buttonsView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(buttonsView) NSLayoutConstraint.activate([ scoreLabel.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor), scoreLabel.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor), cluesLabel.topAnchor.constraint(equalTo: scoreLabel.bottomAnchor), cluesLabel.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor, constant: 100), cluesLabel.widthAnchor.constraint(equalTo: view.layoutMarginsGuide.widthAnchor, multiplier: 0.6, constant: -100), answerLabel.topAnchor.constraint(equalTo: scoreLabel.bottomAnchor), answerLabel.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor, constant: -100), answerLabel.widthAnchor.constraint(equalTo:view.layoutMarginsGuide.widthAnchor, multiplier: 0.4, constant: -100), answerLabel.heightAnchor.constraint(equalTo: cluesLabel.heightAnchor), currentAnswer.centerXAnchor.constraint(equalTo: view.centerXAnchor), currentAnswer.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5), currentAnswer.topAnchor.constraint(equalTo: cluesLabel.bottomAnchor, constant: 20), submit.topAnchor.constraint(equalTo: currentAnswer.bottomAnchor), submit.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: -100), submit.heightAnchor.constraint(equalToConstant: 44), clear.topAnchor.constraint(equalTo: currentAnswer.bottomAnchor), clear.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 100), clear.centerYAnchor.constraint(equalTo: submit.centerYAnchor), clear.heightAnchor.constraint(equalToConstant: 44), buttonsView.widthAnchor.constraint(equalToConstant: 750), buttonsView.heightAnchor.constraint(equalToConstant: 320), buttonsView.centerXAnchor.constraint(equalTo: view.centerXAnchor), buttonsView.topAnchor.constraint(equalTo: submit.bottomAnchor, constant: 20), buttonsView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -20) ]) let width = 150 let height = 80 for row in 0..<4 { for column in 0..<5 { let letterButton = UIButton(type: .system) letterButton.titleLabel?.font = UIFont.systemFont(ofSize: 36) let frame = CGRect(x: column*width, y: row*height, width: width, height: height) letterButton.frame = frame letterButton.addTarget(self, action: #selector(letterTapAction), for: .touchUpInside) letterButton.layer.borderColor = UIColor.lightGray.cgColor letterButton.layer.borderWidth = 1.0 buttonsView.addSubview(letterButton) letterButtons.append(letterButton) } } } override func viewDidLoad() { super.viewDidLoad() loadLevel() } @objc func letterTapAction(_ sender: UIButton) { guard let buttonTitle = sender.titleLabel?.text else { return } currentAnswer.text = currentAnswer.text?.appending(buttonTitle) activetedButtons.append(sender) sender.isHidden = true } @objc func submitTapAction(_ sender: UIButton) { guard let answerText = currentAnswer.text else { return } if let solutionPosition = solutions.firstIndex(of: answerText) { activetedButtons.removeAll() var splitAnswers = answerLabel.text?.components(separatedBy: "\n") splitAnswers?[solutionPosition] = answerText answerLabel.text = splitAnswers?.joined(separator: "\n") currentAnswer.text = "" score += 1 if score % 7 == 0 || totalAnswers == 7 && score > 2 { let ac = UIAlertController(title: "Well done!", message: "Are you ready for the next level?", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Let's go!", style: .default, handler: levelUp)) present(ac, animated: true) } } else { score -= 1 let ac = UIAlertController(title: "Wrong", message: "Please try again!", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Let's go!", style: .default, handler: nil)) present(ac, animated: true) } totalAnswers += 1 } func levelUp(action: UIAlertAction) { level += 1 solutions.removeAll(keepingCapacity: true) loadLevel() for btn in letterButtons { btn.isHidden = false } } @objc func clearTapAction(_ sender: UIButton) { currentAnswer.text = "" for btn in activetedButtons { btn.isHidden = false } activetedButtons.removeAll() } func loadLevel() { var clueString = "" var solutionString = "" var lettersBits = [String]() if let levelFileURL = Bundle.main.url(forResource: "level\(level)", withExtension: "txt") { if let levelContent = try? String(contentsOf: levelFileURL) { var lines = levelContent.components(separatedBy: "\n") lines.shuffle() for (index, line) in lines.enumerated() { let parts = line.components(separatedBy: ":") let answer = parts[0] let clue = parts[1] clueString += "\(index + 1). \(clue)\n" let solutionWord = answer.replacingOccurrences(of: "|", with: "") solutionString += "\(solutionWord.count) letters\n" solutions.append(solutionWord) let bits = answer.components(separatedBy: "|") lettersBits += bits } } } cluesLabel.text = clueString.trimmingCharacters(in: .whitespacesAndNewlines) answerLabel.text = solutionString.trimmingCharacters(in: .whitespacesAndNewlines) lettersBits.shuffle() if lettersBits.count == letterButtons.count { for i in 0..<lettersBits.count { letterButtons[i].setTitle(lettersBits[i], for: .normal) } } } }
40.114894
133
0.612072
7554bf34560b1b43a8e786114bbd1ff0a0db17dc
2,361
// // SceneDelegate.swift // Concentration // // Created by Artyom Gurbovich on 11/21/19. // Copyright © 2019 Artyom Gurbovich. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.722222
147
0.714951
01d8647ce321a8b1522d91450348f0c9c54c01e6
179
// RUN: %target-swift-frontend %s -parse -verify var d = [String:String]() _ = "\(d.map{ [$0 : $0] })" // expected-error {{type of expression is ambiguous without more context}}
35.8
102
0.642458
ffb75eaa5dc084fe7208aac128d8fbe54fac4a33
813
// // Route+Mine.swift // MCRoute_Example // // Created by MC on 2020/5/8. // Copyright © 2020 CocoaPods. All rights reserved. // import Foundation import MCRoute fileprivate let target_Mine = "Mine" extension MCRoute { /// 个人中心 public func MineViewController() -> UIViewController { let vc = perform(target_Mine, params: nil, shouldCacheTarget: false) guard vc != nil else { return errorController() } if let vc2 = vc as? MineViewController { return vc2 }else { return errorController() } } } class Target_Mine: NSObject,RouteTargetProtocol { @objc func Action_ViewController(_ params: [String : Any]) -> UIViewController? { let vc = MineViewController() return vc } }
21.394737
85
0.611316
8a07e1fcd1f74add2427ee44500894914ec3f83d
1,883
// // UserQuizzDataManager.swift // Quizzes // // Created by Jeffrey Almonte on 2/3/19. // Copyright © 2019 Alex Paul. All rights reserved. // import Foundation final class UserQuizzDataManager { static let filename = "UserQuizzData.plist" private static var quizzDataArray = [UserQuizzModel]() private init() {} static func saveUserQuizzes() { let path = DataPersistenceManager.filepathToDocumentsDiretory(filename: filename) print("I have a path: \(path)") do { let data = try PropertyListEncoder().encode(quizzDataArray) try data.write(to: path, options: Data.WritingOptions.atomic) } catch { print("property list encoding error: \(error)") } } static func getUserQuizzes() -> [UserQuizzModel] { let path = DataPersistenceManager.filepathToDocumentsDiretory(filename: filename).path print("This is the path: \(path)") if FileManager.default.fileExists(atPath: path) { if let data = FileManager.default.contents(atPath: path) { do { quizzDataArray = try PropertyListDecoder().decode([UserQuizzModel].self, from: data) } catch { print("property list decoding error: \(error)") } } else { print("getUserQuizz data: is nil") } } else { print("\(filename) does not exist") } quizzDataArray = quizzDataArray.sorted{$0.createdAt.date() > $1.createdAt.date()} return quizzDataArray } static func addEntry(quiz: UserQuizzModel) { quizzDataArray.append(quiz) saveUserQuizzes() } static func delete(atIndex index: Int) { quizzDataArray.remove(at: index) saveUserQuizzes() } }
30.868852
104
0.590016
22872ef54c96487b96e1b37eafb55ec9a2b91383
4,276
// // RSUnifiedCodeGenerator.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/10/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import Foundation import UIKit import AVFoundation open class BarcodeGenerator: RSCodeGenerator { open var isBuiltInCode128GeneratorSelected = false open var fillColor: UIColor = UIColor.white open var strokeColor: UIColor = UIColor.black public static var shared: BarcodeGenerator = BarcodeGenerator() // MARK: RSCodeGenerator open func isValid(_ contents: String) -> Bool { print("Use RSUnifiedCodeValidator.shared.isValid(contents:String, machineReadableCodeObjectType: String) instead") return false } open func generateCode(_ contents: String, inputCorrectionLevel: InputCorrectionLevel, machineReadableCodeObjectType: String) -> UIImage? { var codeGenerator: RSCodeGenerator? switch machineReadableCodeObjectType { case AVMetadataObject.ObjectType.qr.rawValue, AVMetadataObject.ObjectType.pdf417.rawValue, AVMetadataObject.ObjectType.aztec.rawValue: return RSAbstractCodeGenerator.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, filterName: RSAbstractCodeGenerator.filterName(machineReadableCodeObjectType)) case AVMetadataObject.ObjectType.code39.rawValue: codeGenerator = RSCode39Generator() case AVMetadataObject.ObjectType.code39Mod43.rawValue: codeGenerator = RSCode39Mod43Generator() case AVMetadataObject.ObjectType.ean8.rawValue: codeGenerator = RSEAN8Generator() case AVMetadataObject.ObjectType.ean13.rawValue: codeGenerator = RSEAN13Generator() case AVMetadataObject.ObjectType.interleaved2of5.rawValue: codeGenerator = RSITFGenerator() case AVMetadataObject.ObjectType.itf14.rawValue: codeGenerator = RSITF14Generator() case AVMetadataObject.ObjectType.upce.rawValue: codeGenerator = RSUPCEGenerator() case AVMetadataObject.ObjectType.code93.rawValue: codeGenerator = RSCode93Generator() // iOS 8 included, but my implementation's performance is better :) case AVMetadataObject.ObjectType.code128.rawValue: if self.isBuiltInCode128GeneratorSelected { return RSAbstractCodeGenerator.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, filterName: RSAbstractCodeGenerator.filterName(machineReadableCodeObjectType)) } else { codeGenerator = RSCode128Generator() } case AVMetadataObject.ObjectType.dataMatrix.rawValue: codeGenerator = RSCodeDataMatrixGenerator() case RSBarcodesTypeISBN13Code: codeGenerator = RSISBN13Generator() case RSBarcodesTypeISSN13Code: codeGenerator = RSISSN13Generator() case RSBarcodesTypeExtendedCode39Code: codeGenerator = RSExtendedCode39Generator() default: print("No code generator selected.") } if codeGenerator != nil { codeGenerator!.fillColor = self.fillColor codeGenerator!.strokeColor = self.strokeColor return codeGenerator!.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, machineReadableCodeObjectType: machineReadableCodeObjectType) } else { return nil } } open func generateCode(_ contents: String, machineReadableCodeObjectType: String) -> UIImage? { return self.generateCode(contents, inputCorrectionLevel: .Medium, machineReadableCodeObjectType: machineReadableCodeObjectType) } open func generateCode(_ machineReadableCodeObject: AVMetadataMachineReadableCodeObject, inputCorrectionLevel: InputCorrectionLevel) -> UIImage? { return self.generateCode(machineReadableCodeObject.stringValue!, inputCorrectionLevel: inputCorrectionLevel, machineReadableCodeObjectType: machineReadableCodeObject.type.rawValue) } open func generateCode(_ machineReadableCodeObject: AVMetadataMachineReadableCodeObject) -> UIImage? { return self.generateCode(machineReadableCodeObject, inputCorrectionLevel: .Medium) } }
48.044944
192
0.72638
6948fd1271a71aacda7393f41424f924d671912d
2,652
import Foundation // token: e2f51c1d39f50b977247a0cddd49513638aeb0cc var isRequesting = true func main() { guard let args = getArgs() else { return } createDeployment(branch: args.branch, description: "Deploying", owner: args.owner, repo: args.repo, environment: args.environment, targetUrl: args.targetUrl, token: args.token) while isRequesting { } exit(0) } func getArgs() -> (token: String, branch: String, owner: String, repo: String, environment: String, targetUrl: String)? { let args = ProcessInfo.processInfo.arguments let count = args.count guard count > 1 else { print("Token not provided..."); exit(1) } let token = args[1] guard count > 2 else { print("Branch not provided..."); exit(2) } let branch = args[2] guard count > 3 else { print("Owner not provided..."); exit(3) } let owner = args[3] guard count > 4 else { print("Repo not provided..."); exit(4) } let repo = args[4] guard count > 5 else { print("Environment not provided..."); exit(5) } let environment = args[5] guard count > 6 else { print("Target URL not provided..."); exit(6) } let targetUrl = args[6] return (token, branch, owner, repo, environment, targetUrl) } func createDeployment(branch: String, description: String, owner: String, repo: String, environment: String, targetUrl: String, token: String) { let request = CreateDeploymentRequest.init(model: .init(ref: branch, description: description), owner: owner, repo: repo, token: token) request.callback = { (response, error) in guard let response = response else { print(error as Any) return } createDeploymentStatus(deploymentId: "\(response.id)", environment: environment, state: "success", targetUrl: targetUrl, owner: owner, repo: repo, token: token) } do { try request.startRequest() } catch { print(error) } } func createDeploymentStatus(deploymentId: String, environment: String, state: String, targetUrl: String, owner: String, repo: String, token: String) { let request = CreateDeploymentStatusRequest.init(inputModel: .init(environment: "production", state: "success", targetUrl: targetUrl, description: "Deployment test finish"), owner: owner, repo: repo, deploymentId: deploymentId, token: token) do { try request.startRequest() } catch { print(error) } } main()
37.352113
177
0.612368
64adbfde40809e6e3b8a3f794baea9bd91941933
204
import Foundation // Made a list of all network errors users may encounter enum NewtworkError: Error { case badURL case badStatusCode case apiError(Error) case jsonDecodingError(Error) }
20.4
56
0.745098
160f7104a25103c2421010b92332ae170dd8a480
815
// // FileLoaderTests.swift // WordsTests // // Created by Carlos Cáceres González on 17/03/2021. // import XCTest @testable import Words class FileLoaderTests: XCTestCase { let fileLoader = FileLoader() override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testWrongFileName() { let result = fileLoader.load(fileName: "wrongFileName") XCTAssertEqual(result, nil) } func testRightFileName() { let result = fileLoader.load(fileName: "Nombres") XCTAssertTrue(result != nil) } }
23.970588
111
0.674847
71a2ea151d3c7be5c06cf55b610f03081f907a13
266
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a{{struct g{let t=A{extension{class a{init{e=b
33.25
87
0.74812
3a70b61b68944873f4a756426e3db1e8932585a4
404
// // PythonKeyringTests.swift // PythonKeyringTests // // Created by Janis Kirsteins on 12/05/2019. // import XCTest @testable import TwoFaLinux class PythonKeyringTests: XCTestCase { /// Can we init on this system? Depends on Python3 being used by PythonKit func testInit() throws { try PythonKeyring() } static var allTests = [ ("testInit", testInit), ] }
17.565217
78
0.660891
dee52dfb448cb2884ce0768a8bab354da7c26052
1,859
/*: ## App Exercise - Mile Times and Congratulations >These exercises reinforce Swift concepts in the context of a fitness tracking app. The `RunningWorkout` struct below holds information about your users' running workouts. However, you decide to add information about average mile time. Add a computed property called `averageMileTime` that uses `distance` and `time` to compute the user's average mile time. Assume that `distance` is in meters and 1600 meters is a mile. Create an instance of `RunningWorkout` and print the `averageMileTime` property. Check that it works properly. */ struct RunningWorkout { var distance: Double var time: Double var elevation: Double var averageMileTime: Double { return time/distance * 1600 } } var run = RunningWorkout(distance: 5000, time: 1200, elevation: 13) print(run.averageMileTime) /*: In other app exercises, you've provided encouraging messages to the user based on how many steps they've completed. A great place to check whether or not you should display something to the user is in a property observer. In the `Steps` struct below, add a `willSet` to the `steps` property that will check if the new value is equal to `goal`, and if it is, prints a congratulatory message. Create an instance of `Steps` where `steps` is 9999 and `goal` is 10000, then call `takeStep()` and see if your message is printed to the console. */ struct Steps { var steps: Int { willSet { if newValue == goal { print("Congratulations! You met your goal for the day!") } } } var goal: Int mutating func takeStep() { steps += 1 } } var steps = Steps(steps: 9999, goal: 10000) steps.takeStep() //: [Previous](@previous) | page 8 of 10 | [Next: Exercise - Type Properties and Methods](@next)
41.311111
337
0.698763
21a05ecc336609e64993076e9e7db62b3fef2010
869
// Created by Deniss Kaibagarovs [email protected] import Foundation public struct PoliceUKNeighbourhoodPrioritiesEntity: Codable, Equatable { public let action: String? public let issue: String? public let issue_date: String? public let action_date: String? public init(action: String? = nil, issue: String? = nil, issue_date: String? = nil, action_date: String? = nil) { self.action = action self.issue = issue self.issue_date = issue_date self.action_date = action_date } enum CodingKeys: String, CodingKey { case action = "action" case issue = "issue" case issue_date = "issue-date" // "-" cant be parsed because it's invalid as a variable name in swift case action_date = "action-date" // "-" cant be parsed because it's invalid as a variable name in swift } }
31.035714
107
0.673188
8f1833c07584ce7b64523ed33cdd56f47a171e36
4,830
import Foundation import SwiftLSP import SwiftyToolz func languagesJoined(by separator: String) -> String { LanguageServer.Config.all.keys.map { $0.capitalized }.joined(separator: separator) } func isAvailable(language: String) -> Bool { LanguageServer.Config.all[language.lowercased()] != nil } class LanguageServer { static var active: LanguageServer? // MARK: - Life Cycle init(languageKey: String) throws { guard let config = Config.all[languageKey.lowercased()] else { throw "No LSP server config set for language \(languageKey.capitalized)" } guard FileManager.default.fileExists(atPath: config.executablePath) else { throw "Executable does not exist at given path \(config.executablePath)" } didSend = { _ in log(warning: "\(Self.self) did send lsp packet, but handler has not been set") } didSendError = { _ in log(warning: "\(Self.self) did send error, but handler has not been set") } didTerminate = { log(warning: "\(Self.self) did terminate, but handler has not been set") } setupProcess(with: config) setupInput() setupOutput() setupErrorOutput() } deinit { if isRunning { stop() } } // MARK: - LSP Packet Input private func setupInput() { process.standardInput = inPipe } func receive(lspPacket: Data) { guard isRunning else { log(error: "\(Self.self) cannot receive LSP Packet while not running.") return } if lspPacket.isEmpty { log(warning: "\(Self.self) received empty LSP Packet.") } do { if #available(OSX 10.15.4, *) { try inPipe.fileHandleForWriting.write(contentsOf: lspPacket) } else { inPipe.fileHandleForWriting.write(lspPacket) } } catch { log(error) } } private let inPipe = Pipe() // MARK: - LSP Packet Output private func setupOutput() { outPipe.fileHandleForReading.readabilityHandler = { [weak self] outHandle in let serverOutput = outHandle.availableData if serverOutput.count > 0 { self?.packetDetector.read(serverOutput) } } packetDetector.didDetect = { [weak self] packet in self?.didSend(packet) } process.standardOutput = outPipe } private let packetDetector = LSP.PacketDetector() var didSend: (LSP.Packet) -> Void private let outPipe = Pipe() // MARK: - Error Output private func setupErrorOutput() { errorPipe.fileHandleForReading.readabilityHandler = { [weak self] errorHandle in let errorData = errorHandle.availableData if errorData.count > 0 { self?.didSendError(errorData) } } process.standardError = errorPipe } var didSendError: (Data) -> Void private let errorPipe = Pipe() // MARK: - Process private func setupProcess(with config: Config) { process.executableURL = URL(fileURLWithPath: config.executablePath) process.environment = nil process.arguments = config.arguments process.terminationHandler = { [weak self] process in log("\(Self.self) terminated. code: \(process.terminationReason.rawValue)") self?.didTerminate() } } var didTerminate: () -> Void func run() { guard process.executableURL != nil else { log(error: "\(Self.self) has no valid executable set") return } guard !isRunning else { log(warning: "\(Self.self) is already running.") return } do { try process.run() } catch { log(error) } } func stop() { process.terminate() } var isRunning: Bool { process.isRunning } private let process = Process() // MARK: - struct Config { var executablePath: String var arguments: [String] static var all: [LanguageKey: Config] = [ // "swift": .init(executablePath: "/usr/bin/xcrun", // arguments: ["sourcekit-lsp"]), "swift": .init(executablePath: "/Users/seb/Desktop/sourcekit-lsp-release", arguments: []), "python": .init(executablePath: "/Library/Frameworks/Python.framework/Versions/3.9/bin/pyls", arguments: []) ] typealias LanguageKey = String } }
28.75
105
0.556729
18a369c9043c9d6a439350afa5930da411654d65
249
// // Created by Max Desiatov on 13/08/2021. // import Parsing let tupleExprParser = delimitedSequenceParser( startParser: openParenParser, endParser: closeParenParser, separatorParser: commaParser, elementParser: Lazy { exprParser() } )
19.153846
46
0.75502
e070b80823fc9361e41c5fc64d0f6b0e4ad0e6a5
1,389
// Copyright © 2021 Brian Drelling. All rights reserved. import Foundation public extension DecodingError { var cleanedDescription: String { switch self { case let .typeMismatch(type, context): return "Type mismatch for key '\(context.codingPath.jsonPath)'. Expected type '\(String(describing: type))'." case let .valueNotFound(type, context): return "Value not found for key '\(context.codingPath.jsonPath)' of type '\(String(describing: type))'." case let .keyNotFound(key, context): var allKeys = context.codingPath allKeys.append(key) return "Key '\(allKeys.jsonPath)' not found." case let .dataCorrupted(context) where context.codingPath.isEmpty: return "Data corrupted." case let .dataCorrupted(context): return "Data corrupted at key '\(context.codingPath.jsonPath)'." @unknown default: return self.localizedDescription } } } private extension Array where Element == CodingKey { var jsonPath: String { var path = "" for key in self { if let index = key.intValue { path += "[\(index)]" } else { path += ".\(key.stringValue)" } } return path.trimmingCharacters(in: CharacterSet(charactersIn: ".")) } }
33.071429
121
0.593233
f9c5f64d8fc58db970639581e59b595f725819fe
7,565
// // CCImagePickerControllerExtension.swift // CCLocalLibrary-Swift // // Created by 冯明庆 on 20/06/2017. // Copyright © 2017 冯明庆. All rights reserved. // import UIKit private var _CC_ASOCIATE_KEY_IMAGEPICKER_COMPLETE_CLOSURE_ : Void?; private var _CC_ASOCIATE_KEY_IMAGEPICKER_ERROR_CLOSURE_ : Void?; private var _CC_ASOCIATE_KEY_IMAGEPICKER_CANCEL_CLOSURE_ : Void?; extension UIImagePickerController : UINavigationControllerDelegate , UIImagePickerControllerDelegate { enum CCImagePickerSupportType : Int { case nonee = 0 , all , camera , photoLibrary , photosAlbum } enum CCImagePickerPresentType : Int { case nonee , camera , photoLibrary , photosAlbum } enum CCImageSaveType : Int { case nonee = 0 , original , edited , all } typealias ClosureError = ((NSError?) -> Void)?; /// original , edited , cropRect , support types (if images exists) / unsupport types (images are not exist). typealias ClousreComplete = ((UIImage? , UIImage? , CGRect? , [CCImagePickerSupportType]) -> CCImageSaveType?)?; typealias ClousreCancel = CC_Closure_T?; private var closureComplete : ClousreComplete { set { objc_setAssociatedObject(self, &_CC_ASOCIATE_KEY_IMAGEPICKER_COMPLETE_CLOSURE_, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC); } get { return objc_getAssociatedObject(self, &_CC_ASOCIATE_KEY_IMAGEPICKER_COMPLETE_CLOSURE_) as? ((UIImage?, UIImage?, CGRect?, [CCImagePickerSupportType]) -> CCImageSaveType?) } } private var closureError : ClosureError { set { objc_setAssociatedObject(self, &_CC_ASOCIATE_KEY_IMAGEPICKER_ERROR_CLOSURE_, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC); } get { return objc_getAssociatedObject(self, &_CC_ASOCIATE_KEY_IMAGEPICKER_ERROR_CLOSURE_) as? ((NSError?) -> Void); } } private var closureCancel : ClousreCancel { set { objc_setAssociatedObject(self, &_CC_ASOCIATE_KEY_IMAGEPICKER_CANCEL_CLOSURE_, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC); } get { return objc_getAssociatedObject(self, &_CC_ASOCIATE_KEY_IMAGEPICKER_CANCEL_CLOSURE_) as? CC_Closure_T; } } /// support types (if images exists) / unsupport types (images are not exist) private class func ccSupportType() -> [CCImagePickerSupportType] { if (!CCCommonTools.isAllowAccessToAlbum || !CCCommonTools.isAllowAccessToCamera) { return [.nonee]; } var array : [CCImagePickerSupportType] = []; if self.isSourceTypeAvailable(.photoLibrary) { array.append(.photoLibrary); } if self.isSourceTypeAvailable(.savedPhotosAlbum) { array.append(.photosAlbum); } if self.isSourceTypeAvailable(.camera) { array.append(.camera); } if array.count == 3 { return [.all]; } else if array.count == 0 { return [.nonee]; } return array; } convenience init?(complete closureComplete : ClousreComplete) { self.init(present: .photosAlbum, complete: closureComplete, cancel: nil, saveError: nil) } convenience init?(present type : CCImagePickerPresentType , complete closureComplete : ClousreComplete , cancel closureCancel : ClousreCancel , saveError closureError : ClosureError) { let arraySupport = UIImagePickerController.ccSupportType(); if arraySupport.contains(.nonee) { CC_Safe_UI_Closure(closureComplete, { let _ = closureComplete!(nil , nil , nil , arraySupport); }); return nil; } self.init(); let isSupportAll : Bool = arraySupport.contains(.all); var typeUnsupport : CCImagePickerSupportType = .nonee; switch type { case .camera: if (isSupportAll || arraySupport.contains(.camera)) { self.sourceType = .camera; self.cameraCaptureMode = .photo; self.showsCameraControls = true; } else { typeUnsupport = .camera; } case .photosAlbum: if (isSupportAll || arraySupport.contains(.photosAlbum)) { self.sourceType = .savedPhotosAlbum; } else { typeUnsupport = .photosAlbum; } case .photoLibrary: if (isSupportAll || arraySupport.contains(.photoLibrary)) { self.sourceType = .photoLibrary; } else { typeUnsupport = .photoLibrary; } default: return nil; } if typeUnsupport.rawValue > 0 { CC_Safe_UI_Closure(closureComplete, { let _ = closureComplete!(nil , nil , nil , arraySupport); }); return nil; } self.delegate = self; self.allowsEditing = true; self.closureComplete = closureComplete; self.closureCancel = closureCancel; self.closureError = closureError; } public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { CC_Safe_UI_Closure(self.closureComplete) { if let typeSaveT = self.closureComplete!(info["UIImagePickerControllerOriginalImage"] as? UIImage, info["UIImagePickerControllerEditedImage"] as? UIImage, info["UIImagePickerControllerCropRect"] as? CGRect, UIImagePickerController.ccSupportType()) { let closureOriginal = { UIImageWriteToSavedPhotosAlbum(info["UIImagePickerControllerOriginalImage"] as! UIImage, self, #selector(self.image(_:didFinishSavingWith:contextInfo:)), nil); } let closureEdited = { UIImageWriteToSavedPhotosAlbum(info["UIImagePickerControllerOriginalImage"] as! UIImage, self, #selector(self.image(_:didFinishSavingWith:contextInfo:)), nil); } switch typeSaveT { case .original: closureOriginal(); case .edited: closureEdited(); case .all: closureOriginal(); closureEdited(); default: return ; } } } } public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { CC_Safe_UI_Closure(self.closureCancel) { self.closureCancel!(); } } @objc private func image(_ image : UIImage , didFinishSavingWith error : NSError? , contextInfo : UnsafeMutableRawPointer?) { if let errorT = error { CC_Safe_UI_Closure(self.closureError, { self.closureError!(errorT); }) } } }
38.794872
182
0.566028
092f2b6a668657122e16b3f650468948ca4e55a8
520
// // EmptyVC.swift // CustomInstrument2 // // Created by Marin Todorov on 11/5/20. // Copyright © 2020 Underplot ltd. All rights reserved. // import UIKit class EmptyVC: UIViewController { override func viewDidLoad() { view.backgroundColor = UIColor.blue view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTap))) } @objc func didTap() { view.window!.rootViewController = storyboard?.instantiateViewController(withIdentifier: "VC") } }
24.761905
101
0.692308
0a42b87ae5777caf60f2f237c34cd4448c9416a3
2,352
import ioscombined import UIKit private extension Announcement.Type_ { var iconImage: UIImage? { switch self { case .alert: return #imageLiteral(resourceName: "warning_amber_24px") case .feedback: return #imageLiteral(resourceName: "assignment_24px") case .notification: return #imageLiteral(resourceName: "error_outline_24px") default: return nil } } } final class AnnouncementCell: UITableViewCell { enum Constant { static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale.current formatter.calendar = Calendar.current formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "dMMM HH:mm", options: 0, locale: Locale.current) return formatter }() } @IBOutlet weak var iconImageContainerView: UIView! { didSet { iconImageContainerView.clipsToBounds = true iconImageContainerView.backgroundColor = Asset.secondary50.color iconImageContainerView.layer.cornerRadius = 16 } } @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var publishedAtLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var contentTextView: UITextView! func configure(_ announcement: Announcement) { iconImageView.image = announcement.type.iconImage?.withRenderingMode(.alwaysOriginal).tint(with: Asset.secondary300.color) publishedAtLabel.text = Constant.dateFormatter.string(from: Date(timeIntervalSince1970: announcement.publishedAt)) titleLabel.text = announcement.title contentTextView.attributedText = { content in guard let data = content.data(using: .unicode), let attributedString = try? NSMutableAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else { return nil } let range = NSRange(location: 0, length: attributedString.length) attributedString.addAttribute(.font, value: UIFont.preferredFont(forTextStyle: .body), range: range) return attributedString }(announcement.content) } }
38.557377
170
0.66284
1cdf2e41ea351ae0b1eff692943126c5471e10c6
5,194
import Combine import SwiftUI /** TableModel is the data structure being used in DataTable View. ## Code Usage: ``` let header = TableRowItem(leadingAccessories: [], trailingAccessory: nil, data: titles) let model = TableModel(headerData: header, rowData: res, isFirstRowSticky: true, isFirstColumnSticky: true, showListView: true) model.columnAttributes = ... model.didSelectRowAt = { _ in print(model.selectedIndexes) } ``` */ public class TableModel: ObservableObject { /// `TableRowItem`, header data for displaying. @Published public var headerData: TableRowItem? /// Data for each row. public var rowData: [TableRowItem] { get { self._rowData } set { self._rowData = newValue.map { rowItem in getMappedRowItem(for: rowItem) } } } /// Set header to be sticky. @Published public var isHeaderSticky: Bool = false /// Set first column to be sticky. @Published public var isFirstColumnSticky: Bool = false /// Set horizontal scrolling. @Published public var horizontalScrolling: Bool = true /// Show list view in iPhone protrait mode. @Published public var showListView: Bool = false /// Column attribute for each column. @Published public var columnAttributes: [ColumnAttribute] = [] /// Switching between normal and editing mode. @Published public var isEditing: Bool = false /// Enable or disable pinch and zoom. @Published public var isPinchZoomEnable: Bool = false /// Selection did change handler. @Published public var didSelectRowAt: ((_ index: Int) -> Void)? /// Selected Indexes. @Published public var selectedIndexes: [Int] = [] internal var centerPosition: CGPoint? @Published private var _rowData: [TableRowItem] = [] /// Public initializer for TableModel. /// - Parameters: /// - headerData: Header data for displaying. /// - rowData: Data for each row. /// - isHeaderSticky: Set header to be sticky. /// - isFirstColumnSticky: Set first column to be sticky. /// - columnAttributes: Column attribute for each column. /// - isPinchZoomEnable: Set if pinch and zoom enble, the default is false. /// - showListView: Show list view in iPhone protrait mode. public init(headerData: TableRowItem? = nil, rowData: [TableRowItem] = [], isHeaderSticky: Bool = false, isFirstColumnSticky: Bool = false, columnAttributes: [ColumnAttribute] = [], isPinchZoomEnable: Bool = false, showListView: Bool = false) { self.headerData = headerData self.rowData = rowData self.isHeaderSticky = isHeaderSticky self.isFirstColumnSticky = isFirstColumnSticky self.columnAttributes = columnAttributes self.isPinchZoomEnable = isPinchZoomEnable self.showListView = showListView } func getMappedRowItem(for row: TableRowItem) -> TableRowItem { let items = row.data var newRow = row var newItems: [DataItem] = [] if items.filter({ ($0 as? CheckBinding)?.hasBinding ?? false }).isEmpty { var labelIndex: Int = 0 var imageIndex: Int = 0 func textBinding(forIndex index: Int) -> ObjectViewProperty.Text? { switch index { case 0: return .title case 1: return .subtitle case 2: return .footnote case 3: return imageIndex < 2 ? .status : imageIndex < 3 ? .substatus : nil case 4: return imageIndex < 2 ? .substatus : nil default: return nil } } func imageBinding(forIndex index: Int) -> ObjectViewProperty.Image? { switch index { case 0: return .detailImage case 1: return labelIndex < 4 ? .statusImage : labelIndex < 5 ? .substatusImage : nil case 2: return labelIndex < 4 ? .substatusImage : nil default: return nil } } for item in items { switch item { case is DataTextItem: var _item = item as! DataTextItem _item.binding = textBinding(forIndex: labelIndex) labelIndex += 1 newItems.append(_item) case is DataImageItem: var _item = item as! DataImageItem _item.binding = imageBinding(forIndex: imageIndex) imageIndex += 1 newItems.append(_item) default: break } } newRow.data = newItems } return newRow } }
34.171053
128
0.54948
7aabf135b7f7a50953493486721796ae29444b88
1,279
// // TestCellSwiftVersionUITests.swift // TestCellSwiftVersionUITests // // Created by tomfriwel on 20/04/2017. // Copyright © 2017 tomfriwel. All rights reserved. // import XCTest class TestCellSwiftVersionUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.567568
182
0.673182
e0e4726b07da26f03db720c4aa06c53b029c696d
537
// // Chapter.swift // sdkApiVideo // // Created by romain PETIT on 28/01/2020. // Copyright © 2020 Romain. All rights reserved. // import Foundation public struct Chapter: Codable{ public var uri: String public var src: String public var language: String public init(uri: String, src: String, language: String){ self.uri = uri self.src = src self.language = language } enum CodingKeys : String, CodingKey { case uri case src case language } }
18.517241
60
0.608939
fcf3ab384f33cfcea72865c1c334a9dd441d0c5c
5,570
// // CertificateDetailViewController.swift // // // © Copyright IBM Deutschland GmbH 2021 // SPDX-License-Identifier: Apache-2.0 // import CovPassCommon import CovPassUI import PromiseKit import Scanner import UIKit class CertificateDetailViewController: UIViewController { // MARK: - Outlets @IBOutlet var scrollView: UIScrollView! @IBOutlet var stackView: UIStackView! @IBOutlet var vaccinationsStackView: UIStackView! @IBOutlet var nameHeadline: PlainLabel! @IBOutlet var immunizationContainerView: UIView! @IBOutlet var immunizationView: ParagraphView! @IBOutlet var immunizationButtonContainerView: UIStackView! @IBOutlet var immunizationButton: MainButton! @IBOutlet var personalDataHeadline: PlainLabel! @IBOutlet var allCertificatesHeadline: PlainLabel! @IBOutlet var nameView: ParagraphView! @IBOutlet var birtdateView: ParagraphView! // MARK: - Properties private(set) var viewModel: CertificateDetailViewModelProtocol // MARK: - Lifecycle @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init?(coder: NSCoder) not implemented yet") } init(viewModel: CertificateDetailViewModelProtocol) { self.viewModel = viewModel super.init(nibName: String(describing: Self.self), bundle: .main) } override func viewDidLoad() { super.viewDidLoad() viewModel.delegate = self setupView() viewModel.refresh() } // MARK: - Methods private func setupView() { view.backgroundColor = .backgroundPrimary scrollView.contentInset = .init(top: .space_24, left: .zero, bottom: .space_70, right: .zero) setupHeadline() setupImmunizationView() setupPersonalData() setupCertificates() setupNavigationBar() } private func setupNavigationBar() { title = "" navigationController?.navigationBar.backIndicatorImage = .arrowBack navigationController?.navigationBar.backIndicatorTransitionMaskImage = .arrowBack navigationController?.navigationBar.tintColor = .onBackground100 let favoriteIcon = UIBarButtonItem(image: viewModel.favoriteIcon, style: .plain, target: self, action: #selector(toggleFavorite)) favoriteIcon.tintColor = .onBackground100 navigationItem.rightBarButtonItem = favoriteIcon } private func setupHeadline() { nameHeadline.attributedText = viewModel.name.styledAs(.header_1).colored(.onBackground100) nameHeadline.layoutMargins = .init(top: .zero, left: .space_24, bottom: .zero, right: .space_24) stackView.setCustomSpacing(.space_24, after: nameHeadline) } private func setupImmunizationView() { immunizationContainerView.layoutMargins.top = .space_24 immunizationContainerView.layoutMargins.bottom = .space_24 immunizationContainerView.backgroundColor = .neutralWhite immunizationView.stackView.alignment = .top immunizationView.bottomBorder.isHidden = true immunizationView.image = viewModel.immunizationIcon immunizationView.attributedTitleText = viewModel.immunizationTitle.styledAs(.header_3) immunizationView.attributedBodyText = "recovery_certificate_overview_message".localized.styledAs(.body).colored(.onBackground70) immunizationView.layoutMargins.bottom = .space_24 immunizationButton.title = "recovery_certificate_overview_action_button_title".localized immunizationButton.action = { [weak self] in self?.viewModel.immunizationButtonTapped() } stackView.setCustomSpacing(.space_24, after: immunizationButtonContainerView) } private func setupPersonalData() { stackView.setCustomSpacing(.space_12, after: personalDataHeadline) personalDataHeadline.attributedText = "certificates_overview_personal_data_title".localized.styledAs(.header_2) personalDataHeadline.layoutMargins = .init(top: .space_30, left: .space_24, bottom: .zero, right: .space_24) nameView.attributedTitleText = "certificates_overview_personal_data_name".localized.styledAs(.header_3) nameView.attributedBodyText = viewModel.name.styledAs(.body) nameView.contentView?.layoutMargins = .init(top: .space_12, left: .space_24, bottom: .space_12, right: .space_24) birtdateView.attributedTitleText = "certificates_overview_personal_data_date_of_birth".localized.styledAs(.header_3) birtdateView.attributedBodyText = viewModel.birthDate.styledAs(.body) birtdateView.contentView?.layoutMargins = .init(top: .space_12, left: .space_24, bottom: .space_12, right: .space_24) allCertificatesHeadline.attributedText = "certificates_overview_all_certificates_title".localized.styledAs(.header_2) allCertificatesHeadline.layoutMargins = .init(top: .space_30, left: .space_24, bottom: .space_16, right: .space_24) } private func setupCertificates() { vaccinationsStackView.subviews.forEach { $0.removeFromSuperview() self.vaccinationsStackView.removeArrangedSubview($0) } viewModel.items.forEach { self.vaccinationsStackView.addArrangedSubview($0) } } @objc private func toggleFavorite() { viewModel.toggleFavorite() } } extension CertificateDetailViewController: ViewModelDelegate { func viewModelDidUpdate() { setupView() } func viewModelUpdateDidFailWithError(_: Error) { // already handled in ViewModel } }
39.225352
137
0.725314
38aeb5b4cef49d105893bf0a966f821503a1b6d2
2,449
import UIKit final class ImageViewerPresentationTransition: NSObject, UIViewControllerAnimatedTransitioning { private let fromImageView: UIImageView private let animatingRadius: Bool private let fromImage: UIImage? init(fromImageView: UIImageView, fromImage: UIImage?, animatingRadius: Bool) { self.fromImageView = fromImageView self.animatingRadius = animatingRadius self.fromImage = fromImage super.init() } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)! let fromParentView = fromImageView.superview! let transitionImageView = AnimatableImageView() transitionImageView.image = fromImage ?? fromImageView.image if animatingRadius { transitionImageView.setCornerRadius(fromImageView.frame.width / 2) } transitionImageView.frame = fromParentView.convert(fromImageView.frame, to: nil) transitionImageView.contentMode = fromImageView.contentMode let fadeView = UIView(frame: containerView.bounds) fadeView.backgroundColor = .black fadeView.alpha = 0.0 toView.frame = containerView.bounds toView.isHidden = true fromImageView.isHidden = true containerView.addSubview(toView) containerView.addSubview(fadeView) containerView.addSubview(transitionImageView) UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut, animations: { transitionImageView.contentMode = .scaleAspectFit transitionImageView.frame = containerView.bounds transitionImageView.setCornerRadius(0) fadeView.alpha = 1.0 }, completion: { _ in toView.isHidden = false fadeView.removeFromSuperview() transitionImageView.removeFromSuperview() transitionContext.completeTransition(true) }) } }
39.5
109
0.670069
ccd06ea4a297072ab2a04319ad8149bbd3ffaff1
2,632
// Syrup auto-generated file import Foundation public extension MerchantApi { struct BasicFragmentCustomerQueryQuery: GraphApiQuery, ResponseAssociable, Equatable { // MARK: - Query Variables // MARK: - Initializer public init() { } // MARK: - Helpers public static let customEncoder: JSONEncoder = MerchantApi.customEncoder private enum CodingKeys: CodingKey { } public typealias Response = BasicFragmentCustomerQueryResponse public let queryString: String = """ fragment BasicFragment on Customer { __typename id note } query BasicFragmentCustomerQuery { __typename shop { __typename customers(first: 1) { __typename edges { __typename node { __typename ... BasicFragment } } } } } """ } } extension MerchantApi.BasicFragmentCustomerQueryQuery { public static let operationSelections: GraphSelections.Operation? = GraphSelections.Operation( type: .query("QueryRoot"), selectionSet: [ .field(GraphSelections.Field(name: "__typename", alias: nil , arguments: [] , parentType: .object("QueryRoot"), type: .scalar("String"), selectionSet: [] )) , .field(GraphSelections.Field(name: "shop", alias: nil , arguments: [] , parentType: .object("QueryRoot"), type: .object("Shop"), selectionSet: [ .field(GraphSelections.Field(name: "__typename", alias: nil , arguments: [] , parentType: .object("Shop"), type: .scalar("String"), selectionSet: [] )) , .field(GraphSelections.Field(name: "customers", alias: nil , arguments: [ GraphSelections.Argument(name: "first", value: .intValue(1) ) ] , parentType: .object("Shop"), type: .object("CustomerConnection"), selectionSet: [ .field(GraphSelections.Field(name: "__typename", alias: nil , arguments: [] , parentType: .object("CustomerConnection"), type: .scalar("String"), selectionSet: [] )) , .field(GraphSelections.Field(name: "edges", alias: nil , arguments: [] , parentType: .object("CustomerConnection"), type: .object("CustomerEdge"), selectionSet: [ .field(GraphSelections.Field(name: "__typename", alias: nil , arguments: [] , parentType: .object("CustomerEdge"), type: .scalar("String"), selectionSet: [] )) , .field(GraphSelections.Field(name: "node", alias: nil , arguments: [] , parentType: .object("CustomerEdge"), type: .object("Customer"), selectionSet: [ .field(GraphSelections.Field(name: "__typename", alias: nil , arguments: [] , parentType: .object("Customer"), type: .scalar("String"), selectionSet: [] )) , .fragmentSpread(MerchantApi.BasicFragment.fragmentSpread ) ] )) ] )) ] )) ] )) ] ) }
25.066667
221
0.681991
6469be1a630de829a07c00ddefac625bbdeb1681
468
// // ViewController.swift // DateToolsExample // // Created by greyson on 2/26/16. // Copyright © 2016 cube-ua. All rights reserved. // import UIKit class ViewController: UIViewController { 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. } }
18
74
0.720085
082922be082835d1351560526230d0cbf69e51cf
349
// // DeviceIpodTests.swift // // Created by Anton Paliakou on 8/28/21. // import XCTest @testable import PreviewDevice final class DeviceIpodTests: XCTestCase { // MARK: - Ipod func testIpodHasCorretName() { let iphone: Device = .ipod7Gen XCTAssertEqual(iphone.rawValue, "iPod touch (7th generation)") } }
18.368421
70
0.65616
18fc962bd6f2a34712b6084a1794a3fd2cdabb2a
2,614
// // QuizModel.swift // QuizApp // // Created by Deepak Yadav on 07/06/20. // Copyright © 2020 Deepak Yadav. All rights reserved. // import Foundation protocol QuizProtocol { func questionRetrieved(_ questions:[Question]) } class QuizModel{ var delegate:QuizProtocol? func getQuestions(){ // TODO: fetch the questions getRemoteJsonFile() } func getLocalJsonFile(){ // create path to questionData let path = Bundle.main.path(forResource: "QuestionData", ofType: "json") guard path != nil else { print("Couldn't find the json data file") return } //Get the uRL object to the path let url = URL(fileURLWithPath: path!) do{ // get the data from the url let data = try Data(contentsOf: url) let decoder = JSONDecoder() let array = try decoder.decode([Question].self, from: data) delegate?.questionRetrieved(array) } catch{ // Error: couldn't find the data from uRL } } func getRemoteJsonFile(){ // Get a URL OBject from string let urlString = "https://codewithchris.com/code/QuestionData.json" let url = URL(string: urlString) guard url != nil else{ print("Could'nt create the url") return } // Get a URL Session Object let session = URLSession.shared // Get a datatask object // closure type let datatask = session.dataTask(with: url!) { (data, response, error) in if error == nil && data != nil{ do { // Get a jSON Decoder let decoder = JSONDecoder() // Parse the JSON let array = try decoder.decode([Question].self, from: data!) // Use the main thread to notify the view contoller DispatchQueue.main.async { // NOtify the view controller self.delegate?.questionRetrieved(array) } } catch{ print("Couldn't parse the JSON") } } } //Call resume on data task object datatask.resume() } }
25.881188
80
0.470543
c1fb6f1eb354d32d2ed308b2730e238f2372b2aa
1,197
// // MJCodableUtil.swift // MJCore // // Created by Martin Janák on 03/05/2018. // import Foundation public final class MJCodableUtil { public static func decode<D: Decodable>(decodableType: D.Type, data: Data, handler: @escaping (D?, Error?) -> Void) { let decoder = JSONDecoder() do { let decodable = try decoder.decode(decodableType.self, from: data) handler(decodable, nil) } catch let error { handler(nil, error) } } public static func decode<D: Decodable>(decodableType: D.Type, data: Data) throws -> D { let decoder = JSONDecoder() return try decoder.decode(decodableType, from: data) } public static func encode<E: Encodable>(encodable: E, handler: @escaping (Data?, Error?) -> Void) { let encoder = JSONEncoder() do { let data = try encoder.encode(encodable) handler(data, nil) } catch let error { handler(nil, error) } } public static func encode<E: Encodable>(encodable: E) throws -> Data { let encoder = JSONEncoder() return try encoder.encode(encodable) } }
28.5
121
0.588972
e6cfc75f208826bbb226eb13eff4b8a642e7bdf8
64,885
import Flutter import UIKit import Contacts import ContactsUI @available(iOS 9.0, *) public class SwiftContactsServicePlugin: NSObject, FlutterPlugin, CNContactViewControllerDelegate, CNContactPickerDelegate { private var result: FlutterResult? = nil private var localizedLabels: Bool = true private let rootViewController: UIViewController static let FORM_OPERATION_CANCELED: Int = 1 static let FORM_COULD_NOT_BE_OPEN: Int = 2 static let getContactsMethod = "getContacts" static let getContactsByIdentifiersMethod = "getContactsByIdentifiers" static let getIdentifiersMethod = "getIdentifiers" static let getContactsSummaryMethod = "getContactsSummary" static let getContactsForPhoneMethod = "getContactsForPhone" static let getContactsForEmailMethod = "getContactsForEmail" static let deleteContactsByIdentifiersMethod = "deleteContactsByIdentifiers" static let getAllContactsWithPhoneNumbers = "getAllContactsWithPhoneNumbers" static let addContactMethod = "addContact" static let deleteContactMethod = "deleteContact" static let updateContactMethod = "updateContact" static let openContactFormMethod = "openContactForm" static let openExistingContactMethod = "openExistingContact" static let openDeviceContactPickerMethod = "openDeviceContactPicker" static let addContactWithReturnIdentifierMethod = "addContactWithReturnIdentifier" static var noteEntitlementEnabled = true public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "github.com/clovisnicolas/flutter_contacts", binaryMessenger: registrar.messenger()) let rootViewController = UIApplication.shared.delegate!.window!!.rootViewController!; let instance = SwiftContactsServicePlugin(rootViewController) registrar.addMethodCallDelegate(instance, channel: channel) instance.preLoadContactView() } init(_ rootViewController: UIViewController) { self.rootViewController = rootViewController } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case SwiftContactsServicePlugin.getAllContactsWithPhoneNumbers: let arguments = call.arguments as! [String:Any] result(getAllContactsWithPhoneNumbersList(orderByGivenName: arguments["orderByGivenName"] as! Bool)) case SwiftContactsServicePlugin.getIdentifiersMethod: let arguments = call.arguments as! [String:Any] result(getIdentifiers(orderByGivenName: arguments["orderByGivenName"] as! Bool)) case SwiftContactsServicePlugin.getContactsMethod, SwiftContactsServicePlugin.getContactsByIdentifiersMethod, SwiftContactsServicePlugin.getContactsSummaryMethod: let arguments = call.arguments as! [String:Any] result(getContacts(methodName:call.method, query: (arguments["query"] as? String), withThumbnails: arguments["withThumbnails"] as! Bool, photoHighResolution: arguments["photoHighResolution"] as! Bool, phoneQuery: false, orderByGivenName: arguments["orderByGivenName"] as! Bool, localizedLabels: arguments["iOSLocalizedLabels"] as! Bool, identifiers: (arguments["identifiers"] as? String) )) case SwiftContactsServicePlugin.getContactsForPhoneMethod: let arguments = call.arguments as! [String:Any] result( getContacts(methodName:call.method, query: (arguments["phone"] as? String), withThumbnails: arguments["withThumbnails"] as! Bool, photoHighResolution: arguments["photoHighResolution"] as! Bool, phoneQuery: true, orderByGivenName: arguments["orderByGivenName"] as! Bool, localizedLabels: arguments["iOSLocalizedLabels"] as! Bool, identifiers: nil ) ) case SwiftContactsServicePlugin.getContactsForEmailMethod: let arguments = call.arguments as! [String:Any] result( getContacts(methodName:call.method, query: (arguments["email"] as? String), withThumbnails: arguments["withThumbnails"] as! Bool, photoHighResolution: arguments["photoHighResolution"] as! Bool, phoneQuery: false, emailQuery: true, orderByGivenName: arguments["orderByGivenName"] as! Bool, localizedLabels: arguments["iOSLocalizedLabels"] as! Bool, identifiers: nil ) ) case SwiftContactsServicePlugin.addContactMethod: let contact = dictionaryToContact(dictionary: call.arguments as! [String : Any]) let addResult = addContact(contact: contact) if (addResult == "") { result(nil) } else { result(FlutterError(code: "", message: addResult, details: nil)) } case SwiftContactsServicePlugin.addContactWithReturnIdentifierMethod: let contact = dictionaryToContact(dictionary: call.arguments as! [String : Any]) let addResult = addContactWithReturnIdentifier(contact: contact) if (!addResult.starts(with: "Error:")) { var resultDict = [[String:Any]]() resultDict.append(["identifier": addResult]) result(resultDict) } else { let error = addResult.replacingOccurrences(of: "Error:", with: "") result(FlutterError(code: "", message: error, details: nil)) } case SwiftContactsServicePlugin.deleteContactsByIdentifiersMethod: if(deleteContactsByIdentifiers(dictionary: call.arguments as! [String : Any])){ result(nil) } else{ result(FlutterError(code: "", message: "Failed to delete contacts, make sure they have valid identifiers", details: nil)) } case SwiftContactsServicePlugin.deleteContactMethod: if(deleteContact(dictionary: call.arguments as! [String : Any])){ result(nil) } else{ result(FlutterError(code: "", message: "Failed to delete contact, make sure it has a valid identifier", details: nil)) } case SwiftContactsServicePlugin.updateContactMethod: if(updateContact(dictionary: call.arguments as! [String: Any])) { result(nil) } else { result(FlutterError(code: "", message: "Failed to update contact, make sure it has a valid identifier", details: nil)) } case SwiftContactsServicePlugin.openContactFormMethod: let arguments = call.arguments as! [String:Any] localizedLabels = arguments["iOSLocalizedLabels"] as! Bool self.result = result _ = openContactForm() case SwiftContactsServicePlugin.openExistingContactMethod: let arguments = call.arguments as! [String : Any] let contact = arguments["contact"] as! [String : Any] localizedLabels = arguments["iOSLocalizedLabels"] as! Bool self.result = result _ = openExistingContact(contact: contact, result: result) case SwiftContactsServicePlugin.openDeviceContactPickerMethod: let arguments = call.arguments as! [String : Any] openDeviceContactPicker(arguments: arguments, result: result); default: result(FlutterMethodNotImplemented) } } func getIdentifiers(orderByGivenName: Bool = true) -> [[String:Any]] { var result = [[String:Any]]() let store = CNContactStore() do { var contactIdentifiers = [String]() let fetchRequest = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey as CNKeyDescriptor]) if (orderByGivenName) { fetchRequest.sortOrder = CNContactSortOrder.givenName } try store.enumerateContacts(with: fetchRequest, usingBlock: { contact, error -> Void in contactIdentifiers.append(contact.identifier) }) let map = ["identifiers" : contactIdentifiers] result.append(map) } catch let error as NSError { print(error.localizedDescription) return result } return result } func getAllContactsWithPhoneNumbersList(orderByGivenName: Bool) -> [[String:Any]]{ var contacts : [CNContact] = [] var result = [[String:Any]]() //Create the store, keys & fetch request let store = CNContactStore() let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName) as CNKeyDescriptor, CNContactPhoneNumbersKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactGivenNameKey as CNKeyDescriptor, CNContactMiddleNameKey as CNKeyDescriptor, CNContactNamePrefixKey as CNKeyDescriptor, CNContactNameSuffixKey as CNKeyDescriptor, CNContactNicknameKey as CNKeyDescriptor, CNContactThumbnailImageDataKey as CNKeyDescriptor ] as [CNKeyDescriptor] let fetchRequest = CNContactFetchRequest(keysToFetch: keys) do { let allContainers: [CNContainer] = try store.containers(matching: nil) var contactIds: [String] = [] for container in allContainers { fetchRequest.predicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier) if (orderByGivenName) { fetchRequest.sortOrder = CNContactSortOrder.givenName } do { try store.enumerateContacts(with: fetchRequest, usingBlock: { (contact, stop) -> Void in if (!contactIds.contains(contact.identifier)) { contactIds.append(contact.identifier) contacts.append(contact) } }) } catch let error as NSError { print(" Error after removing note key in getContact: \(error.code), \(error.localizedDescription)") return result } } } catch let error as NSError { print(" Error after removing note key in getContact: \(error.code), \(error.localizedDescription)") return result } contacts = contacts.sorted { (contactA, contactB) -> Bool in contactA.givenName.lowercased() < contactB.givenName.lowercased() } for contact : CNContact in contacts{ result.append(contactToPhoneNumberDictionary(contact: contact)) } return result } func getContacts(methodName:String, query : String?, withThumbnails: Bool, photoHighResolution: Bool, phoneQuery: Bool = false, emailQuery: Bool = false, orderByGivenName: Bool = true, localizedLabels: Bool = true, identifiers: String?) -> [[String:Any]]{ var contacts : [CNContact] = [] var result = [[String:Any]]() //Create the store, keys & fetch request let store = CNContactStore() var keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName) as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor, CNContactPhoneNumbersKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactGivenNameKey as CNKeyDescriptor, CNContactMiddleNameKey as CNKeyDescriptor, CNContactNamePrefixKey as CNKeyDescriptor, CNContactNameSuffixKey as CNKeyDescriptor, CNContactPostalAddressesKey as CNKeyDescriptor, CNContactOrganizationNameKey as CNKeyDescriptor, CNContactJobTitleKey as CNKeyDescriptor, CNContactDepartmentNameKey as CNKeyDescriptor, CNContactBirthdayKey as CNKeyDescriptor, CNContactNicknameKey as CNKeyDescriptor, CNContactPreviousFamilyNameKey as CNKeyDescriptor, CNContactPhoneticGivenNameKey as CNKeyDescriptor, CNContactPhoneticMiddleNameKey as CNKeyDescriptor, CNContactPhoneticFamilyNameKey as CNKeyDescriptor, CNContactNonGregorianBirthdayKey as CNKeyDescriptor, CNContactTypeKey as CNKeyDescriptor, CNContactDatesKey as CNKeyDescriptor, CNContactUrlAddressesKey as CNKeyDescriptor, CNContactRelationsKey as CNKeyDescriptor, CNContactSocialProfilesKey as CNKeyDescriptor, CNContactInstantMessageAddressesKey as CNKeyDescriptor ] as [CNKeyDescriptor] if SwiftContactsServicePlugin.noteEntitlementEnabled { keys.append(CNContactNoteKey as CNKeyDescriptor) } var contactIdentifiers: [String]? if (methodName == SwiftContactsServicePlugin.getContactsSummaryMethod) { keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName) as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor, CNContactPhoneNumbersKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactGivenNameKey as CNKeyDescriptor, CNContactMiddleNameKey as CNKeyDescriptor, CNContactNamePrefixKey as CNKeyDescriptor, CNContactNameSuffixKey as CNKeyDescriptor, ] as [CNKeyDescriptor] if let allIdentifiers = identifiers { contactIdentifiers = allIdentifiers.split(separator: "|").map(String.init) } } else if (methodName == SwiftContactsServicePlugin.getContactsByIdentifiersMethod) { if let allIdentifiers = identifiers { contactIdentifiers = allIdentifiers.split(separator: "|").map(String.init) } } if(withThumbnails){ if(photoHighResolution){ keys.append(CNContactImageDataKey as CNKeyDescriptor) } else { keys.append(CNContactThumbnailImageDataKey as CNKeyDescriptor) } } let fetchRequest = CNContactFetchRequest(keysToFetch: keys) var contactIds: [String] = [] do { let allContainers: [CNContainer] = try store.containers(matching: nil) for container in allContainers { fetchRequest.predicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier) if let byContactIdentifiers = contactIdentifiers { // contact by identifiers fetchRequest.predicate = CNContact.predicateForContacts(withIdentifiers: byContactIdentifiers) } else { // Set the predicate if there is a query if query != nil && !phoneQuery && !emailQuery { fetchRequest.predicate = CNContact.predicateForContacts(matchingName: query!) } if #available(iOS 11, *) { if query != nil && phoneQuery { let phoneNumberPredicate = CNPhoneNumber(stringValue: query!) fetchRequest.predicate = CNContact.predicateForContacts(matching: phoneNumberPredicate) } else if query != nil && emailQuery { fetchRequest.predicate = CNContact.predicateForContacts(matchingEmailAddress: query!) } } } if (orderByGivenName) { fetchRequest.sortOrder = CNContactSortOrder.givenName } do { try store.enumerateContacts(with: fetchRequest, usingBlock: { (contact, stop) -> Void in if (!contactIds.contains(contact.identifier)) { contactIds.append(contact.identifier) contacts.append(contact) } }) } catch let error as NSError { print(" Error in getContact: \(error.code), \(error.localizedDescription)") if (error.code == 102) {// iOS13, the note entitilement is introduced. Need to remove note as the entitlemnt is not yet aprroved or appended with plist SwiftContactsServicePlugin.noteEntitlementEnabled = false keys = keys.filter { !$0.isEqual(CNContactNoteKey) } do{ fetchRequest.keysToFetch = keys try store.enumerateContacts(with: fetchRequest, usingBlock: { (contact, stop) -> Void in if (!contactIds.contains(contact.identifier)) { contactIds.append(contact.identifier) contacts.append(contact) } }) } catch let error as NSError { print(" Error after removing note key in getContact: \(error.code), \(error.localizedDescription)") return result } } } } } catch let error as NSError { print(" Error in getContact: \(error.code), \(error.localizedDescription)") if (error.code == 102) {// iOS13, the note entitilement is introduced. Need to remove note as the entitlemnt is not yet aprroved or appended with plist SwiftContactsServicePlugin.noteEntitlementEnabled = false keys = keys.filter { !$0.isEqual(CNContactNoteKey) } do{ fetchRequest.keysToFetch = keys try store.enumerateContacts(with: fetchRequest, usingBlock: { (contact, stop) -> Void in if (!contactIds.contains(contact.identifier)) { contactIds.append(contact.identifier) contacts.append(contact) } }) } catch let error as NSError { print(" Error after removing note key in getContact: \(error.code), \(error.localizedDescription)") return result } } } contacts = contacts.sorted { (contactA, contactB) -> Bool in contactA.givenName.lowercased() < contactB.givenName.lowercased() } if (methodName == SwiftContactsServicePlugin.getContactsSummaryMethod) { for contact : CNContact in contacts{ result.append(contactToSummaryDictionary(contact: contact)) } } else { for contact : CNContact in contacts{ result.append(contactToDictionary(contact: contact, localizedLabels: localizedLabels)) } } return result } private func has(contact: CNContact, phone: String) -> Bool { if (!contact.phoneNumbers.isEmpty) { let phoneNumberToCompareAgainst = phone.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "") for phoneNumber in contact.phoneNumbers { if let phoneNumberStruct = phoneNumber.value as CNPhoneNumber? { let phoneNumberString = phoneNumberStruct.stringValue let phoneNumberToCompare = phoneNumberString.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "") if phoneNumberToCompare == phoneNumberToCompareAgainst { return true } } } } return false } func addContact(contact : CNMutableContact) -> String { let store = CNContactStore() do { let saveRequest = CNSaveRequest() saveRequest.add(contact, toContainerWithIdentifier: nil) try store.execute(saveRequest) } catch { return error.localizedDescription } return "" } func addContactWithReturnIdentifier(contact : CNMutableContact) -> String { let store = CNContactStore() do { let saveRequest = CNSaveRequest() saveRequest.add(contact, toContainerWithIdentifier: nil) try store.execute(saveRequest) return contact.identifier } catch { return "Error:\(error.localizedDescription)" } } func openContactForm() -> [String:Any]? { let contact = CNMutableContact.init() let controller = CNContactViewController.init(forNewContact:contact) controller.delegate = self DispatchQueue.main.async { let navigation = UINavigationController .init(rootViewController: controller) let viewController : UIViewController? = UIApplication.shared.delegate?.window??.rootViewController viewController?.present(navigation, animated:true, completion: nil) } return nil } func preLoadContactView() { DispatchQueue.main.asyncAfter(deadline: .now()+5) { NSLog("Preloading CNContactViewController") _ = CNContactViewController.init(forNewContact: nil) } } @objc func cancelContactForm() { if let result = self.result { let viewController : UIViewController? = UIApplication.shared.delegate?.window??.rootViewController viewController?.dismiss(animated: true, completion: nil) result(SwiftContactsServicePlugin.FORM_OPERATION_CANCELED) self.result = nil } } public func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) { viewController.dismiss(animated: true, completion: nil) if let result = self.result { if let contact = contact { result(contactToDictionary(contact: contact, localizedLabels: localizedLabels)) } else { result(SwiftContactsServicePlugin.FORM_OPERATION_CANCELED) } self.result = nil } } func openExistingContact(contact: [String:Any], result: FlutterResult ) -> [String:Any]? { let store = CNContactStore() do { // Check to make sure dictionary has an identifier guard let identifier = contact["identifier"] as? String else{ result(SwiftContactsServicePlugin.FORM_COULD_NOT_BE_OPEN) return nil; } let backTitle = contact["backTitle"] as? String let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactIdentifierKey, CNContactEmailAddressesKey, CNContactBirthdayKey, CNContactImageDataKey, CNContactPhoneNumbersKey, CNContactViewController.descriptorForRequiredKeys() ] as! [CNKeyDescriptor] let cnContact = try store.unifiedContact(withIdentifier: identifier, keysToFetch: keysToFetch) let viewController = CNContactViewController(for: cnContact) viewController.navigationItem.backBarButtonItem = UIBarButtonItem.init(title: backTitle == nil ? "Cancel" : backTitle, style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancelContactForm)) viewController.delegate = self DispatchQueue.main.async { let navigation = UINavigationController .init(rootViewController: viewController) var currentViewController = UIApplication.shared.keyWindow?.rootViewController while let nextView = currentViewController?.presentedViewController { currentViewController = nextView } let activityIndicatorView = UIActivityIndicatorView.init(style: UIActivityIndicatorView.Style.gray) activityIndicatorView.frame = (UIApplication.shared.keyWindow?.frame)! activityIndicatorView.startAnimating() activityIndicatorView.backgroundColor = UIColor.white navigation.view.addSubview(activityIndicatorView) currentViewController!.present(navigation, animated: true, completion: nil) DispatchQueue.main.asyncAfter(deadline: .now()+0.5 ){ activityIndicatorView.removeFromSuperview() } } return nil } catch { NSLog(error.localizedDescription) result(SwiftContactsServicePlugin.FORM_COULD_NOT_BE_OPEN) return nil } } func openDeviceContactPicker(arguments: [String:Any], result: @escaping FlutterResult) { localizedLabels = arguments["iOSLocalizedLabels"] as! Bool self.result = result let contactPicker = CNContactPickerViewController() contactPicker.delegate = self //contactPicker!.displayedPropertyKeys = [CNContactPhoneNumbersKey]; DispatchQueue.main.async { self.rootViewController.present(contactPicker, animated: true, completion: nil) } } //MARK:- CNContactPickerDelegate Method public func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) { if let result = self.result { result(contactToDictionary(contact: contact, localizedLabels: localizedLabels)) self.result = nil } } public func contactPickerDidCancel(_ picker: CNContactPickerViewController) { if let result = self.result { result(SwiftContactsServicePlugin.FORM_OPERATION_CANCELED) self.result = nil } } func deleteContactsByIdentifiers(dictionary : [String:Any]) -> Bool{ guard let identifiers = dictionary["identifiers"] as? String else{ return false; } let contactIdentifiers = identifiers.split(separator: "|").map(String.init) if contactIdentifiers.count > 0 { let store = CNContactStore() let keys = [CNContactIdentifierKey as NSString] do{ let predicate = CNContact.predicateForContacts(withIdentifiers: contactIdentifiers) let nativeContacts = try store.unifiedContacts(matching: predicate, keysToFetch: keys) for contact in nativeContacts { let request = CNSaveRequest() request.delete(contact.mutableCopy() as! CNMutableContact) try store.execute(request) } } catch{ print(error.localizedDescription) return false; } } return true; } func deleteContact(dictionary : [String:Any]) -> Bool{ guard let identifier = dictionary["identifier"] as? String else{ return false; } let store = CNContactStore() let keys = [CNContactIdentifierKey as NSString] do{ if let contact = try store.unifiedContact(withIdentifier: identifier, keysToFetch: keys).mutableCopy() as? CNMutableContact{ let request = CNSaveRequest() request.delete(contact) try store.execute(request) } } catch{ print(error.localizedDescription) return false; } return true; } func updateContact(dictionary : [String:Any]) -> Bool{ // Check to make sure dictionary has an identifier guard let identifier = dictionary["identifier"] as? String else{ return false; } let store = CNContactStore() var keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName) as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor, CNContactPhoneNumbersKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactGivenNameKey as CNKeyDescriptor, CNContactMiddleNameKey as CNKeyDescriptor, CNContactNamePrefixKey as CNKeyDescriptor, CNContactNameSuffixKey as CNKeyDescriptor, CNContactPostalAddressesKey as CNKeyDescriptor, CNContactOrganizationNameKey as CNKeyDescriptor, CNContactJobTitleKey as CNKeyDescriptor, CNContactDepartmentNameKey as CNKeyDescriptor, CNContactBirthdayKey as CNKeyDescriptor, CNContactNicknameKey as CNKeyDescriptor, CNContactPreviousFamilyNameKey as CNKeyDescriptor, CNContactPhoneticGivenNameKey as CNKeyDescriptor, CNContactPhoneticMiddleNameKey as CNKeyDescriptor, CNContactPhoneticFamilyNameKey as CNKeyDescriptor, CNContactNonGregorianBirthdayKey as CNKeyDescriptor, CNContactTypeKey as CNKeyDescriptor, CNContactDatesKey as CNKeyDescriptor, CNContactUrlAddressesKey as CNKeyDescriptor, CNContactRelationsKey as CNKeyDescriptor, CNContactSocialProfilesKey as CNKeyDescriptor, CNContactInstantMessageAddressesKey as CNKeyDescriptor, CNContactImageDataKey as CNKeyDescriptor, ] as [CNKeyDescriptor] if SwiftContactsServicePlugin.noteEntitlementEnabled { keys.append(CNContactNoteKey as CNKeyDescriptor) } do { // Check if the contact exists if let contact = try store.unifiedContact(withIdentifier: identifier, keysToFetch: keys).mutableCopy() as? CNMutableContact{ setDictionaryToContact(dictionary: dictionary, contact: contact) // Attempt to update the contact let request = CNSaveRequest() request.update(contact) try store.execute(request) } } catch let error as NSError { print("\(error.code), \(error.localizedDescription)") if (error.code == 102) {// iOS13, the note entitilement is introduced. Need to remove note as the entitlemnt is not yet aprroved or appended with plist SwiftContactsServicePlugin.noteEntitlementEnabled = false keys = keys.filter { !$0.isEqual(CNContactNoteKey) } do { if let contact = try store.unifiedContact(withIdentifier: identifier, keysToFetch: keys).mutableCopy() as? CNMutableContact{ setDictionaryToContact(dictionary: dictionary, contact: contact) // Attempt to update the contact let request = CNSaveRequest() request.update(contact) try store.execute(request) } } catch let error as NSError { print("\(error.code), \(error.localizedDescription)") return false; } } else { return false; } } return true; } func dictionaryToContact(dictionary : [String:Any]) -> CNMutableContact{ let contact = CNMutableContact() setDictionaryToContact(dictionary: dictionary, contact: contact) return contact } func setDictionaryToContact(dictionary: [String:Any], contact: CNMutableContact) { //Simple fields contact.givenName = dictionary["givenName"] as? String ?? "" contact.familyName = dictionary["familyName"] as? String ?? "" contact.middleName = dictionary["middleName"] as? String ?? "" contact.namePrefix = dictionary["prefix"] as? String ?? "" contact.nameSuffix = dictionary["suffix"] as? String ?? "" contact.organizationName = dictionary["company"] as? String ?? "" contact.jobTitle = dictionary["jobTitle"] as? String ?? "" contact.nickname = dictionary["nickname"] as? String ?? "" contact.phoneticGivenName = dictionary["phoneticGivenName"] as? String ?? "" contact.phoneticMiddleName = dictionary["phoneticMiddleName"] as? String ?? "" contact.phoneticFamilyName = dictionary["phoneticFamilyName"] as? String ?? "" contact.departmentName = dictionary["department"] as? String ?? "" if SwiftContactsServicePlugin.noteEntitlementEnabled { contact.note = dictionary["note"] as? String ?? "" } if let image = (dictionary["avatar"] as? FlutterStandardTypedData)?.data, image.count > 0 { contact.imageData = image } //Phone numbers if let phoneNumbers = dictionary["phones"] as? [[String:String]]{ var updatedPhoneNumbers = [CNLabeledValue<CNPhoneNumber>]() for phone in phoneNumbers where phone["value"] != nil { updatedPhoneNumbers.append(CNLabeledValue(label:getPhoneLabel(label: phone["label"]),value:CNPhoneNumber(stringValue: phone["value"]!))) // contact.phoneNumbers.append(CNLabeledValue(label:getPhoneLabel(label:phone["label"]),value:CNPhoneNumber(stringValue:phone["value"]!))) } contact.phoneNumbers = updatedPhoneNumbers } //Emails if let emails = dictionary["emails"] as? [[String:String]]{ var updatedEmails = [CNLabeledValue<NSString>]() for email in emails where nil != email["value"] { let emailLabel = email["label"] ?? "" updatedEmails.append(CNLabeledValue(label: getCommonLabel(label: emailLabel), value: email["value"]! as NSString)) // contact.emailAddresses.append(CNLabeledValue(label:getCommonLabel(label: emailLabel), value:email["value"]! as NSString)) } contact.emailAddresses = updatedEmails } //Postal addresses if let postalAddresses = dictionary["postalAddresses"] as? [[String:String]]{ var updatedPostalAddresses = [CNLabeledValue<CNPostalAddress>]() for postalAddress in postalAddresses{ let newAddress = CNMutablePostalAddress() newAddress.street = postalAddress["street"] ?? "" if #available(iOS 10.3, *) { newAddress.subLocality = postalAddress["locality"] ?? "" } else { var street = "" if let s = postalAddress["street"] { street = s } if let l = postalAddress["locality"] { if street.isEmpty { street = l } else { street = "\(street)\n\(l)" } } newAddress.street = street } newAddress.city = postalAddress["city"] ?? "" newAddress.postalCode = postalAddress["postcode"] ?? "" newAddress.country = postalAddress["country"] ?? "" newAddress.state = postalAddress["region"] ?? "" let label = postalAddress["label"] ?? "" // contact.postalAddresses.append(CNLabeledValue(label: getCommonLabel(label: label), value: newAddress)) updatedPostalAddresses.append(CNLabeledValue(label: getCommonLabel(label: label), value: newAddress)) } contact.postalAddresses = updatedPostalAddresses } //BIRTHDAY let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" if let birthday = dictionary["birthday"] as? String { let birthComponents = birthday.split(separator: "-") if birthComponents.count == 3 { var d = DateComponents() d.year = Int(birthComponents[0]) d.month = Int(birthComponents[1]) d.day = Int(birthComponents[2]) contact.birthday = d } else if birthComponents.count == 2 { var d = DateComponents() d.month = Int(birthComponents[0]) d.day = Int(birthComponents[1]) contact.birthday = d } } //Relations if let relations = dictionary["relations"] as? [[String:String]]{ var updatedRelations = [CNLabeledValue<CNContactRelation>]() for relation in relations where nil != relation["value"] { let relationLabel = relation["label"] ?? "" // contact.contactRelations.append(CNLabeledValue(label:getRelationsLabel(label: relationLabel), value:CNContactRelation(name: relation["value"]! as String))) updatedRelations.append(CNLabeledValue(label:getRelationsLabel(label: relationLabel), value:CNContactRelation(name: relation["value"]! as String))) } contact.contactRelations = updatedRelations } //Instant message address if let instantMessageAddresses = dictionary["instantMessageAddresses"] as? [[String:String]]{ var updatedIms = [CNLabeledValue<CNInstantMessageAddress>]() for im in instantMessageAddresses where nil != im["value"] { let imLabel = im["label"] ?? "" // contact.instantMessageAddresses.append(CNLabeledValue(label:getInstantMessageLabel(label: imLabel), value:CNInstantMessageAddress(username: im["value"]! as String, service: im["label"]! as String))) updatedIms.append(CNLabeledValue(label:getInstantMessageLabel(label: imLabel), value:CNInstantMessageAddress(username: im["value"]! as String, service: im["label"]! as String))) } contact.instantMessageAddresses = updatedIms } //Dates if let dates = dictionary["dates"] as? [[String:String]]{ var updatedDates = [CNLabeledValue<NSDateComponents>]() for date in dates where nil != date["value"] { let dateLabel = date["label"] ?? "" let dateValue = date["value"] ?? "" let dateComponents = dateValue.split(separator: "-") if dateComponents.count == 3 { var d = DateComponents() d.year = Int(dateComponents[0]) d.month = Int(dateComponents[1]) d.day = Int(dateComponents[2]) // contact.dates.append(CNLabeledValue(label: getDatesLabel(label: dateLabel), value: d as NSDateComponents)) updatedDates.append(CNLabeledValue(label: getDatesLabel(label: dateLabel), value: d as NSDateComponents)) } else if dateComponents.count == 2 { var d = DateComponents() d.month = Int(dateComponents[0]) d.day = Int(dateComponents[1]) // contact.dates.append(CNLabeledValue(label: getDatesLabel(label: dateLabel), value: d as NSDateComponents)) updatedDates.append(CNLabeledValue(label: getDatesLabel(label: dateLabel), value: d as NSDateComponents)) } } contact.dates = updatedDates } //Social profile if let profiles = dictionary["socialProfiles"] as? [[String:String]]{ var updatedProfiles = [CNLabeledValue<CNSocialProfile>]() for profile in profiles where nil != profile["userName"] { let label = profile["label"] ?? "" let service = (profile["service"] != nil && !profile["service"]!.isEmpty) ? profile["service"] : getSocialProfileLabel(label: label) let userName = profile["userName"] ?? "" let userIdentifier = profile["userIdentifier"] ?? "" var urlString = "" if let urlStringFromMap = profile["urlString"], !urlStringFromMap.isEmpty { urlString = getSocialProfileUrl(label: label, userName: userName) } updatedProfiles.append(CNLabeledValue(label:getSocialProfileLabel(label: label), value:CNSocialProfile(urlString: urlString, username: userName, userIdentifier: userIdentifier, service: service))) } contact.socialProfiles = updatedProfiles } //Websites if let websites = dictionary["websites"] as? [[String:String]]{ var updatedWebsites = [CNLabeledValue<NSString>]() for website in websites where nil != website["value"] { let label = website["label"] ?? "" let url = website["value"] ?? "" // contact.urlAddresses.append(CNLabeledValue(label:getWebsitesLabel(label: label), value:url as NSString)) updatedWebsites.append(CNLabeledValue(label:getWebsitesLabel(label: label), value:url as NSString)) } contact.urlAddresses = updatedWebsites } } func contactToPhoneNumberDictionary(contact: CNContact) -> [String:Any]{ var c = [String:Any]() c["identifier"] = contact.identifier c["displayName"] = CNContactFormatter.string(from: contact, style: CNContactFormatterStyle.fullName) c["givenName"] = contact.givenName c["familyName"] = contact.familyName c["middleName"] = contact.middleName c["prefix"] = contact.namePrefix c["suffix"] = contact.nameSuffix c["nickname"] = contact.nickname if let avatarData = contact.thumbnailImageData { c["avatar"] = FlutterStandardTypedData(bytes: avatarData) } var phoneNumbers = [[String:String]]() for phone in contact.phoneNumbers{ var phoneDictionary = [String:String]() phoneDictionary["identifier"] = phone.identifier phoneDictionary["value"] = phone.value.stringValue phoneDictionary["label"] = "other" if let label = phone.label{ phoneDictionary["label"] = localizedLabels ? CNLabeledValue<NSString>.localizedString(forLabel: label) : getRawPhoneLabel(label); } phoneNumbers.append(phoneDictionary) } c["phones"] = phoneNumbers return c } func contactToSummaryDictionary(contact: CNContact) -> [String:Any]{ var result = [String:Any]() //Simple fields result["identifier"] = contact.identifier result["displayName"] = CNContactFormatter.string(from: contact, style: CNContactFormatterStyle.fullName) result["givenName"] = contact.givenName result["middleName"] = contact.middleName result["familyName"] = contact.familyName result["prefix"] = contact.namePrefix result["suffix"] = contact.nameSuffix if contact.isKeyAvailable(CNContactThumbnailImageDataKey) { if let avatarData = contact.thumbnailImageData { result["avatar"] = FlutterStandardTypedData(bytes: avatarData) } } if contact.isKeyAvailable(CNContactImageDataKey) { if let avatarData = contact.imageData { result["avatar"] = FlutterStandardTypedData(bytes: avatarData) } } return result } func contactToDictionary(contact: CNContact, localizedLabels: Bool) -> [String:Any]{ var result = [String:Any]() //Simple fields result["identifier"] = contact.identifier result["displayName"] = CNContactFormatter.string(from: contact, style: CNContactFormatterStyle.fullName) result["givenName"] = contact.givenName result["familyName"] = contact.familyName result["middleName"] = contact.middleName result["phoneticGivenName"] = contact.phoneticGivenName result["phoneticMiddleName"] = contact.phoneticMiddleName result["phoneticFamilyName"] = contact.phoneticFamilyName result["prefix"] = contact.namePrefix result["suffix"] = contact.nameSuffix result["company"] = contact.organizationName result["jobTitle"] = contact.jobTitle result["department"] = contact.departmentName result["nickname"] = contact.nickname result["sip"] = "" if SwiftContactsServicePlugin.noteEntitlementEnabled { result["note"] = contact.note } else { result["note"] = "" } if contact.isKeyAvailable(CNContactThumbnailImageDataKey) { if let avatarData = contact.thumbnailImageData { result["avatar"] = FlutterStandardTypedData(bytes: avatarData) } } if contact.isKeyAvailable(CNContactImageDataKey) { if let avatarData = contact.imageData { result["avatar"] = FlutterStandardTypedData(bytes: avatarData) } } //Phone numbers var phoneNumbers = [[String:String]]() for phone in contact.phoneNumbers{ var phoneDictionary = [String:String]() phoneDictionary["identifier"] = phone.identifier phoneDictionary["value"] = phone.value.stringValue phoneDictionary["label"] = "other" if let label = phone.label{ phoneDictionary["label"] = localizedLabels ? CNLabeledValue<NSString>.localizedString(forLabel: label) : getRawPhoneLabel(label); } phoneNumbers.append(phoneDictionary) } result["phones"] = phoneNumbers //Emails var emailAddresses = [[String:String]]() for email in contact.emailAddresses{ var emailDictionary = [String:String]() emailDictionary["identifier"] = email.identifier emailDictionary["value"] = String(email.value) emailDictionary["label"] = "other" if let label = email.label{ emailDictionary["label"] = localizedLabels ? CNLabeledValue<NSString>.localizedString(forLabel: label) : getRawCommonLabel(label); } emailAddresses.append(emailDictionary) } result["emails"] = emailAddresses //Postal addresses var postalAddresses = [[String:String]]() for address in contact.postalAddresses{ var addressDictionary = [String:String]() addressDictionary["identifier"] = address.identifier addressDictionary["label"] = "other" if let label = address.label{ addressDictionary["label"] = localizedLabels ? CNLabeledValue<NSString>.localizedString(forLabel: label) : getRawCommonLabel(label); } addressDictionary["street"] = address.value.street if #available(iOS 10.3, *) { addressDictionary["locality"] = address.value.subLocality } else { addressDictionary["locality"] = "" } addressDictionary["city"] = address.value.city addressDictionary["postcode"] = address.value.postalCode addressDictionary["region"] = address.value.state addressDictionary["country"] = address.value.country postalAddresses.append(addressDictionary) } result["postalAddresses"] = postalAddresses //BIRTHDAY if let birthday : Date = contact.birthday?.date { let formatter = DateFormatter() let year = Calendar.current.component(.year, from: birthday) formatter.dateFormat = year == 1 ? "--MM-dd" : "yyyy-MM-dd"; result["birthday"] = formatter.string(from: birthday) } //Relations var relations = [[String:String]]() for relation in contact.contactRelations{ var relationDictionary = [String:String]() relationDictionary["identifier"] = relation.identifier relationDictionary["value"] = String(relation.value.name) relationDictionary["label"] = "other" if let label = relation.label{ relationDictionary["label"] = localizedLabels ? CNLabeledValue<NSString>.localizedString(forLabel: label) : getRawRelationsLabel(label: label); } relations.append(relationDictionary) } result["relations"] = relations //Instant message var instantMessageAddresses = [[String:String]]() for im in contact.instantMessageAddresses{ var imDictionary = [String:String]() imDictionary["identifier"] = im.identifier imDictionary["value"] = String(im.value.username) if let label = im.label{ imDictionary["label"] = localizedLabels ? CNLabeledValue<NSString>.localizedString(forLabel: label) : getRawInstantMessageLabel(label: label); } instantMessageAddresses.append(imDictionary) } result["instantMessageAddresses"] = instantMessageAddresses //Social profile var profiles = [[String:String]]() for profile in contact.socialProfiles{ var profileDictionary = [String:String]() profileDictionary["identifier"] = profile.identifier profileDictionary["service"] = String(profile.value.service) profileDictionary["urlString"] = String(profile.value.urlString) profileDictionary["userIdentifier"] = String(profile.value.userIdentifier) profileDictionary["userName"] = String(profile.value.username) if let label = profile.label{ profileDictionary["label"] = localizedLabels ? CNLabeledValue<NSString>.localizedString(forLabel: label) : getRawSocialProfileLabel(label: label); } else { profileDictionary["label"] = localizedLabels ? CNLabeledValue<NSString>.localizedString(forLabel: String(profile.value.service)) : getRawSocialProfileLabel(label: String(profile.value.service)); } profiles.append(profileDictionary) } result["socialProfiles"] = profiles //Dates var dates = [[String:String]]() let formatter = DateFormatter() for date in contact.dates{ var dateDictionary = [String:String]() dateDictionary["identifier"] = date.identifier if let aDate = date.value.date { let year = Calendar.current.component(.year, from: aDate) formatter.dateFormat = year == 1 ? "--MM-dd" : "yyyy-MM-dd"; dateDictionary["value"] = formatter.string(from: aDate) } if let label = date.label{ dateDictionary["label"] = localizedLabels ? CNLabeledValue<NSString>.localizedString(forLabel: label) : getRawDatesLabel(label: label); } dates.append(dateDictionary) } result["dates"] = dates //Websites var websites = [[String:String]]() for website in contact.urlAddresses{ var websiteDictionary = [String:String]() websiteDictionary["identifier"] = website.identifier websiteDictionary["value"] = String(website.value) websiteDictionary["label"] = "other" if let label = website.label{ websiteDictionary["label"] = localizedLabels ? CNLabeledValue<NSString>.localizedString(forLabel: label) : getRawWebsitesLabel(label: label); } websites.append(websiteDictionary) } result["websites"] = websites //Labels result["labels"] = [String]() return result } func getPhoneLabel(label: String?) -> String{ let labelValue = label ?? "" switch(labelValue.lowercased()){ case "main": return CNLabelPhoneNumberMain case "mobile": return CNLabelPhoneNumberMobile case "iphone": return CNLabelPhoneNumberiPhone case "work": return CNLabelWork case "home": return CNLabelHome case "other": return CNLabelOther case "school" : if #available(iOS 13.0, *) { return CNLabelSchool } else { return labelValue } default: return labelValue } } func getCommonLabel(label:String?) -> String{ let labelValue = label ?? "" switch(labelValue.lowercased()){ case "work": return CNLabelWork case "home": return CNLabelHome case "other": return CNLabelOther case "school" : if #available(iOS 13.0, *) { return CNLabelSchool } else { return labelValue } case "email" : return CNLabelEmailiCloud default: return labelValue } } func getInstantMessageLabel(label: String?) -> String { let labelValue = label ?? "" switch(labelValue.lowercased()){ case "aim": return CNInstantMessageServiceAIM case "facebook": return CNInstantMessageServiceFacebook case "gadu gadu": return CNInstantMessageServiceGaduGadu case "google talk": return CNInstantMessageServiceGoogleTalk case "icq": return CNInstantMessageServiceICQ case "jabber": return CNInstantMessageServiceJabber case "msn": return CNInstantMessageServiceMSN case "qq": return CNInstantMessageServiceQQ case "skype": return CNInstantMessageServiceSkype case "yahoo": return CNInstantMessageServiceYahoo default: return labelValue } } func getRelationsLabel(label: String?) -> String { let labelValue = label ?? "" switch(labelValue.lowercased()){ case "assistant": return CNLabelContactRelationAssistant case "manager": return CNLabelContactRelationManager case "brother": return CNLabelContactRelationBrother case "sister": return CNLabelContactRelationSister case "friend": return CNLabelContactRelationFriend case "spouse": return CNLabelContactRelationSpouse case "partner": return CNLabelContactRelationPartner case "parent": return CNLabelContactRelationParent case "mother": return CNLabelContactRelationMother case "father": return CNLabelContactRelationFather case "child": return CNLabelContactRelationChild default: if #available(iOS 11.0, *) { switch labelValue.lowercased() { case "daughter": return CNLabelContactRelationDaughter case "son": return CNLabelContactRelationSon default: return labelValue } } if #available(iOS 13.0, *) { switch labelValue.lowercased() { //TODO. add all iOS 13 cases default: return labelValue } } return labelValue } } func getSocialProfileLabel(label: String?) -> String { let labelValue = label ?? "" switch(labelValue.lowercased()){ case "flickr": return CNSocialProfileServiceFlickr case "facebook": return CNSocialProfileServiceFacebook case "linkedin": return CNSocialProfileServiceLinkedIn case "myspace": return CNSocialProfileServiceMySpace case "sina weibo": return CNSocialProfileServiceSinaWeibo case "tancent weibo": return CNSocialProfileServiceTencentWeibo case "twitter": return CNSocialProfileServiceTwitter case "yelp": return CNSocialProfileServiceYelp case "game center": return CNSocialProfileServiceGameCenter default: return labelValue } } func getSocialProfileUrl(label: String?, userName: String?) -> String { let labelValue = label ?? "" let userName = userName ?? "" switch(labelValue.lowercased()){ case "flickr": return "http://flickr.com/\(userName)" case "facebook": return "http://facebook.com/\(userName)" case "linkedin": return "http://linkedin.com/in/\(userName)" case "myspace": return "http://myspace.com/\(userName)" case "sina weibo": return "http://weibo.com/n/\(userName)" case "twitter": return "https://twitter.com/\(userName)" default: return "x-apple:\(userName)" } } func getDatesLabel(label: String?) -> String { let labelValue = label ?? "" switch(labelValue.lowercased()){ case "anniversary": return CNLabelDateAnniversary case "other": return CNLabelOther default: return labelValue } } func getWebsitesLabel(label: String?) -> String { let labelValue = label ?? "" switch(labelValue.lowercased()){ case "homepage": return CNLabelURLAddressHomePage case "work": return CNLabelWork case "home": return CNLabelHome case "other": return CNLabelOther case "school" : if #available(iOS 13.0, *) { return CNLabelSchool } else { return labelValue } default: return labelValue } } func getRawPhoneLabel(_ label: String?) -> String{ let labelValue = label ?? "" switch(labelValue.lowercased()){ case CNLabelPhoneNumberMain.lowercased(): return "main" case CNLabelPhoneNumberMobile.lowercased(): return "mobile" case CNLabelPhoneNumberiPhone.lowercased(): return "iPhone" case CNLabelWork.lowercased(): return "work" case CNLabelHome.lowercased(): return "home" case CNLabelOther.lowercased(): return "other" default: if #available(iOS 13.0, *) { if labelValue.lowercased() == CNLabelSchool.lowercased() { return "school" } } return labelValue } } func getRawCommonLabel(_ label: String?) -> String{ let labelValue = label ?? "" switch(labelValue.lowercased()){ case CNLabelWork.lowercased(): return "work" case CNLabelHome.lowercased(): return "home" case CNLabelOther.lowercased(): return "other" case CNLabelEmailiCloud.lowercased(): return "email" default: if #available(iOS 13.0, *) { if labelValue.lowercased() == CNLabelSchool.lowercased() { return "school" } } return labelValue } } func getRawInstantMessageLabel(label: String?) -> String { let labelValue = label ?? "" switch(labelValue.lowercased()){ case CNInstantMessageServiceAIM.lowercased(): return "aim" case CNInstantMessageServiceFacebook.lowercased(): return "facebook" case CNInstantMessageServiceGaduGadu.lowercased(): return "gadu gadu" case CNInstantMessageServiceGoogleTalk.lowercased(): return "google talk" case CNInstantMessageServiceICQ: return "icq" case CNInstantMessageServiceJabber: return "jabber" case CNInstantMessageServiceMSN: return "msn" case CNInstantMessageServiceQQ: return "qq" case CNInstantMessageServiceSkype: return "skype" case CNInstantMessageServiceYahoo: return "yahoo" default: return labelValue } } func getRawRelationsLabel(label: String?) -> String { let labelValue = label ?? "" switch(labelValue.lowercased()){ case CNLabelContactRelationAssistant: return "assistant" case CNLabelContactRelationManager: return "manager" case CNLabelContactRelationBrother: return "brother" case CNLabelContactRelationSister: return "sister" case CNLabelContactRelationFriend: return "friend" case CNLabelContactRelationSpouse: return "spouse" case CNLabelContactRelationPartner: return "partner" case CNLabelContactRelationParent: return "parent" case CNLabelContactRelationMother: return "mother" case CNLabelContactRelationFather: return "father" case CNLabelContactRelationChild: return "child" default: if #available(iOS 11.0, *) { switch(labelValue.lowercased()){ case CNLabelContactRelationDaughter: return "daughter" case CNLabelContactRelationSon: return "son" default: return labelValue } } if #available(iOS 13.0, *) { switch labelValue.lowercased() { //TODO. add all iOS 13 cases default: return labelValue } } return labelValue } } func getRawSocialProfileLabel(label: String?) -> String { let labelValue = label ?? "" switch(labelValue.lowercased()){ case CNSocialProfileServiceFlickr.lowercased(): return "flickr" case CNSocialProfileServiceFacebook.lowercased(): return "facebook" case CNSocialProfileServiceLinkedIn.lowercased(): return "linkedin" case CNSocialProfileServiceMySpace.lowercased(): return "myspace" case CNSocialProfileServiceSinaWeibo.lowercased(): return "sina weibo" case CNSocialProfileServiceTencentWeibo.lowercased(): return "tancent weibo" case CNSocialProfileServiceTwitter.lowercased(): return "twitter" case CNSocialProfileServiceYelp.lowercased(): return "yelp" case CNSocialProfileServiceGameCenter.lowercased(): return "game center" default: return labelValue } } func getRawDatesLabel(label: String?) -> String { let labelValue = label ?? "" switch(labelValue.lowercased()){ case CNLabelDateAnniversary.lowercased(): return "anniversary" case CNLabelOther.lowercased(): return "other" default: return labelValue } } func getRawWebsitesLabel(label: String?) -> String { let labelValue = label ?? "" switch(labelValue.lowercased()){ case CNLabelURLAddressHomePage.lowercased(): return "homepage" case CNLabelWork.lowercased(): return "work" case CNLabelHome.lowercased(): return "home" case CNLabelOther.lowercased(): return "other" default: if #available(iOS 13.0, *) { if labelValue.lowercased() == CNLabelSchool.lowercased() { return "school" } } return labelValue } } }
47.052212
259
0.596887
469feab7e33343bbb84541202b541a7507b7f5ad
1,079
import AsyncDisplayKit fileprivate let userImageHeight = 60 public class PhotoWithOutsetIconOverlay: ASDisplayNode, ASPlayground { public let photoNode = ASNetworkImageNode() public let iconNode = ASNetworkImageNode() override public init() { super.init() backgroundColor = .white automaticallyManagesSubnodes = true setupNodes() } private func setupNodes() { photoNode.url = URL(string: "http://asyncdisplaykit.org/static/images/layout-examples-photo-with-outset-icon-overlay-photo.png") photoNode.backgroundColor = .black iconNode.url = URL(string: "http://asyncdisplaykit.org/static/images/layout-examples-photo-with-outset-icon-overlay-icon.png") iconNode.imageModificationBlock = ASImageNodeRoundBorderModificationBlock(10, .white) } // This is used to expose this function for overriding in extensions override public func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { return ASLayoutSpec() } public func show() { display(inRect: CGRect(x: 0, y: 0, width: 190, height: 190)) } }
31.735294
132
0.746988
f4bf58c6008d8b567e227052d97cd0748a2e3b36
2,193
// // ZFRefreshNormal.swift // ZFListViewDemo // // Created by ZhiFei on 2017/11/29. // Copyright © 2017年 ZhiFei. All rights reserved. // import Foundation import ZFListView import MJRefresh class ZFListViewRefreshNormal: NSObject, ZFListViewRefresh { var tableView: UITableView { get { return self.intrinsicTableView } } fileprivate var intrinsicTableView: UITableView! required init(_ scrollView: UITableView) { super.init() self.intrinsicTableView = scrollView } func startTopRefreshing() { self.tableView.mj_header?.beginRefreshing() } func stopAllLoading() { self.tableView.mj_header?.endRefreshing() self.tableView.mj_footer?.endRefreshing() } func noticeNoMoreData() { self.tableView.mj_footer?.endRefreshingWithNoMoreData() } func addTopPullToRefreshIfNeeded(handler: (() -> ())?) { if let _ = self.tableView.mj_header { return } let normalHeader = MJRefreshNormalHeader(refreshingBlock: { if let handler = handler { handler() } }) normalHeader?.setTitle("下拉刷新", for: .idle) normalHeader?.setTitle("释放立即刷新", for: .pulling) normalHeader?.setTitle("正在加载", for: .refreshing) normalHeader?.setTitle("准备加载", for: .willRefresh) normalHeader?.setTitle("没有更多", for: .noMoreData) normalHeader?.lastUpdatedTimeLabel.isHidden = true self.tableView.mj_header = normalHeader } func removeTopPullToRefreshIfNeeded() { self.tableView.mj_header = nil } func addBottomPullToRefreshIfNeeded(handler: (() -> ())?) { if let _ = self.tableView.mj_footer { return } let footer = MJRefreshAutoNormalFooter(refreshingBlock: { if let handler = handler { handler() } }) footer?.setTitle("上拉刷新", for: .idle) footer?.setTitle("释放立即刷新", for: .pulling) footer?.setTitle("正在加载", for: .refreshing) footer?.setTitle("准备加载", for: .willRefresh) footer?.setTitle("没有更多", for: .noMoreData) footer?.isAutomaticallyHidden = true self.tableView.mj_footer = footer } func removeBottomPullToRefreshIfNeeded() { self.tableView.mj_footer = nil } }
24.366667
63
0.669859
692b6272ffe4288aa3693d52193c0b49d0c810ef
8,263
// // CodeGenerator.swift // GrafQuill // // Created by Matt Fenwick on 8/17/16. // Copyright © 2016 mf. All rights reserved. // import Foundation protocol CodeType { func code(inout text: [String], tabs: Int) } extension CodeType { func code() -> String { var buffer = [String]() self.code(&buffer, tabs: 0) return buffer.joinWithSeparator("") } } func indent(tabs: Int) -> String { return String(count: tabs, repeatedValue: Character("\t")) } extension Variable: CodeType { func code(inout text: [String], tabs: Int) { text.append("$" + self.name) } } extension Argument: CodeType { func code(inout text: [String], tabs: Int) { text.append("\(self.name): ") self.value.code(&text, tabs: tabs) } } extension Directive: CodeType { func code(inout text: [String], tabs: Int) { text.append("@\(self.name)") if self.args.count > 0 { text.append("(") for arg in self.args { arg.code(&text, tabs: tabs) } } text.append(" ") } } extension Enum: CodeType { func code(inout text: [String], tabs: Int) { text.append(self.name + " ") } } extension Number: CodeType { func code(inout text: [String], tabs: Int) { text.append("\(self.int)") if let fraction = self.fraction { text.append(".\(fraction)") } if let exponent = self.exponent { text.append("e\(exponent)") } } } extension List: CodeType { func code(inout text: [String], tabs: Int) { // TODO -- check. is this right? text.append("[\n") for val in self.values { text.append(indent(tabs + 1)) val.code(&text, tabs: tabs + 1) text.append("\n") } text.append(indent(tabs) + "]") } } extension Object: CodeType { func code(inout text: [String], tabs: Int) { // TODO check. is this right? text.append("{\n") for keyval in keyvals { text.append(indent(tabs + 1)) keyval.code(&text, tabs: tabs + 1) text.append("\n") } text.append(indent(tabs) + "}") } } extension Value: CodeType { func code(inout text: [String], tabs: Int) { switch self { case let .Boolean_(bool): text.append("\(bool)") case let .Enum_(value): value.code(&text, tabs: tabs) case let .Number_(number): number.code(&text, tabs: tabs) case let .List_(list): list.code(&text, tabs: tabs) case let .Object_(object): object.code(&text, tabs: tabs) case let .String_(string): text.append("\"\(string)\"") case let .Variable_(variable): variable.code(&text, tabs: tabs) } } } extension TypeCondition: CodeType { func code(inout text: [String], tabs: Int) { text.append("on ") self.namedType.code(&text, tabs: tabs) } } extension Alias: CodeType { func code(inout text: [String], tabs: Int) { text.append("\(self.name): ") } } extension Field: CodeType { func code(inout text: [String], tabs: Int) { if let alias = self.alias { alias.code(&text, tabs: tabs) } text.append("\(self.name) ") if self.arguments.count > 0 { text.append("(") for arg in self.arguments { arg.code(&text, tabs: tabs) } text.append(") ") } for directive in self.directives { directive.code(&text, tabs: tabs) } if let selectionSet = self.selectionSet { selectionSet.code(&text, tabs: tabs) } } } extension FragmentName: CodeType { func code(inout text: [String], tabs: Int) { text.append(self.name) text.append(" ") } } extension FragmentSpread: CodeType { func code(inout text: [String], tabs: Int) { text.append("... ") self.fragmentName.code(&text, tabs: tabs) for directive in self.directives { directive.code(&text, tabs: tabs) } } } extension InlineFragment: CodeType { func code(inout text: [String], tabs: Int) { text.append("... ") if let typeCondition = self.typeCondition { typeCondition.code(&text, tabs: tabs) } for directive in self.directives { directive.code(&text, tabs: tabs) } self.selectionSet.code(&text, tabs: tabs) } } extension Selection: CodeType { func code(inout text: [String], tabs: Int) { switch self { case let .Field_(field): field.code(&text, tabs: tabs) case let .FragmentSpread_(fragmentSpread): fragmentSpread.code(&text, tabs: tabs) case let .InlineFragment_(inlineFragment): inlineFragment.code(&text, tabs: tabs) } } } extension SelectionSet: CodeType { func code(inout text: [String], tabs: Int) { text.append("{\n") for selection in self.selections { text.append(indent(tabs + 1)) selection.code(&text, tabs: tabs + 1) text.append("\n") } text.append(indent(tabs) + "}") } } extension FragmentDefinition: CodeType { func code(inout text: [String], tabs: Int) { self.fragmentName.code(&text, tabs: tabs) self.typeCondition.code(&text, tabs: tabs) for directive in self.directives { directive.code(&text, tabs: tabs) } self.selectionSet.code(&text, tabs: tabs) } } extension OperationType: CodeType { func code(inout text: [String], tabs: Int) { text.append(self.rawValue + " ") } } extension NamedType: CodeType { func code(inout text: [String], tabs: Int) { text.append(name) text.append(" ") } } extension ListType: CodeType { func code(inout text: [String], tabs: Int) { text.append("[") type.code(&text, tabs: tabs) text.append("]") } } extension Type: CodeType { func code(inout text: [String], tabs: Int) { switch self.type { case let .Left(namedType): namedType.code(&text, tabs: tabs) case let .Right(listType): listType.code(&text, tabs: tabs) } if self.isNonNull { text.append("!") } } } extension DefaultValue: CodeType { func code(inout text: [String], tabs: Int) { text.append("= ") self.value.code(&text, tabs: tabs) } } extension VariableDefinition: CodeType { func code(inout text: [String], tabs: Int) { self.variable.code(&text, tabs: tabs) text.append(": ") self.type.code(&text, tabs: tabs) if let defaultValue = self.defaultValue { defaultValue.code(&text, tabs: tabs) } } } extension OperationDefinition: CodeType { func code(inout text: [String], tabs: Int) { self.operationType.code(&text, tabs: tabs) if let name = self.name { text.append("\(name) ") } if self.variableDefinitions.count > 0 { text.append("(") for variableDefinition in self.variableDefinitions { variableDefinition.code(&text, tabs: tabs) text.append(", ") } text.append(") ") } for directive in self.directives { directive.code(&text, tabs: tabs) } self.selectionSet.code(&text, tabs: tabs) } } extension Definition: CodeType { func code(inout text: [String], tabs: Int) { switch self { case let .Fragment_(fragment): fragment.code(&text, tabs: tabs) case let .Operation_(operation): operation.code(&text, tabs: tabs) case let .SelectionSet_(selectionSet): selectionSet.code(&text, tabs: tabs) } } } extension Document: CodeType { func code(inout text: [String], tabs: Int) { for definition in self.definitions { definition.code(&text, tabs: tabs) text.append("\n") } } }
26.148734
64
0.547743
ef0a1dd7354db7f250db7cc36aa4618cac612434
3,863
// // SeparatorView.swift // Storefront // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. 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 class SeparatorView: UIView { enum Position: Int { case top = 0 case left = 1 case bottom = 2 case right = 3 } @IBInspectable dynamic private var separatorPosition: Int = 0 { willSet(positionValue) { self.position = Position(rawValue: positionValue)! } } var position: Position = .top { didSet { guard let superview = self.superview else { return } self.updateFrameIn(superview) self.updateAutoresizeMask() } } // ---------------------------------- // MARK: - Init - // init(position: Position) { self.position = position super.init(frame: .zero) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // ---------------------------------- // MARK: - Superview - // override func willMove(toSuperview newSuperview: UIView?) { if let superview = newSuperview { self.updateFrameIn(superview) self.updateAutoresizeMask() } } // ---------------------------------- // MARK: - Updates - // private func updateFrameIn(_ superview: UIView) { let length = 1.0 / UIScreen.main.scale var frame = superview.bounds switch self.position { case .top: frame.size.height = length frame.size.width = superview.bounds.width case .bottom: frame.size.height = length frame.size.width = superview.bounds.width frame.origin.y = superview.bounds.height - length case .left: frame.size.height = superview.bounds.height frame.size.width = length frame.origin.y = superview.bounds.height - length case .right: frame.size.height = superview.bounds.height frame.size.width = length frame.origin.x = superview.bounds.width - length } self.frame = frame } private func updateAutoresizeMask() { switch self.position { case .top: self.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin] case .left: self.autoresizingMask = [.flexibleHeight, .flexibleRightMargin] case .bottom: self.autoresizingMask = [.flexibleWidth, .flexibleTopMargin] case .right: self.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin] } } }
32.191667
81
0.59125
6aa34aefe474755f3ace9373dc20e2d72546c2e1
1,490
// // DramaSectionReactor.swift // SwiftBilibili // // Created by 罗文 on 2018/3/17. // Copyright © 2018年 罗文. All rights reserved. // import UIKit import SectionReactor import RxSwift import Dollar final class DramaSectionReactor: SectionReactor { enum SectionItem { case vertical(DramaVerticalCellReactor) case edit(DramaEditCellReactor) } enum Action {} enum Mutation {} struct State: SectionReactorState { var sectionItems: [SectionItem] } let initialState: State init(moduleModel:DramaModuleModel) { defer { _ = self.state } var sectionItems: [SectionItem] = [] let resultItems = Dollar.chunk(moduleModel.items, size: 3)[0] if let headers = moduleModel.headers,!headers.isEmpty { for i in 0..<resultItems.count { var model = moduleModel.items[i] model.position = DramaVerticalPosition(rawValue: i)! sectionItems.append(.vertical(DramaVerticalCellReactor(recommend: model))) } }else{ sectionItems = resultItems.map{.edit(DramaEditCellReactor(foot: $0))} } self.initialState = State(sectionItems: sectionItems) } func mutate(action: Action) -> Observable<Mutation> { return .empty() } func reduce(state: State, mutation: Mutation) -> State { return state } }
23.650794
90
0.597987
22965684d2ef1a291e1e8d724fd5b2398368cad1
6,995
// Validation.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // 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 Foundation extension Request { /** Used to represent whether validation was successful or encountered an error resulting in a failure. - Success: The validation was successful. - Failure: The validation failed encountering the provided error. */ public enum ValidationResult { case Success case Failure(NSError) } /** A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid. */ public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult /** Validates the request, using the specified closure. If validation fails, subsequent calls to response handlers will have an associated error. - parameter validation: A closure to validate the request. - returns: The request. */ public func validate(validation: Validation) -> Self { delegate.queue.addOperationWithBlock { if let response = self.response where self.delegate.error == nil, case let .Failure(error) = validation(self.request, response) { self.delegate.error = error } } return self } // MARK: - Status Code /** Validates that the response has a status code in the specified range. If validation fails, subsequent calls to response handlers will have an associated error. - parameter range: The range of acceptable status codes. - returns: The request. */ public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self { return validate { _, response in if acceptableStatusCode.contains(response.statusCode) { return .Success } else { let failureReason = "Response status code was unacceptable: \(response.statusCode)" return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason)) } } } // MARK: - Content-Type private struct MIMEType { let type: String let subtype: String init?(_ string: String) { let components: [String] = { let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) let split = stripped.substringToIndex(stripped.rangeOfString(";")?.endIndex ?? stripped.endIndex) return split.componentsSeparatedByString("/") }() if let type = components.first, subtype = components.last { self.type = type self.subtype = subtype } else { return nil } } func matches(MIME: MIMEType) -> Bool { switch (type, subtype) { case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"): return true default: return false } } } /** Validates that the response has a content type in the specified array. If validation fails, subsequent calls to response handlers will have an associated error. - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. - returns: The request. */ public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self { return validate { _, response in if let responseContentType = response.MIMEType, responseMIMEType = MIMEType(responseContentType) { for contentType in acceptableContentTypes { if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) { return .Success } } } else { for contentType in acceptableContentTypes { if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" { return .Success } } } let failureReason: String if let responseContentType = response.MIMEType { failureReason = ( "Response content type \"\(responseContentType)\" does not match any acceptable " + "content types: \(acceptableContentTypes)" ) } else { failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" } return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason)) } } // MARK: - Automatic /** Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field. If validation fails, subsequent calls to response handlers will have an associated error. - returns: The request. */ public func validate() -> Self { let acceptableStatusCodes: Range<Int> = 200..<300 let acceptableContentTypes: [String] = { if let accept = request?.valueForHTTPHeaderField("Accept") { return accept.componentsSeparatedByString(",") } return ["*/*"] }() return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes) } }
37.207447
127
0.617298
dbc998fba840753b15ba753f9b4a1718e7a851bf
1,311
// // GalleryViewModel.swift // CollectionViewPagingLayout // // Created by Optmega on 12/27/19. // Copyright © 2019 Optmega. All rights reserved. // import Foundation class GalleryViewModel { // MARK: Properties var itemViewModels: [PhotoCellViewModel] = [] private let photos: [Photo] = [ Photo(imageName: "galleryImage07", title: "Oksana", authorName: "Dmitry Simakovichr"), Photo(imageName: "galleryImage03", title: "Christmas", authorName: "Lukáš Kuda"), Photo(imageName: "galleryImage08", title: "Touch You", authorName: "Dmitry Simakovichr"), Photo(imageName: "galleryImage02", title: "Above the Fjord", authorName: "Wim Lassche"), Photo(imageName: "galleryImage01", title: "Milena", authorName: "Edith Laurent-Neuhauser"), Photo(imageName: "galleryImage05", title: "Portrait Anya", authorName: "Dmitry Simakovich"), Photo(imageName: "galleryImage04", title: "Almsee", authorName: "Michael Gruber"), Photo(imageName: "galleryImage06", title: "Piz Beverin", authorName: "Michael Mettier") ] // MARK: Lifecycle init() { itemViewModels = photos.map { PhotoCellViewModel(imageName: $0.imageName, title: $0.title, subtitle: "by " + $0.authorName) } } }
35.432432
105
0.652174
9c1b908fbac927bee42a630548049d5b6e258fef
1,765
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // import UIKit class ___FILEBASENAMEASIDENTIFIER___: ___VARIABLE_cocoaTouchSubclass___ { // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() setUI() } // MARK: - Public Property // MARK: - Private Property } // MARK: - UI extension ___FILEBASENAMEASIDENTIFIER___ { fileprivate func setUI() { } } // MARK: - Action extension ___FILEBASENAMEASIDENTIFIER___ { } // MARK: - Network extension ___FILEBASENAMEASIDENTIFIER___ { } // MARK: - Delegate Internal // MARK: - UICollectionViewDataSource extension ___FILEBASENAMEASIDENTIFIER___ { override func numberOfSections(in collectionView: UICollectionView) -> Int { return 0 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 0 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "", for: indexPath) // Configure the cell return cell } } // MARK: - UICollectionViewDelegate extension ___FILEBASENAMEASIDENTIFIER___ { override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { } } // MARK: - Delegate External // MARK: - // MARK: - Helper extension ___FILEBASENAMEASIDENTIFIER___ { } // MARK: - Other extension ___FILEBASENAMEASIDENTIFIER___ { } // MARK: - Public extension ___FILEBASENAMEASIDENTIFIER___ { }
19.395604
130
0.686686
4bfafcdfda5d1e54a2809026358b80d046ca9c1e
190
// // Board.swift // Set // // Created by Vladislav Tarasevich on 11/08/2019. // Copyright © 2019 Vladislav Tarasevich. All rights reserved. // struct Board { let cards: [Card] }
13.571429
63
0.647368
2fd66ef127c362b4969b5cb11e817d14827e479c
4,248
// // TelemetryManagerSpec.swift // ExponeaSDKTests // // Created by Panaxeo on 21/01/2020. // Copyright © 2020 Exponea. All rights reserved. // import Quick import Nimble @testable import ExponeaSDK final class TelemetryManagerSpec: QuickSpec { var storage: MockTelemetryStorage! var upload: MockTelemetryUpload! var manager: TelemetryManager! override func spec() { beforeEach { self.storage = MockTelemetryStorage() self.upload = MockTelemetryUpload() self.manager = TelemetryManager( userDefaults: MockUserDefaults(), userId: nil, storage: self.storage, upload: self.upload ) } it("should report exception") { self.manager.report( exception: NSException( name: NSExceptionName(rawValue: "name of test exception"), reason: "reason for test exception", userInfo: nil ) ) expect(self.upload.uploadedCrashLogs.count).to(equal(1)) expect(self.upload.uploadedCrashLogs[0].isFatal).to(equal(false)) expect(self.upload.uploadedCrashLogs[0].errorData.type).to(equal("name of test exception")) expect(self.upload.uploadedCrashLogs[0].errorData.message).to(equal("reason for test exception")) } it("should report sdk/swift error") { self.manager.report( error: DatabaseManagerError.objectDoesNotExist, stackTrace: ["something", "something else"] ) expect(self.upload.uploadedCrashLogs.count).to(equal(1)) expect(self.upload.uploadedCrashLogs[0].isFatal).to(equal(false)) expect(self.upload.uploadedCrashLogs[0].errorData.type).to(equal("DatabaseManagerError")) expect(self.upload.uploadedCrashLogs[0].errorData.message) .to(equal("ExponeaSDK.DatabaseManagerError:4 Object does not exist.")) expect(self.upload.uploadedCrashLogs[0].errorData.stackTrace).to(equal(["something", "something else"])) } it("should report NSError") { self.manager.report( error: NSError( domain: "custom domain", code: 123, userInfo: [NSLocalizedDescriptionKey: "localized error"] ), stackTrace: ["something", "something else"] ) expect(self.upload.uploadedCrashLogs.count).to(equal(1)) expect(self.upload.uploadedCrashLogs[0].isFatal).to(equal(false)) expect(self.upload.uploadedCrashLogs[0].errorData.type).to(equal("NSError")) expect(self.upload.uploadedCrashLogs[0].errorData.message) .to(equal("custom domain:123 localized error")) expect(self.upload.uploadedCrashLogs[0].errorData.stackTrace).to(equal(["something", "something else"])) } it("should report event") { self.manager.report( eventWithType: .fetchRecommendation, properties: ["property": "value", "other_property": "other_value"] ) expect(self.upload.uploadedEvents.count).to(equal(1)) expect(self.upload.uploadedEvents[0].name).to(equal("fetchRecommendation")) expect(self.upload.uploadedEvents[0].properties) .to(equal([ "appVersion": "", "appName": "com.apple.dt.xctest.tool", "sdkVersion": TelemetryUtility.sdkVersion, "appNameVersionSdkVersion": "com.apple.dt.xctest.tool - - SDK \(TelemetryUtility.sdkVersion)", "appNameVersion": "com.apple.dt.xctest.tool - ", "property": "value", "other_property": "other_value" ])) } it("should report init event") { self.manager.report(initEventWithConfiguration: Configuration(projectToken: "token")) expect(self.upload.uploadedEvents.count).to(equal(1)) expect(self.upload.uploadedEvents[0].name).to(equal("init")) } } }
42.48
116
0.585217
f9e668ca9d5ee46882544e06e706f9db946be949
900
// // snJsonTests.swift // snJsonTests // // Created by Marc Fiedler on 09/07/15. // Copyright (c) 2015 snakeNet.org. All rights reserved. // import UIKit import XCTest class snJsonTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
24.324324
111
0.613333
262a8793ac3d2abb283778ac5ce37c4c61b0ddaf
1,428
// // ViewController.swift // FRNOPOD // // Created by Sharetrip-iOS on 14/07/2021. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() super.viewDidLoad() let button = UIButton(type: .roundedRect) button.frame = CGRect(x: 20, y: 50, width: 100, height: 30) button.setTitle("SceondVC", for: []) button.addTarget(self, action: #selector(self.crashButtonTapped(_:)), for: .touchUpInside) view.addSubview(button) Crashlytics.crashlytics().log("Second project Controller") Crashlytics.crashlytics().setCustomValue(13037, forKey: "ID") Crashlytics.crashlytics().setUserID("124802") let userInfo = [ NSLocalizedDescriptionKey: NSLocalizedString("The request failed", comment: ""), "ProductID": "0001", "UserID": "Arif Parvez" ] let error = NSError(domain: NSURLErrorDomain, code: -1001, userInfo: userInfo) Crashlytics.crashlytics().record(error: error) } @IBAction func crashButtonTapped(_ sender: AnyObject) { let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let nextViewController = storyBoard.instantiateViewController(withIdentifier: "ThirdVC") as! ThirdVC self.present(nextViewController, animated:true, completion:nil) } }
34
108
0.645658
fcb0e75eb14ed8a5b56754d5344febc0a27bed5e
9,731
@testable import Sentry import XCTest class SentrySystemEventsBreadcrumbsTest: XCTestCase { // This feature only works on iOS #if os(iOS) private class Fixture { func getSut(scope: Scope, currentDevice: UIDevice? = UIDevice.current) -> SentrySystemEventsBreadcrumbs { do { let options = try Options(dict: ["dsn": "https://[email protected]/1"]) let client = Client(options: options) let hub = SentryHub(client: client, andScope: scope) SentrySDK.setCurrentHub(hub) } catch { XCTFail("Failed to setup test") } let systemEvents = SentrySystemEventsBreadcrumbs() systemEvents.start(currentDevice) return systemEvents } } private let fixture = Fixture() private var sut: SentrySystemEventsBreadcrumbs! internal class MyUIDevice: UIDevice { private var _batteryLevel: Float private var _batteryState: UIDevice.BatteryState private var _orientation: UIDeviceOrientation init(batteryLevel: Float = 1, batteryState: UIDevice.BatteryState = UIDevice.BatteryState.charging, orientation: UIDeviceOrientation = UIDeviceOrientation.portrait) { self._batteryLevel = batteryLevel self._batteryState = batteryState self._orientation = orientation } override var batteryLevel: Float { return _batteryLevel } override var batteryState: UIDevice.BatteryState { return _batteryState } override var orientation: UIDeviceOrientation { return _orientation } } func testBatteryLevelBreadcrumb() { let currentDevice = MyUIDevice(batteryLevel: 0.56, batteryState: UIDevice.BatteryState.full) let scope = Scope() sut = fixture.getSut(scope: scope, currentDevice: currentDevice) NotificationCenter.default.post(Notification(name: UIDevice.batteryLevelDidChangeNotification, object: currentDevice)) assertBatteryBreadcrumb(scope: scope, charging: true, level: 56) } func testBatteryUnknownLevelBreadcrumb() { let currentDevice = MyUIDevice(batteryLevel: -1, batteryState: UIDevice.BatteryState.unknown) let scope = Scope() sut = fixture.getSut(scope: scope, currentDevice: currentDevice) NotificationCenter.default.post(Notification(name: UIDevice.batteryLevelDidChangeNotification, object: currentDevice)) assertBatteryBreadcrumb(scope: scope, charging: false, level: -1) } func testBatteryNotUnknownButNoLevelBreadcrumb() { let currentDevice = MyUIDevice(batteryLevel: -1, batteryState: UIDevice.BatteryState.full) let scope = Scope() sut = fixture.getSut(scope: scope, currentDevice: currentDevice) NotificationCenter.default.post(Notification(name: UIDevice.batteryLevelDidChangeNotification, object: currentDevice)) assertBatteryBreadcrumb(scope: scope, charging: true, level: -1) } func testBatteryChargingStateBreadcrumb() { let currentDevice = MyUIDevice() let scope = Scope() sut = fixture.getSut(scope: scope, currentDevice: currentDevice) NotificationCenter.default.post(Notification(name: UIDevice.batteryStateDidChangeNotification, object: currentDevice)) assertBatteryBreadcrumb(scope: scope, charging: true, level: 100) } func testBatteryNotChargingStateBreadcrumb() { let currentDevice = MyUIDevice(batteryState: UIDevice.BatteryState.unplugged) let scope = Scope() sut = fixture.getSut(scope: scope, currentDevice: currentDevice) NotificationCenter.default.post(Notification(name: UIDevice.batteryStateDidChangeNotification, object: currentDevice)) assertBatteryBreadcrumb(scope: scope, charging: false, level: 100) } private func assertBatteryBreadcrumb(scope: Scope, charging: Bool, level: Float) { let ser = scope.serialize() XCTAssertNotNil(ser["breadcrumbs"] as? [[String: Any]], "no scope.breadcrumbs") if let breadcrumbs = ser["breadcrumbs"] as? [[String: Any]] { XCTAssertNotNil(breadcrumbs.first, "scope.breadcrumbs is empty") if let crumb = breadcrumbs.first { XCTAssertEqual("device.event", crumb["category"] as? String) XCTAssertEqual("system", crumb["type"] as? String) XCTAssertEqual("info", crumb["level"] as? String) XCTAssertNotNil(crumb["data"] as? [String: Any], "no breadcrumb.data") if let data = crumb["data"] as? [String: Any] { XCTAssertEqual("BATTERY_STATE_CHANGE", data["action"] as? String) XCTAssertEqual(charging, data["plugged"] as? Bool) // -1 = unknown if level == -1 { XCTAssertNil(data["level"]) } else { XCTAssertEqual(level, data["level"] as? Float) } } } } } func testPortraitOrientationBreadcrumb() { let currentDevice = MyUIDevice() let scope = Scope() sut = fixture.getSut(scope: scope, currentDevice: currentDevice) NotificationCenter.default.post(Notification(name: UIDevice.orientationDidChangeNotification, object: currentDevice)) assertPositionOrientationBreadcrumb(position: "portrait", scope: scope) } func testLandscapeOrientationBreadcrumb() { let currentDevice = MyUIDevice(orientation: UIDeviceOrientation.landscapeLeft) let scope = Scope() sut = fixture.getSut(scope: scope, currentDevice: currentDevice) NotificationCenter.default.post(Notification(name: UIDevice.orientationDidChangeNotification, object: currentDevice)) assertPositionOrientationBreadcrumb(position: "landscape", scope: scope) } func testUnknownOrientationBreadcrumb() { let currentDevice = MyUIDevice(orientation: UIDeviceOrientation.unknown) let scope = Scope() sut = fixture.getSut(scope: scope, currentDevice: currentDevice) NotificationCenter.default.post(Notification(name: UIDevice.orientationDidChangeNotification, object: currentDevice)) let ser = scope.serialize() XCTAssertNil(ser["breadcrumbs"], "there are breadcrumbs") } private func assertPositionOrientationBreadcrumb(position: String, scope: Scope) { let ser = scope.serialize() XCTAssertNotNil(ser["breadcrumbs"] as? [[String: Any]], "no scope.breadcrumbs") if let breadcrumbs = ser["breadcrumbs"] as? [[String: Any]] { XCTAssertNotNil(breadcrumbs.first, "scope.breadcrumbs is empty") if let crumb = breadcrumbs.first { XCTAssertEqual("device.orientation", crumb["category"] as? String) XCTAssertEqual("navigation", crumb["type"] as? String) XCTAssertEqual("info", crumb["level"] as? String) XCTAssertNotNil(crumb["data"] as? [String: Any], "no breadcrumb.data") if let data = crumb["data"] as? [String: Any] { XCTAssertEqual(position, data["position"] as? String) } } } } func testShownKeyboardBreadcrumb() { let scope = Scope() sut = fixture.getSut(scope: scope, currentDevice: nil) NotificationCenter.default.post(Notification(name: UIWindow.keyboardDidShowNotification)) assertBreadcrumbAction(scope: scope, action: "UIKeyboardDidShowNotification") } func testHiddenKeyboardBreadcrumb() { let scope = Scope() sut = fixture.getSut(scope: scope, currentDevice: nil) NotificationCenter.default.post(Notification(name: UIWindow.keyboardDidHideNotification)) assertBreadcrumbAction(scope: scope, action: "UIKeyboardDidHideNotification") } func testScreenshotBreadcrumb() { let scope = Scope() sut = fixture.getSut(scope: scope, currentDevice: nil) NotificationCenter.default.post(Notification(name: UIApplication.userDidTakeScreenshotNotification)) assertBreadcrumbAction(scope: scope, action: "UIApplicationUserDidTakeScreenshotNotification") } private func assertBreadcrumbAction(scope: Scope, action: String) { let ser = scope.serialize() if let breadcrumbs = ser["breadcrumbs"] as? [[String: Any]] { if let crumb = breadcrumbs.first { XCTAssertEqual("device.event", crumb["category"] as? String) XCTAssertEqual("system", crumb["type"] as? String) XCTAssertEqual("info", crumb["level"] as? String) if let data = crumb["data"] as? [String: Any] { XCTAssertEqual(action, data["action"] as? String) } else { XCTFail("no breadcrumb.data") } } else { XCTFail("scope.breadcrumbs is empty") } } else { XCTFail("no scope.breadcrumbs") } } #endif }
40.545833
174
0.613709
f7e9f4213df13d6794450b9910b1d8bce1b988c7
272
// // CityCoordinates.swift // iOS Labs // // Created by Андрей Исаев on 12.10.2021. // import Foundation struct CityCoords { let lat: Double let lon: Double init(_ lat: Double, _ lon: Double) { self.lat = lat self.lon = lon } }
13.6
42
0.577206
336c88dbc05fb82c40797dc3b07de8ce4834608d
4,833
// // LCActivityController.swift // JXLiCai // // Created by dengtao on 2017/6/27. // Copyright © 2017年 JingXian. All rights reserved. // import UIKit let cycleHeight = 520 * width / 1080.0 class LCActivityController: XTViewController { var tableView:UITableView! var cycleScrollView:CycleScrollView? var dataArray = NSMutableArray() override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) cycleScrollView?.timer?.invalidate() cycleScrollView?.timer = nil } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if (cycleScrollView != nil) { cycleScrollView!.reloadData() } } override func viewDidLoad() { super.viewDidLoad() self.title = "活动列表"; self.hiddenLeftButtonItem(); self .configDataSource(); self.automaticallyAdjustsScrollViewInsets = false; tableView = UITableView.init(frame: CGRect(x:0,y:64,width:width,height:height - 64 - 49), style:UITableViewStyle.grouped); tableView.delegate = self; tableView.dataSource = self; self.view.addSubview(tableView); } func configDataSource() { dataArray .add("") dataArray .add("") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension LCActivityController: CycleScrollViewDelegate,UITableViewDelegate, UITableViewDataSource { /// 点击图片事件 func cycleScrollViewDidSelect(at index:Int, cycleScrollView:CycleScrollView) { print("点击了第\(index+1)个图片") } /// 图片滚动事件 func cycleScrollViewDidScroll(to index:Int, cycleScrollView:CycleScrollView) { print("滚动到了第\(index+1)个图片") } // func numberOfSections(in tableView: UITableView) -> Int { // return 1;//dataArray.count // } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 195 + width / 3; } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return cycleHeight; } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.1; } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIImageView.init(frame: CGRect(x:0,y:0,width:width,height:cycleHeight)) headerView.backgroundColor = UIColor.groupTableViewBackground; let frame = CGRect(x: 0, y: 0, width: width, height: cycleHeight) let serverImages = ["http://p.lrlz.com/data/upload/mobile/special/s252/s252_05471521705899113.png", "http://p.lrlz.com/data/upload/mobile/special/s303/s303_05442007678060723.png", "http://p.lrlz.com/data/upload/mobile/special/s303/s303_05442007587372591.png", "http://p.lrlz.com/data/upload/mobile/special/s303/s303_05442007388249407.png", "http://p.lrlz.com/data/upload/mobile/special/s303/s303_05442007470310935.png"] cycleScrollView = CycleScrollView(frame: frame, type: .SERVICE, imgs: serverImages) cycleScrollView?.delegate = self headerView.addSubview(cycleScrollView!) return headerView; } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let footerView = UIView.init(frame: CGRect(x:0,y:0,width:width,height:0.1)) footerView.backgroundColor = UIColor.groupTableViewBackground; return footerView } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellId: String = "cellId" var cell: ActivityListCell? = tableView.dequeueReusableCell(withIdentifier: cellId) as? ActivityListCell if cell == nil { cell = ActivityListCell (style: UITableViewCellStyle.default, reuseIdentifier: cellId) cell?.selectionStyle = UITableViewCellSelectionStyle.none } cell?.configDataWithModel(model: ["1":"2"]) return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView .deselectRow(at: indexPath, animated: true); let detailVC = LCActivityDetailController() self.navigationController!.pushViewController(detailVC, animated: true) NSLog("选择:\(title)") } }
32.655405
130
0.642458
39a0128f668eaeb5a08819ab70415f69af36021c
8,586
// // StockDealInfoView.swift // VDStockChartDemo // // Created by Harwyn T'an on 2018/5/30. // Copyright © 2018年 vvard3n. All rights reserved. // import UIKit class StockDealInfoView: UIView { private var labels = [UILabel]() var sharesPerHand: Int = 100 var data: StockDealInfoViewModel? = nil { didSet { guard let data = data else { return } for i in 0..<10 { // let labelLeft = labels[i * 3] let labelCenter = labels[i * 3 + 1] let labelRight = labels[i * 3 + 2] if i < 5 { var color: UIColor = ThemeColor.CONTENT_TEXT_COLOR_555555 if Double(data.offerGroup[i % 5].price) ?? 0 > data.closePrice { color = ThemeColor.MAIN_COLOR_E63130 } else if Double(data.offerGroup[i % 5].price) ?? 0 < data.closePrice { color = ThemeColor.STOCK_DOWN_GREEN_COLOR_0EAE4E } var centerText = NSAttributedString(string: String(format: " %@", data.offerGroup[i % 5].price), attributes: [.foregroundColor:color, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)]) let amount = data.offerGroup[i % 5].amount / Double(sharesPerHand) var amountStr = "" if amount >= 10000 && amount < 100000000 { amountStr = String(format: "%.2f万", amount / 10000) } else if amount >= 100000000 && amount < 1000000000000 { amountStr = String(format: "%.2f亿", amount / 100000000) } else if amount >= 1000000000000 { amountStr = String(format: "%.2f万亿", amount / 1000000000000) } else { amountStr = String(format: "%.0f", amount) } var rightText = NSAttributedString(string: String(format: "%@", amountStr), attributes: [.foregroundColor:ThemeColor.CONTENT_TEXT_COLOR_555555, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)]) if data.offerGroup[i % 5].price == "0.00" && data.offerGroup[i % 5].amount == 0 { centerText = NSAttributedString(string: " --", attributes: [.foregroundColor:ThemeColor.CONTENT_TEXT_COLOR_555555, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)]) rightText = NSAttributedString(string: "--", attributes: [.foregroundColor:ThemeColor.CONTENT_TEXT_COLOR_555555, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)]) } labelCenter.attributedText = centerText labelRight.attributedText = rightText } else { var color: UIColor = ThemeColor.CONTENT_TEXT_COLOR_555555 if Double(data.bigGroup[i % 5].price) ?? 0 > data.closePrice { color = ThemeColor.MAIN_COLOR_E63130 } else if Double(data.bigGroup[i % 5].price) ?? 0 < data.closePrice { color = ThemeColor.STOCK_DOWN_GREEN_COLOR_0EAE4E } var centerText = NSAttributedString(string: String(format: " %@", data.bigGroup[i % 5].price), attributes: [.foregroundColor:color, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)]) let amount = data.bigGroup[i % 5].amount / Double(sharesPerHand) var amountStr = "" if amount >= 10000 && amount < 100000000 { amountStr = String(format: "%.2f万", amount / 10000) } else if amount >= 100000000 && amount < 1000000000000 { amountStr = String(format: "%.2f亿", amount / 100000000) } else if amount >= 1000000000000 { amountStr = String(format: "%.2f万亿", amount / 1000000000000) } else { amountStr = String(format: "%.0f", amount) } var rightText = NSAttributedString(string: String(format: "%@", amountStr), attributes: [.foregroundColor:ThemeColor.CONTENT_TEXT_COLOR_555555, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)]) if data.bigGroup[i % 5].price == "0.00" && data.bigGroup[i % 5].amount == 0 { centerText = NSAttributedString(string: " --", attributes: [.foregroundColor:ThemeColor.CONTENT_TEXT_COLOR_555555, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)]) rightText = NSAttributedString(string: "--", attributes: [.foregroundColor:ThemeColor.CONTENT_TEXT_COLOR_555555, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)]) } labelCenter.attributedText = centerText labelRight.attributedText = rightText } } } } override init(frame: CGRect) { super.init(frame: frame) let centerText = NSAttributedString(string: " --", attributes: [.foregroundColor:ThemeColor.CONTENT_TEXT_COLOR_555555, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)]) let rightText = NSAttributedString(string: "--", attributes: [.foregroundColor:ThemeColor.CONTENT_TEXT_COLOR_555555, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)]) for i in 0..<10 { let leftText = NSMutableAttributedString() if i < 5 { leftText.append(NSAttributedString(string: "卖", attributes: [.foregroundColor:ThemeColor.CONTENT_TEXT_COLOR_555555, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)])) leftText.append(NSAttributedString(string: "\(5 - i)", attributes: [.foregroundColor:ThemeColor.CONTENT_TEXT_COLOR_555555, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)])) } else { leftText.append(NSAttributedString(string: "买", attributes: [.foregroundColor:ThemeColor.CONTENT_TEXT_COLOR_555555, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)])) leftText.append(NSAttributedString(string: "\(i - 5 + 1)", attributes: [.foregroundColor:ThemeColor.CONTENT_TEXT_COLOR_555555, .font:UIFont(name: "DIN Alternate", size: 12) ?? UIFont.systemFont(ofSize: 12)])) } let labelLeft = UILabel() labelLeft.attributedText = leftText labelLeft.textAlignment = .left labels.append(labelLeft) addSubview(labelLeft) let labelCenter = UILabel() labelCenter.attributedText = centerText labelCenter.textAlignment = .left labelCenter.tag = i labels.append(labelCenter) addSubview(labelCenter) let labelRight = UILabel() labelRight.attributedText = rightText labelRight.textAlignment = .right labels.append(labelRight) addSubview(labelRight) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let itemHeight = frame.height / 10 subviews.enumerated().forEach { (index, label) in guard let label : UILabel = label as? UILabel else { return } label.frame = CGRect(x: 5, y: CGFloat(index / 3) * itemHeight, width: frame.width - 5 * 2, height: itemHeight) } } } public class StockDealInfoViewModel: NSObject { public var closePrice: Double = 0 public var offerGroup: [StockDealInfoViewItemModel] = [] public var bigGroup: [StockDealInfoViewItemModel] = [] } public class StockDealInfoViewItemModel: NSObject { public var price: String = "0.00" public var amount: Double = 0 }
54.687898
244
0.559981
f868c8e90fc7c62e318ba3e28665066aaf6b494b
158
// // Created by Jakob Grumsen. // Copyright © 2018 Grumsen Development ApS. All rights reserved. // import UIKit @objc protocol LoginRouterProtocol { }
14.363636
66
0.721519
d7c25eaa06f5ff31999bcc6bdf9dcf811a687fdd
1,619
//===--------------- BuildModulesFromGraph.swift --------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation let fileName = CommandLine.arguments[1] let swiftPath = CommandLine.arguments[2] let moduleName = CommandLine.arguments[3] let data = try! Data(contentsOf: URL(fileURLWithPath: fileName)) let decoder = JSONDecoder() let moduleDependencyGraph = try! decoder.decode( ModuleDependencyGraph.self, from: data) func findModuleBuildingCommand(_ moduleName: String) -> [String]? { for (_, dep) in moduleDependencyGraph.modules { if URL(fileURLWithPath: dep.modulePath).lastPathComponent == moduleName { switch dep.details { case .swift(let details): return details.commandLine case .clang(let details): return details.commandLine } } else { continue } } return nil } if let command = findModuleBuildingCommand(moduleName) { var result = swiftPath command.forEach { result += " \($0)"} // Pass down additional args to the Swift invocation. CommandLine.arguments.dropFirst(4).forEach { result += " \($0)"} print(result) exit(0) } else { fatalError("cannot find module building commands for \(moduleName)") }
33.040816
80
0.660902
23be83e25374e3855c7912f8e4f25a968536e570
1,158
// https://github.com/Quick/Quick import Quick import Nimble import LocationViewer class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
22.705882
60
0.360104
1633c69cef9691a452116549a541946a79329bc9
3,716
// // SettingsView.swift // Fructus // // Created by Mahdi Mahjoobi on 8/29/21. // import SwiftUI struct SettingsView: View { // MARK: - PROPERTIES @Environment(\.presentationMode) var presentationMode @AppStorage("isOnboarding") var isOnboarding: Bool = false // MARK: - BODY var body: some View { NavigationView { ScrollView(.vertical, showsIndicators: false) { VStack(spacing: 20) { // MARK: - SECTION 1 GroupBox( label: SettingsLabelView(labelText: "Fructus", labelImage: "info.circle") ) { Divider().padding(.vertical, 4) HStack(alignment: .center, spacing: 10) { Image("logo") .resizable() .scaledToFit() .frame(width: 80, height: 80) .cornerRadius(9) Text("Most fruits are naturally low in fat, sodium, and calories. None have cholesterol. Fruits are sources of many essential nutrients, including potassium, dietary fiber, vitamins, and much more.") .font(.footnote) } } // MARK: - SECTION 2 GroupBox( label: SettingsLabelView(labelText: "Customization", labelImage: "paintbrush") ) { Divider().padding(.vertical, 4) Text("If you wish, you can restart the application by toggle the switch in this box. That way it starts the onboarding process and you will see the welcome screen again.") .padding(.vertical, 8) .frame(minHeight: 60) .layoutPriority(1) .font(.footnote) .multilineTextAlignment(.leading) Toggle(isOn: $isOnboarding) { if isOnboarding { Text("Restarted".uppercased()) .fontWeight(.bold) .foregroundColor(Color.green) } else { Text("Restart".uppercased()) .fontWeight(.bold) .foregroundColor(Color.secondary) } } .padding() .background( Color(UIColor.tertiarySystemBackground) .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) ) } // MARK: - SECTION 3 GroupBox( label: SettingsLabelView(labelText: "Application", labelImage: "apps.iphone") ) { SettingsRowView(name: "Developer", content: "Mahdi Mahjoobi") SettingsRowView(name: "Designer", content: "Mahdi Mahjoobi") SettingsRowView(name: "Compatibility", content: "iOS 15") SettingsRowView(name: "Website", linkLabel: "NiliN", linkDestination: "nilin.co") SettingsRowView(name: "Twitter", linkLabel: "@mahdiuser", linkDestination: "twitter.com/mahdiuser") SettingsRowView(name: "SwiftUI", content: "3.0") SettingsRowView(name: "Version", content: "1.0.0") } } //: VSTACK .navigationBarTitle(Text("Settings"), displayMode: .large) .navigationBarItems( trailing: Button(action: { presentationMode.wrappedValue.dismiss() }) { Image(systemName: "xmark") } ) .padding() } //: SCROLL } //: NAVIGATION } } // MARK: - PREVIEW struct SettingsView_Previews: PreviewProvider { static var previews: some View { SettingsView() .preferredColorScheme(.dark) .previewDevice("iPhone 11 Pro") } }
32.596491
213
0.534984
1a9a1e584b707416a989f0d7f9d1b7b277025f21
464
// // UserDefaults+Extensions.swift // JIRA // // Created by Shalva Avanashvili on 31/12/2018. // Copyright © 2018 ashalva. All rights reserved. // import Foundation enum Settings: String { case jiraDomain } extension UserDefaults { func setJiraDomain(_ domain: String) { set(domain, forKey: Settings.jiraDomain.rawValue) } func jiraDomain() -> String { return string(forKey: Settings.jiraDomain.rawValue) ?? "" } }
19.333333
65
0.663793
6af3d854d1b1d529ccc399c25e57e90a21ea9e89
1,959
// // Copyright © 2020 osy. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import SwiftUI @available(iOS 14, macOS 11, *) struct VMConfigSharingView: View { @ObservedObject var config: UTMConfiguration var body: some View { VStack { Form { Section(header: Text("Clipboard Sharing"), footer: Text("Requires SPICE guest agent tools to be installed.").padding(.bottom)) { Toggle(isOn: $config.shareClipboardEnabled, label: { Text("Enable Clipboard Sharing") }) } Section(header: Text("Shared Directory"), footer: Text("Requires SPICE WebDAV service to be installed.").padding(.bottom)) { Toggle(isOn: $config.shareDirectoryEnabled.animation(), label: { Text("Enable Directory Sharing") }) Toggle(isOn: $config.shareDirectoryReadOnly, label: { Text("Read Only") }) Text("Note: select the path to share from the main screen.") } } } } } @available(iOS 14, macOS 11, *) struct VMConfigSharingView_Previews: PreviewProvider { @State static private var config = UTMConfiguration() static var previews: some View { VMConfigSharingView(config: config) } }
36.277778
144
0.602859
640c7bdd3cc7030d283b5a37b9505f4757f147ef
419
// // CDTemplate+Convenience.swift // PCG // // Created by Bobby Keffury on 7/3/21. // Copyright © 2021 Bobby Keffury. All rights reserved. // import Foundation import CoreData extension CDTemplate { convenience init(id: Int16, name: String, context: NSManagedObjectContext) { self.init(context: context) self.id = id self.name = name } }
19.952381
56
0.596659
1d6a86175c0334ef69834032a22d87861e3b94bd
425
// // main.swift // // Created by Jo Hyuk Jun on 2020. // Copyright © 2020 Jo Hyuk Jun. All rights reserved. // import Foundation func solution(_ seoul:[String]) -> String { var answer: String = "" var location: Int = 0 for s in seoul { if (s == "Kim") { answer += "김서방은 " + String(location) + "에 있다" } location += 1 } return answer }
15.740741
57
0.501176
fe00701af52f623c779a2fac7823bbe638600819
3,466
// // Copyright (c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation struct Restaurant { var name: String var category: String // Could become an enum var city: String var price: Int // from 1-3; could also be an enum var ratingCount: Int // numRatings var averageRating: Float var dictionary: [String: Any] { return [ "name": name, "category": category, "city": city, "price": price, "numRatings": ratingCount, "avgRating": averageRating, ] } } extension Restaurant: DocumentSerializable { static let cities = [ "Albuquerque", "Arlington", "Atlanta", "Austin", "Baltimore", "Boston", "Charlotte", "Chicago", "Cleveland", "Colorado Springs", "Columbus", "Dallas", "Denver", "Detroit", "El Paso", "Fort Worth", "Fresno", "Houston", "Indianapolis", "Jacksonville", "Kansas City", "Las Vegas", "Long Beach", "Los Angeles", "Louisville", "Memphis", "Mesa", "Miami", "Milwaukee", "Nashville", "New York", "Oakland", "Oklahoma", "Omaha", "Philadelphia", "Phoenix", "Portland", "Raleigh", "Sacramento", "San Antonio", "San Diego", "San Francisco", "San Jose", "Tucson", "Tulsa", "Virginia Beach", "Washington" ] static let categories = [ "Brunch", "Burgers", "Coffee", "Deli", "Dim Sum", "Indian", "Italian", "Mediterranean", "Mexican", "Pizza", "Ramen", "Sushi" ] init?(dictionary: [String : Any]) { guard let name = dictionary["name"] as? String, let category = dictionary["category"] as? String, let city = dictionary["city"] as? String, let price = dictionary["price"] as? Int, let ratingCount = dictionary["numRatings"] as? Int, let averageRating = dictionary["avgRating"] as? Float else { return nil } self.init(name: name, category: category, city: city, price: price, ratingCount: ratingCount, averageRating: averageRating) } } struct Review { var rating: Int // Can also be enum var userID: String var username: String var text: String var date: Date var dictionary: [String: Any] { return [ "rating": rating, "userId": userID, "userName": username, "text": text, "timestamp": date ] } } extension Review: DocumentSerializable { init?(dictionary: [String : Any]) { guard let rating = dictionary["rating"] as? Int, let userID = dictionary["userId"] as? String, let username = dictionary["userName"] as? String, let text = dictionary["text"] as? String, let date = dictionary["timestamp"] as? Date else { return nil } self.init(rating: rating, userID: userID, username: username, text: text, date: date) } }
23.261745
89
0.603578
897ce040a9fc0fcae5b7c30d13f766aca7351b4f
5,243
// // RequestChain.swift // Siesta // // Created by Paul on 2016/8/2. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Foundation extension Request { /** Gathers multiple requests into a **request chain**, a wrapper that appears from the outside to be a single request. You can use this to add behavior to a request in a way that is transparent to outside observers. For example, you can transparently renew expired tokens. - Note: This returns a new `Request`, and does not alter the original one (thus `chained` and not `chain`). Any hooks attached to the original request will still see that request complete, and will not see any of the chaining behavior. In this pseudocode: let chainedRequest = underlyingRequest.chained { response in …whenCompleted… } …the following things happen, in this order: - The chain waits for `underlyingRequest` to complete. - The response (no matter whether success or failure) gets passed to `whenCompleted`. - The `whenCompleted` closure examines that `response`, and returns a `RequestChainAction`. - If it returns `.useResponse` or `.useThisResponse`, the chain is now done, and any hooks attached to `chainedRequest` see that response. - If it returns `.passTo(newRequest)`, then the chain will wait for `newRequest` (which may itself be a chain), and yield whatever repsonse it produces. Calling `cancel()` on `chainedRequest` cancels the currently executing request and immediately stops the chain, never executing your `whenCompleted` closure. (Note, however, that calling `cancel()` on `underlyingRequest` does _not_ stop the chain; instead, the cancellation error is passed to your `whenCompleted` just like any other error.) - Warning: This cancellation behavior means that your `whenCompleted` closure may never execute. If you want guaranteed execution of cleanup code, attach a handler to the chained request: let foo = ThingThatNeedsCleanup() request .chained { …some logic… } // May not be called if chain is cancelled .onCompletion{ _ in foo.cleanUp() } // Guaranteed to be called exactly once Chained requests currently do not support progress. If you are reading these words and want that feature, please file an issue on Github! - SeeAlso: `Configuration.decorateRequests(...)` */ public func chained(whenCompleted callback: @escaping (ResponseInfo) -> RequestChainAction) -> Request { let chain = Resource.prepareRequest(using: RequestChainDelgate(wrapping: self, whenCompleted: callback)) if state != .notStarted { chain.start() } return chain } } /** The possible actions a chained request may take after the underlying request completes. - See: `Request.chained(...)` */ public enum RequestChainAction { /// The chain will wait for the given request, and its response will become the chain’s response. case passTo(Request) /// The chain will end immediately with the given response. case useResponse(ResponseInfo) /// The chain will end immediately, passing through the response of the underlying request that just completed. case useThisResponse } internal struct RequestChainDelgate: RequestDelegate { typealias ActionCallback = (ResponseInfo) -> RequestChainAction let requestDescription: String private let wrappedRequest: Request private let determineAction: ActionCallback init(wrapping request: Request, whenCompleted determineAction: @escaping ActionCallback) { self.wrappedRequest = request self.determineAction = determineAction requestDescription = "Chain[\(wrappedRequest)]" } func startUnderlyingOperation(passingResponseTo completionHandler: RequestCompletionHandler) { wrappedRequest.onCompletion { self.processResponse($0, completionHandler: completionHandler) } wrappedRequest.start() } func cancelUnderlyingOperation() { wrappedRequest.cancel() } func processResponse(_ responseInfo: ResponseInfo, completionHandler: RequestCompletionHandler) { guard !completionHandler.willIgnore(responseInfo) else { return } switch determineAction(responseInfo) { case .useThisResponse: completionHandler.broadcastResponse(responseInfo) case .useResponse(let customResponseInfo): completionHandler.broadcastResponse(customResponseInfo) case .passTo(let request): request.start() // Necessary if we are passing to deferred original request request.onCompletion { completionHandler.broadcastResponse($0) } } } // TODO: progress reporting func repeated() -> RequestDelegate { return RequestChainDelgate(wrapping: wrappedRequest.repeated(), whenCompleted: determineAction) } }
37.719424
126
0.675758
012094d0d4dbb652a6a465fa224e64fee989a790
1,215
import UIKit /// UIColor extension that generates a UIColor from the provided hex string public extension UIColor { public convenience init?(hex: String) { var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines) hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "") var rgb: UInt64 = 0 var r: CGFloat = 0.0 var g: CGFloat = 0.0 var b: CGFloat = 0.0 var a: CGFloat = 1.0 let length = hexSanitized.count guard Scanner(string: hexSanitized).scanHexInt64(&rgb) else { return nil } if length == 6 { r = CGFloat((rgb & 0xFF0000) >> 16) / 255.0 g = CGFloat((rgb & 0x00FF00) >> 8) / 255.0 b = CGFloat(rgb & 0x0000FF) / 255.0 } else if length == 8 { r = CGFloat((rgb & 0xFF000000) >> 24) / 255.0 g = CGFloat((rgb & 0x00FF0000) >> 16) / 255.0 b = CGFloat((rgb & 0x0000FF00) >> 8) / 255.0 a = CGFloat(rgb & 0x000000FF) / 255.0 } else { return nil } self.init(red: r, green: g, blue: b, alpha: a) } }
31.973684
82
0.51358
1d282ac506cbf04ea45cfd0ac16ca285462080dc
217
// // NetworkError.swift // KTBooks // // Created by pttem-ios on 28.09.2021. // import Foundation enum NetworkError: Error { case noData case invalidResponse case invalidUrl case invalidDecode }
13.5625
39
0.682028
4ae57f49394058c91ca0d68c3b9ba043a8f74d17
4,931
import UIKit public typealias ActionBlock = () -> () public func size(add: CGFloat) -> (UIFont?) -> UIFont? { return { guard let font = $0 else { return nil } return UIFont.init(descriptor: font.fontDescriptor, size: font.pointSize + add) } } public func left(_ value: CGFloat) -> (UIEdgeInsets) -> UIEdgeInsets { return { UIEdgeInsets.init(top: $0.top, left: value, bottom: $0.bottom, right: $0.right) } } public func add(_ point: CGPoint) -> (CGPoint) -> CGPoint { return { ( $0.x + point.x, $0.y + point.y ) |> CGPoint.init } } public func add(_ size: CGSize) -> (CGPoint) -> CGPoint { return { ( $0.x + size.width, $0.y + size.height ) |> CGPoint.init } } public func subtract(_ point: CGPoint) -> (CGPoint) -> CGPoint { return { ( $0.x - point.x, $0.y - point.y ) |> CGPoint.init } } public func subtract(_ size: CGSize) -> (CGSize) -> CGSize { return { ( $0.width - size.width, $0.height - size.height ) |> CGSize.init } } public func multiply(by scalar: CGFloat?) -> (CGSize) -> CGSize { return { ( $0.width * (scalar ?? 1), $0.height * (scalar ?? 1) ) |> CGSize.init } } public func floor() -> (CGPoint) -> CGPoint { return { ( floor($0.x), floor($0.y) ) |> CGPoint.init } } public func multiply(by size: CGSize?) -> (CGPoint) -> CGPoint { return { ( $0.x * (size?.width ?? 1), $0.y * (size?.height ?? 1) ) |> CGPoint.init } } public func multiply(by size: CGSize?) -> (CGSize) -> CGSize { return { ( $0.width * (size?.width ?? 1), $0.height * (size?.height ?? 1) ) |> CGSize.init } } public func multiplyHeight(by scalar: CGFloat?) -> (CGSize) -> CGSize { return { ( $0.width, $0.height * (scalar ?? 1) ) |> CGSize.init } } public func multiplyWidth(by scalar: CGFloat?) -> (CGSize) -> CGSize { return { ( $0.width * (scalar ?? 1), $0.height ) |> CGSize.init } } public func multiply(by point: CGPoint?) -> (CGPoint) -> CGPoint { return { ( $0.x * (point?.x ?? 1), $0.y * (point?.y ?? 1) ) |> CGPoint.init } } public func divide(by scalar: CGFloat?) -> (CGSize) -> CGSize { return { ( $0.width / (scalar ?? 1), $0.height / (scalar ?? 1) ) |> CGSize.init } } public func multiply(by scalar: CGFloat?) -> (CGPoint) -> CGPoint { return { ( $0.x * (scalar ?? 1), $0.y * (scalar ?? 1) ) |> CGPoint.init } } public func divide(by scalar: CGFloat?) -> (CGPoint) -> CGPoint { return { ( $0.x / (scalar ?? 1), $0.y / (scalar ?? 1) ) |> CGPoint.init } } public func offset(by distance: CGPoint?) -> (CGPoint) -> CGPoint { return { ( $0.x + (distance?.x ?? 0), $0.y + (distance?.y ?? 0) ) |> CGPoint.init } } public func divide(by: CGPoint) -> (CGPoint) -> CGPoint { return { ( $0.x / by.x, $0.y / by.y ) |> CGPoint.init } } public func divide(by: CGSize) -> (CGPoint) -> CGPoint { return { ( $0.x / by.width, $0.y / by.height ) |> CGPoint.init } } public func invert() -> (CGSize) -> CGSize { return { $0 |> multiply(by: -1) } } public func invertY() -> (CGPoint) -> CGPoint { return { ( $0.x, $0.y * -1 ) |> CGPoint.init } } public func invert() -> (CGPoint) -> CGPoint { return { $0 |> multiply(by: -1) } } public func half() -> (CGSize) -> CGSize { return { $0 |> divide(by: 2) } } public func centerPoint() -> (CGSize) -> CGPoint { return { $0 |> CGPoint.init |> divide(by: 2) } } public func zoom(by scalar: CGFloat?) -> (CGRect) -> CGRect { return { ( $0.size |> multiply(by: scalar) |> subtract($0.size) |> invert() |> half() |> CGPoint.init, $0.size |> multiply(by: scalar) ) |> CGRect.init } } public func offset(by distance: CGPoint?) -> (CGRect) -> CGRect { return { ( $0.origin |> offset(by: distance), $0.size ) |> CGRect.init } } public func isWithin(_ bounds: CGSize) -> (CGPoint) -> Bool { return { $0.x > 0 && $0.x < bounds.width && $0.y > 0 && $0.y < bounds.height } }
20.718487
87
0.447982
9b1212bb7c93590457086b1d6ce6d1a7ea2a7854
80
import PackageDescription let package = Package( name: "NotNilChallenge" )
13.333333
27
0.75
46ce2fd6704a5bba56422f478529aa691896acb3
969
// // Vox.swift // Pods // // Created by Mariam AlJamea on 1/25/16. // Copyright © 2016 kitz. All rights reserved. // public extension Applications { struct Vox: ExternalApplication { public typealias ActionType = Applications.Vox.Action public let scheme = "com.coppertino.vox:" public let fallbackURL = "http://coppertino.com/vox/iphone" public let appStoreId = "916215494" public init() {} } } // MARK: - Actions public extension Applications.Vox { enum Action { case open } } extension Applications.Vox.Action: ExternalApplicationAction { public var paths: ActionPaths { switch self { case .open: return ActionPaths( app: Path( pathComponents: ["app"], queryParameters: [:] ), web: Path() ) } } }
19.77551
67
0.527348
5db69725aedb2fac9bdb25e1674f2f8177fcf3a7
4,643
// // InterfaceController.swift // watch-Calc Extension // // Created by Salman Qureshi on 18/07/17. // Copyright © 2017 iSalmanLab. All rights reserved. // import WatchKit import Foundation enum Operation { case Sum case Minus case Multiply case Divide case Unknown } class InterfaceController: WKInterfaceController { var displaValue: NSString? var previousValueEntered: NSString? var operationPerform: Operation! @IBOutlet var displayResult: WKInterfaceLabel! @IBAction func oneTap() { print("1") addDigitToDisplay("1") } @IBAction func twoTap() { print("2") addDigitToDisplay("2") } @IBAction func threeTap() { print("3") addDigitToDisplay("3") } @IBAction func fourTap() { print("4") addDigitToDisplay("4") } @IBAction func fiveTap() { print("5") addDigitToDisplay("5") } @IBAction func sixTap() { print("6") addDigitToDisplay("6") } @IBAction func sevenTap() { print("7") addDigitToDisplay("7") } @IBAction func eightTap() { print("8") addDigitToDisplay("8") } @IBAction func nineTap() { print("9") addDigitToDisplay("9") } @IBAction func zeroTap() { print("0") addDigitToDisplay("0") } @IBAction func multiplyOperation() { print("*") previousValueEntered = displaValue operationPerform = Operation.Multiply displayResult.setText("0") } @IBAction func addOperation() { print("+") previousValueEntered = displaValue operationPerform = Operation.Sum displayResult.setText("0") } @IBAction func subtractOperation() { print("-") previousValueEntered = displaValue operationPerform = Operation.Minus displayResult.setText("0") } @IBAction func divideOperation() { print("divide") previousValueEntered = displaValue operationPerform = Operation.Divide displayResult.setText("0") } @IBAction func decimalOperation() { print(".") addDigitToDisplay(".") } @IBAction func resultTap() { print("=") if operationPerform == Operation.Sum { let stringResult = String(format: "%.1f", (previousValueEntered?.floatValue)! + (displaValue?.floatValue)!) displayResult.setText(stringResult) displaValue = stringResult as NSString? } else if operationPerform == Operation.Minus { let stringResult = String(format: "%.1f", (previousValueEntered?.floatValue)! - (displaValue?.floatValue)!) displayResult.setText(stringResult) displaValue = stringResult as NSString? } else if operationPerform == Operation.Multiply { let stringResult = String(format: "%.1f", (previousValueEntered?.floatValue)! * (displaValue?.floatValue)!) displayResult.setText(stringResult) displaValue = stringResult as NSString? } else if operationPerform == Operation.Divide { let stringResult = String(format: "%.1f", (previousValueEntered?.floatValue)! / (displaValue?.floatValue)!) displayResult.setText(stringResult) displaValue = stringResult as NSString? } previousValueEntered = nil operationPerform = Operation.Unknown } func addDigitToDisplay(_ value: String) { displaValue = displaValue!.appending(value as String) as NSString? displayResult.setText(displaValue as String?) } @IBAction func remove() { if (displaValue?.length)! > 0 { displaValue = displaValue?.substring(to: (displaValue?.length)! - 1) as NSString? displayResult.setText(displaValue as String?) } } @IBAction func clear() { previousValueEntered = nil operationPerform = Operation.Unknown displaValue = "" displayResult.setText("0") } override func awake(withContext context: Any?) { super.awake(withContext: context) displaValue = "" } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } }
26.994186
119
0.596597
26f15318a712d2a690536cc607c4c558d2291ae5
1,219
// // TwirlPIX.swift // PixelKit // // Created by Anton Heestand on 2018-08-11. // Open Source - MIT License // import Foundation import CoreGraphics import RenderKit import Resolution final public class TwirlPIX: PIXSingleEffect, PIXViewable { override public var shaderName: String { return "effectSingleTwirlPIX" } // MARK: - Public Properties @LiveFloat("strength", range: 0.0...5.0, increment: 1.0) public var strength: CGFloat = 2.0 // MARK: - Property Helpers public override var liveList: [LiveWrap] { [_strength] } override public var values: [Floatable] { return [strength] } // MARK: - Life Cycle public required init() { super.init(name: "Twirl", typeName: "pix-effect-single-twirl") extend = .mirror } required init(from decoder: Decoder) throws { try super.init(from: decoder) } } public extension NODEOut { func pixTwirl(_ strength: CGFloat) -> TwirlPIX { let twirlPix = TwirlPIX() twirlPix.name = ":twirl:" twirlPix.input = self as? PIX & NODEOut twirlPix.strength = strength return twirlPix } }
21.767857
95
0.611977
6166730a8c4709e94edde1357974ee0acd02ebec
3,958
// // InitialScene.swift // GameElementExample // // Created by Matija Kruljac on 12/1/17. // Copyright © 2017 Matija Kruljac. All rights reserved. // import Foundation import UIKit import SpriteKit class InitialScene: SKScene { private unowned let viewController: GameViewController private let store: Store private let storeNameLabel = SKLabelNode() private let playButton = SKSpriteNode(imageNamed: "play_game") private lazy var explosion = Explosion(particleColor: self.store.backgroundColor, position: CGPoint(x: frame.midX, y: frame.midY + 50)) init(size: CGSize, with store: Store, in viewController: GameViewController) { self.store = store self.viewController = viewController super.init(size: size) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMove(to view: SKView) { super.didMove(to: view) setupInitialSettings() addStoreImage() addStoreNameLabel() addPlayButton() } private func setupInitialSettings() { let background = SKSpriteNode(imageNamed: "background") background.position = CGPoint(x: frame.midX, y: frame.midY) background.zPosition = 0 addChild(background) } private func addStoreImage() { let texture = SKTexture(image: store.image) let size = CGSize(width: 90, height: 90) let storeImage = SKSpriteNode(texture: texture, color: .clear, size: size) storeImage.position = CGPoint(x: frame.midX, y: frame.midY + 150) storeImage.zPosition = 1 addChild(storeImage) } private func addStoreNameLabel() { let position = CGPoint(x: frame.midX, y: frame.midY + 50) storeNameLabel.text = store.name storeNameLabel.fontColor = .white storeNameLabel.fontName = "PingFangTC-Medium" storeNameLabel.fontSize = 35 storeNameLabel.horizontalAlignmentMode = .center storeNameLabel.verticalAlignmentMode = .center storeNameLabel.zPosition = 1 storeNameLabel.isHidden = true storeNameLabel.position = position addChild(storeNameLabel) animateStoreNameLabelExplosion() } private func animateStoreNameLabelExplosion() { addExplosionOnStoreNameLabel() let waitDuration: Double = Double(explosion.numParticlesToEmit) / Double(explosion.particleBirthRate) run(SKAction.wait(forDuration: waitDuration)) { [weak self] in self?.storeNameLabel.isHidden = false self?.explosion.removeFromParent() } } private func addExplosionOnStoreNameLabel() { addChild(explosion) } private func addPlayButton() { playButton.position = CGPoint(x: frame.midX, y: frame.midY-50) playButton.zPosition = 1 addChild(playButton) addPlayButtonAnimation() } private func addPlayButtonAnimation() { let pulseUp = SKAction.scale(to: 1.4, duration: 0.5) let pulseDown = SKAction.scale(to: 1.0, duration: 0.5) let pulse = SKAction.sequence([pulseUp, pulseDown]) playButton.run(SKAction.repeatForever(pulse)) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } let touchLocation = touch.location(in: self) if !playButton.contains(touchLocation) { return } runGameScene() } private func runGameScene() { let transition = SKTransition.fade(withDuration: 1.0) let gameScene = GameScene(size: size, in: viewController, with: store) gameScene.scaleMode = .aspectFill view?.presentScene(gameScene, transition: transition) } }
33.260504
109
0.642244
209278d5c49a5b03798592ce6536f9498ddcbb77
1,193
// // free_blurUITests.swift // free-blurUITests // // Created by Justin Kambic on 6/1/17. // import XCTest class free_blurUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.138889
182
0.659681
1d2c207a494cfe54c5b80fc5dbf579afffc3ab0b
4,532
// // EmployeeDetailViewControllerTests.swift // BankUnited // // @testable import BankUnited import BasicCommons import BasicUIElements import XCTest class EmployeeDetailViewControllerTests: XCTestCase { // MARK: Subject under test var sut: EmployeeDetailViewController! var spyInteractor: EmployeeDetailBusinessLogicSpy! var spyRouter: EmployeeDetailRoutingLogicSpy! var window: UIWindow! // MARK: Test lifecycle override func setUp() { super.setUp() window = UIWindow() setupEmployeeDetailViewController() } override func tearDown() { spyInteractor = nil spyRouter = nil sut = nil window = nil super.tearDown() } // MARK: Test setup func setupEmployeeDetailViewController() { let bundle = Utils.bundle(forClass: EmployeeDetailViewController.classForCoder())! let storyboard = UIStoryboard(name: "EmployeesMain", bundle: bundle) sut = (storyboard.instantiateViewController(withIdentifier: "EmployeeDetailViewController") as! EmployeeDetailViewController) spyInteractor = EmployeeDetailBusinessLogicSpy() sut.interactor = spyInteractor spyRouter = EmployeeDetailRoutingLogicSpy() sut.router = spyRouter loadView() } func loadView() { window.addSubview(sut.view) RunLoop.current.run(until: Date()) } // MARK: Tests func testViewDidLoad() { // Given // When // Then XCTAssertNotNil( sut, "the view should instantiate correctly" ) XCTAssertTrue( spyInteractor.prepareSetUpUICalled, "viewDidLoad should call the interactor to setup the UI" ) XCTAssertTrue( spyInteractor.fetchDataCalled, "viewDidLoad should call the interactor to fetch PaymentMethods" ) } func testRequiredInit() { // Given sut = nil XCTAssertNil( sut, "setting the sut to nil to test its other init" ) // When let archiver = NSKeyedUnarchiver(forReadingWith: Data()) sut = EmployeeDetailViewController(coder: archiver) // Then XCTAssertNotNil( sut, "sut instantiated using the overrideInit" ) XCTAssertTrue( spyInteractor.prepareSetUpUICalled, "viewDidLoad should call the interactor to setup the UI" ) XCTAssertTrue( spyInteractor.fetchDataCalled, "viewDidLoad should call the interactor to fetch PaymentMethods" ) } func testDisplaySetupUI() { // Given let viewModel = EmployeeDetail.Texts.ViewModel( title: "testtitle", nameTitle: "testnameTitle", salaryTitle: "testsalaryTitle", ageTitle: "testageTitle", buttonTitle: "testbuttonTitle" ) // When sut.displaySetupUI(viewModel: viewModel) // Then XCTAssertEqual(sut.nameTitleLabelText, "testnameTitle") XCTAssertEqual(sut.salaryTitleLabelText, "testsalaryTitle") XCTAssertEqual(sut.ageTitleLabelText, "testageTitle") } func testCloseButtonTapped() { // Given // When sut.closeButtonTapped() // Then XCTAssertTrue(spyRouter.closeToDashboardCalled) } func testGoBackTapped() { // Given // When sut.goBackTapped() // Then XCTAssertTrue(spyRouter.routeToBackCalled) } func testDisplayLoadingView() { // Given // When sut.displayLoadingView() // Then XCTAssertTrue(sut.view.subviews.last is MainActivityIndicator) } func testDisplayData() { // Given let viewModel = EmployeeDetail.Base.ViewModel(name: "testname", salary: "testsalary", age: "testage") // When sut.displayData(viewModel: viewModel) // Then XCTAssertEqual(sut.nameDisplayLabelText, "testname") XCTAssertEqual(sut.salaryDisplayLabelText, "testsalary") XCTAssertEqual(sut.ageDisplayLabelText, "testage") } func testDisplayErrorAlert() { // Given let viewModel = EmployeeDetail.Failure.ViewModel(errorType: .internet) // When sut.displayErrorAlert(viewModel: viewModel) // Then XCTAssertTrue(sut.view.subviews.last is FullScreenMessageErrorAnimated) } }
29.620915
133
0.622021
bf08ec210a515ed727cb62c6da0d3f8fb89a7a88
1,978
// swift-tools-version:4.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "ourplace", dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "https://github.com/IBM-Swift/Kitura.git", from: "2.4.0"), .package(url: "https://github.com/IBM-Swift/Kitura-WebSocket.git", from: "2.0.0"), .package(url: "https://github.com/IBM-Swift/Swift-Kuery.git", from: "2.0.0"), .package(url: "https://github.com/IBM-Swift/Kitura-StencilTemplateEngine.git", from: "1.10.0"), .package(url: "https://github.com/RuntimeTools/SwiftMetrics.git", from: "2.4.0"), .package(url: "https://github.com/IBM-Swift/Swift-Kuery-SQLite.git", from: "1.1.0"), .package(url: "https://github.com/IBM-Swift/Kitura-Session.git", from: "3.2.0"), .package(url: "https://github.com/IBM-Swift/Kitura-Credentials.git", from: "2.3.0"), .package(url: "https://github.com/IBM-Swift/Kitura-CredentialsGoogle.git", from: "2.2.1"), //.package(url: "https://github.com/krzyzanowskim/Kitura-Session-Kuery.git", from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "ourplace", dependencies: ["Kitura", "Kitura-WebSocket", "KituraStencil", "SwiftMetrics", "SwiftKuery", "SwiftKuerySQLite", "KituraSession", "Credentials", "CredentialsGoogle"]), ] )
52.052632
122
0.567745
b9cc0d31079acfcd1a3c3d266452e3fbb7bf26a7
7,189
// // ItemsListController.swift // FleaMarket // // Created by Rastislav Mirek on 4/3/20. // Copyright © 2020 FI MU. All rights reserved. // import UIKit import Alamofire import FirebaseFirestore import FirebaseStorage import Firebase import FirebaseUI import FirebaseAuth protocol ItemsListDelegate: class { func add(item: MarketItem) } private let ADD_ITEM_SEGUE_ID = "addItemSegue" private let cloudFirestore = Firestore.firestore() private let itemsCollection = cloudFirestore.collection("items") private let cloudStorage = Storage.storage() private let imagesFolder = cloudStorage.reference(withPath: "itemImages") private let auth = FirebaseAuth.Auth.auth() class ItemsListController: UIViewController { private var items = [MarketItem]() @IBOutlet weak var itemsCollectionView: UICollectionView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! private(set) var dollarRate: Double? { didSet { itemsCollectionView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() ensureAuth() loadItemsList() itemsCollectionView.dataSource = self itemsCollectionView.delegate = self requestDollarRate() } private func ensureAuth() { if auth.currentUser == nil, let authUI = FUIAuth.defaultAuthUI() { authUI.providers = [FUIEmailAuth()] authUI.delegate = self present(authUI.authViewController(), animated: true) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == ADD_ITEM_SEGUE_ID, let addItemController = segue.destination as? AddItemViewController { addItemController.itemsListDelegate = self } } private func imageStorageLocation(for itemId: String) throws -> URL { return try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(itemId).jpeg") } private func removeItem(at indexPath: IndexPath) { let itemId = items[indexPath.item].itemId itemsCollection.document(itemId).delete() imagesFolder.child(itemId).delete() items.remove(at: indexPath.item) itemsCollectionView.deleteItems(at: [indexPath]) } } extension ItemsListController: ItemsListDelegate { func add(item: MarketItem) { items.append(item) itemsCollectionView.insertItems(at: [IndexPath(item: items.count - 1, section: 0)]) if let imageData = item.picture?.jpegData(compressionQuality: 0.5) { imagesFolder.child(item.itemId).putData(imageData) } cloudFirestore.collection("items").document(item.itemId).setData([ "itemId": item.itemId, "name": item.name, "price": item.price, "currency": item.currency.rawValue, ]) } } private let CELL_REUSE_ID = "cellReuseID" extension ItemsListController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CELL_REUSE_ID, for: indexPath) as? ItemCell else { return UICollectionViewCell() } let item = items[indexPath.item] cell.itemNameLabel.text = item.name cell.itemPriceLabel.text = formatWithDollar(for: item) cell.itemId = item.itemId if let localImage = item.picture { cell.itemImageView.image = localImage } else { imagesFolder.child(item.itemId).getData(maxSize: Int64.max) { (data, error) in guard let data = data else { print("Error loading image from remote storage: \(String(describing: error))") return } let picture = UIImage(data: data) self.items[indexPath.item].picture = picture if cell.itemId == item.itemId { cell.itemImageView.image = picture } } } return cell } } extension ItemsListController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let item = items[indexPath.item] let alert = UIAlertController(title: "Do you want to buy \(item.name)?", message: "You will pay \(formatWithDollar(for: item))", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Buy", style: .default) { _ in self.removeItem(at: indexPath) }) present(alert, animated: true, completion: nil) } } // MARK: Currency Exchange Rates Handling extension ItemsListController { private func requestDollarRate() { AF.request("https://api.exchangeratesapi.io/latest?symbols=USD").responseJSON { response in switch response.result { case .success(_): if let responseDict = response.value as? [String: Any], let ratesDict = responseDict["rates"] as? [String: Any], let rate = ratesDict["USD"] as? Double { self.dollarRate = rate } case .failure(let error): print(error) } } } private func formatWithDollar(for item: MarketItem) -> String { return dollarRate == nil || item.currency == .usDollar ? item.formatPrice() : "$\(round(Double(item.price) * dollarRate! * 100) / 100)" } } // MARK: Items Persistance extension ItemsListController { private func loadItemsList() { activityIndicator.isHidden = false itemsCollection.addSnapshotListener { snapshot, err in guard let snapshot = snapshot else { print(err!) return } self.items = snapshot.documents.map { document in let data = document.data() if let name = data["name"] as? String, let currencyId = data["currency"] as? String, let currency = Currency(rawValue: currencyId), let price = data["price"] as? Int, let itemId = data["itemId"] as? String { return MarketItem(itemId: itemId, name: name, price: price, currency: currency) } print("Item stored in unkown format: \(data)") return MarketItem() } self.itemsCollectionView.reloadData() self.activityIndicator.isHidden = true } } } extension ItemsListController: FUIAuthDelegate { // TODO add callbacks }
35.068293
164
0.615663
7649fcc664878c62eade311dab519a7562305cfc
12,407
// RUN: rm -rf %t && mkdir %t // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift // RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience %s | %FileCheck %s // RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -O %s import resilient_enum import resilient_struct // CHECK: %swift.type = type { [[INT:i32|i64]] } // CHECK: %T15enum_resilience5ClassC = type <{ %swift.refcounted }> // CHECK: %T15enum_resilience9ReferenceV = type <{ %T15enum_resilience5ClassC* }> // Public fixed layout struct contains a public resilient struct, // cannot use spare bits // CHECK: %T15enum_resilience6EitherO = type <{ [[REFERENCE_TYPE:\[(4|8) x i8\]]], [1 x i8] }> // Public resilient struct contains a public resilient struct, // can use spare bits // CHECK: %T15enum_resilience15ResilientEitherO = type <{ [[REFERENCE_TYPE]] }> // Internal fixed layout struct contains a public resilient struct, // can use spare bits // CHECK: %T15enum_resilience14InternalEitherO = type <{ [[REFERENCE_TYPE]] }> // Public fixed layout struct contains a fixed layout struct, // can use spare bits // CHECK: %T15enum_resilience10EitherFastO = type <{ [[REFERENCE_TYPE]] }> public class Class {} public struct Reference { public var n: Class } @_fixed_layout public enum Either { case Left(Reference) case Right(Reference) } public enum ResilientEither { case Left(Reference) case Right(Reference) } enum InternalEither { case Left(Reference) case Right(Reference) } @_fixed_layout public struct ReferenceFast { public var n: Class } @_fixed_layout public enum EitherFast { case Left(ReferenceFast) case Right(ReferenceFast) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience25functionWithResilientEnum010resilient_A06MediumOAEF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture) public func functionWithResilientEnum(_ m: Medium) -> Medium { // CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa() // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 9 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* %0, %swift.opaque* %1, %swift.type* [[METADATA]]) // CHECK-NEXT: ret void return m } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience33functionWithIndirectResilientEnum010resilient_A00E8ApproachOAEF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture) public func functionWithIndirectResilientEnum(_ ia: IndirectApproach) -> IndirectApproach { // CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum16IndirectApproachOMa() // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 9 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* %0, %swift.opaque* %1, %swift.type* [[METADATA]]) // CHECK-NEXT: ret void return ia } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience31constructResilientEnumNoPayload010resilient_A06MediumOyF public func constructResilientEnumNoPayload() -> Medium { // CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa() // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 25 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* %0, i32 0, %swift.type* [[METADATA]]) // CHECK-NEXT: ret void return Medium.Paper } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience29constructResilientEnumPayload010resilient_A06MediumO0G7_struct4SizeVF public func constructResilientEnumPayload(_ s: Size) -> Medium { // CHECK: [[METADATA:%.*]] = call %swift.type* @_T016resilient_struct4SizeVMa() // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 6 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: [[COPY:%.*]] = call %swift.opaque* %initializeWithCopy(%swift.opaque* %0, %swift.opaque* %1, %swift.type* [[METADATA]]) // CHECK-NEXT: [[METADATA2:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa() // CHECK-NEXT: [[METADATA_ADDR2:%.*]] = bitcast %swift.type* [[METADATA2]] to i8*** // CHECK-NEXT: [[VWT_ADDR2:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR2]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT2:%.*]] = load i8**, i8*** [[VWT_ADDR2]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT2]], i32 25 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* %0, i32 -2, %swift.type* [[METADATA2]]) // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* %1, %swift.type* [[METADATA]]) // CHECK-NEXT: ret void return Medium.Postcard(s) } // CHECK-LABEL: define{{( protected)?}} swiftcc {{i32|i64}} @_T015enum_resilience19resilientSwitchTestSi0c1_A06MediumOF(%swift.opaque* noalias nocapture) // CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa() // CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 17 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK: [[WITNESS_FOR_SIZE:%.*]] = ptrtoint i8* [[WITNESS]] // CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16 // CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16 // CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16 // CHECK: [[ENUM_STORAGE:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque* // CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 6 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK: [[ENUM_COPY:%.*]] = call %swift.opaque* [[WITNESS_FN]](%swift.opaque* [[ENUM_STORAGE]], %swift.opaque* %0, %swift.type* [[METADATA]]) // CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 23 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK: [[TAG:%.*]] = call i32 %getEnumTag(%swift.opaque* [[ENUM_STORAGE]], %swift.type* [[METADATA]]) // CHECK: switch i32 [[TAG]], label %[[DEFAULT_CASE:.*]] [ // CHECK: i32 -1, label %[[PAMPHLET_CASE:.*]] // CHECK: i32 0, label %[[PAPER_CASE:.*]] // CHECK: i32 1, label %[[CANVAS_CASE:.*]] // CHECK: ] // CHECK: ; <label>:[[PAPER_CASE]] // CHECK: br label %[[END:.*]] // CHECK: ; <label>:[[CANVAS_CASE]] // CHECK: br label %[[END]] // CHECK: ; <label>:[[PAMPHLET_CASE]] // CHECK: br label %[[END]] // CHECK: ; <label>:[[DEFAULT_CASE]] // CHECK: br label %[[END]] // CHECK: ; <label>:[[END]] // CHECK: ret public func resilientSwitchTest(_ m: Medium) -> Int { switch m { case .Paper: return 1 case .Canvas: return 2 case .Pamphlet(let m): return resilientSwitchTest(m) default: return 3 } } public func reabstraction<T>(_ f: (Medium) -> T) {} // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience25resilientEnumPartialApplyySi0c1_A06MediumOcF(i8*, %swift.refcounted*) public func resilientEnumPartialApply(_ f: (Medium) -> Int) { // CHECK: [[CONTEXT:%.*]] = call noalias %swift.refcounted* @swift_rt_swift_allocObject // CHECK: call swiftcc void @_T015enum_resilience13reabstractionyx010resilient_A06MediumOclF(i8* bitcast (void (%TSi*, %swift.opaque*, %swift.refcounted*)* @_T014resilient_enum6MediumOSiIxid_ACSiIxir_TRTA to i8*), %swift.refcounted* [[CONTEXT:%.*]], %swift.type* @_T0SiN) reabstraction(f) // CHECK: ret void } // CHECK-LABEL: define internal swiftcc void @_T014resilient_enum6MediumOSiIxid_ACSiIxir_TRTA(%TSi* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.refcounted* swiftself) // Enums with resilient payloads from a different resilience domain // require runtime metadata instantiation, just like generics. public enum EnumWithResilientPayload { case OneSize(Size) case TwoSizes(Size, Size) } // Make sure we call a function to access metadata of enums with // resilient layout. // CHECK-LABEL: define{{( protected)?}} swiftcc %swift.type* @_T015enum_resilience20getResilientEnumTypeypXpyF() // CHECK: [[METADATA:%.*]] = call %swift.type* @_T015enum_resilience24EnumWithResilientPayloadOMa() // CHECK-NEXT: ret %swift.type* [[METADATA]] public func getResilientEnumType() -> Any.Type { return EnumWithResilientPayload.self } // Public metadata accessor for our resilient enum // CHECK-LABEL: define{{( protected)?}} %swift.type* @_T015enum_resilience24EnumWithResilientPayloadOMa() // CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** @_T015enum_resilience24EnumWithResilientPayloadOML // CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[METADATA]], null // CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: call void @swift_once([[INT]]* @_T015enum_resilience24EnumWithResilientPayloadOMa.once_token, i8* bitcast (void (i8*)* @initialize_metadata_EnumWithResilientPayload to i8*), i8* undef) // CHECK-NEXT: [[METADATA2:%.*]] = load %swift.type*, %swift.type** @_T015enum_resilience24EnumWithResilientPayloadOML // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[METADATA]], %entry ], [ [[METADATA2]], %cacheIsNull ] // CHECK-NEXT: ret %swift.type* [[RESULT]] // Methods inside extensions of resilient enums fish out type parameters // from metadata -- make sure we can do that extension ResilientMultiPayloadGenericEnum { // CHECK-LABEL: define{{( protected)?}} swiftcc %swift.type* @_T014resilient_enum32ResilientMultiPayloadGenericEnumO0B11_resilienceE16getTypeParameterxmyF(%swift.type* %"ResilientMultiPayloadGenericEnum<T>", %swift.opaque* noalias nocapture swiftself) // CHECK: [[METADATA:%.*]] = bitcast %swift.type* %"ResilientMultiPayloadGenericEnum<T>" to %swift.type** // CHECK-NEXT: [[T_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[METADATA]], [[INT]] 3 // CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T_ADDR]] public func getTypeParameter() -> T.Type { return T.self } } // CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_EnumWithResilientPayload(i8*)
46.818868
275
0.678085
20a8a71d695202a6992dd52006958c5fc24f53dd
3,223
// // MultipleCellViewController.swift // Example // // Created by JiongXing on 2019/11/26. // Copyright © 2021 Shenzhen Hive Box Technology Co.,Ltd All rights reserved. // import UIKit import Lantern class MultipleCellViewController: BaseCollectionViewController { override var name: String { "多种类视图" } override var remark: String { "支持不同的类作为项视图,如在最后一页显示更多推荐" } override func makeDataSource() -> [ResourceModel] { makeLocalDataSource() } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.fc.dequeueReusableCell(BaseCollectionViewCell.self, for: indexPath) cell.imageView.image = self.dataSource[indexPath.item].localName.flatMap { UIImage(named: $0) } return cell } override func openLantern(with collectionView: UICollectionView, indexPath: IndexPath) { let lantern = Lantern() lantern.numberOfItems = { self.dataSource.count + 1 } lantern.cellClassAtIndex = { index in if index < self.dataSource.count { return LanternImageCell.self } return MoreCell.self } lantern.reloadCellAtIndex = { context in if context.index < self.dataSource.count { let lanternCell = context.cell as? LanternImageCell let indexPath = IndexPath(item: context.index, section: indexPath.section) lanternCell?.imageView.image = self.dataSource[indexPath.item].localName.flatMap { UIImage(named: $0) } } } lantern.transitionAnimator = LanternZoomAnimator(previousView: { index -> UIView? in if index < self.dataSource.count { let path = IndexPath(item: index, section: indexPath.section) let cell = collectionView.cellForItem(at: path) as? BaseCollectionViewCell return cell?.imageView } return nil }) lantern.pageIndex = indexPath.item lantern.show() } } class MoreCell: UIView, LanternCell { weak var lantern: Lantern? static func generate(with lantern: Lantern) -> Self { let instance = Self.init(frame: .zero) instance.lantern = lantern return instance } var onClick: (() -> Void)? lazy var button: UIButton = { let btn = UIButton(type: .custom) btn.setTitle(" 更多 + ", for: .normal) btn.setTitleColor(UIColor.darkText, for: .normal) return btn }() required override init(frame: CGRect) { super.init(frame: .zero) backgroundColor = .white addSubview(button) button.addTarget(self, action: #selector(click), for: .touchUpInside) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() button.sizeToFit() button.center = CGPoint(x: bounds.width / 2, y: bounds.height / 2) } @objc private func click() { lantern?.dismiss() } }
32.555556
130
0.618678
5609c3fd59a80530bf96f024508e1f1e7b90abe3
429
public enum SupplyKeys { // ModuleName is the module name constant used in many places public static let moduleName = "supply" // StoreKey is the store key string for supply public static let storeKey = moduleName // RouterKey is the message route for supply public static let routerKey = moduleName // QuerierRoute is the querier route for supply public static let querierRoute = moduleName }
30.642857
65
0.729604
11f9c751971a7841f4cee615ccd9e9527a2eeb9f
3,477
// // LongPressRecognizer.swift // WolmoCore // // Created by Gabriel Mazzei on 21/12/2018. // Copyright © 2018 Wolox. All rights reserved. // import Foundation public extension UIView { // In order to create computed properties for extensions, we need a key to // store and access the stored property fileprivate struct AssociatedObjectKeys { static var longPressGestureRecognizer = "MediaViewerAssociatedObjectKey_mediaViewer" } fileprivate typealias Action = ((UILongPressGestureRecognizer) -> Void)? // Set our computed property type to a closure fileprivate var longPressGestureRecognizerAction: Action? { set { if let newValue = newValue { // Computed properties get stored as associated objects objc_setAssociatedObject(self, &AssociatedObjectKeys.longPressGestureRecognizer, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } get { let longPressGestureRecognizerActionInstance = objc_getAssociatedObject(self, &AssociatedObjectKeys.longPressGestureRecognizer) as? Action return longPressGestureRecognizerActionInstance } } /** Adds a long-press gesture recognizer that executes the closure when long pressed - Parameter numberOfTapsRequired: The number of full taps required before the press for gesture to be recognized. Default is 0 - Parameter numberOfTouchesRequired: Number of fingers that must be held down for the gesture to be recognized. Default is 1 - Parameter minimumPressDuration: Time in seconds the fingers must be held down for the gesture to be recognized. Default is 0.5 - Parameter allowableMovement: Maximum movement in pixels allowed before the gesture fails. Once recognized (after minimumPressDuration) there is no limit on finger movement for the remainder of the touch tracking. Default is 10 - Parameter action: The closure that will execute when the view is long pressed */ public func addLongPressGestureRecognizer(numberOfTapsRequired: Int = 0, numberOfTouchesRequired: Int = 1, minimumPressDuration: TimeInterval = 0.5, allowableMovement: CGFloat = 10, action: ((UILongPressGestureRecognizer) -> Void)?) { isUserInteractionEnabled = true longPressGestureRecognizerAction = action let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture)) longPressGestureRecognizer.numberOfTapsRequired = numberOfTapsRequired longPressGestureRecognizer.numberOfTouchesRequired = numberOfTouchesRequired longPressGestureRecognizer.minimumPressDuration = minimumPressDuration longPressGestureRecognizer.allowableMovement = allowableMovement addGestureRecognizer(longPressGestureRecognizer) } // Every time the user long presses on the UIView, this function gets called, // which triggers the closure we stored @objc fileprivate func handleLongPressGesture(sender: UILongPressGestureRecognizer) { if let action = longPressGestureRecognizerAction { action?(sender) } else { print("No action for the long-press gesture") } } }
48.971831
233
0.694852
8ac85e450c59e50722892c0d8b45739eb2d63f91
5,782
// // QueuedAudioPlayer.swift // SwiftAudio // // Created by Jørgen Henrichsen on 24/03/2018. // import Foundation import MediaPlayer /** An audio player that can keep track of a queue of AudioItems. */ public class QueuedAudioPlayer: AudioPlayer { let queueManager: QueueManager = QueueManager<AudioItem>() /** Set wether the player should automatically play the next song when a song is finished. Default is `true`. */ public var automaticallyPlayNextSong: Bool = true public override var currentItem: AudioItem? { return queueManager.current } /** The index of the current item. */ public var currentIndex: Int { return queueManager.currentIndex } /** Stops the player and clears the queue. */ public override func stop() { super.stop() } override func reset() { queueManager.clearQueue() } /** All items currently in the queue. */ public var items: [AudioItem] { return queueManager.items } /** The previous items held by the queue. */ public var previousItems: [AudioItem] { return queueManager.previousItems } /** The upcoming items in the queue. */ public var nextItems: [AudioItem] { return queueManager.nextItems } /** Will replace the current item with a new one and load it into the player. - parameter item: The AudioItem to replace the current item. - throws: APError.LoadError */ public override func load(item: AudioItem, playWhenReady: Bool) throws { try super.load(item: item, playWhenReady: playWhenReady) queueManager.replaceCurrentItem(with: item) } /** Add a single item to the queue. - parameter item: The item to add. - parameter playWhenReady: If the AudioPlayer has no item loaded, it will load the `item`. If this is `true` it will automatically start playback. Default is `true`. - throws: `APError` */ public func add(item: AudioItem, playWhenReady: Bool = true) throws { if currentItem == nil { queueManager.addItem(item) if playWhenReady == true { try self.load(item: item, playWhenReady: playWhenReady) } } else { queueManager.addItem(item) } } /** Add items to the queue. - parameter items: The items to add to the queue. - parameter playWhenReady: If the AudioPlayer has no item loaded, it will load the first item in the list. If this is `true` it will automatically start playback. Default is `true`. - throws: `APError` */ public func add(items: [AudioItem], playWhenReady: Bool = true) throws { if currentItem == nil { queueManager.addItems(items) if playWhenReady == true { try self.load(item: currentItem!, playWhenReady: playWhenReady) } } else { queueManager.addItems(items) } } public func add(items: [AudioItem], at index: Int) throws { try queueManager.addItems(items, at: index) } /** Step to the next item in the queue. - throws: `APError` */ public func next() throws { event.playbackEnd.emit(data: .skippedToNext) delegate?.audioPlayer(itemPlaybackEndedWithReason: .skippedToNext) let nextItem = try queueManager.next() try self.load(item: nextItem, playWhenReady: true) } /** Step to the previous item in the queue. */ public func previous() throws { event.playbackEnd.emit(data: .skippedToPrevious) delegate?.audioPlayer(itemPlaybackEndedWithReason: .skippedToPrevious) let previousItem = try queueManager.previous() try self.load(item: previousItem, playWhenReady: true) } /** Remove an item from the queue. - parameter index: The index of the item to remove. - throws: `APError.QueueError` */ public func removeItem(at index: Int) throws { try queueManager.removeItem(at: index) } /** Jump to a certain item in the queue. - parameter index: The index of the item to jump to. - parameter playWhenReady: Wether the item should start playing when ready. Default is `true`. - throws: `APError` */ public func jumpToItem(atIndex index: Int, playWhenReady: Bool = true) throws { event.playbackEnd.emit(data: .jumpedToIndex) delegate?.audioPlayer(itemPlaybackEndedWithReason: .jumpedToIndex) let item = try queueManager.jump(to: index) try self.load(item: item, playWhenReady: playWhenReady) } /** Move an item in the queue from one position to another. - parameter fromIndex: The index of the item to move. - parameter toIndex: The index to move the item to. - throws: `APError.QueueError` */ func moveItem(fromIndex: Int, toIndex: Int) throws { try queueManager.moveItem(fromIndex: fromIndex, toIndex: toIndex) } /** Remove all upcoming items, those returned by `next()` */ public func removeUpcomingItems() { queueManager.removeUpcomingItems() } /** Remove all previous items, those returned by `previous()` */ public func removePreviousItems() { queueManager.removePreviousItems() } // MARK: - AVPlayerWrapperDelegate override func AVWrapperItemDidPlayToEndTime() { super.AVWrapperItemDidPlayToEndTime() if automaticallyPlayNextSong { try? self.next() } } }
28.766169
186
0.617779
d9e6b6e696dab83ee7823432f5dfe3f1d4590102
1,076
// // UIColor+PBExtension.swift // // Created by pebble8888 on 2017/01/08. // Copyright © 2017年 pebble8888. All rights reserved. // import Foundation #if os(iOS) import UIKit public extension UIColor { @objc convenience init(hexString: String, alpha: CGFloat) { let scanner = Scanner(string: hexString) var color:UInt32 = 0 if !scanner.scanHexInt32(&color) { self.init(white: 0, alpha: 1) return } let r: CGFloat = CGFloat((color & 0xFF0000) >> 16) / 255.0 let g: CGFloat = CGFloat((color & 0x00FF00) >> 8) / 255.0 let b: CGFloat = CGFloat(color & 0x0000FF) / 255.0 self.init(red: r, green: g, blue: b, alpha: alpha) } @objc convenience init(intRed: Int, intGreen: Int, intBlue: Int, intAlpha: Int = 255) { let r: CGFloat = CGFloat(intRed)/255.0 let g: CGFloat = CGFloat(intGreen)/255.0 let b: CGFloat = CGFloat(intBlue)/255.0 let a: CGFloat = CGFloat(intAlpha)/255.0 self.init(red: r, green: g, blue: b, alpha: a) } } #endif
30.742857
91
0.60316
de713f6316406bb2574792550e930f2237823840
2,271
// swift-tools-version:4.0 // The swift-tools-version declares the minimum version of Swift required to build this package. // // Package.swift // Cryptor // // Copyright © 2016-2020 IBM and the Kitura project authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import PackageDescription var dependencies: [Package.Dependency] = [] var targetDependencies: [Target.Dependency] = [] #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) dependencies.append(Package.Dependency.package(url: "https://github.com/Kitura/CommonCrypto.git", from: "1.0.200")) targetDependencies.append(Target.Dependency.byName(name: "CommonCrypto")) #elseif os(Linux) dependencies.append(Package.Dependency.package(url: "https://github.com/Kitura/OpenSSL.git", from: "1.0.200")) targetDependencies.append(Target.Dependency.byName(name: "OpenSSL")) #else fatalError("Unsupported OS") #endif let package = Package( name: "Cryptor", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "Cryptor", targets: ["Cryptor"]), ], dependencies: dependencies, targets: [ // Targets are the basic building blocks of a package. A target defines a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "Cryptor", dependencies: targetDependencies, exclude: ["Cryptor.xcodeproj", "README.md", "Sources/Info.plist"]), .testTarget( name: "CryptorTests", dependencies: ["Cryptor"]), ] )
38.491525
122
0.682078
ddf90d86a5f4e9a13d917ebac12cf8179868ada2
1,289
import UIKit /// View controller for the time shuffle settings section. class TimeShuffleSettingsViewController: BaseSettingsSectionViewController { /// Text field for shuffle time. @IBOutlet weak var shuffleTimeField: UITextField! /// Text field for shuffle time variance. @IBOutlet weak var shuffleTimeVarianceField: UITextField! /// Text field for min shuffle repeats. @IBOutlet weak var minShuffleRepeatsField: UITextField! /// Text field for max shuffle repeats. @IBOutlet weak var maxShuffleRepeatsField: UITextField! override func viewDidLoad() { super.viewDidLoad() registerSetting(settingView: DoubleTextFieldOptionalSettingView(setting: &MusicSettings.settings.shuffleTime, settingModifier: shuffleTimeField)) registerSetting(settingView: DoubleTextFieldOptionalSettingView(setting: &MusicSettings.settings.shuffleTimeVariance, settingModifier: shuffleTimeVarianceField)) registerSetting(settingView: DoubleTextFieldOptionalSettingView(setting: &MusicSettings.settings.minShuffleRepeats, settingModifier: minShuffleRepeatsField)) registerSetting(settingView: DoubleTextFieldOptionalSettingView(setting: &MusicSettings.settings.maxShuffleRepeats, settingModifier: maxShuffleRepeatsField)) } }
56.043478
169
0.796742
899f344ed6ec34a7ae8ffd7ffc09670e7c1ed50d
3,930
// RUN: %target-swift-frontend %s -O -emit-sil | %FileCheck %s // RUN: %target-swift-frontend %s -O -emit-sil -enable-testing | %FileCheck -check-prefix=CHECK-TESTING %s // Check if cycles are removed. @inline(never) func inCycleA() { inCycleB() } @inline(never) func inCycleB() { inCycleA() } // Check if unused vtable methods are removed. class Base { @inline(never) func aliveMethod() { } @inline(never) func deadMethod() { // introduces a cycle testClasses(self) } // alive, because called with super @inline(never) func calledWithSuper() { } // dead, because only overridden method is called @inline(never) func baseNotCalled() { } // alive, because called for Derived but not overridden in Derived @inline(never) func notInDerived() { } // dead, because only overridden method is called @inline(never) func notInOther() { } } class Derived : Base { @inline(never) override func aliveMethod() { } @inline(never) override func deadMethod() { } @inline(never) @_semantics("optimize.sil.never") // avoid devirtualization override func calledWithSuper() { super.calledWithSuper() } @inline(never) override func baseNotCalled() { } @inline(never) override func notInOther() { } } class Other : Derived { @inline(never) override func baseNotCalled() { } @inline(never) override func notInDerived() { } } @inline(never) @_semantics("optimize.sil.never") // avoid devirtualization func testClasses(_ b: Base) { b.aliveMethod() } @inline(never) @_semantics("optimize.sil.never") // avoid devirtualization func testWithDerived(_ d: Derived) { d.baseNotCalled() d.notInDerived() d.calledWithSuper() } @inline(never) @_semantics("optimize.sil.never") // avoid devirtualization func testWithOther(_ o: Other) { o.notInOther() } // Check if dead methods of classes with higher visibility are removed. public class PublicClass { func publicClassMethod() { } } // Check if unused witness table methods are removed. protocol Prot { func aliveWitness() func deadWitness() } struct Adopt : Prot { @inline(never) func aliveWitness() { } @inline(never) func deadWitness() { } } @inline(never) @_semantics("optimize.sil.never") // avoid devirtualization func testProtocols(_ p: Prot) { p.aliveWitness() } @_semantics("optimize.sil.never") // avoid devirtualization public func callTest() { testClasses(Base()) testClasses(Derived()) testWithDerived(Derived()) testWithOther(Other()) testProtocols(Adopt()) } @_semantics("optimize.sil.never") // make sure not eliminated internal func donotEliminate() { return } // CHECK-NOT: sil {{.*}}inCycleA // CHECK-NOT: sil {{.*}}inCycleB // CHECK-NOT: sil {{.*}}deadMethod // CHECK-NOT: sil {{.*}}deadWitness // CHECK-NOT: sil {{.*}}publicClassMethod // CHECK-TESTING: sil {{.*}}inCycleA // CHECK-TESTING: sil {{.*}}inCycleB // CHECK-TESTING: sil {{.*}}deadMethod // CHECK-TESTING: sil {{.*}}publicClassMethod // CHECK-TESTING: sil {{.*}}deadWitness // CHECK-LABEL: @_TF25dead_function_elimination14donotEliminateFT_T_ // CHECK-LABEL: sil_vtable Base // CHECK: aliveMethod // CHECK: calledWithSuper // CHECK-NOT: deadMethod // CHECK-NOT: baseNotCalled // CHECK: notInDerived // CHECK-NOT: notInOther // CHECK-TESTING-LABEL: sil_vtable Base // CHECK-TESTING: deadMethod // CHECK-LABEL: sil_vtable Derived // CHECK: aliveMethod // CHECK-NOT: deadMethod // CHECK: baseNotCalled // CHECK: notInDerived // CHECK: notInOther // CHECK-TESTING-LABEL: sil_vtable Derived // CHECK-TESTING: deadMethod // CHECK-LABEL: sil_vtable Other // CHECK: aliveMethod // CHECK-NOT: deadMethod // CHECK: baseNotCalled // CHECK: notInDerived // CHECK: notInOther // CHECK-LABEL: sil_witness_table hidden Adopt: Prot // CHECK: aliveWitness!1: @{{.*}}aliveWitness // CHECK: deadWitness!1: nil // CHECK-TESTING-LABEL: sil_witness_table [fragile] Adopt: Prot // CHECK-TESTING: deadWitness{{.*}}: @{{.*}}deadWitness
19.552239
106
0.706361
23815e6f2cd6e45e7a73c42cb368bdecc0cd370e
396
// // ViewModel.swift // CopaAmericaStatsScreenPlugin // // Created by Jesus De Meyer on 3/12/19. // Copyright © 2019 Applicaster. All rights reserved. // import Foundation import RxSwift protocol ViewModelProtocol { func fetch() } class ViewModel: NSObject, ViewModelProtocol { let isLoading = PublishSubject<Bool>() func fetch() { // implemented by subclass } }
17.217391
54
0.689394
4868464c1abc39927980a53c8e151ffab2952c46
2,312
// // AppDelegate.swift // ComputingTextHeightFramework // // Created by JOE on 2018/4/13. // Copyright © 2018年 Hongyear Information Technology (Shanghai) Co.,Ltd. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window?.rootViewController = UINavigationController.init(rootViewController: ComputingTextHeightFrameworkSubViewController()) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
47.183673
285
0.758218
d68b0e678a567f01c92c4ff5e97c04cbdc365970
1,132
//: [Previous](@previous) import Foundation import UIKit var str = "Hello, playground" //: [Next](@next) /// Objective C /* // ClassA.h @property (nonatomic, copy) NSString *testString; // ClassA.m - (NSString *)testString { if (!_testString) { _testString = @"Hello"; NSLog(@"只在⾸次访问输出"); } return _testString; } */ class TestClass { lazy var value = 8 lazy var textLabel: UILabel = { let label = UILabel() let rect = CGRect(x: 0, y: 0, width: 20, height: 20) label.frame = rect label.text = "myTitle" label.backgroundColor = UIColor.blue return label }() } // map/flatmap filter let nums = [1, 2, 3, 4, 5] let result = nums.lazy.map { (i: Int) -> Int in print("processing \(i)") return i * 2 } print("ready") for i in result { print("res = \(i)") } print("end") /// using /* public var lazy: LazyCollection<Self> { get } public var lazy: LazyRandomAccessCollection<Self> { get } public var lazy: LazyBidirectionalCollection<Self> { get } public var lazy: LazyForwardCollection<Self> { get } */
16.171429
60
0.594523
23729e9b0811f4ed313e9b81b16bbc1c74c0b948
4,389
// // DeviceRightsSpec.swift // Exposure // // Created by Fredrik Sjöberg on 2017-05-16. // Copyright © 2017 emp. All rights reserved. // import Foundation import Quick import Nimble @testable import Exposure class DeviceRightsSpec: QuickSpec { override func spec() { super.spec() describe("JSON") { it("should succeed with valid response") { let json = DeviceRightsJSON.valid() let result = json.decode(DeviceRights.self) expect(result).toNot(beNil()) expect(result?.type).toNot(beNil()) expect(result?.model).toNot(beNil()) expect(result?.manufacturer).toNot(beNil()) expect(result?.os).toNot(beNil()) expect(result?.osVersion).toNot(beNil()) expect(result?.rights).toNot(beNil()) } it("should init with partial response") { let json = DeviceRightsJSON.missingKeys() let result = json.decode(DeviceRights.self) expect(result).toNot(beNil()) expect(result?.type).toNot(beNil()) expect(result?.model).to(beNil()) expect(result?.manufacturer).to(beNil()) expect(result?.os).to(beNil()) expect(result?.osVersion).to(beNil()) expect(result?.rights).to(beNil()) } it("should init with empty response") { let json = DeviceRightsJSON.empty() let result = json.decode(DeviceRights.self) expect(result).toNot(beNil()) } } describe("DeviceType") { it("should init properly") { let web = DeviceType(string: "WEB") let mobile = DeviceType(string: "MOBILE") let tablet = DeviceType(string: "TABLET") let appleTv = DeviceType(string: "APPLE_TV") let smartTv = DeviceType(string: "SMART_TV") let console = DeviceType(string: "CONSOLE") let stb = DeviceType(string: "STB") let other = DeviceType(string: "Unkown or new type") expect(self.test(value: mobile, against: DeviceType.mobile)).to(beTrue()) expect(self.test(value: tablet, against: DeviceType.tablet)).to(beTrue()) expect(self.test(value: appleTv, against: DeviceType.appleTv)).to(beTrue()) expect(self.test(value: other, against: DeviceType.other(string: "Unkown or new type"))).to(beTrue()) expect(self.test(value: other, against: DeviceType.other(string: "Not Matching"))).to(beFalse()) } } } func test(value: DeviceType, against: DeviceType) -> Bool { switch (value, against) { case (.mobile, .mobile): return true case (.tablet, .tablet): return true case (.appleTv, .appleTv): return true case (.other(let first), .other(let second)): return first == second default: return false } } } extension DeviceRightsSpec { enum DeviceRightsJSON { static let type = "MOBILE" static let model = "iPhone1,1" static let manufacturer = "Apple" static let os = "iOS" static let osVersion = "iOS10.0" static let rights = AssetRightsSpec.AssetRightsJSON.valid() static func valid() -> [String: Any] { return [ "type": DeviceRightsJSON.type, "model": DeviceRightsJSON.model, "manufacturer": DeviceRightsJSON.manufacturer, "os": DeviceRightsJSON.os, "osVersion": DeviceRightsJSON.osVersion, "rights": DeviceRightsJSON.rights ] } static func missingKeys() -> [String: Any] { return [ "type": DeviceRightsJSON.type ] } static func empty() -> [String: Any] { return [:] } static func missformatedAssetRights() -> [String: Any] { return [ "type": DeviceRightsJSON.type, "rights": [] ] } } }
35.395161
117
0.520848
f4b888e8546c3cca1c25588041da861ba84ebeae
856
// // StartPoints.swift // ApLife // // Created by Alexander Ivlev on 24/09/2019. // Copyright © 2019 ApostleLife. All rights reserved. // import Core import Design import UIComponents import Menu import Account import News import Favorites import Biography import Settings enum StartPoints { static let menu = MenuStartPoint() static let account = AccountStartPoint() static let news = NewsStartPoint() static let favorites = FavoritesStartPoint() static let biography = BiographyStartPoint() static let settings = SettingsStartPoint() static let common: [CommonStartPoint] = [ CoreStartPoint(), DesignStartPoint(), UIComponentsStartPoint() ] static let ui: [UIStartPoint] = [ menu, account, news, favorites, biography, settings, ] }
19.454545
54
0.667056
8f683ac564bd0d8cc28b57f9e812c97226651cfe
501
import UIKit import Flutter @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) FLTWebviewFlutterPlugin.register(with: self.registrar(forPlugin: "FLTWebviewFlutterPlugin")) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
31.3125
96
0.800399
3aa0636fa11a876ed1394616f56b7e60aee0dd1f
1,695
// // MaterialLoaderTests.swift // SwiftObjLoader // // Created by Hugo Tunius on 01/02/16. // Copyright © 2016 Hugo Tunius. All rights reserved. // import XCTest @testable import SwiftObjLoader class MaterialLoaderTests: XCTestCase { var fixtureHelper: FixtureHelper! override func setUp() { fixtureHelper = FixtureHelper() } func testSimple() { let source = try? fixtureHelper.loadMtlFixture("simple") let loader = MaterialLoader(source: source!, basePath: "/home/user/myuser/path/to/project/") do { let materials = try loader.read() XCTAssertEqual(materials.count, 1) let material = materials[0] XCTAssertTrue(material.ambientColor.fuzzyEquals(Color.Black)) XCTAssertTrue(material.diffuseColor.fuzzyEquals( Color(r: 0.595140, g:0.074891, b: 0.080111) )) XCTAssertTrue(material.specularColor.fuzzyEquals(Color(r: 0.5, g: 0.5, b: 0.5))) XCTAssertNotNil(material.specularExponent) XCTAssertEqualWithAccuracy(material.specularExponent!, 96.078431, accuracy: 0.001) XCTAssertEqual(material.illuminationModel, IlluminationModel.DiffuseSpecular) XCTAssertEqual(material.ambientTextureMapFilePath, "/home/user/myuser/path/to/project/test.bmp") XCTAssertEqual(material.diffuseTextureMapFilePath, "/home/user/myuser/path/to/project/test_diffuse.bmp") } catch ObjLoadingError.UnexpectedFileFormat(let errorMessage) { XCTFail("Parsing failed with error \(errorMessage)") } catch { XCTFail("Parsing failed with unknown error") } } }
36.06383
116
0.666667
1656eeae5b918f5707f4310060ed0bae6396f797
197
// // Util.swift // SwiftVLC // // Created by sunlubo on 2019/1/31. // /// Allows to "box" another value. final class Box<T> { let value: T init(_ value: T) { self.value = value } }
12.3125
36
0.573604
898dc9e3c2a2c7a524c229d7487affd555ab33ee
2,074
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: request/user/delete_session_request.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. private struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } public struct DeleteSessionRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. private let _protobuf_package = "im.turms.proto" extension DeleteSessionRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".DeleteSessionRequest" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() {} } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func == (lhs: DeleteSessionRequest, rhs: DeleteSessionRequest) -> Bool { if lhs.unknownFields != rhs.unknownFields { return false } return true } }
38.407407
132
0.753616
76b721ef13c09e0f600b08893e0d61c2ed93a44d
2,291
// // SceneDelegate.swift // Calculator // // Created by Moxit Shah on 15/02/22. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.226415
147
0.712789
6793cfeb049a83a8b9876d7d29d8134163adf033
4,034
import Flutter import UIKit import Photos public class SwiftAddToGalleryPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "add_to_gallery", binaryMessenger: registrar.messenger()) let instance = SwiftAddToGalleryPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle( _ call: FlutterMethodCall, result: @escaping FlutterResult ) { if call.method == "addToGallery" { self.addToAssetCollection(call, result) } else { result(FlutterMethodNotImplemented) } } private func addToAssetCollection( _ call: FlutterMethodCall, _ result: @escaping FlutterResult ) { let permissionStatus = PHPhotoLibrary.authorizationStatus() if permissionStatus != .authorized { result(FlutterError(code: "permissions", message: "Please grant PHPhotoLibrary permission", details: nil)) } else { let args = call.arguments as? Dictionary<String, Any> let imagePath = args!["path"] as! String let albumName = args!["album"] as! String if let album = fetchAssetCollectionForAlbum(albumName) { self.addFileToAssetCollection(imagePath, album, result) } else { createAssetCollectionForAlbum(albumName: albumName) { (error) in guard error == nil else { result(FlutterError(code: "album_not_available", message: "Album Not Available", details: nil)) return } if let album = self.fetchAssetCollectionForAlbum(albumName){ self.addFileToAssetCollection(imagePath, album, result) } else { result(FlutterError(code: "could_not_create_album", message: "Could Not Create Album", details: nil)) } } } } } private func addFileToAssetCollection( _ imagePath: String, _ album: PHAssetCollection?, _ result: @escaping FlutterResult ) { let url = URL(fileURLWithPath: imagePath) PHPhotoLibrary.shared().performChanges({ let assetCreationRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: url) if (album != nil) { guard let assetCollectionChangeRequest = PHAssetCollectionChangeRequest(for: album!), let createdAssetPlaceholder = assetCreationRequest?.placeholderForCreatedAsset else { return } assetCollectionChangeRequest.addAssets(NSArray(array: [createdAssetPlaceholder])) } }) { (success, error) in if success { result(imagePath) // Success! } else { result(FlutterError(code: "could_not_save_file", message: "Could Not Save File", details: nil)) } } } private func fetchAssetCollectionForAlbum( _ albumName: String ) -> PHAssetCollection? { let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "title = %@", albumName) let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions) if let _: AnyObject = collection.firstObject { return collection.firstObject } return nil } private func createAssetCollectionForAlbum( albumName: String, completion: @escaping (Error?) -> () ) { PHPhotoLibrary.shared().performChanges({ PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: albumName) }) { (_, error) in DispatchQueue.main.async { completion(error) } } } }
39.165049
125
0.601884
0a9cedae7efdb3567b4b689463cf3357c160d0a2
11,288
/* file: conversion_based_unit.swift generated: Mon Jan 3 16:32:52 2022 */ /* This file was generated by the EXPRESS to Swift translator "exp2swift", derived from STEPcode (formerly NIST's SCL). exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23 WARNING: You probably don't want to edit it since your modifications will be lost if exp2swift is used to regenerate it. */ import SwiftSDAIcore extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { //MARK: -ENTITY DEFINITION in EXPRESS /* ENTITY conversion_based_unit SUBTYPE OF ( named_unit ); name : label; conversion_factor : measure_with_unit; WHERE wr1: ( SELF\named_unit.dimensions = derive_dimensional_exponents( conversion_factor\measure_with_unit. unit_component ) ); END_ENTITY; -- conversion_based_unit (line:10663 file:ap242ed2_mim_lf_v1.101.TY.exp) */ //MARK: - ALL DEFINED ATTRIBUTES /* SUPER- ENTITY(1) named_unit ATTR: dimensions, TYPE: dimensional_exponents -- EXPLICIT (DYNAMIC) -- possibly overriden by ENTITY: si_unit, TYPE: dimensional_exponents (as DERIVED) ENTITY(SELF) conversion_based_unit ATTR: name, TYPE: label -- EXPLICIT ATTR: conversion_factor, TYPE: measure_with_unit -- EXPLICIT SUB- ENTITY(3) externally_defined_conversion_based_unit (no local attributes) */ //MARK: - Partial Entity public final class _conversion_based_unit : SDAI.PartialEntity { public override class var entityReferenceType: SDAI.EntityReference.Type { eCONVERSION_BASED_UNIT.self } //ATTRIBUTES /// EXPLICIT ATTRIBUTE public internal(set) var _name: tLABEL // PLAIN EXPLICIT ATTRIBUTE /// EXPLICIT ATTRIBUTE public internal(set) var _conversion_factor: eMEASURE_WITH_UNIT // PLAIN EXPLICIT ATTRIBUTE public override var typeMembers: Set<SDAI.STRING> { var members = Set<SDAI.STRING>() members.insert(SDAI.STRING(Self.typeName)) //SELECT data types (indirectly) referencing the current type as a member of the select list members.insert(SDAI.STRING(sCLASSIFICATION_ITEM.typeName)) // -> Self members.insert(SDAI.STRING(sACTION_ITEMS.typeName)) // -> sCLASSIFICATION_ITEM members.insert(SDAI.STRING(sCHANGE_MANAGEMENT_OBJECT.typeName)) // -> sACTION_ITEMS members.insert(SDAI.STRING(sIR_USAGE_ITEM.typeName)) // -> sCLASSIFICATION_ITEM return members } //VALUE COMPARISON SUPPORT public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) { super.hashAsValue(into: &hasher, visited: &complexEntities) self._name.value.hashAsValue(into: &hasher, visited: &complexEntities) self._conversion_factor.value.hashAsValue(into: &hasher, visited: &complexEntities) } public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool { guard let rhs = rhs as? Self else { return false } if !super.isValueEqual(to: rhs, visited: &comppairs) { return false } if let comp = self._name.value.isValueEqualOptionally(to: rhs._name.value, visited: &comppairs) { if !comp { return false } } else { return false } if let comp = self._conversion_factor.value.isValueEqualOptionally(to: rhs._conversion_factor.value, visited: &comppairs) { if !comp { return false } } else { return false } return true } public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? { guard let rhs = rhs as? Self else { return false } var result: Bool? = true if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) { if !comp { return false } } else { result = nil } if let comp = self._name.value.isValueEqualOptionally(to: rhs._name.value, visited: &comppairs) { if !comp { return false } } else { result = nil } if let comp = self._conversion_factor.value.isValueEqualOptionally(to: rhs._conversion_factor.value, visited: &comppairs) { if !comp { return false } } else { result = nil } return result } //MARK: WHERE RULES (ENTITY) public static func WHERE_wr1(SELF: eCONVERSION_BASED_UNIT?) -> SDAI.LOGICAL { guard let SELF = SELF else { return SDAI.UNKNOWN } let _TEMP1 = SELF.GROUP_REF(eNAMED_UNIT.self) let _TEMP2 = _TEMP1?.DIMENSIONS let _TEMP3 = SELF.CONVERSION_FACTOR.GROUP_REF(eMEASURE_WITH_UNIT.self) let _TEMP4 = _TEMP3?.UNIT_COMPONENT let _TEMP5 = DERIVE_DIMENSIONAL_EXPONENTS(_TEMP4) let _TEMP6 = _TEMP2 .==. _TEMP5 return _TEMP6 } //EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR public init(NAME: tLABEL, CONVERSION_FACTOR: eMEASURE_WITH_UNIT) { self._name = NAME self._conversion_factor = CONVERSION_FACTOR super.init(asAbstructSuperclass:()) } //p21 PARTIAL ENTITY CONSTRUCTOR public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) { let numParams = 2 guard parameters.count == numParams else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil } guard case .success(let p0) = exchangeStructure.recoverRequiredParameter(as: tLABEL.self, from: parameters[0]) else { exchangeStructure.add(errorContext: "while recovering parameter #0 for entity(\(Self.entityName)) constructor"); return nil } guard case .success(let p1) = exchangeStructure.recoverRequiredParameter(as: eMEASURE_WITH_UNIT.self, from: parameters[1]) else { exchangeStructure.add(errorContext: "while recovering parameter #1 for entity(\(Self.entityName)) constructor"); return nil } self.init( NAME: p0, CONVERSION_FACTOR: p1 ) } } //MARK: - Entity Reference /** ENTITY reference - EXPRESS: ```express ENTITY conversion_based_unit SUBTYPE OF ( named_unit ); name : label; conversion_factor : measure_with_unit; WHERE wr1: ( SELF\named_unit.dimensions = derive_dimensional_exponents( conversion_factor\measure_with_unit. unit_component ) ); END_ENTITY; -- conversion_based_unit (line:10663 file:ap242ed2_mim_lf_v1.101.TY.exp) ``` */ public final class eCONVERSION_BASED_UNIT : SDAI.EntityReference { //MARK: PARTIAL ENTITY public override class var partialEntityType: SDAI.PartialEntity.Type { _conversion_based_unit.self } public let partialEntity: _conversion_based_unit //MARK: SUPERTYPES public let super_eNAMED_UNIT: eNAMED_UNIT // [1] public var super_eCONVERSION_BASED_UNIT: eCONVERSION_BASED_UNIT { return self } // [2] //MARK: SUBTYPES public var sub_eEXTERNALLY_DEFINED_CONVERSION_BASED_UNIT: eEXTERNALLY_DEFINED_CONVERSION_BASED_UNIT? { // [3] return self.complexEntity.entityReference(eEXTERNALLY_DEFINED_CONVERSION_BASED_UNIT.self) } //MARK: ATTRIBUTES /// __EXPLICIT(DYNAMIC)__ attribute /// - origin: SUPER( ``eNAMED_UNIT`` ) public var DIMENSIONS: eDIMENSIONAL_EXPONENTS { get { if let resolved = _named_unit._dimensions__provider(complex: self.complexEntity) { let value = resolved._dimensions__getter(complex: self.complexEntity) return value } else { return SDAI.UNWRAP( super_eNAMED_UNIT.partialEntity._dimensions ) } } set(newValue) { if let _ = _named_unit._dimensions__provider(complex: self.complexEntity) { return } let partial = super_eNAMED_UNIT.partialEntity partial._dimensions = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SELF( ``eCONVERSION_BASED_UNIT`` ) public var CONVERSION_FACTOR: eMEASURE_WITH_UNIT { get { return SDAI.UNWRAP( self.partialEntity._conversion_factor ) } set(newValue) { let partial = self.partialEntity partial._conversion_factor = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SELF( ``eCONVERSION_BASED_UNIT`` ) public var NAME: tLABEL { get { return SDAI.UNWRAP( self.partialEntity._name ) } set(newValue) { let partial = self.partialEntity partial._name = SDAI.UNWRAP(newValue) } } //MARK: INITIALIZERS public convenience init?(_ entityRef: SDAI.EntityReference?) { let complex = entityRef?.complexEntity self.init(complex: complex) } public required init?(complex complexEntity: SDAI.ComplexEntity?) { guard let partial = complexEntity?.partialEntityInstance(_conversion_based_unit.self) else { return nil } self.partialEntity = partial guard let super1 = complexEntity?.entityReference(eNAMED_UNIT.self) else { return nil } self.super_eNAMED_UNIT = super1 super.init(complex: complexEntity) } public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) { guard let entityRef = generic?.entityReference else { return nil } self.init(complex: entityRef.complexEntity) } public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) } public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) } //MARK: WHERE RULE VALIDATION (ENTITY) public override class func validateWhereRules(instance:SDAI.EntityReference?, prefix:SDAI.WhereLabel) -> [SDAI.WhereLabel:SDAI.LOGICAL] { guard let instance = instance as? Self else { return [:] } let prefix2 = prefix + " \(instance)" var result = super.validateWhereRules(instance:instance, prefix:prefix2) result[prefix2 + " .WHERE_wr1"] = _conversion_based_unit.WHERE_wr1(SELF: instance) return result } //MARK: DICTIONARY DEFINITION public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition } private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition() private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition { let entityDef = SDAIDictionarySchema.EntityDefinition(name: "CONVERSION_BASED_UNIT", type: self, explicitAttributeCount: 2) //MARK: SUPERTYPE REGISTRATIONS entityDef.add(supertype: eNAMED_UNIT.self) entityDef.add(supertype: eCONVERSION_BASED_UNIT.self) //MARK: ATTRIBUTE REGISTRATIONS entityDef.addAttribute(name: "DIMENSIONS", keyPath: \eCONVERSION_BASED_UNIT.DIMENSIONS, kind: .explicit, source: .superEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "CONVERSION_FACTOR", keyPath: \eCONVERSION_BASED_UNIT.CONVERSION_FACTOR, kind: .explicit, source: .thisEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "NAME", keyPath: \eCONVERSION_BASED_UNIT.NAME, kind: .explicit, source: .thisEntity, mayYieldEntityReference: false) return entityDef } } }
38.525597
185
0.705705
8f7bef0e3b29dd54bd969cb3186da1f73e84d3e1
2,523
/*: ## App Exercise - Workout Extensions >These exercises reinforce Swift concepts in the context of a fitness tracking app. Add an extension to the `Workout` struct below and make it adopt the `CustomStringConvertible` protocol. */ struct Workout { var distance: Double var time: Double var averageHR: Int } extension Workout: CustomStringConvertible { var description: String { return "Workout(distance: \(distance), time: \(time), averageHR: \(averageHR))" } } /*: Now create another extension for `Workout` and add a property `speed` of type `Double`. It should be a computed property that returns the average meters per second traveled during the workout. */ extension Workout { var speed: Double { return distance / time } func harderWorkout() -> Workout { return Workout(distance: distance*2, time: time*2, averageHR: averageHR + 40) } } /*: Now add a method `harderWorkout` that takes no parameters and returns another `Workout` instance. This method should double the `distance` and `time` properties, and add 40 to `averageHR`. Create an instance of `Workout` and print it to the console. Then call `harderWorkout` and print the new `Workout` instance to the console. */ let workout = Workout(distance: 1000, time: 100, averageHR: 120) print(workout) let harderWorkout = workout.harderWorkout() print(harderWorkout) /*: _Copyright © 2017 Apple Inc._ _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._ */ //: [Previous](@previous) | page 2 of 2
51.489796
463
0.748712
209514f8a189ce3355fde222a4516892d6d10a10
1,314
// // IssueCommentTextCell.swift // Freetime // // Created by Ryan Nystrom on 5/19/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import IGListKit import StyledText final class IssueCommentTextCell: IssueCommentBaseCell, ListBindable { static let inset = UIEdgeInsets( top: 0, left: Styles.Sizes.commentGutter, bottom: Styles.Sizes.rowSpacing, right: Styles.Sizes.commentGutter ) let textView = MarkdownStyledTextView() override init(frame: CGRect) { super.init(frame: frame) isAccessibilityElement = true contentView.addSubview(textView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() textView.reposition(width: contentView.bounds.width) } // MARK: Accessibility override var accessibilityLabel: String? { get { return AccessibilityHelper.generatedLabel(forCell: self) } set { } } // MARK: ListBindable func bindViewModel(_ viewModel: Any) { guard let viewModel = viewModel as? StyledTextRenderer else { return } textView.configure(renderer: viewModel, width: contentView.bounds.width) } }
24.333333
80
0.671233