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
|
---|---|---|---|---|---|
f5d945e7147b07f5dda44aa3a9ef4d72e32dde36 | 6,522 | //
// ViewController.swift
// RPG OOP II
//
// Created by Sibrian on 7/11/16.
// Copyright © 2016 Sibrian. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var attackUpdateLabel: UILabel!
var attackSound: AVAudioPlayer!
var punchSound: AVAudioPlayer!
var deathSound: AVAudioPlayer!
var gameMusic: AVAudioPlayer!
@IBOutlet weak var trollHPLabel: UILabel!
@IBOutlet weak var heroHPLabel: UILabel!
@IBOutlet weak var muteButton: UIButton!
@IBOutlet weak var unmuteButton: UIButton!
@IBOutlet weak var restartButton: UIButton!
@IBOutlet weak var heroAttackButton: UIButton!
@IBOutlet weak var trollAttackButton: UIButton!
var hero: Hero!
var troll: Enemy!
@IBOutlet weak var trollImageView: UIImageView!
@IBOutlet weak var heroImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initializeSounds()
initializeGame()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initializeGame() {
troll = Enemy(startingHP: 110, initialAttackPower: 16)
hero = Hero(heroName: "Sir Nauticus", HP: 170, attackPower: 22)
initializeHPLabel(troll, hero: hero)
gameMusic.play()
}
@IBAction func trollAttackButtonPressed(sender: UIButton) {
if punchSound.playing {
punchSound.currentTime = 0
}
punchSound.play()
if hero.attemptAttack(troll.attackPower) {
attackUpdateLabel.text = "\(troll.type) attacked the hero for \(troll.attackPower) damage!!"
heroHPLabel.text = "\(hero.HP) HP"
} else {
attackUpdateLabel.text = "The hero has dodged the attack!!! "
}
if hero.isDead {
deathSound.play()
attackUpdateLabel.text = "THE TROLL HAS VANQUISHED \(hero.name)!"
heroHPLabel.hidden = true
heroImageView.alpha = 0.5
disableAndFadeButtons()
}
}
@IBAction func heroAttackButtonPressed(sender: UIButton) {
if attackSound.playing {
attackSound.currentTime = 0
}
attackSound.play()
if troll.attemptAttack(hero.attackPower) {
attackUpdateLabel.text = "\(hero.name) attacks \(troll.type) for \(hero.attackPower) damage!"
trollHPLabel.text = "\(troll.HP) HP"
} else {
attackUpdateLabel.text = "Troll has dodged the attack by \(hero.name)!!!"
}
if troll.isDead {
deathSound.play()
attackUpdateLabel.text = "\(hero.name) HAS VANQUISHED THE TROLL!"
trollHPLabel.hidden = true
trollImageView.alpha = 0.5
disableAndFadeButtons()
}
}
@IBAction func muteButtonPressed(sender: UIButton) {
if gameMusic.playing {
gameMusic.stop()
}
muteButton.hidden = true
unmuteButton.hidden = false
}
@IBAction func unmuteButtonPressed(sender: UIButton) {
if !gameMusic.playing {
gameMusic.play()
}
muteButton.hidden = false
unmuteButton.hidden = true
}
@IBAction func restartButtonPressed(sender: UIButton) {
resetGame()
}
func resetGame() {
initializeGame()
gameMusic.currentTime = 0 //restart the menu music
gameMusic.play()
enableAndUnfadeButtons()
}
func initializeHPLabel(troll: Enemy, hero: Hero) {
trollHPLabel.text = "\(troll.HP) HP"
heroHPLabel.text = "\(hero.HP) HP"
}
func disableAndFadeButtons() {
trollAttackButton.enabled = false
trollAttackButton.alpha = 0.5
heroAttackButton.enabled = false
heroAttackButton.alpha = 0.5
restartButton.hidden = false
}
func enableAndUnfadeButtons() {
trollAttackButton.enabled = true
trollAttackButton.alpha = 1.0
heroAttackButton.enabled = true
heroAttackButton.alpha = 1.0
restartButton.hidden = true
trollHPLabel.hidden = false
trollImageView.alpha = 1.0
heroHPLabel.hidden = false
heroImageView.alpha = 1.0
}
func initializeSounds() {
//initialize the attack sound (hero)
let attackSoundPath = NSBundle.mainBundle().pathForResource("attack", ofType: "wav")
let attackSoundURL = NSURL(fileURLWithPath: attackSoundPath!)
do {
try attackSound = AVAudioPlayer(contentsOfURL: attackSoundURL)
attackSound.prepareToPlay()
} catch let error as NSError {
print(error.debugDescription)
}
//initialize the punch sound (troll)
let punchSoundPath = NSBundle.mainBundle().pathForResource("punch", ofType: "mp3")
let punchSoundURL = NSURL(fileURLWithPath: punchSoundPath!)
do {
try punchSound = AVAudioPlayer(contentsOfURL: punchSoundURL)
punchSound.prepareToPlay()
} catch let error as NSError {
print(error.debugDescription)
}
//initialize the deathSound
let deathSoundPath = NSBundle.mainBundle().pathForResource("death", ofType: "wav")
let deathSoundURL = NSURL(fileURLWithPath: deathSoundPath!)
do {
try deathSound = AVAudioPlayer(contentsOfURL: deathSoundURL)
deathSound.prepareToPlay()
} catch let error as NSError {
print(error.debugDescription)
}
//initialize the game music
let gameMusicPath = NSBundle.mainBundle().pathForResource("menuMusic", ofType: "mp3")
let gameMusicPathURL = NSURL(fileURLWithPath: gameMusicPath!)
do {
try gameMusic = AVAudioPlayer(contentsOfURL: gameMusicPathURL)
gameMusic.prepareToPlay()
} catch let error as NSError {
print(error.debugDescription)
}
}
}
| 29.116071 | 105 | 0.588623 |
1a72df357a19ac55b454656bee1467dc298f19c3 | 5,810 | //
// Cached.swift
// MEOKit
//
// Created by Mitsuhau Emoto on 2018/12/09.
// Copyright © 2018 Mitsuharu Emoto. All rights reserved.
//
import UIKit
/// データをキャッシュする
public class Cached: NSObject {
private static var shared: Cached = Cached()
private var cache: NSCache<AnyObject, AnyObject>!
private var pathCacheDir : String!
private let dirName:String = "CachesByCached"
private override init() {
super.init()
self.cache = NSCache()
self.cache.countLimit = 20
let paths = NSSearchPathForDirectoriesInDomains(.libraryDirectory,
.userDomainMask,
true)
let url = URL(string: paths[0])!
self.pathCacheDir = url.appendingPathComponent(dirName).absoluteString
self.makeTempDirs()
NotificationCenter.default.addObserver(self,
selector: #selector(didReceiveMemoryWarning(notification:)),
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self,
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil)
}
@objc func didReceiveMemoryWarning(notification: Notification){
self.clearCachesOnMemory()
}
private func clearCachesOnMemory(){
self.cache.removeAllObjects()
}
private func pathForUrl(urlString: String) -> URL{
let md5 = urlString.meo.md5
let path = URL(string: self.pathCacheDir)!.appendingPathComponent(md5)
return path
}
private func makeTempDirs(){
var isDir: ObjCBool = ObjCBool(false)
let exists: Bool = FileManager.default.fileExists(atPath: self.pathCacheDir,
isDirectory: &isDir)
if exists == false || isDir.boolValue == false{
do{
try FileManager.default.createDirectory(atPath: self.pathCacheDir,
withIntermediateDirectories: true,
attributes: nil)
}catch{
}
}
}
private func cachedEntity(key: String) -> CachedEntity?{
var data = self.cache.object(forKey: key.meo.md5 as AnyObject)
if data == nil{
data = CachedEntity.load(path: self.pathForUrl(urlString: key))
}
return (data as? CachedEntity)
}
private func setCachedEntity(cachedEntity: CachedEntity, key:String){
cachedEntity.write(path: self.pathForUrl(urlString: key))
self.cache.setObject(cachedEntity, forKey: key.meo.md5 as AnyObject)
}
}
// 公開メソッド
public extension Cached{
static func data(key: String) -> Data?{
let cached = Cached.shared
guard let cachedEntity = cached.cachedEntity(key: key) else {
return nil
}
return cachedEntity.data
}
static func string(key: String) -> String?{
let cached = Cached.shared
guard let cachedEntity = cached.cachedEntity(key: key) else {
return nil
}
return cachedEntity.string
}
static func image(url: URL) -> UIImage?{
return Cached.image(key: url.absoluteString)
}
static func image(key: String) -> UIImage?{
let cached = Cached.shared
guard let cachedEntity = cached.cachedEntity(key: key) else {
return nil
}
return cachedEntity.image
}
static func add(data: Data, key:String, validity:CachedValidity = .oneweek){
let cached = Cached.shared
let cachedEntity:CachedEntity = CachedEntity(data: data, validity: validity)
cached.setCachedEntity(cachedEntity: cachedEntity, key: key)
}
static func add(string: String, key:String, validity:CachedValidity = .oneweek) {
let cached = Cached.shared
let cachedEntity:CachedEntity = CachedEntity(string: string, validity: validity)
cached.setCachedEntity(cachedEntity: cachedEntity, key: key)
}
static func add(image: UIImage, url:URL, validity:CachedValidity = .oneweek) {
Cached.add(image: image, key: url.absoluteString, validity:validity)
}
static func add(image: UIImage, key:String, validity:CachedValidity = .oneweek) {
var imageFormat:CachedImageFormat = .jpg
if key.hasSuffix(".jpg") || key.hasSuffix(".jpeg"){
imageFormat = .jpg
}else if key.hasSuffix(".png"){
imageFormat = .png
}
let cached = Cached.shared
let cachedEntity:CachedEntity = CachedEntity(image: image,
imageFormat: imageFormat,
validity: validity)
cached.setCachedEntity(cachedEntity: cachedEntity, key: key)
}
static func delete(key: String){
let cached = Cached.shared
cached.cache.removeObject(forKey: key.meo.md5 as AnyObject)
CachedEntity.delete(path: cached.pathForUrl(urlString: key))
}
static func deleteAll(){
let cached = Cached.shared
cached.clearCachesOnMemory()
if FileManager.default.fileExists(atPath: cached.pathCacheDir){
do{
try FileManager.default.removeItem(atPath: cached.pathCacheDir)
cached.makeTempDirs()
}catch{
}
}
}
}
| 35 | 107 | 0.572806 |
6a8d72cfa4671de41ff39a6222cd2816c52e62f1 | 1,302 | //
// HZMeTableViewCell.swift
// NoteBook
//
// Created by DH on 16/4/29.
// Copyright © 2016年 chris. All rights reserved.
//
import UIKit
import SnapKit
class HZMeTableViewCell: UITableViewCell {
// 内容
lazy var contentLabel: UILabel = {
let contentLabel = UILabel()
contentLabel.textAlignment = .Center
return contentLabel
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(contentLabel)
contentLabel.snp_makeConstraints { (make) -> Void in
make.center.equalTo(contentView)
}
}
var contentString: String? {
didSet{
contentLabel.text = contentString
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 快速创建一个cell
class func meTableViewCell(tableView: UITableView) ->HZMeTableViewCell {
let ID: String = "me"
var cell: HZMeTableViewCell? = (tableView.dequeueReusableCellWithIdentifier(ID) as? HZMeTableViewCell)
if cell == nil {
cell = HZMeTableViewCell(style: .Default, reuseIdentifier: ID)
}
return cell!
}
}
| 26.571429 | 110 | 0.631336 |
e6681d114df0b756aefdf32d299982bf90d98c70 | 2,986 | import RxSwift
class FullTransactionInfoInteractor {
private let disposeBag = DisposeBag()
weak var delegate: IFullTransactionInfoInteractorDelegate?
private let providerFactory: IFullTransactionInfoProviderFactory
private var provider: IFullTransactionInfoProvider?
private let reachabilityManager: IReachabilityManager
private let dataProviderManager: IFullTransactionDataProviderManager
private let pasteboardManager: IPasteboardManager
private let async: Bool
init(providerFactory: IFullTransactionInfoProviderFactory, reachabilityManager: IReachabilityManager, dataProviderManager: IFullTransactionDataProviderManager, pasteboardManager: IPasteboardManager, async: Bool = true) {
self.providerFactory = providerFactory
self.reachabilityManager = reachabilityManager
self.dataProviderManager = dataProviderManager
self.pasteboardManager = pasteboardManager
self.async = async
}
private func showError() {
delegate?.onError(providerName: provider?.providerName)
}
}
extension FullTransactionInfoInteractor: IFullTransactionInfoInteractor {
var reachableConnection: Bool { return reachabilityManager.isReachable }
func didLoad() {
// Reachability Manager Signal
var reachabilitySignal: Observable = reachabilityManager.reachabilitySignal.asObserver()
if async {
reachabilitySignal = reachabilitySignal.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background)).observeOn(MainScheduler.instance)
}
reachabilitySignal.subscribe(onNext: { [weak self] in
self?.delegate?.onConnectionChanged()
}).disposed(by: disposeBag)
// DataProvider Manager Signal
var dataProviderUpdatedSignal: Observable = dataProviderManager.dataProviderUpdatedSignal.asObserver()
if async {
dataProviderUpdatedSignal = dataProviderUpdatedSignal.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background)).observeOn(MainScheduler.instance)
}
dataProviderUpdatedSignal.subscribe(onNext: { [weak self] in
self?.delegate?.onProviderChanged()
}).disposed(by: disposeBag)
}
func updateProvider(for wallet: Wallet) {
provider = providerFactory.provider(for: wallet)
}
func retrieveTransactionInfo(transactionHash: String) {
provider?.retrieveTransactionInfo(transactionHash: transactionHash).subscribe(onSuccess: { [weak self] record in
if let record = record {
self?.delegate?.didReceive(transactionRecord: record)
} else {
self?.showError()
}
}, onError: { [weak self] _ in
self?.showError()
}).disposed(by: disposeBag)
}
func url(for hash: String) -> String? {
return provider?.url(for: hash)
}
func copyToPasteboard(value: String) {
pasteboardManager.set(value: value)
}
} | 35.975904 | 224 | 0.712659 |
0979d48c0c3ff7ab61cccfe7680611a07e3737ce | 213 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{{{b
return[T:{struct E{class A{let a}}}}}{
| 30.428571 | 87 | 0.732394 |
0e9354ed860629ebc14f344b50efa9d06b4c3366 | 815 | //
// ReadingScreenViewController.swift
// GrioBookChallenge
//
// Created by Santos Solorzano on 2/3/16.
// Copyright © 2016 santosjs. All rights reserved.
//
import UIKit
class ReadingScreenViewController: UIViewController {
var webviewUrl: String?
@IBOutlet weak var readingWebview: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// load corresponding book url in webview
if let webviewUrl = self.webviewUrl {
let url = NSURL (string: webviewUrl);
let requestObj = NSURLRequest(URL: url!);
readingWebview.loadRequest(requestObj);
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 24.69697 | 58 | 0.64908 |
f73e97750094fe45892cc0877c4821426baed36a | 213 | //
// Error.swift
// ios-architecture-example
//
// Created by DongHeeKang on 06/12/2018.
// Copyright © 2018 k-lpmg. All rights reserved.
//
enum APIError: Error {
case urlIsInvalid
case dataIsNil
}
| 16.384615 | 49 | 0.671362 |
b9b09f967b9289059f267cc0f106acdbf1b98f12 | 2,118 | // MIT License
//
// Copyright YOOX NET-A-PORTER (c) 2018
//
// 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
/// Alphabet types
public enum Alphabet: String, Codable {
case arabic
case greek
case greekExtended
case latin
case latinSupplementary
case myanmar
case russian
case russianSupplementary
/// A valid CountableClosedRange<UInt32> based on Self
public var range: CountableClosedRange<UInt32> {
switch self {
case .arabic: return 0x600...0x6FF
case .greek: return 0x370...0x3FF
case .greekExtended: return 0x1F00...0x1FFF
case .latin: return 0x20...0x7F
case .latinSupplementary: return 0xA0...0xFF
case .myanmar: return 0x1000...0x109F
case .russian: return 0x400...0x4FF
case .russianSupplementary: return 0x500...0x52F
}
}
public static var available: [Alphabet] = [.arabic, .greek, .greekExtended, .latin, .latinSupplementary, .myanmar, .russian, .russianSupplementary]
}
public enum SpecialChar: UInt32 {
case whiteSpace = 32
}
| 37.821429 | 151 | 0.720963 |
1d4ce5454d66677709391906cdb09cd552077a14 | 1,738 | // RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -whole-module-optimization -module-name PlaygroundSupport -emit-module-path %t/PlaygroundSupport.swiftmodule -parse-as-library -c -o %t/PlaygroundSupport.o %S/Inputs/SilentPCMacroRuntime.swift %S/Inputs/PlaygroundsRuntime.swift
// RUN: %target-build-swift -Xfrontend -playground -Xfrontend -debugger-support -o %t/main -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main2 -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-codesign %t/main2
// RUN: %target-run %t/main2 | %FileCheck %s
// REQUIRES: executable_test
import PlaygroundSupport
struct S {
var dict: [Int : Int?]
subscript(_ int: Int) -> Int? {
get {
dict[int, default: Int(String(int))]
}
set {
dict[int] = newValue
}
}
init() {
dict = [:]
}
}
var s = S()
s[13] = 33
s[14]
s[13]
// CHECK: {{.*}} __builtin_log_scope_entry
// CHECK-NEXT: {{.*}} __builtin_log_scope_exit
// CHECK: {{.*}} __builtin_log_scope_entry
// CHECK-NEXT: {{.*}} __builtin_log[='Optional(Optional(33))']
// CHECK-NEXT: {{.*}} __builtin_log_scope_exit
// CHECK: {{.*}} __builtin_log_scope_entry
// CHECK-NEXT: {{.*}} __builtin_log[='Optional(14)']
// CHECK-NEXT: {{.*}} __builtin_log_scope_exit
// CHECK-NEXT: {{.*}} __builtin_log[='Optional(14)']
// CHECK: {{.*}} __builtin_log_scope_entry
// CHECK-NEXT: {{.*}} __builtin_log[='Optional(33)']
// CHECK-NEXT: {{.*}} __builtin_log_scope_exit
// CHECK-NEXT: {{.*}} __builtin_log[='Optional(33)']
| 36.208333 | 255 | 0.652474 |
7a0183b5c6b3581dd7e0b17327e31da1f3772794 | 268 | import Foundation
var stringOne = "Hello Swift"
var stringTwo = ""
stringOne.isEmpty //false
stringTwo.isEmpty //true
stringOne == "hello swift" //false
stringOne == "Hello Swift" //true
stringOne.hasPrefix("Hello") //true
stringOne.hasSuffix("Hello") //false
| 22.333333 | 37 | 0.720149 |
ff6a383cbce9878693a8bcb157aaaadd2cef9f93 | 741 | //
// MainMenuScene.swift
// 14Bis
//
// Created by Matheus Aeroso on 01/06/15.
//
//
import SpriteKit;
class MainMenuScene: SKScene {
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch in (touches as! Set<UITouch>) {
let location: CGPoint = touch.locationInNode(self);
let node = self.nodeAtPoint(location);
if node.name == "playButton" {
let reveal = SKTransition.revealWithDirection(SKTransitionDirection.Left, duration: 0.5)
let gameScene = GameScene.unarchiveFromFile("GameScene") as? GameScene
self.view?.presentScene(gameScene, transition: reveal)
}
}
}
}
| 29.64 | 104 | 0.612686 |
111ba94637a8b00c9f1cd678b44263137b87f902 | 1,474 | // Deinitialization Chapter
// Class definitions can have at most one deinitializer per class. The deinitializer does not take any parameters and is written without parentheses:
struct Bank {
static var coinsInBank = 10_000
static func vendCoins(var numberOfCoinsToVend: Int) -> Int {
numberOfCoinsToVend = min(numberOfCoinsToVend, coinsInBank)
coinsInBank -= numberOfCoinsToVend
return numberOfCoinsToVend
}
static func receiveCoins(coins: Int) {
coinsInBank += coins
}
}
class Player {
var coinsInPurse: Int
init(coins: Int) {
coinsInPurse = Bank.vendCoins(coins)
}
func winCoins(coins: Int) {
coinsInPurse += Bank.vendCoins(coins)
}
deinit {
Bank.receiveCoins(coinsInPurse)
}
}
var playerOne: Player? = Player(coins: 100)
println("A new player has joined the game with \(playerOne!.coinsInPurse) coins")
println("There are now \(Bank.coinsInBank) coins left in the bank")
playerOne!.winCoins(2_000)
println("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins")
println("The bank now only has \(Bank.coinsInBank) coins left")
playerOne = nil
println("PlayerOne has left the game")
println("The bank now has \(Bank.coinsInBank) coins")
Bank.coinsInBank // This should be back to 10_000. The playerOne variable doesn't get deinitialized in the playground because the GUI keeps it around in case it is referred to again I presume.
| 32.043478 | 192 | 0.712347 |
c1cdc47bd4d9db432aa4b08ca724679b5bd4fdb7 | 466 | //
// Introductory information is in the `README.md` file in the root directory of the repository this file is in.
// Licensing information is in the `LICENSE` file in the root directory of the repository this file is in.
//
public struct TypeIntrospection: RawRepresentable {
// MARK: RawRepresentable
public typealias RawValue = Any.Type
public init(rawValue: RawValue) {
self.rawValue = rawValue
}
public let rawValue: RawValue
}
| 25.888889 | 111 | 0.72103 |
23fd418e84b443e630f244ac99c0bcf32dd76c78 | 593 | //
// PhotoCell.swift
// LPAlbum
//
// Created by 郜宇 on 2017/9/13.
// Copyright © 2017年 Loopeer. All rights reserved.
//
import UIKit
class PhotoCell: UICollectionViewCell {
let photoView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
photoView.frame = bounds
photoView.clipsToBounds = true
photoView.contentMode = .scaleAspectFit
contentView.addSubview(photoView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 20.448276 | 59 | 0.625632 |
dd4fd7ac4f0130476f8f744f1033f74483b335c7 | 2,261 | //
// UIColor-Extension.swift
// LZBPageView
//
// Created by zibin on 2017/5/12.
// Copyright © 2017年 项目共享githud地址:https://github.com/lzbgithubcode/LZBPageView 简书详解地址:http://www.jianshu.com/p/3170d0d886a2 作者喜欢分享技术与开发资料,如果你也是喜欢分享的人可以加入我们iOS资料demo共享群:490658347. All rights reserved.
//
import UIKit
extension UIColor {
//类函数 class func func 函数
class func getRandomColor() ->UIColor
{
return UIColor(red: CGFloat(arc4random_uniform(255))/255.0, green: CGFloat(arc4random_uniform(255))/255.0, blue: CGFloat(arc4random_uniform(255))/255.0, alpha: 1.0)
}
//特性:1、在extension扩展,必须使用convenience便利构造函数
// 2.必须调用self.init,构造默认没有返回值,但是系统会自动返回但是不能返回nil
convenience init(r : CGFloat , g : CGFloat, b : CGFloat, a : CGFloat = 1.0){
self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}
//颜色转换
convenience init?(colorHexString : String) {
//1.判断字符串长度是否大于6
guard colorHexString.characters.count >= 6 else {
return nil
}
//2.将字符串转化为大写
var hextempString = colorHexString.uppercased()
//3.判断字符串是否是颜色字符串
if hextempString.hasPrefix("0X") || hextempString.hasPrefix("##"){
hextempString = (hextempString as NSString).substring(to: 2)
}
//4.分离出rgb的十六进制
var range = NSRange(location: 0, length: 2)
let rhex = (hextempString as NSString).substring(with: range)
range.location = 2
let ghex = (hextempString as NSString).substring(with: range)
range.location = 4
let bhex = (hextempString as NSString).substring(with: range)
//5.scaner转化
var r : UInt32 = 0
var g : UInt32 = 0
var b : UInt32 = 0
Scanner(string: rhex).scanHexInt32(&r)
Scanner(string: ghex).scanHexInt32(&g)
Scanner(string: bhex).scanHexInt32(&b)
self.init(r: CGFloat(r), g: CGFloat(g), b: CGFloat(b))
}
//获取颜色的RGB值
func getRGBValue() -> (CGFloat , CGFloat , CGFloat){
guard let components = self.cgColor.components else {
fatalError("获取颜色的RGB值失败")
}
return (components[0] * 255,components[1] * 255,components[2] * 255)
}
}
| 34.784615 | 201 | 0.615215 |
76d07b8b76974d7a940de7bea2f3315695e0f1ad | 1,947 | import SwiftUI
/// https://developer.apple.com/videos/play/wwdc2020/10031/ - Stacks, Grids, and Outlines in SwiftUI
// Adaptive LazyVGrid
/*
LazyVGrid(columns: [GridItem(.adaptive(minimum: 80))]) {
ForEach(0 ..< 20) { item in
Rectangle()
.frame(height: 100)
}
}
*/
// Grid and Item Spacing
/*
LazyVGrid(
columns: [GridItem(.adaptive(minimum: 80), spacing: 16)],
spacing: 16) {
ForEach(0 ..< 12) { item in
RoundedRectangle(cornerRadius: 10)
.fill(Color.blue)
.frame(height: 100)
}
}
.padding()
*/
// LazyHGrid
/*
LazyHGrid(
rows: [GridItem(.adaptive(minimum: 80), spacing: 16)],
spacing: 12) {
ForEach(0 ..< 20) { item in
Rectangle().frame(width: 100)
}
}
ScrollView(.horizontal) {
LazyHGrid(
rows: [GridItem(.adaptive(minimum: 80), spacing: 8)],
spacing: 12) {
ForEach(0 ..< 20) { item in
Rectangle().frame(width: 300)
}
}
.frame(height: 300)
}
*/
// Fixed Column
/*
LazyVGrid(
columns: [
GridItem(.fixed(100), spacing: 8),
GridItem(.fixed(160), spacing: 8),
GridItem(.fixed(80), spacing: 8)
], spacing: 12) {
ForEach(0 ..< 20) { item in
Rectangle()
.frame(height: 80)
}
}
*/
// Repeating Columns
// Array(repeating: .init(.flexible(), spacing: 8), count: 4)
struct LazyGrid: View {
var body: some View {
ScrollView(.horizontal) {
LazyHGrid(
rows: [GridItem(.adaptive(minimum: 80), spacing: 8)],
spacing: 12) {
ForEach(0 ..< 20) { item in
Rectangle().frame(width: 300)
}
}
.frame(height: 300)
}
}
}
#if DEBUG
struct LazyGrid_Previews: PreviewProvider {
static var previews: some View {
LazyGrid()
}
}
#endif
| 20.28125 | 100 | 0.522342 |
7a5043f1c16c62dd2fc0277eedec0296b539039e | 1,102 | import UIKit
extension String {
/**
Convert a string from snake case to pascal/capital camel case
This is useful for class names
```
"foo_bar".snakeToCamelCase => "FooBar"
```
- returns: A string in the ClassCase
*/
var snakeToClassCase: String {
var ss = NSMutableArray(array: (self as String).componentsSeparatedByString("_") as NSArray)
for (var i = 0; i < ss.count; ++i) {
ss[i] = ss[i].capitalizedString
}
return ss.componentsJoinedByString("") as String
}
/**
Convert a string from snake case to camel case
```
"foo_bar".snakeToCamelCase => "fooBar"
```
- returns: A string in the camelCase
*/
var snakeToCamelCase: String {
var ss = NSMutableArray(array: (self as String).componentsSeparatedByString("_") as NSArray)
for (var i = 1; i < ss.count; ++i) {
ss[i] = ss[i].capitalizedString
}
return ss.componentsJoinedByString("") as String
}
} | 25.627907 | 100 | 0.553539 |
e616193c31ee3724b9d4664cf8474e3ae4d23490 | 946 | import Foundation
public func cURL(_ request: URLRequest) -> String {
guard let url = request.url
, let method = request.httpMethod else {
return "$ curl command could not be created"
}
var components = ["$ curl -v"]
components.append("-X \(method)")
for header in request.allHTTPHeaderFields ?? [:] {
let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-H \"\(header.key): \(escapedValue)\"")
}
if let httpBodyData = request.httpBody {
let httpBody = String(decoding: httpBodyData, as: UTF8.self)
var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(url.absoluteString)\"")
return components.joined(separator: " \\\n\t")
}
| 31.533333 | 84 | 0.608879 |
bbfaeaa4df411a66f2ff4b019e949d392e8de608 | 21,564 | //
// SwiftCurrent_NavigationLinkTests.swift
// SwiftCurrent
//
// Created by Tyler Thompson on 7/12/21.
// Copyright © 2021 WWT and Tyler Thompson. All rights reserved.
//
import XCTest
import SwiftUI
import ViewInspector
import SwiftCurrent
@testable import SwiftCurrent_SwiftUI // testable sadly needed for inspection.inspect to work
@available(iOS 15.0, macOS 11, tvOS 14.0, watchOS 7.0, *)
final class SwiftCurrent_NavigationLinkTests: XCTestCase, View {
func testWorkflowCanBeFollowed() async throws {
struct FR1: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR1 type") }
}
struct FR2: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR2 type") }
}
let expectOnFinish = expectation(description: "OnFinish called")
let wfr1 = try await MainActor.run {
WorkflowView {
WorkflowItem(FR1.self).presentationType(.navigationLink)
WorkflowItem(FR2.self)
}
.onFinish { _ in
expectOnFinish.fulfill()
}
}
.hostAndInspect(with: \.inspection)
.extractWorkflowLauncher()
.extractWorkflowItemWrapper()
print(type(of: wfr1))
XCTAssertEqual(try wfr1.find(FR1.self).text().string(), "FR1 type")
try await wfr1.proceedAndCheckNavLink(on: FR1.self)
let wfr2 = try await wfr1.extractWrappedWrapper()
XCTAssertEqual(try wfr2.find(FR2.self).text().string(), "FR2 type")
try await wfr2.find(FR2.self).proceedInWorkflow()
wait(for: [expectOnFinish], timeout: TestConstant.timeout)
}
func testWorkflowCanBeFollowed_WithWorkflowGroup() async throws {
struct FR1: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR1 type") }
}
struct FR2: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR2 type") }
}
let expectOnFinish = expectation(description: "OnFinish called")
let wfr1 = try await MainActor.run {
WorkflowView {
WorkflowItem(FR1.self).presentationType(.navigationLink)
WorkflowGroup {
WorkflowItem(FR2.self)
}
}
.onFinish { _ in
expectOnFinish.fulfill()
}
}
.hostAndInspect(with: \.inspection)
.extractWorkflowLauncher()
.extractWorkflowItemWrapper()
print(type(of: wfr1))
XCTAssertEqual(try wfr1.find(FR1.self).text().string(), "FR1 type")
try await wfr1.proceedAndCheckNavLink(on: FR1.self)
let wfr2 = try await wfr1.extractWrappedWrapper()
XCTAssertEqual(try wfr2.find(FR2.self).text().string(), "FR2 type")
try await wfr2.find(FR2.self).proceedInWorkflow()
wait(for: [expectOnFinish], timeout: TestConstant.timeout)
}
func testWorkflowCanBeFollowed_WithBuildOptions_WhenTrue() async throws {
struct FR1: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR1 type") }
}
struct FR2: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR2 type") }
}
let expectOnFinish = expectation(description: "OnFinish called")
let wfr1 = try await MainActor.run {
WorkflowView {
WorkflowItem(FR1.self).presentationType(.navigationLink)
if true {
WorkflowItem(FR2.self)
}
}
.onFinish { _ in
expectOnFinish.fulfill()
}
}
.hostAndInspect(with: \.inspection)
.extractWorkflowLauncher()
.extractWorkflowItemWrapper()
print(type(of: wfr1))
XCTAssertEqual(try wfr1.find(FR1.self).text().string(), "FR1 type")
try await wfr1.proceedAndCheckNavLink(on: FR1.self)
let wfr2 = try await wfr1.extractWrappedWrapper()
XCTAssertEqual(try wfr2.find(FR2.self).text().string(), "FR2 type")
try await wfr2.find(FR2.self).proceedInWorkflow()
wait(for: [expectOnFinish], timeout: TestConstant.timeout)
}
func testWorkflowCanBeFollowed_WithBuildOptions_WhenFalse() async throws {
struct FR1: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR1 type") }
}
struct FR2: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR2 type") }
}
struct FR3: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR3 type") }
}
let expectOnFinish = expectation(description: "OnFinish called")
let wfr1 = try await MainActor.run {
WorkflowView {
WorkflowItem(FR1.self).presentationType(.navigationLink)
if false {
WorkflowItem(FR2.self)
}
WorkflowItem(FR3.self)
}
.onFinish { _ in
expectOnFinish.fulfill()
}
}
.hostAndInspect(with: \.inspection)
.extractWorkflowLauncher()
.extractWorkflowItemWrapper()
print(type(of: wfr1))
XCTAssertEqual(try wfr1.find(FR1.self).text().string(), "FR1 type")
try await wfr1.proceedAndCheckNavLink(on: FR1.self)
let wfr3 = try await wfr1.extractWrappedWrapper().extractWrappedWrapper()
XCTAssertEqual(try wfr3.find(FR3.self).text().string(), "FR3 type")
try await wfr3.find(FR3.self).proceedInWorkflow()
wait(for: [expectOnFinish], timeout: TestConstant.timeout)
}
func testWorkflowCanBeFollowed_WithBuildEither_WhenTrue() async throws {
struct FR1: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR1 type") }
}
struct FR2: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR2 type") }
}
struct FR3: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR3 type") }
}
let expectOnFinish = expectation(description: "OnFinish called")
let wfr1 = try await MainActor.run {
WorkflowView {
WorkflowItem(FR1.self).presentationType(.navigationLink)
if true {
WorkflowItem(FR2.self)
} else {
WorkflowItem(FR3.self)
}
}
.onFinish { _ in
expectOnFinish.fulfill()
}
}
.hostAndInspect(with: \.inspection)
.extractWorkflowLauncher()
.extractWorkflowItemWrapper()
print(type(of: wfr1))
XCTAssertEqual(try wfr1.find(FR1.self).text().string(), "FR1 type")
try await wfr1.proceedAndCheckNavLink(on: FR1.self)
let wfr2 = try await wfr1.extractWrappedWrapper()
XCTAssertEqual(try wfr2.find(FR2.self).text().string(), "FR2 type")
try await wfr2.find(FR2.self).proceedInWorkflow()
wait(for: [expectOnFinish], timeout: TestConstant.timeout)
}
func testWorkflowCanBeFollowed_WithBuildEither_WhenFalse() async throws {
struct FR1: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR1 type") }
}
struct FR2: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR2 type") }
}
struct FR3: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR3 type") }
}
let expectOnFinish = expectation(description: "OnFinish called")
let wfr1 = try await MainActor.run {
WorkflowView {
WorkflowItem(FR1.self).presentationType(.navigationLink)
if false {
WorkflowItem(FR2.self)
} else {
WorkflowItem(FR3.self)
}
}
.onFinish { _ in
expectOnFinish.fulfill()
}
}
.hostAndInspect(with: \.inspection)
.extractWorkflowLauncher()
.extractWorkflowItemWrapper()
print(type(of: wfr1))
XCTAssertEqual(try wfr1.find(FR1.self).text().string(), "FR1 type")
try await wfr1.proceedAndCheckNavLink(on: FR1.self)
let wfr2 = try await wfr1.extractWrappedWrapper()
XCTAssertEqual(try wfr2.find(FR3.self).text().string(), "FR3 type")
try await wfr2.find(FR3.self).proceedInWorkflow()
wait(for: [expectOnFinish], timeout: TestConstant.timeout)
}
func testWorkflowItemsOfTheSameTypeCanBeFollowed() async throws {
struct FR1: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR1 type") }
}
let wfr1 = try await MainActor.run {
WorkflowView {
WorkflowItem(FR1.self).presentationType(.navigationLink)
WorkflowItem(FR1.self).presentationType(.navigationLink)
WorkflowItem(FR1.self)
}
}
.hostAndInspect(with: \.inspection)
.extractWorkflowLauncher()
.extractWorkflowItemWrapper()
let model = try await MainActor.run {
try XCTUnwrap((Mirror(reflecting: try wfr1.actualView()).descendant("_model") as? EnvironmentObject<WorkflowViewModel>)?.wrappedValue)
}
let launcher = try await MainActor.run {
try XCTUnwrap((Mirror(reflecting: try wfr1.actualView()).descendant("_launcher") as? EnvironmentObject<Launcher>)?.wrappedValue)
}
XCTAssertFalse(try wfr1.find(ViewType.NavigationLink.self).isActive())
try await wfr1.find(FR1.self).proceedInWorkflow()
// needed to re-host to avoid some kind of race with the nav link
try await wfr1.actualView().host { $0.environmentObject(model).environmentObject(launcher) }
XCTAssert(try wfr1.find(ViewType.NavigationLink.self).isActive())
let wfr2 = try await wfr1.extractWrappedWrapper()
XCTAssertFalse(try wfr2.find(ViewType.NavigationLink.self).isActive())
try await wfr2.find(FR1.self).proceedInWorkflow()
try await wfr2.actualView().host { $0.environmentObject(model).environmentObject(launcher) }
XCTAssert(try wfr2.find(ViewType.NavigationLink.self).isActive())
let wfr3 = try await wfr2.extractWrappedWrapper()
try await wfr3.find(FR1.self).proceedInWorkflow()
}
func testLargeWorkflowCanBeFollowed() async throws {
struct FR1: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR1 type") }
}
struct FR2: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR2 type") }
}
struct FR3: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR3 type") }
}
struct FR4: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR4 type") }
}
struct FR5: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR5 type") }
}
struct FR6: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR6 type") }
}
struct FR7: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR7 type") }
}
let wfr1 = try await MainActor.run {
WorkflowView {
WorkflowItem(FR1.self).presentationType(.navigationLink)
WorkflowItem(FR2.self).presentationType(.navigationLink)
WorkflowItem(FR3.self).presentationType(.navigationLink)
WorkflowItem(FR4.self).presentationType(.navigationLink)
WorkflowItem(FR5.self).presentationType(.navigationLink)
WorkflowItem(FR6.self).presentationType(.navigationLink)
WorkflowItem(FR7.self).presentationType(.navigationLink)
}
}
.hostAndInspect(with: \.inspection)
.extractWorkflowLauncher()
.extractWorkflowItemWrapper()
try await wfr1.proceedAndCheckNavLink(on: FR1.self)
let wfr2 = try await wfr1.extractWrappedWrapper()
try await wfr2.proceedAndCheckNavLink(on: FR2.self)
let wfr3 = try await wfr2.extractWrappedWrapper()
try await wfr3.proceedAndCheckNavLink(on: FR3.self)
let wfr4 = try await wfr3.extractWrappedWrapper()
try await wfr4.proceedAndCheckNavLink(on: FR4.self)
let wfr5 = try await wfr4.extractWrappedWrapper()
try await wfr5.proceedAndCheckNavLink(on: FR5.self)
let wfr6 = try await wfr5.extractWrappedWrapper()
try await wfr6.proceedAndCheckNavLink(on: FR6.self)
let wfr7 = try await wfr6.extractWrappedWrapper()
try await wfr7.find(FR7.self).proceedInWorkflow()
}
func testNavLinkWorkflowsCanSkipTheFirstItem() async throws {
struct FR1: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR1 type") }
func shouldLoad() -> Bool { false }
}
struct FR2: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR2 type") }
}
struct FR3: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR3 type") }
}
let wfr1 = try await MainActor.run {
WorkflowView {
WorkflowItem(FR1.self).presentationType(.navigationLink)
WorkflowItem(FR2.self).presentationType(.navigationLink)
WorkflowItem(FR3.self)
}
}
.hostAndInspect(with: \.inspection)
.extractWorkflowLauncher()
.extractWorkflowItemWrapper()
XCTAssertThrowsError(try wfr1.find(FR1.self).actualView())
let wfr2 = try await wfr1.extractWrappedWrapper()
try await wfr2.proceedAndCheckNavLink(on: FR2.self)
let wfr3 = try await wfr2.extractWrappedWrapper()
XCTAssertNoThrow(try wfr3.find(FR3.self).actualView())
}
func testNavLinkWorkflowsCanSkipOneItemInTheMiddle() async throws {
struct FR1: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR1 type") }
}
struct FR2: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR2 type") }
func shouldLoad() -> Bool { false }
}
struct FR3: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR3 type") }
}
let wfr1 = try await MainActor.run {
WorkflowView {
WorkflowItem(FR1.self).presentationType(.navigationLink)
WorkflowItem(FR2.self).presentationType(.navigationLink)
WorkflowItem(FR3.self)
}
}
.hostAndInspect(with: \.inspection)
.extractWorkflowLauncher()
.extractWorkflowItemWrapper()
try await wfr1.proceedAndCheckNavLink(on: FR1.self)
let wfr2 = try await wfr1.extractWrappedWrapper()
XCTAssertThrowsError(try wfr2.find(FR2.self))
let wfr3 = try await wfr2.extractWrappedWrapper()
XCTAssertNoThrow(try wfr3.find(FR3.self).actualView())
}
func testNavLinkWorkflowsCanSkipTwoItemsInTheMiddle() async throws {
struct FR1: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR1 type") }
}
struct FR2: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR2 type") }
func shouldLoad() -> Bool { false }
}
struct FR3: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR3 type") }
func shouldLoad() -> Bool { false }
}
struct FR4: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR3 type") }
}
let wfr1 = try await MainActor.run {
WorkflowView {
WorkflowItem(FR1.self).presentationType(.navigationLink)
WorkflowItem(FR2.self).presentationType(.navigationLink)
WorkflowItem(FR3.self)
WorkflowItem(FR4.self)
}
}
.hostAndInspect(with: \.inspection)
.extractWorkflowLauncher()
.extractWorkflowItemWrapper()
try await wfr1.proceedAndCheckNavLink(on: FR1.self)
let wfr2 = try await wfr1.extractWrappedWrapper()
XCTAssertThrowsError(try wfr2.find(FR2.self))
let wfr3 = try await wfr2.extractWrappedWrapper()
XCTAssertThrowsError(try wfr3.find(FR3.self).actualView())
let wfr4 = try await wfr3.extractWrappedWrapper()
XCTAssertNoThrow(try wfr4.find(FR4.self).actualView())
}
func testNavLinkWorkflowsCanSkipLastItem() async throws {
struct FR1: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR1 type") }
}
struct FR2: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR2 type") }
}
struct FR3: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR3 type") }
func shouldLoad() -> Bool { false }
}
let expectOnFinish = expectation(description: "onFinish called")
let wfr1 = try await MainActor.run {
WorkflowView {
WorkflowItem(FR1.self).presentationType(.navigationLink)
WorkflowItem(FR2.self).presentationType(.navigationLink)
WorkflowItem(FR3.self)
}
.onFinish { _ in
expectOnFinish.fulfill()
}
}
.hostAndInspect(with: \.inspection)
.extractWorkflowLauncher()
.extractWorkflowItemWrapper()
try await wfr1.proceedAndCheckNavLink(on: FR1.self)
let wfr2 = try await wfr1.extractWrappedWrapper()
try await wfr2.proceedAndCheckNavLink(on: FR2.self)
let wfr3 = try await wfr2.extractWrappedWrapper()
XCTAssertThrowsError(try wfr3.find(FR3.self))
XCTAssertNoThrow(try wfr2.find(FR2.self))
wait(for: [expectOnFinish], timeout: TestConstant.timeout)
}
func testConvenienceEmbedInNavViewFunction() async throws {
struct FR1: View, FlowRepresentable, Inspectable {
var _workflowPointer: AnyFlowRepresentable?
var body: some View { Text("FR1 type") }
}
let launcherView = try await MainActor.run {
WorkflowView {
WorkflowItem(FR1.self).presentationType(.navigationLink)
}.embedInNavigationView()
}.hostAndInspect(with: \.inspection)
.extractWorkflowLauncher()
let navView = try launcherView.navigationView()
XCTAssert(try navView.navigationViewStyle() is StackNavigationViewStyle)
XCTAssertNoThrow(try navView.view(WorkflowItemWrapper<WorkflowItem<FR1, FR1>, Never>.self, 0))
}
}
@available(iOS 15.0, macOS 11, tvOS 14.0, watchOS 7.0, *)
extension InspectableView where View: CustomViewType & SingleViewContent, View.T: _WorkflowItemProtocol {
fileprivate func proceedAndCheckNavLink<FR: FlowRepresentable & Inspectable>(on: FR.Type) async throws where FR.WorkflowOutput == Never {
XCTAssertFalse(try find(ViewType.NavigationLink.self).isActive())
try await find(FR.self).proceedInWorkflow()
}
}
| 39.422303 | 146 | 0.622055 |
7949f151b5fecd26a246e71ce0b85af41aaf314d | 1,620 | // RUN: %target-swift-frontend -emit-sil -O %s %S/Inputs/whole_module_optimization_helper.swift -o %t.sil -module-name main
// RUN: %FileCheck %s < %t.sil
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.sil
// RUN: %target-swift-frontend -emit-sil -O -primary-file %s %S/Inputs/whole_module_optimization_helper.swift -o %t.unopt.sil -module-name main
// RUN: %FileCheck %s -check-prefix=CHECK-SINGLE-FILE < %t.unopt.sil
// RUN: %target-swift-frontend -emit-sil -O -enable-testing %s %S/Inputs/whole_module_optimization_helper.swift -o %t.testing.sil -module-name main
// RUN: %FileCheck %s < %t.testing.sil
// RUN: %FileCheck %s -check-prefix=NEGATIVE-TESTABLE < %t.testing.sil
private func privateFn() -> Int32 {
return 2
}
// CHECK-LABEL: sil @_T04main9getAnswers5Int32VyF
// CHECK-SINGLE-FILE-LABEL: sil @_T04main9getAnswers5Int32VyF
public func getAnswer() -> Int32 {
// CHECK: %0 = integer_literal $Builtin.Int32, 42
// CHECK-NEXT: %1 = struct $Int32 (%0 : $Builtin.Int32)
// CHECK-NEXT: return %1 : $Int32
// CHECK-SINGLE-FILE: %0 = function_ref @_T04main9privateFn33_4704C82F83811927370AA02DFDC75B5ALLs5Int32VyF
// CHECK-SINGLE-FILE: %1 = thin_to_thick_function %0
// CHECK-SINGLE-FILE: %2 = convert_function %1
// CHECK-SINGLE-FILE: %3 = function_ref @_T04main7computeys5Int32VADycF
// CHECK-SINGLE-FILE: %4 = apply %3(%2)
// CHECK-SINGLE-FILE: return %4 : $Int
return compute(privateFn)
}
// CHECK: }
// CHECK-SINGLE-FILE: }
// NEGATIVE-NOT: sil {{.+}}privateFn
// NEGATIVE-TESTABLE-NOT: sil {{.+}}privateFn
// NEGATIVE-NOT: sil {{.+}}compute
// CHECK-TESTABLE: sil {{.+}}compute
| 41.538462 | 147 | 0.705556 |
2f1818fa89edb22dbee9a5beaf93f5c493253009 | 1,836 | //
// TrustlineEntryXDR.swift
// stellarsdk
//
// Created by Rogobete Christian on 12.02.18.
// Copyright © 2018 Soneso. All rights reserved.
//
import Foundation
public struct TrustLineFlags {
// issuer has authorized account to perform transactions with its credit
public static let AUTHORIZED_FLAG: UInt32 = 1
// issuer has authorized account to maintain and reduce liabilities for its
// credit
public static let AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG: UInt32 = 2
}
public struct TrustlineEntryXDR: XDRCodable {
public let accountID: PublicKey
public let asset: AssetXDR
public let balance: Int64
public let limit: Int64
public let flags: UInt32 // see TrustLineFlags
public let reserved: AccountEntryExtXDR
public init(accountID: PublicKey, asset:AssetXDR, balance:Int64, limit:Int64, flags:UInt32) {
self.accountID = accountID
self.asset = asset
self.balance = balance
self.limit = limit
self.flags = flags
self.reserved = .void
}
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
accountID = try container.decode(PublicKey.self)
asset = try container.decode(AssetXDR.self)
balance = try container.decode(Int64.self)
limit = try container.decode(Int64.self)
flags = try container.decode(UInt32.self)
reserved = try container.decode(AccountEntryExtXDR.self)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(accountID)
try container.encode(asset)
try container.encode(balance)
try container.encode(limit)
try container.encode(flags)
try container.encode(reserved)
}
}
| 31.655172 | 97 | 0.684096 |
bffa8a13b39040fd31836d99773a933cfbcbd6d6 | 765 | //
// FudaSetsScreenDelegate.swift
// Shuffle100
//
// Created by Yoshifumi Sato on 2020/05/25.
// Copyright © 2020 里 佳史. All rights reserved.
//
import UIKit
extension FudaSetsScreen: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
settings.state100 = settings.savedFudaSets[indexPath.row].state100
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
settings.savedFudaSets.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath] , with: .automatic)
}
}
| 28.333333 | 128 | 0.712418 |
1d65b65373133c8ebfd25aeb73efad9055e68823 | 2,765 | //
// SceneDelegate.swift
// Hacker News
//
// Created by Rafael Plinio on 30/10/19.
// Copyright © 2019 Rafael Plinio. All rights reserved.
//
import UIKit
import SwiftUI
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).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
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.
}
}
| 42.538462 | 147 | 0.705967 |
61e843da91d2a7bae755c655d8a02b31640bf260 | 1,257 | //
// Death_DodgerUITests.swift
// Death DodgerUITests
//
// Created by Eli Bradley on 9/10/16.
// Copyright © 2016 Animator Joe. All rights reserved.
//
import XCTest
class Death_DodgerUITests: 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.972973 | 182 | 0.665076 |
4602123edfac7df869899a427090b35a592a4854 | 8,610 | /* file: and_expression.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 and_expression
SUBTYPE OF ( multiple_arity_boolean_expression );
END_ENTITY; -- and_expression (line:6825 file:ap242ed2_mim_lf_v1.101.TY.exp)
*/
//MARK: - ALL DEFINED ATTRIBUTES
/*
SUPER- ENTITY(1) generic_expression
(no local attributes)
SUPER- ENTITY(2) expression
(no local attributes)
SUPER- ENTITY(3) boolean_expression
(no local attributes)
SUPER- ENTITY(4) multiple_arity_generic_expression
ATTR: operands, TYPE: LIST [2 : ?] OF generic_expression -- EXPLICIT (DYNAMIC)
-- possibly overriden by
ENTITY: series_composed_function, TYPE: LIST [2 : ?] OF maths_function
ENTITY: concat_expression, TYPE: LIST [2 : ?] OF string_expression
ENTITY: multiple_arity_numeric_expression, TYPE: LIST [2 : ?] OF numeric_expression
*** ENTITY: multiple_arity_boolean_expression, TYPE: LIST [2 : ?] OF boolean_expression
ENTITY: basic_sparse_matrix, TYPE: LIST [3 : 3] OF maths_function
ENTITY: parallel_composed_function, TYPE: LIST [2 : ?] OF generic_expression (as DERIVED)
ENTITY: function_application, TYPE: LIST [2 : ?] OF generic_expression (as DERIVED)
SUPER- ENTITY(5) multiple_arity_boolean_expression
REDCR: operands, TYPE: LIST [2 : ?] OF boolean_expression -- EXPLICIT
-- OVERRIDING ENTITY: multiple_arity_generic_expression
ENTITY(SELF) and_expression
(no local attributes)
*/
//MARK: - Partial Entity
public final class _and_expression : SDAI.PartialEntity {
public override class var entityReferenceType: SDAI.EntityReference.Type {
eAND_EXPRESSION.self
}
//ATTRIBUTES
// (no local attributes)
public override var typeMembers: Set<SDAI.STRING> {
var members = Set<SDAI.STRING>()
members.insert(SDAI.STRING(Self.typeName))
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)
}
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 }
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 }
return result
}
//EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR
public init() {
super.init(asAbstructSuperclass:())
}
//p21 PARTIAL ENTITY CONSTRUCTOR
public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) {
let numParams = 0
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 }
self.init( )
}
}
//MARK: - Entity Reference
/** ENTITY reference
- EXPRESS:
```express
ENTITY and_expression
SUBTYPE OF ( multiple_arity_boolean_expression );
END_ENTITY; -- and_expression (line:6825 file:ap242ed2_mim_lf_v1.101.TY.exp)
```
*/
public final class eAND_EXPRESSION : SDAI.EntityReference {
//MARK: PARTIAL ENTITY
public override class var partialEntityType: SDAI.PartialEntity.Type {
_and_expression.self
}
public let partialEntity: _and_expression
//MARK: SUPERTYPES
public let super_eGENERIC_EXPRESSION: eGENERIC_EXPRESSION // [1]
public let super_eEXPRESSION: eEXPRESSION // [2]
public let super_eBOOLEAN_EXPRESSION: eBOOLEAN_EXPRESSION // [3]
public let super_eMULTIPLE_ARITY_GENERIC_EXPRESSION: eMULTIPLE_ARITY_GENERIC_EXPRESSION // [4]
public let super_eMULTIPLE_ARITY_BOOLEAN_EXPRESSION: eMULTIPLE_ARITY_BOOLEAN_EXPRESSION // [5]
public var super_eAND_EXPRESSION: eAND_EXPRESSION { return self } // [6]
//MARK: SUBTYPES
//MARK: ATTRIBUTES
/// __EXPLICIT REDEF(DYNAMIC)__ attribute
/// - origin: SUPER( ``eMULTIPLE_ARITY_BOOLEAN_EXPRESSION`` )
public var OPERANDS: SDAI.LIST<eBOOLEAN_EXPRESSION>/*[2:nil]*/ {
get {
if let resolved = _multiple_arity_generic_expression._operands__provider(complex: self.complexEntity) {
let value = SDAI.UNWRAP( SDAI.LIST<eBOOLEAN_EXPRESSION>(resolved._operands__getter(
complex: self.complexEntity)) )
return value
}
else {
return SDAI.UNWRAP( SDAI.LIST<eBOOLEAN_EXPRESSION>(super_eMULTIPLE_ARITY_GENERIC_EXPRESSION
.partialEntity._operands) )
}
}
set(newValue) {
if let _ = _multiple_arity_generic_expression._operands__provider(complex: self.complexEntity) { return }
let partial = super_eMULTIPLE_ARITY_GENERIC_EXPRESSION.partialEntity
partial._operands = SDAI.UNWRAP(
SDAI.LIST<eGENERIC_EXPRESSION>(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(_and_expression.self) else { return nil }
self.partialEntity = partial
guard let super1 = complexEntity?.entityReference(eGENERIC_EXPRESSION.self) else { return nil }
self.super_eGENERIC_EXPRESSION = super1
guard let super2 = complexEntity?.entityReference(eEXPRESSION.self) else { return nil }
self.super_eEXPRESSION = super2
guard let super3 = complexEntity?.entityReference(eBOOLEAN_EXPRESSION.self) else { return nil }
self.super_eBOOLEAN_EXPRESSION = super3
guard let super4 = complexEntity?.entityReference(eMULTIPLE_ARITY_GENERIC_EXPRESSION.self) else { return nil }
self.super_eMULTIPLE_ARITY_GENERIC_EXPRESSION = super4
guard let super5 = complexEntity?.entityReference(eMULTIPLE_ARITY_BOOLEAN_EXPRESSION.self) else { return nil }
self.super_eMULTIPLE_ARITY_BOOLEAN_EXPRESSION = super5
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: 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: "AND_EXPRESSION", type: self, explicitAttributeCount: 0)
//MARK: SUPERTYPE REGISTRATIONS
entityDef.add(supertype: eGENERIC_EXPRESSION.self)
entityDef.add(supertype: eEXPRESSION.self)
entityDef.add(supertype: eBOOLEAN_EXPRESSION.self)
entityDef.add(supertype: eMULTIPLE_ARITY_GENERIC_EXPRESSION.self)
entityDef.add(supertype: eMULTIPLE_ARITY_BOOLEAN_EXPRESSION.self)
entityDef.add(supertype: eAND_EXPRESSION.self)
//MARK: ATTRIBUTE REGISTRATIONS
entityDef.addAttribute(name: "OPERANDS", keyPath: \eAND_EXPRESSION.OPERANDS,
kind: .explicitRedeclaring, source: .superEntity, mayYieldEntityReference: true)
return entityDef
}
}
}
| 37.763158 | 185 | 0.721138 |
143c46dde0942ab12c794f93aecd68fad1980e31 | 1,085 | //
// MindMapNodeType.swift
// PlistMapper
//
// Created by Grzegorz Maciak on 25/03/2019.
// Copyright © 2019 kodelit. All rights reserved.
//
import Foundation
protocol MindMapNodeType {
var id:String { get }
// var text:String { get }
var children:[Self] { get set }
init<T>(with info:T, fullMap:Bool) where T:UniquePlistDataProtocol
init<T>(with info:T, ancestorsById:[String: T]?, fullMap:Bool) where T:UniquePlistDataProtocol
}
extension MindMapNodeType {
func ancestorNodes<T>(with info:T, availableAncestorsById:[String: T], fullMap:Bool) -> [Self] where T:UniquePlistDataProtocol {
if let ancestors = info.ancestorsIds() {
let children = ancestors.reduce(into: [Self](), { (result, identifier) in
if let ancestorInfo = availableAncestorsById[identifier] {
let child = Self(with: ancestorInfo, ancestorsById: availableAncestorsById, fullMap: fullMap)
result.append(child)
}
})
return children
}
return []
}
}
| 31 | 132 | 0.634101 |
91e4426be92ba9936800b27d362fd24db762d758 | 816 | //
// ViewController.swift
// FoodFactsSDK
//
// Created by mackensiealvarez on 02/16/2017.
// Copyright (c) 2017 mackensiealvarez. All rights reserved.
//
import UIKit
import FoodFactsSDK
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//One line of code to show products
FoodFacts().productsByCategory(21, subcategory_id: 256, per_page: 4, page: 1, sort_by: "peg_name.sort", callback: {response in
for products in response.results.products{
print(products.title)
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 22.054054 | 134 | 0.607843 |
5635ff94198c8f5052e56764dc08820117bcc675 | 842 | //
// HSVColorSpace.swift
// ExampleApp_iOS
//
// Created by Lorenzo Bernaschina on 23/02/2019.
// Copyright © 2019 Lorenzo Bernaschina. All rights reserved.
//
import ColorKit
public class HSVColorSpace: ColorSpace {
private let name = "HSV"
private var colorSpace: HSVSpace
public override init(mediator: ColorSpaceMediator) {
self.colorSpace = HSVSpace()
super.init(mediator: mediator)
}
public func getName() -> String {
return self.name
}
public func colorSpaceUpdate(space: HSVSpace) {
self.colorSpace = space
self.changed()
}
public func setColorSpaceFrom(space: RGBSpace) {
self.colorSpace.fromRGBSpace(space: space)
}
public func getColorSpace() -> HSVSpace {
return self.colorSpace
}
}
| 21.05 | 62 | 0.634204 |
ed779bd5477101d495f08b4350835fa92f6ba67e | 521 | //
// NetworkLayerMock.swift
// OpenWeatherMapTests
//
// Created by Gamil Ali Qaid Shamar on 04/07/2020.
// Copyright © 2020 Jamil. All rights reserved.
//
import XCTest
import OpenWeatherMap
class NetworkLayerMock: Network {
private var mockedWeather: Weather!
init(mockedWeather:Weather) {
self.mockedWeather = mockedWeather
}
override func getWeather(city: String, completion: @escaping (Weather?) -> Void) {
completion(self.mockedWeather)
}
}
| 18.607143 | 86 | 0.660269 |
f9155dd31c3b3f4387dcc0771882b12c067cf039 | 7,570 | //
/*
CIAddressTypeahead.swift
Created on: 7/5/18
Abstract:
- user can type in any string, which will show the matching addresses in a tableview
- opt for the typeaheadDelegate, which will give the selected localSearchCompletion object
*/
import UIKit
import MapKit
/**
delegate to receive the selected address
*/
@objc protocol CIAddressTypeaheadProtocol {
func didSelectAddress(placemark: MKPlacemark)
}
final class CIAddressTypeahead: UITextField {
// MARK: Properties
/// set this to receive the selected address
@IBOutlet var typeaheadDelegate: CIAddressTypeaheadProtocol?
/// set this to show the results tableview on top of the textfield.
@IBInspectable public var displayTop: Bool = false
public var title: String? {
set(value) {
text = value
}
get {
return text
}
}
// MARK: Private properties
private var searchCompleter = MKLocalSearchCompleter()
private var resultsTable: UITableView!
private var results = [MKLocalSearchCompletion]()
// MARK: Lifecycle
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
placeholder = "Please search for an address"
resultsTable = UITableView(coder: aDecoder)
searchCompleter.delegate = self
addResultsTable()
}
override func layoutSubviews() {
resultsTable.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: resultsTable,
attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal,
toItem: self,
attribute: NSLayoutAttribute.centerX,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: resultsTable,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: frame.size.width).isActive = true
NSLayoutConstraint(item: resultsTable,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: 176).isActive = true
if displayTop {
addConstraintToShowResultsTableInTop()
} else {
addConstraintToShowResultsTableInBottom()
}
}
/**
captures the touches in the tableview which is overflown from textfield
*/
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if clipsToBounds || isHidden || alpha == 0 {
return nil
}
for subview in subviews.reversed() {
let subPoint = subview.convert(point, from: self)
if let result = subview.hitTest(subPoint, with: event) {
return result
}
}
return super.hitTest(point, with: event)
}
}
private extension CIAddressTypeahead {
// MARK: Helper methods
/**
adds the tableview as a subview to the textfield
*/
func addResultsTable() {
addSubview(resultsTable)
resultsTable.dataSource = self
resultsTable.delegate = self
resultsTable.isHidden = true
}
/**
adds the constraints to show the results table below the textfield.
*/
func addConstraintToShowResultsTableInBottom() {
NSLayoutConstraint(item: resultsTable,
attribute: NSLayoutAttribute.top,
relatedBy: NSLayoutRelation.equal,
toItem: self,
attribute: NSLayoutAttribute.bottom,
multiplier: 1,
constant: 12).isActive = true
}
/**
adds the constraints to show the results table above the textfield.
*/
func addConstraintToShowResultsTableInTop() {
NSLayoutConstraint(item: resultsTable,
attribute: NSLayoutAttribute.bottom,
relatedBy: NSLayoutRelation.equal,
toItem: self,
attribute: NSLayoutAttribute.top,
multiplier: 1,
constant: -12).isActive = true
}
}
// MARK: CIAddressTypeahead -> UITextFieldDelegate
extension CIAddressTypeahead: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
// only search after 3rd character
guard let previousText = textField.text, previousText.count > 3 else {
resultsTable.isHidden = true
return true
}
let newString = previousText.replacingCharacters(in: Range(range, in: previousText)!, with: string)
searchCompleter.queryFragment = newString
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.resignFirstResponder()
return true
}
}
// MARK: CIAddressTypeahead -> MKLocalSearchCompleterDelegate
extension CIAddressTypeahead: MKLocalSearchCompleterDelegate {
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
results = completer.results
resultsTable.isHidden = results.count == 0
resultsTable.reloadData()
}
func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
// handle error
}
}
// MARK: CIAddressTypeahead -> UITableViewDataSource, UITableViewDelegate
extension CIAddressTypeahead: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
}
let result = results[indexPath.row]
cell?.textLabel?.text = result.title
cell?.detailTextLabel?.text = result.subtitle
return cell!
}
/**
on select, calls the protocol method (`didSelectAddress`) with placemark of the selected address
*/
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
text = results[indexPath.row].title
let completion = results[indexPath.row]
let searchRequest = MKLocalSearchRequest(completion: completion)
let search = MKLocalSearch(request: searchRequest)
search.start { [unowned self] (response, error) in
let placemark = response?.mapItems[0].placemark
if let placemark = placemark {
self.typeaheadDelegate?.didSelectAddress(placemark: placemark)
tableView.isHidden = true
}
}
}
}
| 33.794643 | 107 | 0.598415 |
ed3d9f8fca2eac09035275e2b508fb158cfdd425 | 2,876 | import Foundation
import UIKit
public class AnimatableDegrees {
public init(value: CGFloat = 0) {
self.value = value
}
public var viewForInvalidate: UIView? = nil
public var actionForInvalidate: (()->Void)? = nil
private (set) public var currentValue: CGFloat = 0 {
didSet {
if let viewForInvalidate = self.viewForInvalidate {
viewForInvalidate.setNeedsDisplay()
}
actionForInvalidate?()
}
}
private var targetValue: CGFloat = 0
public var value: CGFloat {
get {
return targetValue
}
set {
cancel()
self.targetValue = newValue
self.currentValue = newValue
}
}
public var animating: Bool {
get {
return self.animator != nil
}
}
private var animator: Animator? = nil
public func animate(to value: CGFloat, duration: Double = 0.3, easing: @escaping EasingFunction = CubicEaseInOut, completion: (()->Void)? = nil) {
self.animate(to: value, timing: .duration(duration: duration), easing: easing, completion: completion)
}
public func animate(to value: CGFloat, timing: Timing, easing: @escaping EasingFunction, completion: (()->Void)? = nil) {
cancel()
var from = self.value.normalizeDegrees360()
var to = value.normalizeDegrees360()
let difference = abs(from - to)
if (difference > 180) {
if (to > from) {
from += 360
} else {
to += 360
}
}
self.targetValue = to
let duration: Double
switch timing {
case .duration(duration: let d):
duration = d
break
case .speed(unitDuration: let unitDuration):
let units = Double(abs(to - from))
duration = units * unitDuration
break
}
self.animator = Animator(
from: from,
to: to,
duration: duration,
easing: easing,
onTick: { [unowned self] value in
self.currentValue = value
},
onCompleted: { [unowned self] ok in
self.animator = nil
if ok {
completion?()
}
}
)
self.animator?.start()
}
public func change(value: CGFloat, animated: Bool, completion: (()->Void)? = nil) {
if animated {
animate(to: value, completion: completion)
} else {
self.value = value
completion?()
}
}
public func cancel() {
animator?.cancel()
animator = nil
}
}
| 25.90991 | 150 | 0.496175 |
081fc24b0abd764a00187626ac64b673fae68f34 | 16,180 | //
// ItemProvider.swift
// Networker
//
// Created by Twig on 5/10/19.
// Copyright © 2019 Lickability. All rights reserved.
//
import Foundation
import Combine
import Networking
import Persister
/// Retrieves items from persistence or networking and stores them in persistence.
public final class ItemProvider {
private typealias CacheItemsResponse<T: Providable> = (itemContainers: [ItemContainer<T>], partialErrors: [ProviderError.PartialRetrievalFailure])
/// Performs network requests when items cannot be retrieved from persistence.
public let networkRequestPerformer: NetworkRequestPerformer
/// The cache used to persist / recall previously retrieved items.
public let cache: Cache?
private let defaultProviderBehaviors: [ProviderBehavior]
private let providerQueue = DispatchQueue(label: "ProviderQueue", attributes: .concurrent)
private var cancellables = Set<AnyCancellable?>()
/// Creates a new `ItemProvider`.
/// - Parameters:
/// - networkRequestPerformer: Performs network requests when items cannot be retrieved from persistence.
/// - cache: The cache used to persist / recall previously retrieved items.
/// - defaultProviderBehaviors: Actions to perform before _every_ provider request is performed and / or after _every_ provider request is completed.
public init(networkRequestPerformer: NetworkRequestPerformer, cache: Cache?, defaultProviderBehaviors: [ProviderBehavior] = []) {
self.networkRequestPerformer = networkRequestPerformer
self.cache = cache
self.defaultProviderBehaviors = defaultProviderBehaviors
}
}
extension ItemProvider: Provider {
// MARK: - Provider
public func provide<Item: Providable>(request: ProviderRequest, decoder: ItemDecoder = JSONDecoder(), providerBehaviors: [ProviderBehavior] = [], requestBehaviors: [RequestBehavior] = [], handlerQueue: DispatchQueue = .main, allowExpiredItem: Bool = false, itemHandler: @escaping (Result<Item, ProviderError>) -> Void) {
var cancellable: AnyCancellable?
cancellable = provide(request: request,
decoder: decoder,
providerBehaviors: providerBehaviors,
requestBehaviors: requestBehaviors,
allowExpiredItem: allowExpiredItem)
.receive(on: handlerQueue)
.sink(receiveCompletion: { [weak self] result in
switch result {
case let .failure(error):
itemHandler(.failure(error))
case .finished: break
}
self?.cancellables.remove(cancellable)
}, receiveValue: { (item: Item) in
itemHandler(.success(item))
})
handlerQueue.async { self.cancellables.insert(cancellable) }
}
public func provideItems<Item: Providable>(request: ProviderRequest, decoder: ItemDecoder = JSONDecoder(), providerBehaviors: [ProviderBehavior] = [], requestBehaviors: [RequestBehavior] = [], handlerQueue: DispatchQueue = .main, allowExpiredItems: Bool = false, itemsHandler: @escaping (Result<[Item], ProviderError>) -> Void) {
var cancellable: AnyCancellable?
cancellable = provideItems(request: request,
decoder: decoder,
providerBehaviors: providerBehaviors,
requestBehaviors: requestBehaviors,
allowExpiredItems: allowExpiredItems)
.receive(on: handlerQueue)
.sink(receiveCompletion: { [weak self] result in
switch result {
case let .failure(error):
itemsHandler(.failure(error))
case .finished: break
}
self?.cancellables.remove(cancellable)
}, receiveValue: { (items: [Item]) in
itemsHandler(.success(items))
})
handlerQueue.async { self.cancellables.insert(cancellable) }
}
public func provide<Item: Providable>(request: ProviderRequest, decoder: ItemDecoder = JSONDecoder(), providerBehaviors: [ProviderBehavior] = [], requestBehaviors: [RequestBehavior] = [], allowExpiredItem: Bool = false) -> AnyPublisher<Item, ProviderError> {
let cachePublisher: Result<ItemContainer<Item>?, ProviderError>.Publisher = itemCachePublisher(for: request)
let networkPublisher: AnyPublisher<Item, ProviderError> = itemNetworkPublisher(for: request, behaviors: requestBehaviors, decoder: decoder)
let providerPublisher = cachePublisher
.flatMap { item -> AnyPublisher<Item, ProviderError> in
if let item = item {
let itemPublisher = Just(item)
.map { $0.item }
.setFailureType(to: ProviderError.self)
.eraseToAnyPublisher()
if let expiration = item.expirationDate, expiration >= Date() {
return itemPublisher
} else if allowExpiredItem, let expiration = item.expirationDate, expiration < Date() {
return itemPublisher.merge(with: networkPublisher).eraseToAnyPublisher()
} else {
return networkPublisher
}
} else {
return networkPublisher
}
}
return providerPublisher
.handleEvents(receiveSubscription: { _ in
providerBehaviors.providerWillProvide(forRequest: request)
}, receiveOutput: { item in
providerBehaviors.providerDidProvide(item: item, forRequest: request)
})
.subscribe(on: providerQueue)
.eraseToAnyPublisher()
}
private func itemCachePublisher<Item: Providable>(for request: ProviderRequest) -> Result<ItemContainer<Item>?, ProviderError>.Publisher {
let cachePublisher: Result<ItemContainer<Item>?, ProviderError>.Publisher
if !request.ignoresCachedContent, let persistenceKey = request.persistenceKey {
cachePublisher = Just<ItemContainer<Item>?>(try? self.cache?.read(forKey: persistenceKey))
.setFailureType(to: ProviderError.self)
} else {
cachePublisher = Just<ItemContainer<Item>?>(nil)
.setFailureType(to: ProviderError.self)
}
return cachePublisher
}
private func itemNetworkPublisher<Item: Providable>(for request: ProviderRequest, behaviors: [RequestBehavior], decoder: ItemDecoder) -> AnyPublisher<Item, ProviderError> {
return networkRequestPerformer.send(request, requestBehaviors: behaviors)
.mapError { ProviderError.networkError($0) }
.unpackData(errorTransform: { _ in ProviderError.networkError(.noData) })
.decodeItem(decoder: decoder, errorTransform: { ProviderError.decodingError($0) })
.handleEvents(receiveOutput: { [weak self] item in
if let persistenceKey = request.persistenceKey {
try? self?.cache?.write(item: item, forKey: persistenceKey)
}
})
.eraseToAnyPublisher()
}
public func provideItems<Item: Providable>(request: ProviderRequest, decoder: ItemDecoder = JSONDecoder(), providerBehaviors: [ProviderBehavior] = [], requestBehaviors: [RequestBehavior] = [], allowExpiredItems: Bool = false) -> AnyPublisher<[Item], ProviderError> {
let cachePublisher: Result<CacheItemsResponse<Item>?, ProviderError>.Publisher = itemsCachePublisher(for: request)
let networkPublisher: AnyPublisher<[Item], ProviderError> = itemsNetworkPublisher(for: request, behaviors: requestBehaviors, decoder: decoder)
let providerPublisher = cachePublisher
.flatMap { response -> AnyPublisher<[Item], ProviderError> in
if let response = response {
let itemContainers = response.itemContainers
let itemPublisher = Just(itemContainers.map { $0.item })
.setFailureType(to: ProviderError.self)
.eraseToAnyPublisher()
if !response.partialErrors.isEmpty {
return networkPublisher
.mapError { providerError in
let itemsAreExpired = response.itemContainers.first?.expirationDate < Date()
if !itemsAreExpired || (itemsAreExpired && allowExpiredItems) {
return ProviderError.partialRetrieval(retrievedItems: response.itemContainers.map { $0.item }, persistenceFailures: response.partialErrors, providerError: providerError)
} else {
return providerError
}
}
.eraseToAnyPublisher()
} else if let expiration = itemContainers.first?.expirationDate, expiration >= Date() {
return itemPublisher
} else if allowExpiredItems, let expiration = itemContainers.first?.expirationDate, expiration < Date() {
return itemPublisher.merge(with: networkPublisher).eraseToAnyPublisher()
} else {
return networkPublisher
}
} else {
return networkPublisher
}
}
return providerPublisher
.handleEvents(receiveSubscription: { _ in
providerBehaviors.providerWillProvide(forRequest: request)
}, receiveOutput: { item in
providerBehaviors.providerDidProvide(item: item, forRequest: request)
})
.subscribe(on: providerQueue)
.eraseToAnyPublisher()
}
private func itemsCachePublisher<Item: Providable>(for request: ProviderRequest) -> Result<CacheItemsResponse<Item>?, ProviderError>.Publisher {
let cachePublisher: Result<CacheItemsResponse<Item>?, ProviderError>.Publisher
if !request.ignoresCachedContent, let persistenceKey = request.persistenceKey {
cachePublisher = Just<CacheItemsResponse<Item>?>(try? self.cache?.readItems(forKey: persistenceKey))
.setFailureType(to: ProviderError.self)
} else {
cachePublisher = Just<CacheItemsResponse<Item>?>(nil)
.setFailureType(to: ProviderError.self)
}
return cachePublisher
}
private func itemsNetworkPublisher<Item: Providable>(for request: ProviderRequest, behaviors: [RequestBehavior], decoder: ItemDecoder) -> AnyPublisher<[Item], ProviderError> {
return networkRequestPerformer.send(request, requestBehaviors: behaviors)
.mapError { ProviderError.networkError($0) }
.unpackData(errorTransform: { _ in ProviderError.networkError(.noData) })
.decodeItems(decoder: decoder, errorTransform: { ProviderError.decodingError($0) })
.handleEvents(receiveOutput: { [weak self] items in
if let persistenceKey = request.persistenceKey {
self?.cache?.writeItems(items, forKey: persistenceKey)
}
})
.eraseToAnyPublisher()
}
}
extension ItemProvider {
/// Creates an `ItemProvider` configured with a `Persister` (memory and disk cache) and `NetworkController`.
/// - Parameters:
/// - persistenceURL: The location on disk in which items are persisted. Defaults to the Application Support directory.
/// - memoryCacheCapacity: The capacity of the LRU memory cache. Defaults to a limited capacity of 100 items.
public static func configuredProvider(withRootPersistenceURL persistenceURL: URL = FileManager.default.applicationSupportDirectoryURL, memoryCacheCapacity: CacheCapacity = .limited(numberOfItems: 100)) -> ItemProvider {
let memoryCache = MemoryCache(capacity: memoryCacheCapacity)
let diskCache = DiskCache(rootDirectoryURL: persistenceURL)
let persister = Persister(memoryCache: memoryCache, diskCache: diskCache)
return ItemProvider(networkRequestPerformer: NetworkController(), cache: persister, defaultProviderBehaviors: [])
}
}
extension FileManager {
public var applicationSupportDirectoryURL: URL! { //swiftlint:disable:this implicitly_unwrapped_optional
return urls(for: .applicationSupportDirectory, in: .userDomainMask).first
}
}
private extension Cache {
func readItems<Item: Codable>(forKey key: Key) throws -> ([ItemContainer<Item>], [ProviderError.PartialRetrievalFailure]) {
guard let itemIDsContainer: ItemContainer<[String]> = try read(forKey: key) else {
throw PersistenceError.noValidDataForKey
}
var failedItemErrors: [ProviderError.PartialRetrievalFailure] = []
let validItems: [ItemContainer<Item>] = itemIDsContainer.item.compactMap { key in
let fallbackError = ProviderError.PartialRetrievalFailure(key: key, persistenceError: .noValidDataForKey)
do {
if let container: ItemContainer<Item> = try read(forKey: key) {
return container
}
failedItemErrors.append(fallbackError)
return nil
} catch {
if let persistenceError = error as? PersistenceError {
let retrievalError = ProviderError.PartialRetrievalFailure(key: key, persistenceError: persistenceError)
failedItemErrors.append(retrievalError)
} else {
failedItemErrors.append(fallbackError)
}
return nil
}
}
return (validItems, failedItemErrors)
}
func writeItems<Item: Providable>(_ items: [Item], forKey key: Key) {
items.forEach { item in
try? write(item: item, forKey: item.identifier)
}
let itemIdentifiers = items.compactMap { $0.identifier }
try? write(item: itemIdentifiers, forKey: key)
}
}
private func <(lhs: Date?, rhs: Date) -> Bool {
if let lhs = lhs {
return lhs < rhs
}
return false
}
private extension Publisher {
func unpackData(errorTransform: @escaping (Error) -> Failure) -> Publishers.FlatMap<AnyPublisher<Data, ProviderError>, Self> where Failure == ProviderError, Self.Output == NetworkResponse {
return flatMap {
Just($0)
.tryCompactMap { $0.data }
.mapError { errorTransform($0) }
.eraseToAnyPublisher()
}
}
func decodeItem<Item: Providable>(decoder: ItemDecoder, errorTransform: @escaping (Error) -> Failure) -> Publishers.FlatMap<AnyPublisher<Item, ProviderError>, Self> where Failure == ProviderError, Self.Output == Data {
return flatMap {
Just($0)
.tryMap { try decoder.decode(Item.self, from: $0) }
.mapError { errorTransform($0) }
.eraseToAnyPublisher()
}
}
func decodeItems<Item: Providable>(decoder: ItemDecoder, errorTransform: @escaping (Error) -> Failure) -> Publishers.FlatMap<AnyPublisher<[Item], ProviderError>, Self> where Failure == ProviderError, Self.Output == Data {
return flatMap {
Just($0)
.tryMap { try decoder.decode([Item].self, from: $0) }
.mapError { errorTransform($0) }
.eraseToAnyPublisher()
}
}
}
| 47.869822 | 333 | 0.611928 |
69c7f1bc14d82bc5fbb36887a120a97bf88b06c2 | 5,105 | //
// StringExtension.swift
// NetWork
//
// Created by GK on 2017/1/11.
// Copyright © 2017年 GK. All rights reserved.
//
import Foundation
extension String {
//输入的文字音译
func transliterationToPinYin() -> String {
let str = NSMutableString(string: self) as CFMutableString
var cfRange = CFRangeMake(0, CFStringGetLength(str))
//转变为拉丁文
let latinSuccess = CFStringTransform(str, &cfRange, kCFStringTransformToLatin, false)
//去掉音调
if latinSuccess {
let combiningMarksSuccess = CFStringTransform(str, &cfRange, kCFStringTransformStripCombiningMarks, false)
if combiningMarksSuccess {
//转为小写
CFStringLowercase(str, nil)
//去掉空格
CFStringTrimWhitespace(str)
}
}
return str as String
}
//首字母大写
func wordFirstLetterUpperCase() -> String {
let str = NSMutableString(string: self) as CFMutableString
var cfRange = CFRangeMake(0, CFStringGetLength(str))
CFStringTransform(str, &cfRange, "Any-Title" as CFString, false)
return str as String
}
//保证输出的都是ASCII字符
func transferToASCII() -> String {
let str = NSMutableString(string: self) as CFMutableString
var cfRange = CFRangeMake(0, CFStringGetLength(str))
CFStringTransform(str, &cfRange, "Any-Latin; Latin-ASCII; [:^ASCII:] Remove" as CFString, false)
return str as String
}
//去掉首尾空格
func removeWhiteSpaceAndNewLine() -> String {
let whitespace = CharacterSet.whitespacesAndNewlines
return self.trimmingCharacters(in: whitespace)
}
//去掉所有的空格
func removeAllWhiteSpace() -> String {
let words = self.tokenize()
let resultString = words.joined(separator: "")
return resultString
}
//分词
func separatedByCharacter() -> [String] {
var characters = CharacterSet.whitespacesAndNewlines
let punctuation = CharacterSet.punctuationCharacters
characters.formUnion(punctuation)
characters.remove(charactersIn: "'")
let words = self.components(separatedBy: characters).filter({ x in !x.isEmpty
})
return words
}
func tokenize() -> [String] {
let inputRange = CFRangeMake(0, self.utf16.count)
let flag = UInt(kCFStringTokenizerUnitWord)
let locale = CFLocaleCopyCurrent()
let tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, self as CFString!, inputRange, flag, locale)
var tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)
var tokens: [String] = []
while tokenType == CFStringTokenizerTokenType.normal {
let currentTokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer)
let subString = self.substringWithRange(aRange: currentTokenRange)
tokens.append(subString)
tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)
}
return tokens
}
private func substringWithRange(aRange: CFRange) -> String {
let range = NSMakeRange(aRange.location, aRange.length)
let subString = (self as NSString).substring(with: range)
return subString
}
func separateString() -> [String] {
var words = [String]()
let range = self.startIndex ..< self.endIndex
self.enumerateSubstrings(in: range, options: String.EnumerationOptions.byWords) {
w,_,_,_ in
guard let word = w else { return }
words.append(word)
}
return words
}
func linguisticTokenize() -> [String] {
let options: NSLinguisticTagger.Options = [.omitWhitespace,.omitPunctuation,.omitOther]
let schemes = [NSLinguisticTagSchemeLexicalClass]
let tagger = NSLinguisticTagger(tagSchemes: schemes, options: Int(options.rawValue))
let range = NSMakeRange(0, (self as NSString).length)
tagger.string = self
var tokens: [String] = []
tagger.enumerateTags(in: range, scheme: NSLinguisticTagSchemeLexicalClass, options: options) { (tag, tokenRange,_,_) in
let token = (self as NSString).substring(with: tokenRange)
tokens.append(token)
}
return tokens
}
}
extension String {
static func UUIDString() -> String {
return UUID().uuidString
}
}
extension String {
func MD5() -> String {
let context = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: 1)
var digest = Array<UInt8>(repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5_Init(context)
CC_MD5_Update(context, self, CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8)))
CC_MD5_Final(&digest, context)
context.deinitialize(count: 1)
var hexString = ""
for byte in digest {
hexString += String(format: "%02x", byte)
}
return hexString
}
}
| 28.20442 | 127 | 0.623115 |
dd51fd621b8204dfa3e77fd7bbd3e6ec5a6dbb6a | 281 | //
// Text-Extensions.swift
// LearnMovieSwiftUI
//
// Created by MC on 2021/2/7.
//
import SwiftUI
extension Text {
func singleLineBodyStyle() -> some View {
self
.foregroundColor(.secondary)
.font(.body)
.lineLimit(1)
}
}
| 15.611111 | 45 | 0.562278 |
e8368ec6893be90b217a1800e34cc1a2ef2516fd | 716 | //
// Modifiers.swift
// MirrorableHR
//
// Created by Roberto D’Angelo on 25/09/2020.
//
import Foundation
import SwiftUI
#if os(iOS)
@available(iOS 13.0, watchOS 6.0, *)
extension View {
public func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
clipShape( RoundedCorner(radius: radius, corners: corners))
}
}
public struct RoundedCorner: Shape {
var radius: CGFloat = .infinity
var corners: UIRectCorner = .allCorners
public func path(in rect: CGRect) -> Path {
let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
return Path(path.cgPath)
}
}
#endif
| 23.096774 | 130 | 0.673184 |
69603fda0884a4e80deb1e4e2045ea7a0c07893c | 235 | //
// AnyOfPrehandlerCreateRequestActionsItems.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public struct AnyOfPrehandlerCreateRequestActionsItems: Codable {
}
| 13.055556 | 65 | 0.778723 |
de91386344684978d891725460d0017b434bd6d5 | 5,832 | //
// HGPageContentView.swift
// HG_DUZB
//
// Created by day-day-Smile on 2017/12/22.
// Copyright © 2017年 day-day-Smile. All rights reserved.
//
import UIKit
private let contentCellId = "contentCellId"
protocol HGPageContentViewDelegate : class {
func pageContentView(contentView:HGPageContentView,progress:CGFloat,sourceIndex:Int,targetIndex:Int)
}
class HGPageContentView: UIView {
/// MARK: - 定义属性
fileprivate var childVcs:[UIViewController]
/// 容易形成循环引用 weak 修饰 ?类型
fileprivate weak var parentViewController:UIViewController?
/// 获取当前偏移量
fileprivate var startOffsetX:CGFloat = 0
/// 判断是否点击滚动
fileprivate var isForbidScorllDelegate:Bool = false
weak var delegate:HGPageContentViewDelegate?
/// 懒加载
lazy var collectionView:UICollectionView = { [weak self] in
/// 设置 collectionView,必须先设置 layout
let layout = UICollectionViewFlowLayout()
/// 闭包里面不能用self
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
/// 创建UICollectionView
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellId)
return collectionView
}()
/// 构造函数
init(frame: CGRect,childVcs:[UIViewController],parentViewController:UIViewController?) {
self.childVcs = childVcs
self.parentViewController = parentViewController
super.init(frame: frame)
/// 设置UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - 设置UI
extension HGPageContentView{
func setupUI(){
/// 1.先把所有的自控制添加进来
for childVc in childVcs {
parentViewController?.addChildViewController(childVc)
}
// 2.用collectionView,用于cell中存放控制器view
addSubview(collectionView)
collectionView.frame = bounds
}
}
// MARK: - 遵守UICollectionViewDelegate
extension HGPageContentView:UICollectionViewDelegate {
/// 0.首先拿到当前要拖拽的那一个item
/// 开始拖拽
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScorllDelegate = false
startOffsetX = scrollView.contentOffset.x
}
/// 实现scrollView滚动方法
func scrollViewDidScroll(_ scrollView: UIScrollView) {
/// 判断是否是点击事件
if isForbidScorllDelegate {return}
/// 1.获取需要的数据
/// 获取滚动的 - 进度
var progress:CGFloat = 0
/// 获取源title - 源来的下标
var sourceIndex:Int = 0
/// 获取目标title - 当前下标
var targetIndex:Int = 0
/// 判断是左滑还是右滑
/// 如果获取的偏移量大就是 右滑
let currentOffset = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
/// 滚动的偏移量大于之前的偏移量 - 右滑
if currentOffset > startOffsetX {
/// FIXMI: - 警告
/// 1. 进度 - floor(x) 即取不大于x的最大整数
progress = currentOffset / scrollViewW - floor(currentOffset / scrollViewW)
/// 2. 源 sourceIndex
sourceIndex = Int(currentOffset / scrollViewW)
/// 3. 目标 targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
/// 4. 如果完全滑过去
if currentOffset - startOffsetX == scrollViewW{
progress = 1
targetIndex = sourceIndex
}
/// 或者 - 左滑
}else{
progress = 1 - (currentOffset / scrollViewW - floor(currentOffset / scrollViewW))
targetIndex = Int(currentOffset / scrollViewW)
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count {
sourceIndex = childVcs.count - 1
}
}
/// 将 progress、targetIndex、sourceIndex传递给titleView
print("progress\(progress)---targetIndex\(targetIndex)--sourceIndex\(sourceIndex)")
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
// MARK: - 遵守UICollectionViewDataSource
extension HGPageContentView:UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
/// 1. 创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellId, for: indexPath)
/// 2. 给cell设置内容
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
// MARK: - 实现点击titleLabel 控制器进行滚动 到 对应的界面
extension HGPageContentView {
func setCurrentIndex(currentIndex:Int) {
/// 记录需要进行执行代理方法
isForbidScorllDelegate = true
///
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint.init(x: offsetX, y: 0), animated: false)
}
}
| 31.695652 | 124 | 0.626543 |
72c791d0f7ef572a19024a130a365a7f5045726e | 2,220 | //
// MainController.swift
// XiaoHongshu_Swift
//
// Created by SMART on 2017/7/6.
// Copyright © 2017年 com.smart.swift. All rights reserved.
//
import UIKit
class MainController: UITabBarController {
// MARK: - 初始化
override func viewDidLoad() {
//添加并设置子控制器
addChildViewControllers();
}
}
extension MainController{
// MARK: 添加子控制器
func addChildViewControllers() {
//首页
let homeIndexVc = HomeIndexController();
addChildViewController(childController: homeIndexVc, title: "首页", icon:"tab_home");
//发现
let discoverIndexVc = DiscoverIndexController();
addChildViewController(childController: discoverIndexVc, title: "发现", icon: "tab_search");
//购物车
let cartIndexVc = CartIndexController();
addChildViewController(childController: cartIndexVc, title: "购物车", icon: "tab_store");
//消息
let messageIndexVc = MessageIndexController();
addChildViewController(childController: messageIndexVc, title: "消息", icon: "tab_msn");
//我
let profileVc = ProfileIndexController();
addChildViewController(childController: profileVc, title: "我", icon:"tab_me");
}
//MARK: 添加并设置单个子控制器
func addChildViewController(childController: UIViewController,title:String,icon:String) {
//添加子控制器
let navigationVc = NavigationController(rootViewController: childController);
addChildViewController(navigationVc);
//设置子控制器标题及图标显示
childController.title = title;
childController.tabBarItem.image = UIImage(named: icon+"_25x25_")
childController.tabBarItem.selectedImage = UIImage(named: icon+"_h_25x25_");
//设置标题属性
childController.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 11*APP_SCALE),NSForegroundColorAttributeName:UIColor.lightGray], for: UIControlState.normal);
childController.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 11*APP_SCALE),NSForegroundColorAttributeName:UIColor.red], for: UIControlState.selected);
}
}
| 32.647059 | 198 | 0.673423 |
713ebe0b73317257ba00f66f6384316c99a37e47 | 2,322 | //
// PushTransition.swift
// MyiOSApp
//
// Created by Soufiane SALOUF on 20-06-08.
// Copyright © 2020 Soufiane SALOUF. All rights reserved.
//
import UIKit
class PushTransition: NSObject {
var animator: Animator?
var isAnimated: Bool = true
var swipeBack: Bool = true
var completionHandler: (() -> Void)?
weak var viewController: UIViewController?
init(animator: Animator? = nil, isAnimated: Bool = true, swipeBack: Bool = true) {
self.animator = animator
self.isAnimated = isAnimated
self.swipeBack = swipeBack
}
}
// MARK: - Transition
extension PushTransition: Transition, UIGestureRecognizerDelegate {
func open(_ viewController: UIViewController) {
self.viewController?.navigationController?.delegate = self
self.viewController?.navigationController?.interactivePopGestureRecognizer?.delegate = self
self.viewController?.navigationController?.interactivePopGestureRecognizer?.isEnabled = swipeBack
self.viewController?.navigationController?.pushViewController(viewController, animated: isAnimated)
}
func close(_ viewController: UIViewController) {
self.viewController?.navigationController?.popViewController(animated: isAnimated)
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
// MARK: - UINavigationControllerDelegate
extension PushTransition: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
completionHandler?()
}
func navigationController(_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationController.Operation,
from fromVC: UIViewController,
to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
guard let animator = animator else {
return nil
}
if operation == .push {
animator.isPresenting = true
return animator
}
else {
animator.isPresenting = false
return animator
}
}
}
| 32.25 | 137 | 0.674849 |
031629c8fb1bc0d385b71225a64f6b8af51a84c0 | 1,383 | import XCTest
import class Foundation.Bundle
final class TheGameNewsTests: XCTestCase {
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
// Some of the APIs that we use below are available in macOS 10.13 and above.
guard #available(macOS 10.13, *) else {
return
}
let fooBinary = productsDirectory.appendingPathComponent("TheGameNews")
let process = Process()
process.executableURL = fooBinary
let pipe = Pipe()
process.standardOutput = pipe
try process.run()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
XCTAssertEqual(output, "Hello, world!\n")
}
/// Returns path to the built products directory.
var productsDirectory: URL {
#if os(macOS)
for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") {
return bundle.bundleURL.deletingLastPathComponent()
}
fatalError("couldn't find the products directory")
#else
return Bundle.main.bundleURL
#endif
}
static var allTests = [
("testExample", testExample),
]
}
| 28.8125 | 87 | 0.637021 |
9b70ae777d669927c2f288303ded7c166452a2a1 | 846 | //
// MovieCell.swift
// flix
//
// Created by Farid Ramos on 1/11/18.
// Copyright © 2018 Farid Ramos. All rights reserved.
//
import UIKit
import AlamofireImage
class MovieCell: UITableViewCell {
@IBOutlet weak var movieOverview: UILabel!
@IBOutlet weak var movieTitle: UILabel!
@IBOutlet weak var movieImg: UIImageView!
var movie: Movie! {
didSet {
movieOverview.text = movie.overview
movieTitle.text = movie.title
movieImg.af_setImage(withURL: movie.posterURL!)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 22.263158 | 65 | 0.638298 |
016e735ccb31a0eb4482aae3696e64e5c980521a | 4,748 | //
// WebviewMemoryViewController.swift
// iOSWork
//
// Created by Stan Hu on 2022/3/5.
//
import UIKit
import WebKit
class WebviewMemoryViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "webview内存"
view.backgroundColor = UIColor.white
view.addSubview(panelView)
panelView.snp.makeConstraints { make in
make.left.right.equalTo(0)
make.top.equalTo(100)
make.height.equalTo(50)
}
panelView.addArrangedSubview(btnAddWebView)
panelView.addArrangedSubview(btnRemoveWebView)
panelView.addArrangedSubview(UIView())
// Do any additional setup after loading the view.
}
@objc func addWebView(){
let vc = webVC()
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)
}
@objc func removeWebView(){
}
lazy var btnAddWebView: UIButton = {
let v = UIButton()
v.setTitle("添加Webview", for: .normal)
v.setTitleColor(UIColor.random, for: .normal)
v.addTarget(self, action: #selector(addWebView), for: .touchUpInside)
return v.borderWidth(width: 1).borderColor(color: UIColor.random)
}()
lazy var btnRemoveWebView: UIButton = {
let v = UIButton()
v.setTitle("删除Webview", for: .normal)
v.setTitleColor(UIColor.random, for: .normal)
v.addTarget(self, action: #selector(removeWebView), for: .touchUpInside)
return v.borderWidth(width: 1).borderColor(color: UIColor.random)
}()
lazy var panelView: UIStackView = {
let v = UIStackView()
v.axis = .horizontal
return v
}()
}
class webVC:UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.addSubview(progressView)
progressView.snp.makeConstraints { make in
make.top.equalTo(95)
make.left.right.equalTo(0)
make.height.equalTo(4)
}
view.addSubview(webView)
webView.addObserver(self, forKeyPath: "estimatedProgress", options: [.new,.old], context: nil)
webView.snp.makeConstraints { make in
make.left.right.equalTo(0)
make.top.equalTo(100)
make.bottom.equalTo(-50)
}
view.addSubview(btnClose)
btnClose.snp.makeConstraints { make in
make.left.equalTo(10)
make.top.equalTo(webView.snp.bottom)
}
let req = URLRequest(url: URL(string: "https://www.sohu.com/")!,cachePolicy: .reloadIgnoringLocalAndRemoteCacheData)
webView.load(req)
}
@objc func close(){
webView.removeFromSuperview()
clearCache()
dismiss(animated: true)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "estimatedProgress"{
self.progressView.setProgress(Float(self.webView.estimatedProgress), animated: true)
}
}
fileprivate func clearCache() {
URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0
}
lazy var btnClose : UIButton = {
let v = UIButton().title(title: "关闭").color(color: UIColor.random)
v.addTarget(self, action: #selector(close), for: .touchUpInside)
return v
}()
lazy var progressView: UIProgressView = {
let v = UIProgressView()
v.tintColor = UIColor.random
return v
}()
lazy var webView : MMWwb = {
let config = WKWebViewConfiguration()
config.preferences = WKPreferences()
config.preferences.minimumFontSize = 10
config.websiteDataStore = WKWebsiteDataStore.nonPersistent()
let v = MMWwb.init(frame: CGRect.zero, configuration: config)
v.isMultipleTouchEnabled = true
v.navigationDelegate = self
v.uiDelegate = self
v.autoresizesSubviews = true
v.scrollView.alwaysBounceVertical = true
v.scrollView.contentInsetAdjustmentBehavior = .never
v.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
v.scrollView.scrollIndicatorInsets = v.scrollView.contentInset
return v
}()
deinit {
print("webVC 已经被deinit")
}
}
extension webVC:WKUIDelegate,WKNavigationDelegate{
}
class MMWwb:WKWebView{
deinit {
print("=========WKWebView deinit =========")
}
}
| 28.95122 | 151 | 0.614996 |
162c62c4de675610dfb16fe48d87f87eb4a39a53 | 1,487 | //
// Copyright (C) 2005-2020 Alfresco Software Limited.
//
// This file is part of the Alfresco Content Mobile iOS App.
//
// 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 UIKit
import MaterialComponents.MaterialActivityIndicator
class ActivityIndicatorFooterView: UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
let activityIndicator = MDCActivityIndicator()
activityIndicator.cycleColors = [#colorLiteral(red: 0.137254902, green: 0.3960784314, blue: 0.8549019608, alpha: 1)]
activityIndicator.radius = 15
activityIndicator.strokeWidth = 4
activityIndicator.sizeToFit()
activityIndicator.startAnimating()
addSubview(activityIndicator)
activityIndicator.center = CGPoint(x: self.center.x, y: activityIndicator.frame.origin.y + activityIndicator.frame.size.height / 2)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
| 37.175 | 139 | 0.724277 |
647648daa92a62f29e2b7403fe79302ea03fa62f | 2,158 | //
// Statio
// Varun Santhanam
//
import Foundation
import UIKit
public enum Device {
// MARK: - API
/// Available iOS Interface Types
public enum Interface: String {
/// iPhone
case phone = "iPhone"
/// iPad
case tablet = "iPad"
/// Apple TV
case tv = "tv"
/// CarPlay
case car = "CarPlay"
/// Mac
case mac = "Mac"
/// Unknown
case unknown = "Unknown Device"
}
public struct System {
/// The name of the system
public let name: String
/// The version of the system
public let version: String
/// The uptime of the system
public let uptime: TimeInterval
}
public static var name: String {
UIDevice.current.name
}
public static var genericName: String {
UIDevice.current.localizedModel
}
public static var identifier: String {
modelIdentifier
}
public static var interface: Interface {
UIDevice.current.interfaceType
}
/// The system info of the device
public static var system: System {
.init(name: UIDevice.current.systemName,
version: UIDevice.current.systemVersion,
uptime: ProcessInfo.processInfo.systemUptime)
}
// MARK: - Private
private static var modelIdentifier: String {
var systemInfo = utsname()
uname(&systemInfo)
let modelCode = withUnsafePointer(to: &systemInfo.machine) { pointer in
pointer.withMemoryRebound(to: CChar.self, capacity: 1) { ptr in
String(validatingUTF8: ptr)
}
}
return String(validatingUTF8: modelCode ?? "") ?? "Unknown Identifier"
}
}
private extension UIDevice {
var interfaceType: Device.Interface {
switch userInterfaceIdiom {
case .phone: return .phone
case .pad: return .tablet
case .tv: return .tv
case .carPlay: return .car
case .unspecified: return .unknown
case .mac: return .mac
@unknown default:
return .unknown
}
}
}
| 20.75 | 79 | 0.575996 |
dec7629a822351251f705684236bf57f25dc8f5a | 31,633 | //
// PrimitiveSequence.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/5/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
/// Observable sequences containing 0 or 1 element.
public struct PrimitiveSequence<Trait, Element> {
fileprivate let source: Observable<Element>
init(raw: Observable<Element>) {
self.source = raw
}
}
/// Sequence containing exactly 1 element
public enum SingleTrait { }
/// Represents a push style sequence containing 1 element.
public typealias Single<Element> = PrimitiveSequence<SingleTrait, Element>
/// Sequence containing 0 or 1 elements
public enum MaybeTrait { }
/// Represents a push style sequence containing 0 or 1 element.
public typealias Maybe<Element> = PrimitiveSequence<MaybeTrait, Element>
/// Sequence containing 0 elements
public enum CompletableTrait { }
/// Represents a push style sequence containing 0 elements.
public typealias Completable = PrimitiveSequence<CompletableTrait, Swift.Never>
/// Observable sequences containing 0 or 1 element
public protocol PrimitiveSequenceType {
/// Additional constraints
associatedtype TraitType
/// Sequence element type
associatedtype ElementType
// Converts `self` to primitive sequence.
///
/// - returns: Observable sequence that represents `self`.
var primitiveSequence: PrimitiveSequence<TraitType, ElementType> { get }
}
extension PrimitiveSequence: PrimitiveSequenceType {
/// Additional constraints
public typealias TraitType = Trait
/// Sequence element type
public typealias ElementType = Element
// Converts `self` to primitive sequence.
///
/// - returns: Observable sequence that represents `self`.
public var primitiveSequence: PrimitiveSequence<TraitType, ElementType> {
return self
}
}
extension PrimitiveSequence: ObservableConvertibleType {
/// Type of elements in sequence.
public typealias E = Element
/// Converts `self` to `Observable` sequence.
///
/// - returns: Observable sequence that represents `self`.
public func asObservable() -> Observable<E> {
return source
}
}
// <Single>
public enum SingleEvent<Element> {
/// One and only sequence element is produced. (underlying observable sequence emits: `.next(Element)`, `.completed`)
case success(Element)
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
}
extension PrimitiveSequenceType where TraitType == SingleTrait {
public typealias SingleObserver = (SingleEvent<ElementType>) -> ()
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(subscribe: @escaping (@escaping SingleObserver) -> Disposable) -> PrimitiveSequence<TraitType, ElementType> {
let source = Observable<ElementType>.create { observer in
return subscribe { event in
switch event {
case .success(let element):
observer.on(.next(element))
observer.on(.completed)
case .error(let error):
observer.on(.error(error))
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (SingleEvent<ElementType>) -> ()) -> Disposable {
var stopped = false
return self.primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case .next(let element):
observer(.success(element))
case .error(let error):
observer(.error(error))
case .completed:
rxFatalErrorInDebug("Singles can't emit a completion event")
}
}
}
/**
Subscribes a success handler, and an error handler for this sequence.
- parameter onSuccess: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onSuccess: ((ElementType) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil) -> Disposable {
return self.primitiveSequence.subscribe { event in
switch event {
case .success(let element):
onSuccess?(element)
case .error(let error):
onError?(error)
}
}
}
}
// </Single>
// <Maybe>
public enum MaybeEvent<Element> {
/// One and only sequence element is produced. (underlying observable sequence emits: `.next(Element)`, `.completed`)
case success(Element)
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
/// Sequence completed successfully.
case completed
}
public extension PrimitiveSequenceType where TraitType == MaybeTrait {
public typealias MaybeObserver = (MaybeEvent<ElementType>) -> ()
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(subscribe: @escaping (@escaping MaybeObserver) -> Disposable) -> PrimitiveSequence<TraitType, ElementType> {
let source = Observable<ElementType>.create { observer in
return subscribe { event in
switch event {
case .success(let element):
observer.on(.next(element))
observer.on(.completed)
case .error(let error):
observer.on(.error(error))
case .completed:
observer.on(.completed)
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (MaybeEvent<ElementType>) -> ()) -> Disposable {
var stopped = false
return self.primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case .next(let element):
observer(.success(element))
case .error(let error):
observer(.error(error))
case .completed:
observer(.completed)
}
}
}
/**
Subscribes a success handler, an error handler, and a completion handler for this sequence.
- parameter onSuccess: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onSuccess: ((ElementType) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil) -> Disposable {
return self.primitiveSequence.subscribe { event in
switch event {
case .success(let element):
onSuccess?(element)
case .error(let error):
onError?(error)
case .completed:
onCompleted?()
}
}
}
}
// </Maybe>
// <Completable>
public enum CompletableEvent {
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
/// Sequence completed successfully.
case completed
}
public extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Swift.Never {
public typealias CompletableObserver = (CompletableEvent) -> ()
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(subscribe: @escaping (@escaping CompletableObserver) -> Disposable) -> PrimitiveSequence<TraitType, ElementType> {
let source = Observable<ElementType>.create { observer in
return subscribe { event in
switch event {
case .error(let error):
observer.on(.error(error))
case .completed:
observer.on(.completed)
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (CompletableEvent) -> ()) -> Disposable {
var stopped = false
return self.primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case .next:
rxFatalError("Completables can't emit values")
case .error(let error):
observer(.error(error))
case .completed:
observer(.completed)
}
}
}
/**
Subscribes a completion handler and an error handler for this sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onCompleted: (() -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil) -> Disposable {
return self.primitiveSequence.subscribe { event in
switch event {
case .error(let error):
onError?(error)
case .completed:
onCompleted?()
}
}
}
}
// </Completable>
extension PrimitiveSequence {
/**
Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
public static func deferred(_ observableFactory: @escaping () throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.deferred {
try observableFactory().asObservable()
})
}
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: Element) -> PrimitiveSequence<Trait, ElementType> {
return PrimitiveSequence(raw: Observable.just(element))
}
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- parameter: Scheduler to send the single element on.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> PrimitiveSequence<Trait, ElementType> {
return PrimitiveSequence(raw: Observable.just(element, scheduler: scheduler))
}
/**
Returns an observable sequence that terminates with an `error`.
- seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: The observable sequence that terminates with specified error.
*/
public static func error(_ error: Swift.Error) -> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.error(error))
}
/**
Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence whose observers will never get called.
*/
public static func never() -> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.never())
}
/**
Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the subscription.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: Time-shifted sequence.
*/
public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.delaySubscription(dueTime, scheduler: scheduler))
}
/**
Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the source by.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: the source Observable shifted in time by the specified delay.
*/
public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.delay(dueTime, scheduler: scheduler))
}
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onSubscribed: Action to invoke after subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
public func `do`(onNext: ((E) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> ())? = nil, onSubscribed: (() -> ())? = nil, onDispose: (() -> ())? = nil)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.do(
onNext: onNext,
onError: onError,
onCompleted: onCompleted,
onSubscribe: onSubscribe,
onSubscribed: onSubscribed,
onDispose: onDispose)
)
}
/**
Filters the elements of an observable sequence based on a predicate.
- seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html)
- parameter predicate: A function to test each source element for a condition.
- returns: An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
public func filter(_ predicate: @escaping (E) throws -> Bool)
-> Maybe<Element> {
return Maybe(raw: source.filter(predicate))
}
/**
Projects each element of an observable sequence into a new form.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter transform: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<R>(_ transform: @escaping (E) throws -> R)
-> PrimitiveSequence<Trait, R> {
return PrimitiveSequence<Trait, R>(raw: source.map(transform))
}
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
- seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
*/
public func flatMap<R>(_ selector: @escaping (ElementType) throws -> PrimitiveSequence<Trait, R>)
-> PrimitiveSequence<Trait, R> {
return PrimitiveSequence<Trait, R>(raw: source.flatMap(selector))
}
/**
Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription
actions have side-effects that require to be run on a scheduler, use `subscribeOn`.
- seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html)
- parameter scheduler: Scheduler to notify observers on.
- returns: The source sequence whose observations happen on the specified scheduler.
*/
public func observeOn(_ scheduler: ImmediateSchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.observeOn(scheduler))
}
/**
Wraps the source sequence in order to run its subscription and unsubscription logic on the specified
scheduler.
This operation is not commonly used.
This only performs the side-effects of subscription and unsubscription on the specified scheduler.
In order to invoke observer callbacks on a `scheduler`, use `observeOn`.
- seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html)
- parameter scheduler: Scheduler to perform subscription and unsubscription actions on.
- returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
public func subscribeOn(_ scheduler: ImmediateSchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.subscribeOn(scheduler))
}
/**
Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- parameter handler: Error handler function, producing another observable sequence.
- returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred.
*/
public func catchError(_ handler: @escaping (Swift.Error) throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.catchError { try handler($0).asObservable() })
}
/**
Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates.
If you encounter an error and want it to retry once, then you must use `retry(2)`
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter maxAttemptCount: Maximum number of times to repeat the sequence.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
public func retry(_ maxAttemptCount: Int)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retry(maxAttemptCount))
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType, Error: Swift.Error>(_ notificationHandler: @escaping (Observable<Error>) -> TriggerObservable)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retryWhen(notificationHandler))
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType>(_ notificationHandler: @escaping (Observable<Swift.Error>) -> TriggerObservable)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retryWhen(notificationHandler))
}
/**
Prints received events for all observers on standard output.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter identifier: Identifier that is printed together with event description to standard output.
- parameter trimOutput: Should output be trimmed to max 40 characters.
- returns: An observable sequence whose events are printed to standard output.
*/
public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.debug(identifier, trimOutput: trimOutput, file: file, line: line, function: function))
}
/**
Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
- seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html)
- parameter resourceFactory: Factory function to obtain a resource object.
- parameter primitiveSequenceFactory: Factory function to obtain an observable sequence that depends on the obtained resource.
- returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
public static func using<Resource: Disposable>(_ resourceFactory: @escaping () throws -> Resource, primitiveSequenceFactory: @escaping (Resource) throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.using(resourceFactory, observableFactory: { (resource: Resource) throws -> Observable<E> in
return try primitiveSequenceFactory(resource).asObservable()
}))
}
}
extension PrimitiveSequenceType where ElementType: SignedInteger
{
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
- parameter dueTime: Relative time at which to produce the first value.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
public static func timer(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable<ElementType>.timer(dueTime, scheduler: scheduler))
}
}
extension PrimitiveSequenceType where TraitType == MaybeTrait {
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
public static func empty() -> PrimitiveSequence<MaybeTrait, ElementType> {
return PrimitiveSequence(raw: Observable.empty())
}
}
extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Never {
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
public static func empty() -> PrimitiveSequence<CompletableTrait, Never> {
return PrimitiveSequence(raw: Observable.empty())
}
/**
Merges elements from all observable sequences from collection into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge<C: Collection>(_ sources: C) -> PrimitiveSequence<CompletableTrait, Never>
where C.Iterator.Element == PrimitiveSequence<CompletableTrait, Never> {
let source = Observable.merge(sources.map { $0.asObservable() })
return PrimitiveSequence<CompletableTrait, Never>(raw: source)
}
/**
Merges elements from all observable sequences from array into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Array of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge(_ sources: [PrimitiveSequence<CompletableTrait, Never>]) -> PrimitiveSequence<CompletableTrait, Never> {
let source = Observable.merge(sources.map { $0.asObservable() })
return PrimitiveSequence<CompletableTrait, Never>(raw: source)
}
/**
Merges elements from all observable sequences into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge(_ sources: PrimitiveSequence<CompletableTrait, Never>...) -> PrimitiveSequence<CompletableTrait, Never> {
let source = Observable.merge(sources.map { $0.asObservable() })
return PrimitiveSequence<CompletableTrait, Never>(raw: source)
}
}
extension ObservableType {
/**
The `asSingle` operator throws a `RxError.noElements` or `RxError.moreThanOneElement`
if the source Observable does not emit exactly one element before successfully completing.
- seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html)
- returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted.
*/
public func asSingle() -> Single<E> {
return PrimitiveSequence(raw: AsSingle(source: self.asObservable()))
}
/**
The `asMaybe` operator throws a ``RxError.moreThanOneElement`
if the source Observable does not emit at most one element before successfully completing.
- seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html)
- returns: An observable sequence that emits a single element, completes or throws an exception if more of them are emitted.
*/
public func asMaybe() -> Maybe<E> {
return PrimitiveSequence(raw: AsMaybe(source: self.asObservable()))
}
}
extension ObservableType where E == Never {
/**
- returns: An observable sequence that completes.
*/
public func asCompletable()
-> Completable {
return PrimitiveSequence(raw: self.asObservable())
}
}
| 44.057103 | 254 | 0.694433 |
f5419f3a6062798516d4d5f893af5c58a69c045b | 558 | //
// PinLocation+CoreDataProperties.swift
// PinDit
//
// Created by Zachary Johnson on 9/6/20.
// Copyright © 2020 Zachary Johnson. All rights reserved.
//
//
import Foundation
import CoreData
extension PinLocation {
@nonobjc public class func fetchRequest() -> NSFetchRequest<PinLocation> {
return NSFetchRequest<PinLocation>(entityName: "PinLocation")
}
@NSManaged public var title: String?
@NSManaged public var latitude: Double
@NSManaged public var subtitle: String?
@NSManaged public var longitude: Double
}
| 21.461538 | 78 | 0.716846 |
4a38c0d2aa9b749ae023096267cfe3ecee4ee3fa | 1,410 | //
// AppDelegate.swift
// UnsafePointer
//
// Created by hanwe on 2020/07/19.
// Copyright © 2020 hanwe. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.105263 | 179 | 0.747518 |
e86f2da71666f4ef5ea24198b17689e747579960 | 683 | //
// LoginViewModel.swift
// LoginSignupModule
//
// Created by Christian Slanzi on 22.03.21.
//
import Foundation
class LoginViewModel: NSObject {
weak var view: LoginViewControllerProtocol?
init(view: LoginViewControllerProtocol) {
super.init()
self.view = view
}
func performInitialViewSetup() {
view?.clearUserNameField()
view?.clearPasswordField()
view?.enableLoginButton(false)
view?.enableCreateAccountButton(true)
view?.hideKeyboard()
}
func userNameDidEndOnExit() {
view?.hideKeyboard()
}
func passwordDidEndOnExit() {
view?.hideKeyboard()
}
}
| 20.088235 | 47 | 0.63104 |
909a3e01a50814b86ca2609825b5619a60bfc425 | 2,232 | //
// UIViewControllerLoader.swift
// BetterKit
//
// Created by Nathan Jangula on 3/15/18.
//
import Foundation
private struct AssociatedKeys {
static var firstWillAppear: UInt8 = 0
static var firstWillAppearDispatch: UInt8 = 0
static var firstDidAppear: UInt8 = 0
static var firstDidAppearDispatch: UInt8 = 0
static var firstPresentDispatch: UInt8 = 0
}
@objc internal extension UIViewController {
@objc private class func loadExtension() {
DispatchOnce.load(key: &AssociatedKeys.firstWillAppearDispatch).perform {
Swizzler.swizzleInstanceSelector(class: UIViewController.self, origSelector: #selector(viewWillAppear(_:)),
newSelector: #selector(viewWillAppear_swizzled(_:)))
}
DispatchOnce.load(key: &AssociatedKeys.firstDidAppearDispatch).perform {
Swizzler.swizzleInstanceSelector(class: UIViewController.self, origSelector: #selector(viewDidAppear(_:)),
newSelector: #selector(viewDidAppear_swizzled(_:)))
}
}
@objc func viewWillAppear_swizzled(_ animated: Bool) {
viewWillAppear_swizzled(animated)
if !firstWillAppearFlag {
firstWillAppearFlag = true
viewWillFirstAppear(animated)
}
}
@objc func viewDidAppear_swizzled(_ animated: Bool) {
viewDidAppear_swizzled(animated)
if !firstDidAppearFlag {
firstDidAppearFlag = true
viewDidFirstAppear(animated)
}
}
private var firstWillAppearFlag: Bool {
get { return objc_getAssociatedObject(self, &AssociatedKeys.firstWillAppear) as? Bool ?? false }
set(newValue) { objc_setAssociatedObject(self, &AssociatedKeys.firstWillAppear, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
private var firstDidAppearFlag: Bool {
get { return objc_getAssociatedObject(self, &AssociatedKeys.firstDidAppear) as? Bool ?? false }
set(newValue) { objc_setAssociatedObject(self, &AssociatedKeys.firstDidAppear, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
}
| 37.2 | 157 | 0.673835 |
d741458a1461f9b2b62bb71d8b1e07d84df34934 | 450 | //
// FileSizeUnit.swift
// Aural
//
// Copyright © 2021 Kartik Venugopal. All rights reserved.
//
// This software is licensed under the MIT software license.
// See the file "LICENSE" in the project root directory for license terms.
//
import Foundation
///
/// An enumeration of all possible file size units.
///
enum FileSizeUnit: String {
case tb = "TB"
case gb = "GB"
case mb = "MB"
case kb = "KB"
case b = "B"
}
| 19.565217 | 75 | 0.637778 |
16c46adc9d3c9470aa5973b7de7711f2dd22b7cd | 1,590 | //
// AppDelegate.swift
// OCReact
//
// Created by Konrad Roj on 18/07/2019.
// Copyright © 2019 Konrad Roj. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
extension AppDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = prepareScanListScene()
return true
}
func applicationWillResignActive(_ application: UIApplication) {}
func applicationDidEnterBackground(_ application: UIApplication) {
/* some logic to stop text recognition */
}
func applicationWillEnterForeground(_ application: UIApplication) {
/* some logic to continue text recognition */
}
func applicationDidBecomeActive(_ application: UIApplication) {}
func applicationWillTerminate(_ application: UIApplication) {
/* some logic to restore text recognition */
}
}
extension AppDelegate {
private func prepareScanListScene() -> UINavigationController {
let viewModel = ScanListViewModel(database: Service.database, textRecognition: Service.textRecognition)
let viewController = ScanListViewController(viewModel: viewModel)
let navigationController = UINavigationController(rootViewController: viewController)
return navigationController
}
}
| 30.576923 | 145 | 0.713836 |
2337face41991c8ae004b2c4fb9b32aeffa4cb17 | 2,319 | //
// SceneDelegate.swift
// SwiftSample
//
// Created by Sven Herzberg on 18.10.19.
//
import UIKit
@available(iOS 13.0, *)
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.754717 | 147 | 0.712807 |
de937bd6ec8b59c0dd83656b9ffa3bb7600f6c94 | 1,339 | //
// AppDelegate.swift
// Example
//
// Created by 王叶庆 on 2021/9/20.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.189189 | 179 | 0.744586 |
87f79f94ca2cc588634e3de4333d3d2255712624 | 446 | //
// CollectionTableViewCell.swift
// Alababic
//
// Created by Dima Paliychuk on 6/12/17.
// Copyright © 2017 Roman Sorochak. All rights reserved.
//
import UIKit
import Reusable
class CollectionTableViewCell: UITableViewCell, Reusable {
@IBOutlet weak var collectionView: UICollectionView!
// life cycle
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| 17.153846 | 58 | 0.665919 |
6a91cbb5415d185e07abb8c4c3285433c8a54c7c | 334 | import XCTest
@testable import Swift_CAN_Anywhere
final class Swift_CAN_AnywhereTests: XCTestCase {
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
XCTAssertTrue(true)
}
}
| 27.833333 | 87 | 0.697605 |
fba347464d33db79abc69ad4dd41c7b448bee842 | 501 | //
// Curator.swift
// Cider
//
// Created by Scott Hoyt on 8/25/17.
// Copyright © 2017 Scott Hoyt. All rights reserved.
//
import Foundation
public typealias Curator = Resource<CuratorAttributes, CuratorRelationships>
public struct CuratorAttributes: Codable {
public let artwork: Artwork
public let editorialNotes: EditorialNotes?
public let name: String
public let url: URL
}
public struct CuratorRelationships: Codable {
public let playlists: Relationship<Playlist>
}
| 21.782609 | 76 | 0.740519 |
bbe9f64e3329dcab726edf7b8c66d8bcef502bde | 1,770 | /// Returns the Boolean value of the input
///
/// - parameter value: A Boolean type
///
/// - returns: The Bool value of the input
public func boolValue<T: BooleanType>(value: T) -> Bool {
return value.boolValue
}
/// Negates a Boolean-returning transformer.
///
/// - parameter transform: The transformer to negate.
///
/// - returns: The negated transformer.
public func not<T, B: BooleanType>(transform: T -> B) -> T -> Bool {
return { !transform($0) }
}
/// `undefined()` pretends to be able to produce a value of any type `T` which can
/// be very useful whilst writing a program. It happens that you need a value
/// (which can be a function as well) of a certain type but you can't produce it
/// just yet. However, you can always temporarily replace it by `undefined()`.
///
/// Inspired by Haskell's
/// [undefined](http://hackage.haskell.org/package/base-4.7.0.2/docs/Prelude.html#v:undefined).
///
/// Invoking `undefined()` will crash your program.
///
/// Some examples:
///
/// - `let x : String = undefined()`
/// - `let f : String -> Int? = undefined("string to optional int function")`
/// - `return undefined() /* in any function */`
/// - `let x : String = (undefined() as Int -> String)(42)`
/// - ...
///
/// What a crash looks like:
///
/// `fatal error: undefined: main.swift, line 131`
///
/// Thanks to Johannes Weiß <https://github.com/weissi/swift-undefined>.
public func undefined<T>(hint: String = "", file: StaticString = #file, line: UInt = #line) -> T {
let message = hint == "" ? "" : ": \(hint)"
fatalError("undefined \(T.self)\(message)", file: file, line: line)
}
/// A no-op function.
public func void() { }
/// A no-op function that accepts a parameter of arbitrary type.
public func void<T>(value: T) { }
| 34.038462 | 98 | 0.643503 |
d5fb69ea9674ace7642ac64fad197c0ae87cb2e4 | 14,506 | // Generated by the protocol buffer compiler. DO NOT EDIT!
import Foundation
import ProtocolBuffers
public struct ProtoPerfomanceRoot {
public static var sharedInstance : ProtoPerfomanceRoot {
struct Static {
static let instance : ProtoPerfomanceRoot = ProtoPerfomanceRoot()
}
return Static.instance
}
var extensionRegistry:ExtensionRegistry
init() {
extensionRegistry = ExtensionRegistry()
registerAllExtensions(extensionRegistry)
SwiftDescriptorRoot.sharedInstance.registerAllExtensions(extensionRegistry)
}
public func registerAllExtensions(registry:ExtensionRegistry) {
}
}
public func == (lhs: ProtoPerfomance, rhs: ProtoPerfomance) -> Bool {
if (lhs === rhs) {
return true
}
var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)
fieldCheck = fieldCheck && (lhs.hasInts == rhs.hasInts) && (!lhs.hasInts || lhs.ints == rhs.ints)
fieldCheck = fieldCheck && (lhs.hasInts64 == rhs.hasInts64) && (!lhs.hasInts64 || lhs.ints64 == rhs.ints64)
fieldCheck = fieldCheck && (lhs.hasDoubles == rhs.hasDoubles) && (!lhs.hasDoubles || lhs.doubles == rhs.doubles)
fieldCheck = fieldCheck && (lhs.hasFloats == rhs.hasFloats) && (!lhs.hasFloats || lhs.floats == rhs.floats)
fieldCheck = fieldCheck && (lhs.hasStr == rhs.hasStr) && (!lhs.hasStr || lhs.str == rhs.str)
fieldCheck = fieldCheck && (lhs.hasBytes == rhs.hasBytes) && (!lhs.hasBytes || lhs.bytes == rhs.bytes)
fieldCheck = fieldCheck && (lhs.hasDescription == rhs.hasDescription) && (!lhs.hasDescription || lhs.description_ == rhs.description_)
return (fieldCheck && (lhs.unknownFields == rhs.unknownFields))
}
final public class ProtoPerfomance : GeneratedMessage {
public private(set) var hasInts:Bool = false
public private(set) var ints:Int32 = Int32(0)
public private(set) var hasInts64:Bool = false
public private(set) var ints64:Int64 = Int64(0)
public private(set) var hasDoubles:Bool = false
public private(set) var doubles:Double = Double(0)
public private(set) var hasFloats:Bool = false
public private(set) var floats:Float = Float(0)
public private(set) var hasStr:Bool = false
public private(set) var str:String = ""
public private(set) var hasBytes:Bool = false
public private(set) var bytes:Array<Byte> = [Byte]()
public private(set) var hasDescription:Bool = false
public private(set) var description_:String = ""
required public init() {
super.init()
}
override public func isInitialized() -> Bool {
if !hasInts {
return false
}
if !hasInts64 {
return false
}
if !hasDoubles {
return false
}
if !hasFloats {
return false
}
return true
}
override public func writeToCodedOutputStream(output:CodedOutputStream) {
if hasInts {
output.writeInt32(1, value:ints)
}
if hasInts64 {
output.writeInt64(2, value:ints64)
}
if hasDoubles {
output.writeDouble(3, value:doubles)
}
if hasFloats {
output.writeFloat(4, value:floats)
}
if hasStr {
output.writeString(5, value:str)
}
if hasBytes {
output.writeData(6, value:bytes)
}
if hasDescription {
output.writeString(7, value:description_)
}
unknownFields.writeToCodedOutputStream(output)
}
override public func serializedSize() -> Int32 {
var size:Int32 = memoizedSerializedSize
if size != -1 {
return size
}
size = 0
if hasInts {
size += WireFormat.computeInt32Size(1, value:ints)
}
if hasInts64 {
size += WireFormat.computeInt64Size(2, value:ints64)
}
if hasDoubles {
size += WireFormat.computeDoubleSize(3, value:doubles)
}
if hasFloats {
size += WireFormat.computeFloatSize(4, value:floats)
}
if hasStr {
size += WireFormat.computeStringSize(5, value:str)
}
if hasBytes {
size += WireFormat.computeDataSize(6, value:bytes)
}
if hasDescription {
size += WireFormat.computeStringSize(7, value:description_)
}
size += unknownFields.serializedSize()
memoizedSerializedSize = size
return size
}
public class func parseFromData(data:[Byte]) -> ProtoPerfomance {
return ProtoPerfomance.builder().mergeFromData(data).build()
}
public class func parseFromData(data:[Byte], extensionRegistry:ExtensionRegistry) -> ProtoPerfomance {
return ProtoPerfomance.builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()
}
public class func parseFromInputStream(input:NSInputStream) -> ProtoPerfomance {
return ProtoPerfomance.builder().mergeFromInputStream(input).build()
}
public class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) ->ProtoPerfomance {
return ProtoPerfomance.builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream) -> ProtoPerfomance {
return ProtoPerfomance.builder().mergeFromCodedInputStream(input).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) -> ProtoPerfomance {
return ProtoPerfomance.builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func builder() -> ProtoPerfomanceBuilder {
return ProtoPerfomance.classBuilder() as ProtoPerfomanceBuilder
}
public func builder() -> ProtoPerfomanceBuilder {
return classBuilder() as ProtoPerfomanceBuilder
}
public override class func classBuilder() -> MessageBuilder {
return ProtoPerfomanceBuilder()
}
public override func classBuilder() -> MessageBuilder {
return ProtoPerfomance.builder()
}
public func toBuilder() -> ProtoPerfomanceBuilder {
return ProtoPerfomance.builderWithPrototype(self)
}
public class func builderWithPrototype(prototype:ProtoPerfomance) -> ProtoPerfomanceBuilder {
return ProtoPerfomance.builder().mergeFrom(prototype)
}
override public func writeDescriptionTo(inout output:String, indent:String) {
if hasInts {
output += "\(indent) ints: \(ints) \n"
}
if hasInts64 {
output += "\(indent) ints64: \(ints64) \n"
}
if hasDoubles {
output += "\(indent) doubles: \(doubles) \n"
}
if hasFloats {
output += "\(indent) floats: \(floats) \n"
}
if hasStr {
output += "\(indent) str: \(str) \n"
}
if hasBytes {
output += "\(indent) bytes: \(bytes) \n"
}
if hasDescription {
output += "\(indent) description_: \(description_) \n"
}
unknownFields.writeDescriptionTo(&output, indent:indent)
}
override public var hashValue:Int {
get {
var hashCode:Int = 7
if hasInts {
hashCode = (hashCode &* 31) &+ ints.hashValue
}
if hasInts64 {
hashCode = (hashCode &* 31) &+ ints64.hashValue
}
if hasDoubles {
hashCode = (hashCode &* 31) &+ doubles.hashValue
}
if hasFloats {
hashCode = (hashCode &* 31) &+ floats.hashValue
}
if hasStr {
hashCode = (hashCode &* 31) &+ str.hashValue
}
if hasBytes {
for oneValuebytes in bytes {
hashCode = (hashCode &* 31) &+ oneValuebytes.hashValue
}
}
if hasDescription {
hashCode = (hashCode &* 31) &+ description_.hashValue
}
hashCode = (hashCode &* 31) &+ unknownFields.hashValue
return hashCode
}
}
//Meta information declaration start
override public class func className() -> String {
return "ProtoPerfomance"
}
override public func className() -> String {
return "ProtoPerfomance"
}
override public func classMetaType() -> GeneratedMessage.Type {
return ProtoPerfomance.self
}
//Meta information declaration end
}
final public class ProtoPerfomanceBuilder : GeneratedMessageBuilder {
private var builderResult:ProtoPerfomance
required override public init () {
builderResult = ProtoPerfomance()
super.init()
}
public var hasInts:Bool {
get {
return builderResult.hasInts
}
}
public var ints:Int32 {
get {
return builderResult.ints
}
set (value) {
builderResult.hasInts = true
builderResult.ints = value
}
}
public func clearInts() -> ProtoPerfomanceBuilder{
builderResult.hasInts = false
builderResult.ints = Int32(0)
return self
}
public var hasInts64:Bool {
get {
return builderResult.hasInts64
}
}
public var ints64:Int64 {
get {
return builderResult.ints64
}
set (value) {
builderResult.hasInts64 = true
builderResult.ints64 = value
}
}
public func clearInts64() -> ProtoPerfomanceBuilder{
builderResult.hasInts64 = false
builderResult.ints64 = Int64(0)
return self
}
public var hasDoubles:Bool {
get {
return builderResult.hasDoubles
}
}
public var doubles:Double {
get {
return builderResult.doubles
}
set (value) {
builderResult.hasDoubles = true
builderResult.doubles = value
}
}
public func clearDoubles() -> ProtoPerfomanceBuilder{
builderResult.hasDoubles = false
builderResult.doubles = Double(0)
return self
}
public var hasFloats:Bool {
get {
return builderResult.hasFloats
}
}
public var floats:Float {
get {
return builderResult.floats
}
set (value) {
builderResult.hasFloats = true
builderResult.floats = value
}
}
public func clearFloats() -> ProtoPerfomanceBuilder{
builderResult.hasFloats = false
builderResult.floats = Float(0)
return self
}
public var hasStr:Bool {
get {
return builderResult.hasStr
}
}
public var str:String {
get {
return builderResult.str
}
set (value) {
builderResult.hasStr = true
builderResult.str = value
}
}
public func clearStr() -> ProtoPerfomanceBuilder{
builderResult.hasStr = false
builderResult.str = ""
return self
}
public var hasBytes:Bool {
get {
return builderResult.hasBytes
}
}
public var bytes:Array<Byte> {
get {
return builderResult.bytes
}
set (value) {
builderResult.hasBytes = true
builderResult.bytes = value
}
}
public func clearBytes() -> ProtoPerfomanceBuilder{
builderResult.hasBytes = false
builderResult.bytes = [Byte]()
return self
}
public var hasDescription:Bool {
get {
return builderResult.hasDescription
}
}
public var description_:String {
get {
return builderResult.description_
}
set (value) {
builderResult.hasDescription = true
builderResult.description_ = value
}
}
public func clearDescription() -> ProtoPerfomanceBuilder{
builderResult.hasDescription = false
builderResult.description_ = ""
return self
}
override public var internalGetResult:GeneratedMessage {
get {
return builderResult
}
}
public override func clear() -> ProtoPerfomanceBuilder {
builderResult = ProtoPerfomance()
return self
}
public override func clone() -> ProtoPerfomanceBuilder {
return ProtoPerfomance.builderWithPrototype(builderResult)
}
public override func build() -> ProtoPerfomance {
checkInitialized()
return buildPartial()
}
public func buildPartial() -> ProtoPerfomance {
var returnMe:ProtoPerfomance = builderResult
return returnMe
}
public func mergeFrom(other:ProtoPerfomance) -> ProtoPerfomanceBuilder {
if (other == ProtoPerfomance()) {
return self
}
if other.hasInts {
ints = other.ints
}
if other.hasInts64 {
ints64 = other.ints64
}
if other.hasDoubles {
doubles = other.doubles
}
if other.hasFloats {
floats = other.floats
}
if other.hasStr {
str = other.str
}
if other.hasBytes {
bytes = other.bytes
}
if other.hasDescription {
description_ = other.description_
}
mergeUnknownFields(other.unknownFields)
return self
}
public override func mergeFromCodedInputStream(input:CodedInputStream) ->ProtoPerfomanceBuilder {
return mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())
}
public override func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) -> ProtoPerfomanceBuilder {
var unknownFieldsBuilder:UnknownFieldSetBuilder = UnknownFieldSet.builderWithUnknownFields(self.unknownFields)
while (true) {
var tag = input.readTag()
switch tag {
case 0:
self.unknownFields = unknownFieldsBuilder.build()
return self
case 8 :
ints = input.readInt32()
case 16 :
ints64 = input.readInt64()
case 25 :
doubles = input.readDouble()
case 37 :
floats = input.readFloat()
case 42 :
str = input.readString()
case 50 :
bytes = input.readData()
case 58 :
description_ = input.readString()
default:
if (!parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag)) {
unknownFields = unknownFieldsBuilder.build()
return self
}
}
}
}
}
//Class extensions: NSData
public extension ProtoPerfomance {
class func parseFromNSData(data:NSData) -> ProtoPerfomance {
var bytes = [Byte](count: data.length, repeatedValue: 0)
data.getBytes(&bytes)
return ProtoPerfomance.builder().mergeFromData(bytes).build()
}
class func parseFromNSData(data:NSData, extensionRegistry:ExtensionRegistry) -> ProtoPerfomance {
var bytes = [Byte](count: data.length, repeatedValue: 0)
data.getBytes(&bytes)
return ProtoPerfomance.builder().mergeFromData(bytes, extensionRegistry:extensionRegistry).build()
}
}
// @@protoc_insertion_point(global_scope)
| 29.48374 | 137 | 0.648283 |
217417b7e461fd9286e971138374712233c61215 | 395 | //
// MarvelVsDCApp.swift
// MarvelVsDC
//
// Created by Salih Çakmak on 12.01.2022.
//
import SwiftUI
@main
struct MarvelVsDCApp: App {
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
}
| 18.809524 | 97 | 0.653165 |
fccdb4e675d93d70bf22ef4326d899bdee9d445a | 2,397 | //
// ICUReader.swift
// TRETJapanNFCReader
//
// Created by Qs-F on 2019/09/26.
// Copyright © 2019 treastrain / Tanaka Ryoga. All rights reserved.
//
import CoreNFC
@available(iOS 13.0, *)
public typealias ICUCardTag = NFCFeliCaTag
@available(iOS 13.0, *)
public class ICUReader: FeliCaReader {
private var ICUCardItemTypes: [ICUCardItemType] = []
private init() {
fatalError()
}
/// ICUReader を初期化する。
/// - Parameter feliCaReader: FeliCaReader
public init(feliCaReader: FeliCaReader) {
super.init(delegate: feliCaReader.delegate!)
}
/// ICUReader を初期化する。
/// - Parameter delegate: FeliCaReaderSessionDelegate
public override init(delegate: FeliCaReaderSessionDelegate) {
super.init(delegate: delegate)
}
/// ICUReader を初期化する。
/// - Parameter viewController: FeliCaReaderSessionDelegate を適用した UIViewController
public override init(viewController: FeliCaReaderViewController) {
super.init(viewController: viewController)
}
/// IICUカードからデータを読み取る
/// - Parameter itemTypes: ICUカードから読み取りたいデータのタイプ
public func get(itemTypes: [ICUCardItemType]) {
self.ICUCardItemTypes = itemTypes
self.beginScanning()
}
public func getItems(_ session: NFCTagReaderSession, feliCaTag: NFCFeliCaTag, idm: String, systemCode: FeliCaSystemCode, itemTypes: [ICUCardItemType], completion: @escaping (FeliCaCard) -> Void) {
self.ICUCardItemTypes = itemTypes
self.getItems(session, feliCaTag: feliCaTag, idm: idm, systemCode: systemCode) { (feliCaCard) in
completion(feliCaCard)
}
}
public override func getItems(_ session: NFCTagReaderSession, feliCaTag: NFCFeliCaTag, idm: String, systemCode: FeliCaSystemCode, completion: @escaping (FeliCaCard) -> Void) {
var icuCard = ICUCard(tag: feliCaTag, data: ICUCardData(idm: idm, systemCode: systemCode))
DispatchQueue(label: "TRETJPNRICUReader", qos: .default).async {
var data: [FeliCaServiceCode : [Data]] = [:]
for itemType in self.ICUCardItemTypes {
data[itemType.serviceCode] = self.readWithoutEncryption(session: session, tag: icuCard.tag, serviceCode: itemType.serviceCode, blocks: itemType.blocks)
}
icuCard.data.data = data
completion(icuCard)
}
}
}
| 35.25 | 200 | 0.675428 |
11c5df7405d9c4444c33214ba1a6abf7d8047a0d | 2,556 | //
// FRBook.swift
// FolioReaderKit
//
// Created by Heberti Almeida on 09/04/15.
// Extended by Kevin Jantzer on 12/30/15
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
open class FRBook: NSObject {
var resources = FRResources()
var metadata = FRMetadata()
var spine = FRSpine()
var smils = FRSmils()
var tableOfContents: [FRTocReference]!
var flatTableOfContents: [FRTocReference]!
var opfResource: FRResource!
var tocResource: FRResource?
var coverImage: FRResource?
var version: Double?
var uniqueIdentifier: String?
func hasAudio() -> Bool {
return smils.smils.count > 0 ? true : false
}
func title() -> String? {
return metadata.titles.first
}
func authorName() -> String? {
return metadata.creators.first?.name
}
// MARK: - Media Overlay Metadata
// http://www.idpf.org/epub/301/spec/epub-mediaoverlays.html#sec-package-metadata
func duration() -> String? {
return metadata.findMetaByProperty("media:duration");
}
// @NOTE: should "#" be automatically prefixed with the ID?
func durationFor(_ ID: String) -> String? {
return metadata.findMetaByProperty("media:duration", refinedBy: ID)
}
func activeClass() -> String {
guard let className = metadata.findMetaByProperty("media:active-class") else {
return "epub-media-overlay-active"
}
return className
}
func playbackActiveClass() -> String {
guard let className = metadata.findMetaByProperty("media:playback-active-class") else {
return "epub-media-overlay-playing"
}
return className
}
// MARK: - Media Overlay (SMIL) retrieval
/**
Get Smil File from a resource (if it has a media-overlay)
*/
func smilFileForResource(_ resource: FRResource!) -> FRSmilFile! {
if( resource == nil || resource.mediaOverlay == nil ){
return nil
}
// lookup the smile resource to get info about the file
let smilResource = resources.findById(resource.mediaOverlay)
// use the resource to get the file
return smils.findByHref( smilResource!.href )
}
func smilFileForHref(_ href: String) -> FRSmilFile! {
return smilFileForResource(resources.findByHref(href))
}
func smilFileForId(_ ID: String) -> FRSmilFile! {
return smilFileForResource(resources.findById(ID))
}
}
| 28.087912 | 95 | 0.625978 |
3a7e907cab7956560a1e9cda536c33de78411f20 | 717 | import Foundation
import Combine
import SwiftUI
class UISettings: ObservableObject {
let objectWillChange = PassthroughSubject<UISettings,Never>()
var showToolBar : Bool = true {
didSet{
//withAnimation() {
objectWillChange.send(self)
//}
}
}
var showTopNav : Bool = true {
didSet{
//withAnimation() {
objectWillChange.send(self)
//}
}
}
var currentPage : String = "home" {
didSet{
//withAnimation() {
objectWillChange.send(self)
//}
}
}
func toggleView(){
showToolBar = !showToolBar
}
}
| 19.916667 | 65 | 0.497908 |
d9b197d002ce3fb36ed2f9b50e457404082a83c4 | 1,140 | //
// CreditNoteFacade.swift
// mandayFaktura
//
// Created by Wojciech Kicior on 17.02.2019.
// Copyright © 2019 Wojciech Kicior. All rights reserved.
//
import Foundation
class CreditNoteFacade {
let creditNoteRepository: CreditNoteRepository = CreditNoteRepositoryFactory.instance
let invoiceNumbering: InvoiceNumbering = InvoiceNumbering()
let creditNoteNumbering: CreditNoteNumbering = CreditNoteNumbering()
func saveCreditNote(_ creditNote: CreditNote) throws {
try creditNoteNumbering.verifyCreditNoteWithNumberDoesNotExist(creditNoteNumber: creditNote.number)
try invoiceNumbering.verifyInvoiceWithNumberDoesNotExist(invoiceNumber: creditNote.number)
creditNoteRepository.addCreditNote(creditNote)
}
func getCreditNotes() -> [CreditNote] {
return creditNoteRepository.getCreditNotes()
}
func delete(_ creditNote: CreditNote) {
creditNoteRepository.deleteCreditNote(creditNote)
}
func creditNoteForInvoice(invoiceNumber: String) -> CreditNote? {
return creditNoteRepository.findBy(invoiceNumber: invoiceNumber)
}
}
| 33.529412 | 107 | 0.750877 |
502aced9a1c1de32bd3c5a91f09988e244fb2631 | 432 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
c{p}class B<f where B:a{class a{var f=1
| 43.2 | 78 | 0.74537 |
3afa748015e35211821ce955f662a8a27190d3ba | 403 | //
// BackgroundView.swift
// NiceAlert
//
// Created by iya on 2020/12/1.
//
import UIKit
class BackgroundView: UIView {
var alert: Container?
var willRemoveHandler: (() -> Void)?
override func willMove(toSuperview newSuperview: UIView?) {
superview?.willMove(toSuperview: newSuperview)
if newSuperview == nil {
willRemoveHandler?()
}
}
}
| 18.318182 | 63 | 0.617866 |
1adf166223400dccfd4db6840ca3feae0e8b2b9b | 1,065 | import Vapor
import HTTP
/// Here we have a controller that helps facilitate
/// creating typical REST patterns
final class Daminik00Controller: ResourceRepresentable {
let view: ViewRenderer
init(_ view: ViewRenderer) {
self.view = view
}
/// GET /daminik00
func index(_ req: Request) throws -> ResponseRepresentable {
return try view.make("daminik00")
}
/// GET /daminik00/:string
func show(_ req: Request, _ string: String) throws -> ResponseRepresentable {
switch string {
case "github":
return Response(redirect: "https://github.com/daminik00")
default:
return try view.make("daminik00")
}
}
/// When making a controller, it is pretty flexible in that it
/// only expects closures, this is useful for advanced scenarios, but
/// most of the time, it should look almost identical to this
/// implementation
func makeResource() -> Resource<String> {
return Resource(index: index, show: show)
}
}
| 28.783784 | 81 | 0.633803 |
cc50cb769cb2f133d1bdddf159b2bcf0639607a4 | 370 | //
// EditEmployeePage.swift
// Grafeio
//
// Created by Ryan Octavius on 01/12/20.
//
import SwiftUI
struct EditEmployeePage: View {
var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
}
}
struct EditEmployeePage_Previews: PreviewProvider {
static var previews: some View {
EditEmployeePage()
}
}
| 17.619048 | 71 | 0.654054 |
6194a500d0f28535dbcefa332938a56e70fea856 | 1,988 | //
// SFAVPlayerViewController.swift
// iOSTips
//
// Created by brian on 2018/4/15.
// Copyright © 2018年 brian. All rights reserved.
//
import UIKit
import AVFoundation
/*
AVPlayer的优点:
AVPlayer的缺点:单纯播放视频,没有显示界面,如果希望视频显示出来需要借助AVPlayerLayer层才能显示出来
创建AVPlayer通过以上两种方式都可以
> public init(url URL: URL)
> public init(playerItem item: AVPlayerItem?)
切换AVPlayerItem通过AVPlayerLayer的player播放器的replaceCurrentItem实现
*/
class SFAVPlayerViewController: UIViewController {
lazy var playerLayerByURL: AVPlayerLayer = {
let url = URL(string: "http://7xnvxr.com1.z0.glb.clouddn.com/5fc5ef97a05d4e8481058a401f054086/L4_nvqjpassesg4dytj.mp4")!
let player = AVPlayer(url: url)
let playerLayer = AVPlayerLayer(player: player)
return playerLayer
}()
lazy var playerLayerByPlayerItem: AVPlayerLayer = {
let url = URL(string: "http://cache.utovr.com/65e1e2929d924d6f80f6cfb8b06b38da/L4_ftqcoiyjhysyii89.mp4")!
let playerItem = AVPlayerItem(url: url)
let player = AVPlayer(playerItem: playerItem)
let playerLayer = AVPlayerLayer(player: player)
return playerLayer
}()
override func viewDidLoad() {
super.viewDidLoad()
view.layer.addSublayer(playerLayerByURL)
playerLayerByURL.player?.play()
/*
or
view.layer.addSublayer(playerLayerByPlayerItem)
playerLayerByPlayerItem?.play()
*/
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
playerLayerByURL.frame = view.bounds
/*
or
playerLayerByPlayerItem.frame = view.bounds
*/
}
@IBAction func replaceVideo() {
let url = URL(string: "http://cache.utovr.com/s1tytu9bfy2znke4w8/L3_2880_5_25.mp4")!
let playerItem = AVPlayerItem(url: url)
playerLayerByURL.player?.replaceCurrentItem(with: playerItem)
}
}
| 27.611111 | 128 | 0.661972 |
5b8be92b48be708dfa2b94bc5394a1a143347ff8 | 322 | import HyperionCore
class GoTopPluginModule: GoViewControllerHyperionPluginModule {
required init(with ext: HYPPluginExtensionProtocol) {
super.init(with: ext) {
TopViewController.newInstance()
}
}
override func pluginMenuItemTitle() -> String {
return "トップ画面へ遷移"
}
}
| 23 | 63 | 0.670807 |
28cb2e17ad8e374ce08db86ba145655e69787f23 | 1,010 | //
// ReformGraphicsTests.swift
// ReformGraphicsTests
//
// Created by Laszlo Korte on 15.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
import XCTest
@testable import ReformGraphics
final class ReformGraphicsTests: 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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 27.297297 | 111 | 0.645545 |
e6e154db71cb1559ad3448eead08ab6d7aca177f | 196 | //
// InfluenceMap.swift
// SmartAILibrary
//
// Created by Michael Rommel on 20.01.20.
// Copyright © 2020 Michael Rommel. All rights reserved.
//
import Foundation
class InfluenceMap {
}
| 14 | 57 | 0.69898 |
e48d05373c8a86643adf6a9cd0d09baadbfa49ec | 3,876 | //
// PlayerInfoOverlayViewController.swift
// F1A-TV
//
// Created by Noah Fetz on 06.04.21.
//
import UIKit
import Kingfisher
class PlayerInfoOverlayViewController: BaseViewController {
@IBOutlet weak var contentStackView: UIStackView!
var topBarView: UIStackView?
var contentItem: ContentItem?
var backgroundImageView: UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
self.setupViewController()
}
func initialize(contentItem: ContentItem) {
self.contentItem = contentItem
}
func setupViewController() {
self.view.backgroundColor = .clear
let swipeUpRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeUpRegognized))
swipeUpRecognizer.direction = .up
self.view.addGestureRecognizer(swipeUpRecognizer)
self.setupTopBar()
self.addContentToTopBar()
}
override func viewDidAppear(_ animated: Bool) {
self.applyImage(pictureId: self.contentItem?.container.metadata?.pictureUrl ?? "", imageView: self.backgroundImageView ?? UIImageView())
}
func setupTopBar() {
self.contentStackView.arrangedSubviews.forEach({$0.removeFromSuperview()})
self.topBarView = UIStackView()
self.topBarView?.axis = .vertical
self.topBarView?.backgroundColor = ConstantsUtil.brandingBackgroundColor
self.topBarView?.layer.cornerRadius = 20
NSLayoutConstraint.activate([
(self.topBarView ?? UIView()).heightAnchor.constraint(equalToConstant: 500)
])
self.topBarView?.backgroundShadow()
self.contentStackView.addArrangedSubview(self.topBarView ?? UIView())
let spaceTakingView = UIView()
spaceTakingView.backgroundColor = .clear
self.contentStackView.addArrangedSubview(spaceTakingView)
}
func addContentToTopBar() {
self.topBarView?.arrangedSubviews.forEach({$0.removeFromSuperview()})
self.backgroundImageView = UIImageView()
self.backgroundImageView?.layer.cornerRadius = 20
self.backgroundImageView?.contentMode = .scaleAspectFill
self.topBarView?.addArrangedSubview(self.backgroundImageView ?? UIView())
}
func applyImage(pictureId: String, imageView: UIImageView) {
let width = UIScreen.main.nativeBounds.width
let height = UIScreen.main.nativeBounds.height
var newApiUrlString = "https://ott.formula1.com/image-resizer/image/"
newApiUrlString.append(pictureId)
newApiUrlString.append("?w=\(width)&h=\(height)&q=HI&o=L")
self.applyImage(imageUrl: newApiUrlString, imageView: imageView)
}
func applyImage(imageUrl: String, imageView: UIImageView) {
if let url = URL(string: imageUrl) {
let processor = DownsamplingImageProcessor(size: imageView.bounds.size)
imageView.kf.indicatorType = .activity
imageView.kf.setImage(
with: url,
options: [
.processor(processor),
.scaleFactor(UIScreen.main.scale),
.transition(.fade(0.2)),
.cacheOriginalImage
], completionHandler:
{
result in
switch result {
case .success(_):
break
// print("Task done for: \(value.source.url?.absoluteString ?? "")")
case .failure(let error):
print("Job failed: \(error.localizedDescription)")
}
})
}
}
@objc func swipeUpRegognized() {
self.dismiss(animated: true)
}
}
| 35.236364 | 144 | 0.607585 |
fb8a9b57a3151fcfb8f0909b679f95748fcdc61e | 305 | //
// navigationItemCellCollectionViewCell.swift
// CollectionViewFun
//
// Created by Zach McArtor on 3/21/15.
// Copyright (c) 2015 HackaZach. All rights reserved.
//
import UIKit
class navigationItemCellCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var nameLabel: UILabel!
}
| 20.333333 | 66 | 0.747541 |
e064a8b6ab8b96a2ac22eb16c44c9972d51b7f7d | 3,026 | //
// ContentView.swift
// BarChartApp
//
// Created by giordano scalzo on 02/03/2020.
// Copyright © 2020 giordano scalzo. All rights reserved.
//
import SwiftUI
enum Month: String, CaseIterable {
case jan, feb, mar, apr, may, jun,
jul, aug, sep, oct, nov, dec
}
struct MonthDataPoint: Identifiable {
let id = UUID()
let month: Month
let value: Double
var name: String {
month.rawValue.capitalized
}
}
extension Array where Element == Double {
func monthDataPoints() -> [MonthDataPoint] {
zip(Month.allCases, self).map { (month, value) in
MonthDataPoint(month: month, value: value)
}
}
}
// data from: https://www.climatestotravel.com/
struct DataSet {
static let dublin = [
0.65, 0.50, 0.55, 0.55, 0.60, 0.65,
0.55, 0.75, 0.60, 0.80, 0.75, 0.75
].monthDataPoints()
static let milan = [
0.65, 0.65, 0.80, 0.80, 0.95, 0.65,
0.70, 0.95, 0.70, 1.00, 1.00, 0.60
].monthDataPoints()
static let london = [
0.55, 0.40, 0.40, 0.45, 0.50, 0.45,
0.45, 0.50, 0.50, 0.70, 0.60, 0.55,
].monthDataPoints()
}
struct BarView: View {
var dataPoint: MonthDataPoint
var body: some View {
VStack {
ZStack (alignment: .bottom) {
Rectangle()
.fill(Color.blue)
.frame(width: 18,
height: 180)
Rectangle()
.fill(Color.white)
.frame(width: 18,
height: CGFloat(dataPoint.value * 180.0))
}
Text(dataPoint.name)
.font(.system(size: 12))
.rotationEffect(.degrees(-45))
}
}
}
struct BarChartView: View {
var dataPoints: [MonthDataPoint]
var body: some View {
HStack (spacing: 12) {
ForEach(dataPoints) {
BarView(dataPoint: $0)
}
}
}
}
struct ContentView: View {
@State
var dataSet = [
DataSet.dublin, DataSet.milan, DataSet.london
]
@State
var selectedCity = 0
var body: some View {
ZStack {
Color.blue.opacity(0.4)
.edgesIgnoringSafeArea(.all)
VStack (spacing: 24) {
Spacer()
Text("Average Precipitation")
.font(.system(size: 32))
Picker(selection: self.$selectedCity, label: Text("Average Precipitation")) {
Text("Dublin").tag(0)
Text("Milan").tag(1)
Text("London").tag(2)
}
.pickerStyle(SegmentedPickerStyle())
BarChartView(dataPoints: dataSet[selectedCity])
Spacer()
}.padding(.horizontal, 10)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 25.008264 | 93 | 0.503966 |
222f3074613a4d4d7152a9dd750ecaef2e12ab79 | 2,776 | //
// String+Builder.swift
// Sluthware
//
// Created by Pat Sluth on 2018-02-13.
// Copyright © 2018 Pat Sluth. All rights reserved.
//
import Foundation
//extension String
//{
//
//}
//public extension NSAttributedString
//{
// public static func +(lhs: NSAttributedString, rhs: NSAttributedString) -> NSAttributedString
// {
// let attributedString = NSMutableAttributedString()
// attributedString.append(lhs)
// attributedString.append(rhs)
// return attributedString as NSAttributedString
// }
//
// public static func +(lhs: NSAttributedString, rhs: String) -> NSAttributedString
// {
// return lhs + NSAttributedString(string: rhs)
// }
//
// public static func +=(lhs: inout NSAttributedString, rhs: NSAttributedString)
// {
// lhs = lhs + rhs
// }
//
// public static func +=(lhs: inout NSAttributedString, rhs: String)
// {
// lhs = lhs + rhs
// }
//}
public typealias StringBuilder = String.Builder
public extension String
{
struct Builder
{
public typealias RawAttribute = (NSAttributedString.Key, Any)
private typealias Attributes = [NSAttributedString.Key: Any]
fileprivate(set) public var attributed = NSMutableAttributedString()
public var string: String {
return self.attributed.string
}
public init()
{
}
public init(_ string: String, _ rawAttributes: RawAttribute...)
{
self._append(string, self.attributes(for: rawAttributes))
}
@discardableResult
public func append(_ string: String?, _ rawAttributes: RawAttribute...) -> StringBuilder
{
guard let string = string else { return self }
return self._append(string, self.attributes(for: rawAttributes))
}
@discardableResult
public func append(line: String?, _ rawAttributes: RawAttribute...) -> StringBuilder
{
guard let line = line else { return self }
return self._append(line: line, self.attributes(for: rawAttributes))
}
@discardableResult
private func _append(_ string: String, _ attributes: Attributes?) -> StringBuilder
{
self.attributed.append(NSAttributedString(string: string, attributes: attributes))
return self
}
@discardableResult
private func _append(line: String, _ attributes: Attributes?) -> StringBuilder
{
self.attributed.append(NSAttributedString(string: "\n" + line, attributes: attributes))
return self
}
@discardableResult
public mutating func clear() -> StringBuilder
{
self.attributed = NSMutableAttributedString()
return self
}
private func attributes(for rawAttributes: [RawAttribute]) -> Attributes?
{
guard !rawAttributes.isEmpty else { return nil }
return rawAttributes.reduce(into: Attributes()) { result, element in
result[element.0] = element.1
}
}
}
}
| 20.716418 | 95 | 0.692003 |
4bc8b0911e936deec65f788da10dc5f81d54d566 | 994 | //
// Tip_CalculatorTests.swift
// Tip CalculatorTests
//
// Created by user141707 on 8/27/18.
// Copyright © 2018 user141707. All rights reserved.
//
import XCTest
@testable import Tip_Calculator
class Tip_CalculatorTests: 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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.864865 | 111 | 0.641851 |
ef5fd5c18a1b2a727ed3b6aadb4e2cd6ce44119a | 1,436 | //
// DownloadOperation.swift
// CrowdinSDK
//
// Created by Serhii Londar on 3/24/19.
//
import Foundation
class CrowdinStringsDownloadOperation: CrowdinDownloadOperation {
var completion: (([String: String]?, Error?) -> Void)? = nil
var timestamp: TimeInterval?
init(filePath: String, localization: String, timestamp: TimeInterval?, contentDeliveryAPI: CrowdinContentDeliveryAPI, completion: (([AnyHashable: Any]?, Error?) -> Void)?) {
self.timestamp = timestamp
super.init(filePath: CrowdinPathsParser.shared.parse(filePath, localization: localization), contentDeliveryAPI: contentDeliveryAPI)
self.completion = completion
}
required init(filePath: String, localization: String, timestamp: TimeInterval?, contentDeliveryAPI: CrowdinContentDeliveryAPI) {
self.timestamp = timestamp
super.init(filePath: CrowdinPathsParser.shared.parse(filePath, localization: localization), contentDeliveryAPI: contentDeliveryAPI)
}
override func main() {
let etag = ETagStorage.shared.etags[self.filePath]
contentDeliveryAPI.getStrings(filePath: filePath, etag: etag, timestamp: timestamp) { [weak self] (strings, etag, error) in
guard let self = self else { return }
ETagStorage.shared.etags[self.filePath] = etag
self.completion?(strings, error)
self.finish(with: error != nil)
}
}
}
| 41.028571 | 177 | 0.695682 |
5d4f1bbc8795d95a792a293bb6054df19338d430 | 2,011 | //
// IterateTests.swift
// IterateTests
//
// Created by Michael Singleton on 12/20/19.
// Copyright © 2020 Pickaxe LLC. (DBA Iterate). All rights reserved.
//
import XCTest
@testable import IterateSDK
/// Valid Iterate API key (suitable for use in integration tests)
let testCompanyApiKey = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb21wYW55X2lkIjoiNWRmZTM2OGEwOWI2ZWYwMDAxYjNlNjE4IiwiaWF0IjoxNTc2OTQxMTk0fQ.QBWr2goMwOngVhi6wY9sdFAKEvBGmn-JRDKstVMFh6M"
/// Valid Iterate user API key (suitable for use in integration tests)
let testUserApiKey = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb21wYW55X2lkIjoiNWRmZTM2OGEwOWI2ZWYwMDAxYjNlNjE4IiwidXNlcl9pZCI6IjVlMGQwNzFlM2IxMzkwMDAwMTBlMjVhMiIsImlhdCI6MTU3NzkxMjA5NH0.utTdqt32vltkWcTzS82rg3_jORqozhiTvx3RYIS_aVA"
/// Valid survey id for an event-triggered mobile survey (suitable for use in integration tests)
let testIntegrationSurvey = "5edfaeb2c591ad0001ead90d"
/// Valid event name for integration tests
let testEventName = "test-event"
/// Contains tests for the primary Iterate class and shared singleton object
class IterateTests: XCTestCase {
/// Test basic initialization
func testInit() {
XCTAssertNoThrow(Iterate())
}
/// Test that the shared singleton is available
func testSharedInstance() {
XCTAssertNoThrow(Iterate.shared)
}
/// Test that the company API key is correctly used when the user API key isn't present
func testCompanyApiKeyUsed() {
let client = Iterate(storage: MockStorageEngine())
client.companyApiKey = "COMPANY_123"
XCTAssertEqual(client.api?.apiKey, "COMPANY_123")
}
/// Test that the user API key is correctly used when it's set
func testNewUserApiKeyUsed() {
let client = Iterate(storage: MockStorageEngine())
client.companyApiKey = "COMPANY_123"
XCTAssertEqual(client.api?.apiKey, "COMPANY_123")
client.userApiKey = "USER_123"
XCTAssertEqual(client.api?.apiKey, "USER_123")
}
}
| 38.673077 | 231 | 0.751865 |
c179841ba2cf891323d4f14d17020dada71c994e | 398 | public extension Double {
/// Creates a new measurement from the Double with the provided unit.
/// - Parameter unit: The unit to use in the resulting measurement
/// - Returns: A new measurement with a scalar value of the Double and the
/// provided unit of measure
func measured(in unit: Unit) -> Measurement {
return Measurement(value: self, unit: unit)
}
}
| 36.181818 | 78 | 0.673367 |
d98bc34b3feb0d548f2dafce9b41b571ef736eb3 | 1,378 | //
// Model.swift
// SwiftExP
//
// Created by Marius Rackwitz on 15.6.15.
// Copyright © 2015 Marius Rackwitz. All rights reserved.
//
public enum Expression {
case StringAtom(String)
case DecimalAtom(Double)
case IntegerAtom(Int)
case List([Expression])
}
extension Expression : Equatable {
}
public func ==(lhs: Expression, rhs: Expression) -> Bool {
switch (lhs, rhs) {
case (.StringAtom(let l), .StringAtom(let r)):
return l == r
case (.DecimalAtom(let l), .DecimalAtom(let r)):
return l == r
case (.IntegerAtom(let l), .IntegerAtom(let r)):
return l == r
case (.List(let l), .List(let r)):
return l == r
default:
return false // you're comparing apples with oranges
}
}
extension Expression : CustomStringConvertible {
public var description: String {
switch self {
case .StringAtom(let x):
let escaped = "\\\"".join(split(x.characters) { $0 == "\"" }.map { String($0) })
return "\"\(escaped)\""
case .DecimalAtom(let x):
return "\(x)"
case .IntegerAtom(let x):
return "\(x)"
case .List(let xs):
let jointXs = " ".join(xs.map { String($0) })
return "(\(jointXs))"
}
}
}
| 26.5 | 96 | 0.525399 |
6201f28d695038434b75e6ddb912ff71f0d588c5 | 824 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "MinimalBlogPublishTheme",
products: [
.library(
name: "MinimalBlogPublishTheme",
targets: ["MinimalBlogPublishTheme"]),
],
dependencies: [
.package(name: "Publish", url: "https://github.com/johnsundell/publish.git", from: "0.7.0"),
.package(url: "https://github.com/apple/swift-collections", from: "0.0.1"),
],
targets: [
.target(
name: "MinimalBlogPublishTheme",
dependencies: [
"Publish",
.product(name: "Collections", package: "swift-collections"),
]),
.testTarget(
name: "MinimalBlogPublishThemeTests",
dependencies: ["MinimalBlogPublishTheme"]),
]
)
| 29.428571 | 100 | 0.566748 |
2f1476b9757bf5b6b54ecf9f34db6acd616b2b24 | 1,191 | // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import AWSSDKSwiftCore
/// Error enum for Batch
public enum BatchErrorType: AWSErrorType {
case clientException(message: String?)
case serverException(message: String?)
}
extension BatchErrorType {
public init?(errorCode: String, message: String?){
var errorCode = errorCode
if let index = errorCode.firstIndex(of: "#") {
errorCode = String(errorCode[errorCode.index(index, offsetBy: 1)...])
}
switch errorCode {
case "ClientException":
self = .clientException(message: message)
case "ServerException":
self = .serverException(message: message)
default:
return nil
}
}
}
extension BatchErrorType : CustomStringConvertible {
public var description : String {
switch self {
case .clientException(let message):
return "ClientException: \(message ?? "")"
case .serverException(let message):
return "ServerException: \(message ?? "")"
}
}
}
| 31.342105 | 158 | 0.639798 |
6aedc98949ca9e47f57a1409da7b81627481b0a5 | 5,474 | // Copyright SIX DAY LLC. All rights reserved.
import Foundation
import UIKit
import Result
import MBProgressHUD
import SafariServices
enum ConfirmationError: LocalizedError {
case cancel
}
extension UIViewController {
func displaySuccess(title: String? = .none, message: String? = .none) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
alertController.popoverPresentationController?.sourceView = view
alertController.addAction(UIAlertAction(title: R.string.localizable.oK(), style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
func displayError(message: String) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertController.popoverPresentationController?.sourceView = view
alertController.addAction(UIAlertAction(title: R.string.localizable.oK(), style: .default))
present(alertController, animated: true)
}
func displayError(title: String = "", error: Error) {
var title = title
let message: String
if title.isEmpty {
title = error.prettyError
message = ""
} else {
message = error.prettyError
}
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.popoverPresentationController?.sourceView = view
alertController.addAction(UIAlertAction(title: R.string.localizable.oK(), style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
func confirm(
title: String? = .none,
message: String? = .none,
okTitle: String = R.string.localizable.oK(),
okStyle: UIAlertAction.Style = .default,
completion: @escaping (Result<Void, ConfirmationError>) -> Void
) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.popoverPresentationController?.sourceView = view
alertController.addAction(UIAlertAction(title: okTitle, style: okStyle, handler: { _ in
completion(.success(()))
}))
alertController.addAction(UIAlertAction(title: R.string.localizable.cancel(), style: .cancel, handler: { _ in
completion(.failure(ConfirmationError.cancel))
}))
present(alertController, animated: true, completion: nil)
}
func displayLoading(
text: String = R.string.localizable.loadingDots(),
animated: Bool = true
) {
let hud = MBProgressHUD.showAdded(to: view, animated: animated)
hud.label.text = text
}
func hideLoading(animated: Bool = true) {
MBProgressHUD.hide(for: view, animated: animated)
}
public var isVisible: Bool {
if isViewLoaded {
return view.window != nil
}
return false
}
public var isTopViewController: Bool {
if navigationController != nil && navigationController?.tabBarController != nil {
return (tabBarController?.selectedViewController as? UINavigationController)?.visibleViewController == self
} else if navigationController != nil {
return navigationController?.visibleViewController === self
} else if tabBarController != nil {
return tabBarController?.selectedViewController == self && presentedViewController == nil
}
return presentedViewController == nil && isVisible
}
func add(asChildViewController viewController: UIViewController) {
addChild(viewController)
view.addSubview(viewController.view)
viewController.view.frame = view.bounds
viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
viewController.didMove(toParent: self)
}
func remove(asChildViewController viewController: UIViewController) {
viewController.willMove(toParent: nil)
viewController.view.removeFromSuperview()
viewController.removeFromParent()
}
func showShareActivity(fromSource source: PopoverPresentationControllerSource, with items: [Any], completion: (() -> Swift.Void)? = nil) {
let activityViewController = UIActivityViewController.make(items: items)
switch source {
case .barButtonItem(let barButtonItem):
activityViewController.popoverPresentationController?.barButtonItem = barButtonItem
case .view(let view):
activityViewController.popoverPresentationController?.sourceView = view
//Cannot use view.rect because it might be too small (e.g. it's a button)
activityViewController.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: 500, height: 500)
}
present(activityViewController, animated: true, completion: completion)
}
//TODO remove all callers for this function. This is added for a scoped down migration to Xcode 11.x (building for iOS 13), to make sure that all presented screens remain fullscreen. We should decide to either show them by presenting as (A) fullscreen (B) card or (C) push onto a navigation controller
//Shouldn't be called for UIActivityViewController and UIAlertController
func makePresentationFullScreenForiOS13Migration() {
modalPresentationStyle = .fullScreen
}
}
| 43.792 | 305 | 0.691633 |
5038d0359f904fd6a2e9dabe497224c922f72aee | 22,368 | //
// SignUpViewController.swift
// MeetPoint
//
// Created by yusuf_kildan on 16/09/2017.
// Copyright © 2017 yusuf_kildan. All rights reserved.
//
import UIKit
import PureLayout
import SafariServices
import Firebase
import Whisper
import AudioToolbox
class SignUpViewController: BaseScrollViewController {
fileprivate let DefaultInset: CGFloat = 20.0
fileprivate let AvatarDimension: CGFloat = 90.0
fileprivate var avatarImageView: UIImageView!
fileprivate var firstNameTextField: CustomTextField!
fileprivate var lastNameTextField: CustomTextField!
fileprivate var emailTextField: CustomTextField!
fileprivate var usernameTextField: CustomTextField!
fileprivate var passwordTextField: CustomTextField!
fileprivate var passwordConfirmationTextField: CustomTextField!
fileprivate var approveField: InteractiveApprovalField!
fileprivate var signUpButton: OverlayButton!
fileprivate var selectedImage: UIImage?
fileprivate var isUsernameAvailable: Bool?
// MARK: - Constructors
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init() {
super.init()
commonInit()
}
fileprivate func commonInit() {
let customBackButton = UIButton(type: UIButtonType.custom)
customBackButton.setImage(UIImage(named: "iconBackButton"), for: UIControlState())
customBackButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.center
customBackButton.addTarget(self,
action: #selector(backButtonTapped(_:)),
for: UIControlEvents.touchUpInside)
view.addSubview(customBackButton)
customBackButton.autoPinEdge(toSuperviewEdge: ALEdge.left)
customBackButton.autoPinEdge(toSuperviewEdge: ALEdge.top,
withInset: 20.0)
customBackButton.autoSetDimensions(to: CGSize(width: 44.0, height: 44.0))
}
// MARK: - View's Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.primaryBackgroundColor()
avatarImageView = UIImageView.newAutoLayout()
avatarImageView.image = UIImage(named: "iconAddAvatar")
avatarImageView.contentMode = UIViewContentMode.scaleAspectFill
avatarImageView.isUserInteractionEnabled = true
avatarImageView.layer.masksToBounds = true
avatarImageView.layer.cornerRadius = AvatarDimension / 2
avatarImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapAvatarImageView(_:))))
contentView.addSubview(avatarImageView)
avatarImageView.autoSetDimensions(to: CGSize(width: AvatarDimension, height: AvatarDimension))
avatarImageView.autoPinEdge(toSuperviewEdge: ALEdge.top, withInset: DefaultInset)
avatarImageView.autoAlignAxis(toSuperviewAxis: ALAxis.vertical)
firstNameTextField = CustomTextField.newAutoLayout()
firstNameTextField.returnKeyType = UIReturnKeyType.next
firstNameTextField.customTextFieldDelegate = self
firstNameTextField.placeholder = "First Name".requiredSuffix()
contentView.addSubview(firstNameTextField)
firstNameTextField.autoSetDimension(ALDimension.height, toSize: CustomTextFieldDefaultHeight)
firstNameTextField.autoPinEdge(ALEdge.top, to: ALEdge.bottom, of: avatarImageView, withOffset: DefaultInset)
firstNameTextField.autoPinEdge(toSuperviewEdge: ALEdge.left, withInset: DefaultInset)
firstNameTextField.autoPinEdge(toSuperviewEdge: ALEdge.right, withInset: DefaultInset)
lastNameTextField = CustomTextField.newAutoLayout()
lastNameTextField.returnKeyType = UIReturnKeyType.next
lastNameTextField.customTextFieldDelegate = self
lastNameTextField.placeholder = "Last Name".requiredSuffix()
contentView.addSubview(lastNameTextField)
lastNameTextField.autoSetDimension(ALDimension.height, toSize: CustomTextFieldDefaultHeight)
lastNameTextField.autoPinEdge(ALEdge.top, to: ALEdge.bottom, of: firstNameTextField)
lastNameTextField.autoPinEdge(toSuperviewEdge: ALEdge.left, withInset: DefaultInset)
lastNameTextField.autoPinEdge(toSuperviewEdge: ALEdge.right, withInset: DefaultInset)
emailTextField = CustomTextField.newAutoLayout()
emailTextField.returnKeyType = UIReturnKeyType.next
emailTextField.autocapitalizationType = UITextAutocapitalizationType.none
emailTextField.customTextFieldDelegate = self
emailTextField.keyboardType = UIKeyboardType.emailAddress
emailTextField.placeholder = "Email".requiredSuffix()
contentView.addSubview(emailTextField)
emailTextField.autoSetDimension(ALDimension.height, toSize: CustomTextFieldDefaultHeight)
emailTextField.autoPinEdge(ALEdge.top, to: ALEdge.bottom, of: lastNameTextField)
emailTextField.autoPinEdge(toSuperviewEdge: ALEdge.left, withInset: DefaultInset)
emailTextField.autoPinEdge(toSuperviewEdge: ALEdge.right, withInset: DefaultInset)
usernameTextField = CustomTextField.newAutoLayout()
usernameTextField.returnKeyType = UIReturnKeyType.next
usernameTextField.autocapitalizationType = UITextAutocapitalizationType.none
usernameTextField.customTextFieldDelegate = self
usernameTextField.placeholder = "Username".requiredSuffix()
contentView.addSubview(usernameTextField)
usernameTextField.autoSetDimension(ALDimension.height, toSize: CustomTextFieldDefaultHeight)
usernameTextField.autoPinEdge(ALEdge.top, to: ALEdge.bottom, of: emailTextField)
usernameTextField.autoPinEdge(toSuperviewEdge: ALEdge.left, withInset: DefaultInset)
usernameTextField.autoPinEdge(toSuperviewEdge: ALEdge.right, withInset: DefaultInset)
passwordTextField = CustomTextField.newAutoLayout()
passwordTextField.returnKeyType = UIReturnKeyType.next
passwordTextField.autocapitalizationType = UITextAutocapitalizationType.none
passwordTextField.customTextFieldDelegate = self
passwordTextField.isSecureTextEntry = true
passwordTextField.placeholder = "Password".requiredSuffix()
contentView.addSubview(passwordTextField)
passwordTextField.autoSetDimension(ALDimension.height, toSize: CustomTextFieldDefaultHeight)
passwordTextField.autoPinEdge(ALEdge.top, to: ALEdge.bottom, of: usernameTextField)
passwordTextField.autoPinEdge(toSuperviewEdge: ALEdge.left, withInset: DefaultInset)
passwordTextField.autoPinEdge(toSuperviewEdge: ALEdge.right, withInset: DefaultInset)
passwordConfirmationTextField = CustomTextField.newAutoLayout()
passwordConfirmationTextField.returnKeyType = UIReturnKeyType.done
passwordConfirmationTextField.autocapitalizationType = UITextAutocapitalizationType.none
passwordConfirmationTextField.customTextFieldDelegate = self
passwordConfirmationTextField.isSecureTextEntry = true
passwordConfirmationTextField.placeholder = "Password Confirmation".requiredSuffix()
contentView.addSubview(passwordConfirmationTextField)
passwordConfirmationTextField.autoSetDimension(ALDimension.height, toSize: CustomTextFieldDefaultHeight)
passwordConfirmationTextField.autoPinEdge(ALEdge.top, to: ALEdge.bottom, of: passwordTextField)
passwordConfirmationTextField.autoPinEdge(toSuperviewEdge: ALEdge.left, withInset: DefaultInset)
passwordConfirmationTextField.autoPinEdge(toSuperviewEdge: ALEdge.right, withInset: DefaultInset)
approveField = InteractiveApprovalField.newAutoLayout()
approveField.delegate = self
let termsOfUseText = NSMutableAttributedString()
termsOfUseText.append(NSAttributedString(string: "Terms of use",
attributes: [NSFontAttributeName: UIFont.montserratMediumFont(withSize: 15.0),
NSForegroundColorAttributeName: UIColor.white,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]))
approveField.addInteractiveAttributedText(termsOfUseText, forScheme: InteractiveTextScheme.termsOfUse)
let andText = NSMutableAttributedString()
andText.append(NSAttributedString(string: " and ",
attributes: [NSFontAttributeName: UIFont.montserratMediumFont(withSize: 15.0),
NSForegroundColorAttributeName: UIColor.primaryDarkTextColor()]))
approveField.addNonInteractiveAttributedText(andText)
let privacyPolicyText = NSMutableAttributedString()
privacyPolicyText.append(NSAttributedString(string: "Privacy policy",
attributes: [NSFontAttributeName: UIFont.montserratMediumFont(withSize: 15.0),
NSForegroundColorAttributeName: UIColor.white,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]))
approveField.addInteractiveAttributedText(privacyPolicyText, forScheme: InteractiveTextScheme.privacyPolicy)
contentView.addSubview(approveField)
approveField.autoPinEdge(ALEdge.top, to: ALEdge.bottom, of: passwordConfirmationTextField, withOffset: 8.0)
approveField.autoPinEdge(toSuperviewEdge: ALEdge.left)
approveField.autoPinEdge(toSuperviewEdge: ALEdge.right)
approveField.autoSetDimension(ALDimension.height, toSize: 44.0)
signUpButton = OverlayButton(type: UIButtonType.system)
signUpButton.titleLabel?.font = UIFont.montserratSemiboldFont(withSize: 17.0)
signUpButton.setTitle("SIGN UP", for: UIControlState.normal)
signUpButton.addTarget(self, action: #selector(signUpButtonTapped(_:)), for: UIControlEvents.touchUpInside)
contentView.addSubview(signUpButton)
signUpButton.autoSetDimensions(to: OverlayButtonDefaultSize)
signUpButton.autoPinEdge(ALEdge.top, to: ALEdge.bottom, of: approveField, withOffset: 8.0)
signUpButton.autoAlignAxis(toSuperviewAxis: ALAxis.vertical)
signUpButton.autoPinEdge(ALEdge.bottom, to: ALEdge.bottom, of: contentView, withOffset: -DefaultInset)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
Whisper.hide()
}
// MARK: - Interface
override func shouldShowNavigationBar() -> Bool {
return false
}
// MARK: - Actions
func signUpButtonTapped(_ button: OverlayButton) {
signUp()
}
// MARK: - Sign Up
fileprivate func signUp() {
view.endEditing(true)
var shouldSignUp = true
if !validate(Field: firstNameTextField) {
shouldSignUp = false
}
if !validate(Field: lastNameTextField) {
shouldSignUp = false
}
if !validate(Field: emailTextField) {
shouldSignUp = false
}
if !validate(Field: usernameTextField) {
shouldSignUp = false
}
if !validate(Field: passwordTextField) {
shouldSignUp = false
}
if !validate(Field: passwordConfirmationTextField) {
shouldSignUp = false
}
if !shouldSignUp {
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
return
}
if approveField.state == ApprovalState.disapproved {
self.showPopupWith(Title: "Error",
andMessage: "You should approve Terms of Use & Privacy Policy.")
return
}
createUser()
}
// MARK: - Validation
fileprivate func validate(Field field: CustomTextField) -> Bool {
if field == firstNameTextField {
let firstName = field.text
if ((firstName == nil) || (firstName!.count == 0)) {
shakeTheTextField(field)
return false
} else if firstName?.isValidFirstName() == false {
shakeTheTextField(field)
return false
}
} else if field == lastNameTextField {
let lastName = field.text
if ((lastName == nil) || (lastName!.count == 0)) {
shakeTheTextField(field)
return false
} else if lastName?.isValidLastName() == false {
shakeTheTextField(field)
return false
}
} else if field == emailTextField {
let email = field.text
if email == nil || email!.count == 0 {
shakeTheTextField(field)
return false
} else if email?.isValidEmail() == false {
shakeTheTextField(field)
return false
}
} else if field == usernameTextField {
let username = field.text
if ((username == nil) || (username!.count == 0)) {
shakeTheTextField(field)
return false
} else if username?.isValidUsername() == false {
shakeTheTextField(field)
return false
} else if isUsernameAvailable == false {
self.usernameTextField.shake()
self.showNotifyView("This username already taken. Please enter different username!")
return false
}
} else if field == passwordTextField {
let password = field.text
if password?.count == 0 {
shakeTheTextField(field)
return false
} else if password?.isValidPassword() == false {
shakeTheTextField(field)
return false
}
} else if field == passwordConfirmationTextField {
let password = field.text
if password?.count == 0 {
shakeTheTextField(field)
return false
} else if password?.isValidPassword() == false {
shakeTheTextField(field)
return false
}
}
if passwordConfirmationTextField.text != passwordTextField.text {
shakeTheTextField(passwordConfirmationTextField)
return false
}
return true
}
fileprivate func shakeTheTextField(_ textField: CustomTextField) {
textField.shake()
}
fileprivate func checkAvailabilityOf(Username username: String) {
AuthManager.sharedManager.isUsernameAvailable(username) { (isAvailable) in
self.isUsernameAvailable = isAvailable
if isAvailable == false {
self.usernameTextField.shake()
self.showNotifyView("This username already taken. Please enter different username!")
} else {
Whisper.hide()
}
}
}
// MARK: - Create User
fileprivate func createUser() {
let firstName = firstNameTextField.text!
let lastName = lastNameTextField.text!
let email = emailTextField.text!
let username = usernameTextField.text!
let password = passwordTextField.text!
let user = User()
user.username = username
user.fullName = firstName + " " + lastName
user.email = email
user.createdTimestamp = Date().timeIntervalSince1970 as NSNumber
user.activityCount = 0
user.followerCount = 0
user.followingCount = 0
user.profileImage = self.selectedImage
user.fcmToken = Messaging.messaging().fcmToken
LoadingView.startAnimating()
AuthManager.sharedManager.signUp(email, password: password, user: user) { (error) in
if let error = error {
LoadingView.stopAnimating {
self.showPopupWith(Title: "Error", andMessage: error.localizedDescription)
}
return
}
LoadingView.stopAnimating {
DispatchQueue.main.async(execute: { () -> Void in
NotificationCenter.default
.post(name: Notification.Name(rawValue: UserAuthenticationNotification),
object: nil)
})
}
}
}
// MARK: - Gestures
func didTapAvatarImageView(_ recognizer: UITapGestureRecognizer) {
presentPhotoSourceSelection()
}
// MARK: - Photo Source
func presentPhotoSourceSelection() {
let alertController = UIAlertController(title: nil,
message: nil,
preferredStyle: UIAlertControllerStyle.actionSheet)
alertController.addAction(UIAlertAction(title: "Choose From Library",
style: UIAlertActionStyle.default) { (action) in
self.presentImagePicker()
})
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
alertController.addAction(UIAlertAction(title: "Capture Photo",
style: UIAlertActionStyle.default) { (action) in
self.presentCamera()
})
}
alertController.addAction(UIAlertAction(title: "Cancel",
style: UIAlertActionStyle.cancel) { (action) in
})
self.present(alertController, animated: true, completion: nil)
}
func presentImagePicker() {
let controller = UIImagePickerController()
controller.delegate = self
controller.allowsEditing = true
controller.sourceType = UIImagePickerControllerSourceType.photoLibrary
present(controller, animated: true, completion: nil)
}
func presentCamera() {
let controller = UIImagePickerController()
controller.delegate = self
controller.allowsEditing = true
controller.sourceType = UIImagePickerControllerSourceType.camera
present(controller, animated: true, completion: nil)
}
// MARK: - Helpers
func showNotifyView(_ title: String) {
var murmur = Murmur(title: title)
murmur.font = UIFont.montserratLightFont(withSize: 13.0)
murmur.backgroundColor = UIColor.red
murmur.titleColor = UIColor.secondaryLightTextColor()
Whisper.show(whistle: murmur, action: .present)
}
}
// MARK: - CustomTextFieldDelegate
extension SignUpViewController: CustomTextFieldDelegate {
func customTextFieldShouldReturn(_ textField: CustomTextField) -> Bool {
if textField == firstNameTextField {
lastNameTextField.becomeFirstResponder()
} else if textField == lastNameTextField {
emailTextField.becomeFirstResponder()
} else if textField == emailTextField {
usernameTextField.becomeFirstResponder()
} else if textField == usernameTextField {
passwordTextField.becomeFirstResponder()
} else if textField == passwordTextField {
passwordConfirmationTextField.becomeFirstResponder()
} else if textField == passwordConfirmationTextField {
view.endEditing(true)
}
return true
}
func customTextFieldDidEndEditing(_ textField: CustomTextField) {
if textField == usernameTextField && textField.text != "" {
checkAvailabilityOf(Username: textField.text!)
}
}
}
// MARK: - InteractiveApprovalFieldDelegate
extension SignUpViewController: InteractiveApprovalFieldDelegate {
func interactiveApprovalField(_ field: InteractiveApprovalField, didTriggerScheme scheme: InteractiveTextScheme) {
let type: DocumentType
switch scheme {
case .termsOfUse:
type = DocumentType.termsOfUse
case .privacyPolicy:
type = DocumentType.privacyPolicy
}
let viewController = DocumentsWebViewController(withDocumentType: type)
let navigationController = BaseNavigationController(rootViewController: viewController)
self.present(navigationController, animated: true, completion: nil)
}
}
// MARK: - UINavigationControllerDelegate & UIImagePickerControllerDelegate
extension SignUpViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
dismiss(animated: true) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
self.selectedImage = image
self.avatarImageView.image = image
}
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
| 40.375451 | 136 | 0.629739 |
87a15dfd082fa87781aae59e9b4faa36d3b34382 | 3,675 | //
// ShortcutKeyField.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2014-12-16.
//
// ---------------------------------------------------------------------------
//
// © 2004-2007 nakamuxu
// © 2014-2018 1024jp
//
// 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
//
// https://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 Cocoa
final class ShortcutKeyField: NSTextField {
// MARK: Private Properties
private var keyDownMonitor: Any?
// MARK: -
// MARK: Text Field Methods
/// text field turns into edit mode
override func becomeFirstResponder() -> Bool {
guard super.becomeFirstResponder() else { return false }
// hide insertion point
(self.currentEditor() as? NSTextView)?.insertionPointColor = .textBackgroundColor
self.keyDownMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: { [weak self] (event: NSEvent) -> NSEvent? in
guard
let self = self,
var charsIgnoringModifiers = event.charactersIgnoringModifiers,
!charsIgnoringModifiers.isEmpty
else { return event }
var modifierMask = event.modifierFlags
// correct Backspace and Delete keys
// -> "backspace" key: the key above "return"
// "delete (forword)" key: the key with printed "Delete" where next to the ten key pad.
switch Int(charsIgnoringModifiers.utf16.first!) {
case NSDeleteCharacter:
charsIgnoringModifiers = String(UnicodeScalar(NSBackspaceCharacter)!)
case NSDeleteFunctionKey:
charsIgnoringModifiers = String(UnicodeScalar(NSDeleteCharacter)!)
default: break
}
// remove unwanted Shift
let ignoringShiftSet = CharacterSet(charactersIn: "`~!@#$%^&()_{}|\":<>?=/*-+.'")
if ignoringShiftSet.contains(charsIgnoringModifiers.unicodeScalars.first!), modifierMask.contains(.shift) {
modifierMask.remove(.shift)
}
// set input shortcut string to field
let keySpecChars = Shortcut(modifierMask: modifierMask, keyEquivalent: charsIgnoringModifiers).keySpecChars
self.objectValue = {
guard keySpecChars != "\u{8}" else { return nil } // single NSDeleteCharacter works as delete
return keySpecChars
}()
// end editing
self.window?.endEditing(for: nil)
return nil
})
return true
}
/// end editing
override func textDidEndEditing(_ notification: Notification) {
// restore insertion point
(self.currentEditor() as? NSTextView)?.insertionPointColor = .controlTextColor
// end monitoring key down event
if let monitor = self.keyDownMonitor {
NSEvent.removeMonitor(monitor)
self.keyDownMonitor = nil
}
super.textDidEndEditing(notification)
}
}
| 34.345794 | 137 | 0.587755 |
dd90a672bea6404b1184e8642cb9a005003a9226 | 1,498 | //
// LoadPokemonRequest.swift
// SwiftUI_Demo_Second
//
// Created by LFZ on 2020/2/26.
// Copyright © 2020 LFZ. All rights reserved.
//
import Foundation
import Combine
struct LoadPokemonRequest {
let id: Int
func pokemonPublisher(_ id: Int) -> AnyPublisher<Pokemon, Error> {
URLSession.shared
.dataTaskPublisher(
for: URL(string: "https://pokeapi.co/api/v2/pokemon/\(id)")!
)
.map { $0.data }
.decode(type: Pokemon.self, decoder: appDecoder)
.eraseToAnyPublisher()
}
func speciesPublisher(_ pokemon: Pokemon) -> AnyPublisher<(Pokemon, PokemonSpecies), Error> {
URLSession.shared
.dataTaskPublisher(for: pokemon.species.url)
.map { $0.data }
.decode(type: PokemonSpecies.self, decoder: appDecoder)
.map { (pokemon, $0) }
.eraseToAnyPublisher()
}
var publisher: AnyPublisher<PokemonViewModel, AppError> {
pokemonPublisher(id)
.flatMap { self.speciesPublisher($0) }
.map { PokemonViewModel(pokemon: $0, species: $1) }
.mapError { AppError.networkingFailed($0) }
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
static var all: AnyPublisher<[PokemonViewModel], AppError> {
(1...30).map {
LoadPokemonRequest(id: $0).publisher
}.zipAll
}
}
| 27.236364 | 97 | 0.568091 |
9cba74de4a9e46421cfd5b33b3a3e3913ca2f6f5 | 325 | import Foundation
import SwiftSyntax
/// Skip public syntax
struct SkipPublicRule: SourceCollectRule {
func skip(_ node: SyntaxProtocol, location: SourceLocation) -> Bool {
if let modifierSyntax = node as? ModifierSyntax {
return modifierSyntax.isPublic()
}
return false
}
}
| 23.214286 | 73 | 0.667692 |
6afa66ff7b3cb1667217b1fcaf10e48958d958a5 | 1,412 | //
// Tests_iOS.swift
// Tests iOS
//
// Created by Dan Halliday on 28/07/2021.
//
import XCTest
class Tests_iOS: XCTestCase {
override func setUpWithError() throws {
// 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
// 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 tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 32.837209 | 182 | 0.651558 |
182a4cd652f8d83a426d0e1716873bf77583ce09 | 1,176 | import EurofurenceModel
import Foundation
public struct DefaultKnowledgeGroupViewModelFactory: KnowledgeGroupViewModelFactory {
private struct ViewModel: KnowledgeGroupEntriesViewModel {
var title: String
var entries: [KnowledgeEntry]
var numberOfEntries: Int { return entries.count }
func knowledgeEntry(at index: Int) -> KnowledgeListEntryViewModel {
let entry = entries[index]
return KnowledgeListEntryViewModel(title: entry.title)
}
func identifierForKnowledgeEntry(at index: Int) -> KnowledgeEntryIdentifier {
return entries[index].identifier
}
}
private let service: KnowledgeService
public init(service: KnowledgeService) {
self.service = service
}
public func makeViewModelForGroup(
identifier: KnowledgeGroupIdentifier,
completionHandler: @escaping (KnowledgeGroupEntriesViewModel) -> Void
) {
service.fetchKnowledgeGroup(identifier: identifier) { (group) in
let viewModel = ViewModel(title: group.title, entries: group.entries)
completionHandler(viewModel)
}
}
}
| 28.682927 | 85 | 0.683673 |
18a1e06e8260490c0fd0f50a7ee21081d1819f9f | 650 | //
// ViewController.swift
// Parallex Auto Layout Demo
//
// Created by Rune Madsen on 2015-08-30.
// Copyright © 2015 The App Boutique. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.tableHeaderView = HeaderView.init(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 200))
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let headerView = self.tableView.tableHeaderView as! HeaderView
headerView.scrollViewDidScroll(scrollView: scrollView)
}
}
| 26 | 128 | 0.692308 |
1dfec79397e6a344110427cf5a7dbba1b3d7b9a2 | 463 | //
// String+Truncate.swift
// CurriculaTable
//
// Created by Sun Yaozhu on 2016-09-11.
// Copyright © 2016 Sun Yaozhu. All rights reserved.
//
import Foundation
extension String {
func truncated(_ length: Int) -> String {
let end = index(startIndex, offsetBy: length, limitedBy: endIndex) ?? endIndex
return String(self[..<end])
}
mutating func truncate(_ length: Int) {
self = truncated(length)
}
}
| 20.130435 | 86 | 0.62203 |
5d780736f0c96688308d790a799e68abf32142ca | 947 | //
// TableViewController.swift
// CollectionModel_Example
//
// Created by Denis Poifol on 10/03/2020.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
typealias EmptyInitTableViewDataSource = UITableViewDataSource & UITableViewDelegate & EmptyInit & TableViewContent
class TableViewController<DataSource: EmptyInitTableViewDataSource>: UIViewController {
private lazy var tableView = UITableView()
private lazy var dataSource = DataSource()
override func loadView() {
view = tableView
dataSource.register(in: tableView)
tableView.backgroundColor = UIColor.white
tableView.tableFooterView = UIView()
tableView.dataSource = dataSource
tableView.delegate = dataSource
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.smoothlyDeselectItems(in: transitionCoordinator)
}
}
| 28.69697 | 115 | 0.732841 |
11a123ca3dd149c00e517e3d35a43e5289f9464a | 4,837 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A class that contains all the information needed to display the circular progress indicator badge in the Glance.
*/
import WatchKit
/**
The `GlanceBadge` class is responsible for rendering the glance badge text found in the Glance. It's also
responsible for maintaining the image and animation information for the circular indicator displayed in the
Glance. The information is calculated based on the percentage of complete items out of the total number
of items.
*/
class GlanceBadge {
// MARK: Types
struct Constants {
static let maxDuration: NSTimeInterval = 0.75
}
// MARK: Properties
/// The total number of items.
let totalItemCount: Int
/// The number of complete items.
let completeItemCount: Int
/// The number of incomplete items.
let incompleteItemCount: Int
/// The image name of the image to be used for the Glance badge.
let imageName = "glance-"
/// The range of images to display in the Glance badge.
var imageRange: NSRange {
return NSMakeRange(0, rangeLength)
}
/// The length that the Glance badge image will animate.
var animationDuration: NSTimeInterval {
return percentage * Constants.maxDuration
}
/**
The background image to be displayed in the Glance badge. The `groupBackgroundImage` draws the text that
containing the number of remaining items to complete.
*/
var groupBackgroundImage: UIImage {
UIGraphicsBeginImageContextWithOptions(groupBackgroundImageSize, false, 2.0)
drawCompleteItemsCountInCurrentContext()
let frame = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return frame
}
let groupBackgroundImageSize = CGSizeMake(136, 101)
private let percentage: Double
/**
Determines the number of images to animate based on `percentage`. If `percentage` is larger than 1.0,
the `rangeLength` is the total number of available images.
*/
private var rangeLength: Int {
var normalizedPercentage = percentage
if normalizedPercentage > 1.0 {
normalizedPercentage = 1.0
}
else if normalizedPercentage == 0.0 {
return 1
}
return Int(normalizedPercentage * 45)
}
/// The color that is used to draw the number of complete items.
private var completeTextPathColor: UIColor {
return UIColor(hue: 199.0 / 360.0, saturation: 0.64, brightness: 0.98, alpha: 1.0)
}
// MARK: Initializers
/**
Initialize a `GlanceBadge` with the information it needs to render the `groupBackgroundImage` in addition
to the information it needs to animate the circular progress indicator.
*/
init(totalItemCount: Int, completeItemCount: Int) {
self.totalItemCount = totalItemCount
self.completeItemCount = completeItemCount
incompleteItemCount = totalItemCount - completeItemCount
percentage = totalItemCount > 0 ? Double(completeItemCount) / Double(totalItemCount) : 0
}
// MARK: Drawing
/// Draw the text containing the number of complete items.
func drawCompleteItemsCountInCurrentContext() {
let center = CGPoint(x: groupBackgroundImageSize.width / 2.0, y: groupBackgroundImageSize.height / 2.0)
let itemsCompleteText = "\(completeItemCount)"
let completeAttributes = [
NSFontAttributeName: UIFont.systemFontOfSize(36),
NSForegroundColorAttributeName: completeTextPathColor
]
let completeSize = itemsCompleteText.sizeWithAttributes(completeAttributes)
// Build and gather information about the done string.
let doneText = NSLocalizedString("Done", comment: "")
let doneAttributes = [
NSFontAttributeName: UIFont.systemFontOfSize(16),
NSForegroundColorAttributeName: UIColor.darkGrayColor()
]
let doneSize = doneText.sizeWithAttributes(doneAttributes)
let completeRect = CGRect(x: center.x - 0.5 * completeSize.width, y: center.y - 0.5 * completeSize.height - 0.5 * doneSize.height, width: completeSize.width, height: completeSize.height)
let doneRect = CGRect(x: center.x - 0.5 * doneSize.width, y: center.y + 0.125 * doneSize.height, width: doneSize.width, height: doneSize.height)
itemsCompleteText.drawInRect(completeRect.integral, withAttributes: completeAttributes)
doneText.drawInRect(doneRect.integral, withAttributes: doneAttributes)
}
}
| 35.566176 | 194 | 0.671904 |
1ed81fbd7dbb3ffa1711017a582d8d3adec09ff9 | 1,088 | //
// Pierre_Penguin_Escapes_the_AntarcticTests.swift
// Pierre Penguin Escapes the AntarcticTests
//
// Created by Stephen Haney on 7/5/16.
// Copyright © 2016 JoyfulGames.io. All rights reserved.
//
import XCTest
@testable import Pierre_Penguin_Escapes_the_Antarctic
class Pierre_Penguin_Escapes_the_AntarcticTests: 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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 29.405405 | 111 | 0.668199 |
76d5e9f8ba08d203416717c6ce542150821c9c32 | 8,986 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei (hello@ivanvorobei.by)
//
// 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
// MARK: - layout
public extension UIView {
var bootomXPosition: CGFloat {
return self.frame.bottomXPosition
}
var bootomYPosition: CGFloat {
return self.frame.bottomYPosition
}
var minSideSize: CGFloat {
return self.frame.minSideSize
}
var isWidthLessThanHeight: Bool {
return self.frame.isWidthLessThanHeight
}
func rounded() {
self.layer.cornerRadius = self.minSideSize / 2
}
func setHeight(_ height: CGFloat) {
self.frame = CGRect.init(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.width, height: height)
}
func setWidth(_ width: CGFloat) {
self.frame = CGRect.init(x: self.frame.origin.x, y: self.frame.origin.y, width: width, height: self.frame.height)
}
func setEqualsFrameFromBounds(_ view: UIView, withWidthFactor widthFactor: CGFloat = 1, maxWidth: CGFloat? = nil, withHeightFactor heightFactor: CGFloat = 1, maxHeight: CGFloat? = nil, withCentering: Bool = false) {
var width = view.bounds.width * widthFactor
if maxWidth != nil {
width.setIfMore(when: maxWidth!)
}
var height = view.bounds.height * heightFactor
if maxHeight != nil {
height.setIfMore(when: maxHeight!)
}
self.frame = CGRect.init(x: 0, y: 0, width: width, height: height)
if withCentering {
self.center.x = view.frame.width / 2
self.center.y = view.frame.height / 2
}
}
func setEqualsBoundsFromSuperview(customWidth: CGFloat? = nil, customHeight: CGFloat? = nil) {
if self.superview == nil {
return
}
self.frame = CGRect.init(origin: CGPoint.zero, size: self.superview!.frame.size)
if customWidth != nil {
self.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: customWidth!, height: self.frame.height))
}
if customHeight != nil {
self.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: self.frame.width, height: customHeight!))
}
}
func resize(to width: CGFloat) {
let relativeFactor = self.frame.width / self.frame.height
self.frame = CGRect.init(
x: self.frame.origin.x,
y: self.frame.origin.y,
width: width,
height: self.frame.height * relativeFactor
)
}
func setXCenteringFromSuperview() {
self.center.x = (self.superview?.frame.width ?? 0) / 2
}
}
public extension UIView {
func setParalax(amountFactor: CGFloat) {
let amount = self.minSideSize * amountFactor
self.setParalax(amount: amount)
}
func setParalax(amount: CGFloat) {
self.motionEffects.removeAll()
let horizontal = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis)
horizontal.minimumRelativeValue = -amount
horizontal.maximumRelativeValue = amount
let vertical = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis)
vertical.minimumRelativeValue = -amount
vertical.maximumRelativeValue = amount
let group = UIMotionEffectGroup()
group.motionEffects = [horizontal, vertical]
self.addMotionEffect(group)
}
}
// MARK: - convertToImage
public extension UIView {
func convertToImage() -> UIImage {
return UIImage.drawFromView(view: self)
}
}
// MARK: - gradeView
public extension UIView {
func addGrade(alpha: CGFloat, color: UIColor = UIColor.black) -> UIView {
let gradeView = UIView.init()
gradeView.alpha = 0
self.addSubview(gradeView)
SPConstraintsAssistent.setEqualSizeConstraint(gradeView, superVuew: self)
gradeView.alpha = alpha
gradeView.backgroundColor = color
return gradeView
}
}
// MARK: - shadow
extension UIView {
func setShadow(
xTranslationFactor: CGFloat,
yTranslationFactor: CGFloat,
widthRelativeFactor: CGFloat,
heightRelativeFactor: CGFloat,
blurRadiusFactor: CGFloat,
shadowOpacity: CGFloat,
cornerRadiusFactor: CGFloat = 0
) {
let shadowWidth = self.frame.width * widthRelativeFactor
let shadowHeight = self.frame.height * heightRelativeFactor
let xTranslation = (self.frame.width - shadowWidth) / 2 + (self.frame.width * xTranslationFactor)
let yTranslation = (self.frame.height - shadowHeight) / 2 + (self.frame.height * yTranslationFactor)
let cornerRadius = self.minSideSize * cornerRadiusFactor
let shadowPath = UIBezierPath.init(
roundedRect: CGRect.init(x: xTranslation, y: yTranslation, width: shadowWidth, height: shadowHeight),
cornerRadius: cornerRadius
)
let blurRadius = self.minSideSize * blurRadiusFactor
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize.zero
self.layer.shadowOpacity = Float(shadowOpacity)
self.layer.shadowRadius = blurRadius
self.layer.masksToBounds = false
self.layer.shadowPath = shadowPath.cgPath;
}
func setShadow(
xTranslation: CGFloat,
yTranslation: CGFloat,
widthRelativeFactor: CGFloat,
heightRelativeFactor: CGFloat,
blurRadius: CGFloat,
shadowOpacity: CGFloat,
cornerRadius: CGFloat = 0
) {
let shadowWidth = self.frame.width * widthRelativeFactor
let shadowHeight = self.frame.height * heightRelativeFactor
let shadowPath = UIBezierPath.init(
roundedRect: CGRect.init(x: xTranslation, y: yTranslation, width: shadowWidth, height: shadowHeight),
cornerRadius: cornerRadius
)
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize.zero
self.layer.shadowOpacity = Float(shadowOpacity)
self.layer.shadowRadius = blurRadius
self.layer.masksToBounds = false
self.layer.shadowPath = shadowPath.cgPath
}
func removeShadow() {
self.layer.shadowColor = nil
self.layer.shadowOffset = CGSize.zero
self.layer.shadowOpacity = 0
self.layer.shadowPath = nil
}
func addShadowOpacityAnimation(to: CGFloat, duration: CFTimeInterval) {
let animation = CABasicAnimation(keyPath:"shadowOpacity")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animation.fromValue = self.layer.cornerRadius
animation.fromValue = self.layer.shadowOpacity
animation.toValue = to
animation.duration = duration
self.layer.add(animation, forKey: "shadowOpacity")
self.layer.shadowOpacity = Float(to)
}
}
// MARK: - animation
extension UIView {
func addCornerRadiusAnimation(to: CGFloat, duration: CFTimeInterval) {
let animation = CABasicAnimation(keyPath:"cornerRadius")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animation.fromValue = self.layer.cornerRadius
animation.toValue = to
animation.duration = duration
self.layer.add(animation, forKey: "cornerRadius")
self.layer.cornerRadius = to
}
func removeFromSupervVewWithAlphaAnimatable(duration: CGFloat = 0.3) {
SPAnimation.animate(TimeInterval(duration), animations: {
self.alpha = 0
}, withComplection: {
self.removeFromSuperview()
})
}
}
| 35.65873 | 219 | 0.652014 |
229ac723c267d640e12cb76732ae346fcf7a8e0e | 1,777 | //
// PlaceholderTextView.swift
// talkative-iOS
//
// Created by German Lopez on 6/6/16.
// Copyright © 2016 Rootstrap. All rights reserved.
//
import UIKit
class PlaceholderTextView: UITextView {
override var text: String! {
didSet {
// First text set, when placeholder is empty
if text.isEmpty && text != placeholder && !self.isFirstResponder {
text = placeholder
return
}
textColor = text == placeholder ? placeholderColor : fontColor
}
}
@IBInspectable var placeholder: String = "" {
didSet {
if text.isEmpty {
text = placeholder
textColor = placeholderColor
}
}
}
@IBInspectable var placeholderColor: UIColor? = .lightGray
var fontColor: UIColor = .black
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
if let txtC = textColor {
self.fontColor = txtC
}
}
override func awakeFromNib() {
super.awakeFromNib()
textColor = text == placeholder ? placeholderColor : fontColor
}
convenience init(
frame: CGRect, placeholder: String = "", placeholderColor: UIColor = .lightGray
) {
self.init(frame: frame)
self.placeholderColor = placeholderColor
self.placeholder = placeholder
if let txtC = textColor {
self.fontColor = txtC
}
}
override func becomeFirstResponder() -> Bool {
let isFirstResponder = super.becomeFirstResponder()
if text == placeholder && textColor == placeholderColor {
text = ""
}
textColor = fontColor
return isFirstResponder
}
override func resignFirstResponder() -> Bool {
if text.isEmpty {
text = placeholder
textColor = placeholderColor
}
return super.resignFirstResponder()
}
}
| 23.693333 | 83 | 0.643782 |
dbe046c3641a9256403c7699b0c766e4cf514a9c | 685 | // Copyright 2020 Itty Bitty Apps Pty Ltd
import ArgumentParser
import Foundation
public struct LocalizationsCommand: ParsableCommand {
public static var configuration = CommandConfiguration(
commandName: "localization",
abstract: "Beta test information about builds, specific to a locale.",
subcommands: [
CreateBuildLocalizationsCommand.self,
DeleteBuildLocalizationsCommand.self,
ListBuildLocalizationsCommand.self,
ReadBuildLocalizationCommand.self,
UpdateBuildLocalizationsCommand.self,
],
defaultSubcommand: ListBuildLocalizationsCommand.self
)
public init() { }
}
| 32.619048 | 78 | 0.70365 |
769e66f5d0549f65322aa52c8e6fa749e07c7784 | 3,222 | //
// IntentViewController.swift
// tpg offline SiriUI
//
// Created by レミー on 13/07/2018.
// Copyright © 2018 Remy. All rights reserved.
//
import IntentsUI
class IntentViewController: UIViewController, INUIHostedViewControlling {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var titleLabel: UILabel!
var departures: [String] = [] {
didSet {
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
func configureView(for parameters: Set<INParameter>,
of interaction: INInteraction,
interactiveBehavior: INUIInteractiveBehavior,
context: INUIHostedViewContext,
completion: @escaping (Bool, Set<INParameter>, CGSize) -> Void) {
// swiftlint:disable:previous line_length
guard let intent = interaction.intent as? DeparturesIntent,
let intentResponse = interaction.intentResponse as? DeparturesIntentResponse
else { return }
titleLabel.text = intent.stop?.displayString ?? ""
var departuresTemp: [String] = []
for departure in (intentResponse.departures ?? []) {
if let id = departure.identifier {
departuresTemp.append(id)
}
}
departures = departuresTemp
self.tableView.layoutIfNeeded()
completion(true, parameters, self.desiredSize)
}
var desiredSize: CGSize {
return CGSize(width: self.extensionContext!.hostedViewMaximumAllowedSize.width,
height: CGFloat(self.departures.count * 44) + 45 + 16)
}
}
extension IntentViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return departures.count
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "departureCell",
for: indexPath)
as? SiriDepartureCell else {
return UITableViewCell()
}
cell.departureString = self.departures[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView,
heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
}
class SiriDepartureCell: UITableViewCell {
@IBOutlet weak var lineLabel: UILabel!
@IBOutlet weak var destinationLabel: UILabel!
@IBOutlet weak var leftTimeLabel: UILabel!
var departureString = "" {
didSet {
let components = departureString.split(separator: ",")
guard components.count == 3 else { return }
let line = String(components[0])
let destination = String(components[1])
var leftTime = String(components[2])
if leftTime == ">1h" {
leftTime = ">1h"
}
lineLabel.text = line
destinationLabel.text = destination
leftTimeLabel.text = "\(leftTime)'"
lineLabel.textColor = LineColorManager.color(for: line).contrast
lineLabel.backgroundColor = LineColorManager.color(for: line)
lineLabel.layer.cornerRadius = lineLabel.bounds.height / 2
lineLabel.clipsToBounds = true
}
}
}
| 30.980769 | 86 | 0.663563 |
48799ab36f0a463cb02cfb3f39b01ce51686ea84 | 686 | //
// NibTableViewCell.swift
// BFWControls
//
// Created by Tom Brodhurst-Hill on 26/3/17.
// Copyright © 2017 BareFeetWare. Free to use and modify, without warranty.
//
import UIKit
open class NibTableViewCell: UITableViewCell {
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addNib()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
addNib()
}
}
extension NibTableViewCell: NibReplaceable {
public var nibView: NibView {
fatalError("nibView must be implemented in subclass")
}
}
| 21.4375 | 81 | 0.66035 |
1c6cf3e551b689171257b7ce44431f826025e270 | 2,596 | //
// WhoToFollowViewController.swift
// ReactiveCocoaCatalog
//
// Created by Yasuhiro Inami on 2015-09-16.
// Copyright © 2015 Yasuhiro Inami. All rights reserved.
//
import UIKit
import Result
import ReactiveSwift
import APIKit
import Haneke
///
/// Original demo:
///
/// - The introduction to Reactive Programming you've been missing"
/// https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
///
/// - "Who to follow" Demo (JavaScript)
/// http://jsfiddle.net/staltz/8jFJH/48/
///
class WhoToFollowViewController: UIViewController, NibSceneProvider
{
@IBOutlet var user1Button: UIButton?
@IBOutlet var user2Button: UIButton?
@IBOutlet var user3Button: UIButton?
@IBOutlet var refreshButton: UIButton?
override func viewDidLoad()
{
super.viewDidLoad()
self._setupButtons()
}
func _setupButtons()
{
let refreshProducer = SignalProducer(self.refreshButton!.reactive.controlEvents(.touchUpInside))
.map { Optional($0) }
let fetchedUsersProducer = refreshProducer
.prefix(value: nil) // startup refresh
.flatMap(.merge) { _ in
return _randomUsersProducer()
.ignoreCastError(NoError.self)
}
func bindButton(_ button: UIButton)
{
let buttonTapProducer = SignalProducer(button.reactive.controlEvents(.touchUpInside))
.map { Optional($0) }
.prefix(value: nil) // startup userButton tap
SignalProducer.combineLatest(buttonTapProducer, fetchedUsersProducer)
.map { _, users -> GitHubAPI.User? in
return users[random(users.count)]
}
.merge(with: refreshProducer.map { _ in nil })
.prefix(value: nil) // user = nil for emptying labels
.startWithValues { [weak button] user in
// update UI
button?.setTitle(user?.login, for: .normal)
button?.setImage(nil, for: .normal)
if let avatarURL = user?.avatarURL {
button?.hnk_setImageFromURL(avatarURL, state: .normal)
}
}
}
bindButton(self.user1Button!)
bindButton(self.user2Button!)
bindButton(self.user3Button!)
}
}
private func _randomUsersProducer(since: Int = random(500)) -> SignalProducer<[GitHubAPI.User], SessionTaskError>
{
let request = GitHubAPI.UsersRequest(since: since)
return Session.responseProducer(request)
}
| 30.186047 | 113 | 0.610169 |