repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
webim/webim-client-sdk-ios
WebimClientLibrary/Department.swift
1
4482
// // Department.swift // WebimClientLibrary // // Created by Nikita Lazarev-Zubov on 12.12.17. // Copyright © 2017 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** Single department entity. Provides methods to get department information. Department objects can be received through `DepartmentListChangeListener` protocol methods and `getDepartmentList()` method of `MessageStream` protocol. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public protocol Department { /** Department key is used to start chat with some department. - seealso: `startChat(departmentKey:)` method of `MessageStream` protocol. - returns: Department key value that uniquely identifies this department. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getKey() -> String /** - returns: Department public name. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getName() -> String /** - seealso: `DepartmentOnlineStatus`. - returns: Department online status. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getDepartmentOnlineStatus() -> DepartmentOnlineStatus /** - returns: Order number. Higher numbers match higher priority. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getOrder() -> Int /** - returns: Dictionary of department localized names (if exists). Key is custom locale descriptor, value is matching name. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getLocalizedNames() -> [String: String]? /** - returns: Department logo URL (if exists). - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ func getLogoURL() -> URL? } /** Possible department online statuses. - seealso: `getDepartmentOnlineStatus()` of `Department` protocol. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ public enum DepartmentOnlineStatus { /** Offline state with chats' count limit exceeded. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case busyOffline @available(*, unavailable, renamed: "busyOffline") case BUSY_OFFLINE /** Online state with chats' count limit exceeded. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case busyOnline @available(*, unavailable, renamed: "busyOnline") case BUSY_ONLINE /** Visitor is able to send offline messages. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case offline @available(*, unavailable, renamed: "offline") case OFFLINE /** Visitor is able to send both online and offline messages. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case online @available(*, unavailable, renamed: "online") case ONLINE /** Any status that is not supported by this version of the library. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ case unknown @available(*, unavailable, renamed: "unknown") case UNKNOWN }
mit
prolificinteractive/Yoshi
Yoshi/Yoshi/Utility/Color.swift
1
1263
// // Color.swift // Yoshi // // Created by Christopher Jones on 2/9/16. // Copyright © 2016 Prolific Interactive. All rights reserved. // /** A color object */ struct Color { /// The red value. let red: UInt8 /// The green value let green: UInt8 /// The blue value. let blue: UInt8 /// The alpha value. let alpha: Float /** Initializes a new color. - parameter red: The red component. - parameter green: The green component. - parameter blue: The blue component. - parameter alpha: The alpha channel. By default, this is 1.0. */ init(_ red: UInt8, _ green: UInt8, _ blue: UInt8, alpha: Float = 1.0) { self.red = red self.green = green self.blue = blue self.alpha = alpha } /** Generates a UIColor. - returns: The UIColor value. */ func toUIColor() -> UIColor { let rFloat = CGFloat(red) let gFloat = CGFloat(green) let bFloat = CGFloat(blue) let maxValue = CGFloat(UInt8.max) return UIColor(red: (rFloat / maxValue), green: (gFloat / maxValue), blue: (bFloat / maxValue), alpha: CGFloat(alpha)) } }
mit
artsy/eigen
ios/ArtsyTests/ArtsyWidget/ScheduleTests.swift
1
1147
import XCTest class ScheduleTests: XCTestCase { // it returns an array of dates that match our schedule (8am, noon, 4pm, 8pm) func testHoursOfUpdate() throws { let times = Schedule.generate() let hours: [Int] = times.map() { Calendar.current.component(.hour, from: $0) } XCTAssertEqual(hours, [8, 12, 16, 20]) } // it returns a date that is 20 hours from the morning time func testNextUpdateIn20Hours() throws { let formatter = Foundation.ISO8601DateFormatter() let morning = formatter.date(from: "2021-11-16T08:00:00Z")! let updateTimes = [morning] let schedule = Schedule(tomorrow: Schedule.tomorrow, updateTimes: updateTimes) let nextTime = schedule.nextUpdate XCTAssertEqual(formatter.string(from: nextTime), "2021-11-17T04:00:00Z") } // it returns tomorrow when morning is not provided func testNextUpdateFallsBack() throws { let schedule = Schedule(tomorrow: Schedule.tomorrow, updateTimes: []) let nextTime = schedule.nextUpdate XCTAssertEqual(nextTime, Schedule.tomorrow) } }
mit
coderZsq/coderZsq.target.swift
StudyNotes/iOS Collection/Business/Business/Extension/ExtensionViewController.swift
1
2724
// // ExtensionViewController.swift // Business // // Created by 朱双泉 on 2018/12/7. // Copyright © 2018 Castie!. All rights reserved. // import UIKit import MobileCoreServices class ExtensionViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() title = "Extension" let d = UserDefaults(suiteName: "group.business") print(d?.value(forKey: "key") ?? "") } @IBAction func actionButtonClick(_ sender: UIButton) { let image = UIImage(named: "Castiel")! let vc = UIActivityViewController(activityItems: [image, "Castiel"], applicationActivities: nil) weak var weakImageView = self.imageView vc.completionWithItemsHandler = { (activityType, complete, returnedItems, activityError) in if activityError == nil { if complete == true && returnedItems != nil { for item in returnedItems! { if let item = item as? NSExtensionItem { for provider in item.attachments! { if provider.hasItemConformingToTypeIdentifier(kUTTypeImage as String) { provider.loadItem(forTypeIdentifier: kUTTypeImage as String, options: nil, completionHandler: { (img, error) in OperationQueue.main.addOperation { if let strongImageView = weakImageView { if let img = img as? UIImage { strongImageView.image = img } } } }) } else if provider.hasItemConformingToTypeIdentifier(kUTTypeText as String) { provider.loadItem(forTypeIdentifier: kUTTypeText as String, options: nil, completionHandler: { (text, error) in guard error == nil else { print(error!) return } print(text!) }) } } } } } } else { print(activityError!) } } present(vc, animated: true, completion: nil) } }
mit
szehnder/emitter-kit
src/Event.swift
2
1060
public class Event <EventData: Any> : Emitter { public func on (handler: EventData -> Void) -> Listener { return EmitterListener(self, nil, castData(handler), false) } public func on (target: AnyObject, _ handler: EventData -> Void) -> Listener { return EmitterListener(self, target, castData(handler), false) } public func once (handler: EventData -> Void) -> Listener { return EmitterListener(self, nil, castData(handler), true) } public func once (target: AnyObject, _ handler: EventData -> Void) -> Listener { return EmitterListener(self, target, castData(handler), true) } public func emit (data: EventData) { super.emit(nil, data) } public func emit (target: AnyObject, _ data: EventData) { super.emit(target, data) } public func emit (targets: [AnyObject], _ data: EventData) { super.emit(targets, data) } public override init () { super.init() } private func castData (handler: EventData -> Void) -> Any! -> Void { return { handler($0 as! EventData) } } }
mit
inkyfox/SwiftySQL
Sources/SQLAliasGenerator.swift
3
1099
// // SQLAliasGenerator.swift // SwiftySQL // // Created by indy on 2016. 10. 23.. // Copyright © 2016년 Gen X Hippies Company. All rights reserved. // import Foundation class SQLAliasGenerator: SQLElementGenerator<SQLAlias> { override func generate(_ element: SQLAlias, forRead: Bool) -> String { let name = element.sql.sqlStringBoxedIfNeeded(forRead: forRead, by: generator) if forRead { return name + " AS " + element.alias } else { return name } } override func generateFormatted(_ element: SQLAlias, forRead: Bool, withIndent indent: Int) -> String { let name = element.sql.formattedSQLStringBoxedIfNeeded(forRead: forRead, withIndent: indent, by: generator) if forRead { return name + " AS " + element.alias } else { return name } } }
mit
FlameTinary/weiboSwift
weiboSwift/weiboSwift/Classes/Main/BaseTableViewController.swift
1
1582
// // BaseTableViewController.swift // weiboSwift // // Created by 田宇 on 16/4/25. // Copyright © 2016年 Tinary. All rights reserved. // import UIKit class BaseTableViewController: UITableViewController { var visibleView : VisibleView? var login = true override func loadView() { if login { super.loadView() } else { visibleView = VisibleView.visibleView() view = visibleView } //添加导航条按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(BaseTableViewController.registerButtonClick)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(BaseTableViewController.loginButtonClick)) //visible界面按钮的点击 visibleView?.registerButton.addTarget(self, action: #selector(BaseTableViewController.registerButtonClick), forControlEvents: UIControlEvents.TouchUpInside) visibleView?.loginButton.addTarget(self, action: #selector(BaseTableViewController.loginButtonClick), forControlEvents: UIControlEvents.TouchUpInside) } //注册按钮点击方法 @objc private func registerButtonClick(){ print("注册") } @objc private func loginButtonClick(){ print("登录") } override func viewDidLoad() { super.viewDidLoad() } }
mit
grandquista/ReQL-Core
test/ObjC/polyglot/datum/binary.swift
1
190
// Copyright 2015 Adam Grandquist import Cocoa import Quick import Nimble import libReQL class ObjcTestsOfConverstionToAndFromTheRqlBinaryType : QuickSpec { override func spec() { } }
apache-2.0
duliodenis/gallery
Gallery/Gallery/ViewController.swift
1
8083
// // ViewController.swift // Gallery // // Created by Dulio Denis on 4/5/16. // Copyright © 2016 Dulio Denis. All rights reserved. // import UIKit import CoreData import StoreKit class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, SKProductsRequestDelegate, SKPaymentTransactionObserver { @IBOutlet weak var collectionView: UICollectionView! var gallery = [Art]() var products = [SKProduct]() override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self updateGallery() if gallery.count == 0 { createArt("Mona Lisa", imageName: "mona-lisa.jpg", productIdentifier: "", purchased: true) createArt("The Starry Night", imageName: "starry-night.jpg", productIdentifier: "StarryNight", purchased: false) createArt("The Scream", imageName: "the-scream.jpg", productIdentifier: "Scream", purchased: false) createArt("The Persistence of Memory", imageName: "the-persistence-of-memory-1931.jpg", productIdentifier: "PersistenceOfMemory", purchased: false) updateGallery() collectionView.reloadData() } requestProductsForSale() } // MARK: IAP Functions / StoreKit Delegate Methods func requestProductsForSale() { let ids: Set<String> = ["StarryNight", "Scream", "PersistenceOfMemory"] let productsRequest = SKProductsRequest(productIdentifiers: ids) productsRequest.delegate = self productsRequest.start() } func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) { print("Received requested products") print("Products Ready: \(response.products.count)") print("Invalid Products: \(response.invalidProductIdentifiers.count)") for product in response.products { print("Product: \(product.productIdentifier), Price: \(product.price)") } products = response.products collectionView.reloadData() } func unlockProduct(productIdentifier: String) { for art in gallery { if art.productIdentifier == productIdentifier { art.purchased = 1 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let context = appDelegate.managedObjectContext do { try context.save() } catch{} collectionView.reloadData() } } } @IBAction func restorePurchase(sender: AnyObject) { SKPaymentQueue.defaultQueue().restoreCompletedTransactions() } // MARK: Payment Transaction Observer Delegate Method func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { switch transaction.transactionState { case .Purchased: print("Purchased") unlockProduct(transaction.payment.productIdentifier) SKPaymentQueue.defaultQueue().finishTransaction(transaction) case .Failed: print("Failed") SKPaymentQueue.defaultQueue().finishTransaction(transaction) case .Restored: print("Restored") unlockProduct(transaction.payment.productIdentifier) SKPaymentQueue.defaultQueue().finishTransaction(transaction) // Keep in the Queue case .Purchasing: print("Purchasing") case .Deferred: print("Deferred") } } } // MARK: Core Data Function func createArt(title: String, imageName: String, productIdentifier: String, purchased: Bool) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let context = appDelegate.managedObjectContext if let entity = NSEntityDescription.entityForName("Art", inManagedObjectContext: context) { let art = NSManagedObject(entity: entity, insertIntoManagedObjectContext: context) as! Art art.title = title art.imageName = imageName art.productIdentifier = productIdentifier art.purchased = NSNumber(bool: purchased) } do { try context.save() } catch{} } func updateGallery() { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let context = appDelegate.managedObjectContext let fetch = NSFetchRequest(entityName: "Art") do { let artPieces = try context.executeFetchRequest(fetch) self.gallery = artPieces as! [Art] } catch {} } // MARK: Collection View Delegate Methods func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.gallery.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ArtCollectionViewCell", forIndexPath: indexPath) as! ArtCollectionViewCell let art = gallery[indexPath.row] cell.imageView.image = UIImage(named: art.imageName!) cell.titleLabel.text = art.title! for subview in cell.imageView.subviews { subview.removeFromSuperview() } if art.purchased!.boolValue { cell.purchaseLabel.hidden = true } else { cell.purchaseLabel.hidden = false let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) let blurView = UIVisualEffectView(effect: blurEffect) cell.layoutIfNeeded() blurView.frame = cell.imageView.bounds cell.imageView.addSubview(blurView) // Tie Store Product to Gallery Item for product in products { if product.productIdentifier == art.productIdentifier { // Show Local Currency for IAP let formatter = NSNumberFormatter() formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle formatter.locale = product.priceLocale if let price = formatter.stringFromNumber(product.price) { cell.purchaseLabel.text = "Buy for \(price)" } } } } return cell } // When the user taps an item in the collection view that hasn't been purchased - add the product to the payment queue func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let art = gallery[indexPath.row] if !art.purchased!.boolValue { for product in products { if product.productIdentifier == art.productIdentifier { SKPaymentQueue.defaultQueue().addTransactionObserver(self) let payment = SKPayment(product: product) SKPaymentQueue.defaultQueue().addPayment(payment) } } } } // MARK: Collection View Layout Delegate Methods func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: collectionView.bounds.size.width - 80, height: collectionView.bounds.size.height - 40) } }
mit
stuartbreckenridge/UISearchControllerWithSwift
SearchController/ViewController.swift
1
3959
// // ViewController.swift // SearchController // // Created by Stuart Breckenridge on 17/8/14. // Copyright (c) 2014 Stuart Breckenridge. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var countryTable: UITableView! var searchArray = [String]() { didSet { NotificationCenter.default.post(name: NSNotification.Name.init("searchResultsUpdated"), object: searchArray) } } lazy var countrySearchController: UISearchController = ({ // Display search results in a separate view controller let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main) let alternateController = storyBoard.instantiateViewController(withIdentifier: "aTV") as! AlternateTableViewController let controller = UISearchController(searchResultsController: alternateController) //let controller = UISearchController(searchResultsController: nil) controller.hidesNavigationBarDuringPresentation = false controller.dimsBackgroundDuringPresentation = false controller.searchBar.searchBarStyle = .minimal controller.searchResultsUpdater = self controller.searchBar.sizeToFit() return controller })() override func viewDidLoad() { super.viewDidLoad() definesPresentationContext = true // Configure navigation item to display search controller. navigationItem.searchController = countrySearchController navigationItem.hidesSearchBarWhenScrolling = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch countrySearchController.isActive { case true: return searchArray.count case false: return countries.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = countryTable.dequeueReusableCell(withIdentifier: "Cell") as! SearchTableViewCell cell.textLabel?.text = "" cell.textLabel?.attributedText = NSAttributedString(string: "") switch countrySearchController.isActive { case true: cell.configureCell(with: countrySearchController.searchBar.text!, cellText: searchArray[indexPath.row]) return cell case false: cell.textLabel?.text! = countries[indexPath.row] return cell } } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } } extension ViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { if searchController.searchBar.text?.utf8.count == 0 { searchArray = countries countryTable.reloadData() } else { searchArray.removeAll(keepingCapacity: false) let range = searchController.searchBar.text!.startIndex ..< searchController.searchBar.text!.endIndex var searchString = String() searchController.searchBar.text?.enumerateSubstrings(in: range, options: .byComposedCharacterSequences, { (substring, substringRange, enclosingRange, success) in searchString.append(substring!) searchString.append("*") }) let searchPredicate = NSPredicate(format: "SELF LIKE[cd] %@", searchString) searchArray = countries.filter({ searchPredicate.evaluate(with: $0) }) countryTable.reloadData() } } }
mit
radex/swift-compiler-crashes
crashes-duplicates/08065-resolvetypedecl.swift
11
236
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension A protocol A { { } struct Q< > : S } enum S<T where I :b
mit
radex/swift-compiler-crashes
crashes-fuzzing/21939-swift-protocoltype-canonicalizeprotocols.swift
11
234
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { { { { { } } { } func f { { enum A { class case c, case
mit
XWJACK/PageKit
Sources/CycleContainer.swift
1
2233
// // CycleContainer.swift // // Copyright (c) 2017 Jack // // 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 open class CycleContainer: ReuseContainer { open override var contentSize: CGSize { return CGSize(width: scrollView.frame.width * CGFloat(numberOfPages) * 2, height: scrollView.frame.height) } private var realIndex: Int = 0 open override func reloadData() { super.reloadData() } open override func scrollViewDidScroll(_ scrollView: UIScrollView) { super.scrollViewDidScroll(scrollView) // scrollView.setContentOffset(<#T##contentOffset: CGPoint##CGPoint#>, animated: false) switching(toIndex: 1, animated: false) } // open override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { // let index = super.index(withOffset: scrollView.contentOffset.x) // if index == 0 { // if realIndex == 0 { realIndex = numberOfPages - 1 } // else { realIndex -= 1 } // } else if index == 2 { realIndex = (realIndex + 1) % numberOfPages } // switching(toIndex: 1, animated: false) // } }
mit
natemann/PlaidClient
PlaidClient/PlaidTransaction.swift
1
2701
// // PlaidStructs.swift // Budget // // Created by Nathan Mann on 11/5/14. // Copyright (c) 2014 Nate. All rights reserved. // import Foundation public struct PlaidTransaction { public let account: String public let id: String public let pendingID: String? public let amount: NSDecimalNumber public let date: Date public let pending: Bool public let type: [String : String] public let categoryID: String? public let category: [String]? public let name: String public let address: String? public let city: String? public let state: String? public let zip: String? public let latitude: String? public let longitude: String? public init(transaction: [String : Any]) { let meta = transaction["meta"] as! [String : Any] let location = meta["location"] as? [String : Any] let coordinates = location?["coordinates"] as? [String : Any] let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" account = transaction["_account"]! as! String id = transaction["_id"]! as! String pendingID = transaction["_pendingTransaction"] as? String amount = NSDecimalNumber(value: transaction["amount"] as! Double).roundTo(2).multiplying(by: NSDecimalNumber(value: -1.0)) //Plaid stores withdraws as positves and deposits as negatives date = formatter.date(from: transaction["date"] as! String)! pending = transaction["pending"]! as! Bool type = transaction["type"]! as! [String : String] categoryID = transaction["category_id"] as? String category = transaction["category"] as? [String] name = transaction["name"]! as! String address = location?["address"] as? String city = location?["city"] as? String state = location?["state"] as? String zip = location?["zip"] as? String latitude = coordinates?["lat"] as? String longitude = coordinates?["lng"] as? String } } extension PlaidTransaction: Equatable {} public func ==(lhs: PlaidTransaction, rhs: PlaidTransaction) -> Bool { return lhs.id == lhs.id } protocol Roundable { func roundTo(_ places: Int16) -> NSDecimalNumber } extension NSDecimalNumber: Roundable { func roundTo(_ places: Int16) -> NSDecimalNumber { return self.rounding(accordingToBehavior: NSDecimalNumberHandler(roundingMode: .plain, scale: places, raiseOnExactness: true, raiseOnOverflow: true, raiseOnUnderflow: true,raiseOnDivideByZero: true)) } }
mit
wenghengcong/Coderpursue
BeeFun/BeeFun/Model/Repos/ObjRepos.swift
1
16888
// // ObjRepos.swift // BeeFun // // Created by wenghengcong on 16/1/23. // Copyright © 2016年 JungleSong. All rights reserved. // import Foundation import ObjectMapper /* { "id": 3739481, "name": "ZXingObjC", "full_name": "TheLevelUp/ZXingObjC", "owner": { "login": "TheLevelUp", "id": 1521628, "avatar_url": "https://avatars3.githubusercontent.com/u/1521628?v=4", "gravatar_id": "", "url": "https://api.github.com/users/TheLevelUp", "html_url": "https://github.com/TheLevelUp", "followers_url": "https://api.github.com/users/TheLevelUp/followers", "following_url": "https://api.github.com/users/TheLevelUp/following{/other_user}", "gists_url": "https://api.github.com/users/TheLevelUp/gists{/gist_id}", "starred_url": "https://api.github.com/users/TheLevelUp/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/TheLevelUp/subscriptions", "organizations_url": "https://api.github.com/users/TheLevelUp/orgs", "repos_url": "https://api.github.com/users/TheLevelUp/repos", "events_url": "https://api.github.com/users/TheLevelUp/events{/privacy}", "received_events_url": "https://api.github.com/users/TheLevelUp/received_events", "type": "Organization", "site_admin": false }, "private": false, "html_url": "https://github.com/TheLevelUp/ZXingObjC", "description": "An Objective-C Port of ZXing", "fork": false, "url": "https://api.github.com/repos/TheLevelUp/ZXingObjC", "forks_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/forks", "keys_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/teams", "hooks_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/hooks", "issue_events_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/issues/events{/number}", "events_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/events", "assignees_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/assignees{/user}", "branches_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/branches{/branch}", "tags_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/tags", "blobs_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/git/refs{/sha}", "trees_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/statuses/{sha}", "languages_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/languages", "stargazers_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/stargazers", "contributors_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/contributors", "subscribers_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/subscribers", "subscription_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/subscription", "commits_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/commits{/sha}", "git_commits_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/git/commits{/sha}", "comments_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/comments{/number}", "issue_comment_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/issues/comments{/number}", "contents_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/contents/{+path}", "compare_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/merges", "archive_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/downloads", "issues_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/issues{/number}", "pulls_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/pulls{/number}", "milestones_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/milestones{/number}", "notifications_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/labels{/name}", "releases_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/releases{/id}", "deployments_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/deployments", "created_at": "2012-03-16T14:09:18Z", "updated_at": "2018-05-02T02:14:07Z", "pushed_at": "2018-04-18T07:42:30Z", "git_url": "git://github.com/TheLevelUp/ZXingObjC.git", "ssh_url": "git@github.com:TheLevelUp/ZXingObjC.git", "clone_url": "https://github.com/TheLevelUp/ZXingObjC.git", "svn_url": "https://github.com/TheLevelUp/ZXingObjC", "homepage": "", "size": 187508, "stargazers_count": 2644, "watchers_count": 2644, "language": "Objective-C", "has_issues": true, "has_projects": false, "has_downloads": true, "has_wiki": true, "has_pages": false, "forks_count": 666, "mirror_url": null, "archived": false, "open_issues_count": 21, "license": { "key": "apache-2.0", "name": "Apache License 2.0", "spdx_id": "Apache-2.0", "url": "https://api.github.com/licenses/apache-2.0" }, "forks": 666, "open_issues": 21, "watchers": 2644, "default_branch": "master", "permissions": { "admin": false, "push": false, "pull": true } } */ public class ObjRepos: NSObject, Mappable { //1 var archive_url: String? var assignees_url: String? var blobs_url: String? var branches_url: String? var clone_url: String? var collaborators_url: String? var comments_url: String? var commits_url: String? var compare_url: String? var contents_url: String? //11 var contributors_url: String? var created_at: String? var default_branch: String? var deployments_url: String? var cdescription: String? //description同关键字冲突,加c前缀 var downloads_url: String? var events_url: String? var fork: Bool? var forks: Int? var forks_count: Int? //21 var forks_url: String? var full_name: String? var git_commits_url: String? var git_refs_url: String? var git_tags_url: String? var git_url: String? var has_downloads: Bool? var has_projects: Bool? var has_issues: Bool? var has_pages: Bool? var has_wiki: Bool? //31 var homepage: String? var hooks_url: String? var html_url: String? var id: Int? var issue_comment_url: String? var issue_events_url: String? var issues_url: String? var keys_url: String? var labels_url: String? var language: String? //41 var languages_url: String? var merges_url: String? var milestones_url: String? var mirror_url: String? var name: String? var notifications_url: String? var open_issues: Int? var open_issues_count: Int? var owner: ObjUser? var star_owner: String? var permissions: ObjPermissions? //51 var cprivate: Bool? //private同关键字冲突,加c前缀 var pulls_url: String? var pushed_at: String? var releases_url: String? var size: Int? var ssh_url: String? var stargazers_count: Int? var stargazers_url: String? var statuses_url: String? var subscribers_url: String? //61 var subscription_url: String? var svn_url: String? var tags_url: String? var teams_url: String? var trees_url: String? var updated_at: String? var url: String? var watchers: Int? var watchers_count: Int? var subscribers_count: Int? //以下字段为单独增加 var star_tags: [String]? var star_lists: [String]? /// 是否订阅该项目 var watched: Bool? = false /// 是否关注该项目 var starred: Bool? = false /// 关注该repo的时间,从网络请求中截取 var starred_at: String? /// Trending中 var trending_star_text: String? /// star var trending_fork_text: String? /// star var trending_star_interval_text: String? /// 200 stars this week var trending_showcase_update_text: String? ///Updated Jul 5, 2017 var score: Double? //搜索得分 struct ReposKey { static let archiveUrlKey = "archive_url" static let assigneesUrlKey = "assignees_url" static let blobsUrlKey = "blobs_url" static let branchesUrlKey = "branches_url" static let cloneUrlKey = "clone_url" static let collaboratorsUrlKey = "collaborators_url" static let commentsUrlKey = "comments_url" static let commitsUrlKey = "commits_url" static let compareUrlKey = "compare_url" static let contentsUrlKey = "contents_url" static let contributorsUrlKey = "contributors_url" static let createdAtKey = "created_at" static let defaultBranchKey = "default_branch" static let deploymentsUrlKey = "deployments_url" static let descriptionKey = "description" static let downloadsUrlKey = "downloads_url" static let eventsUrlKey = "events_url" static let forkKey = "fork" static let forksKey = "forks" static let forksCountKey = "forks_count" static let forksUrlKey = "forks_url" static let fullNameKey = "full_name" static let gitCommitsUrlKey = "git_commits_url" static let gitRefsUrlKey = "git_refs_url" static let gitTagsUrlKey = "git_tags_url" static let gitUrlKey = "git_url" static let hasDownloadsKey = "has_downloads" static let hasProjects = "has_projects" static let hasIssuesKey = "has_issues" static let hasPagesKey = "has_pages" static let hasWikiKey = "has_wiki" static let homepageKey = "homepage" static let hooksUrlKey = "hooks_url" static let htmlUrlKey = "html_url" static let idKey = "id" static let issueCommentUrlKey = "issue_comment_url:" static let issueEventsUrlKey = "issue_events_url" static let issuesUrlKey = "issues_url" static let keysUrlKey = "keys_url" static let labelsUrlKey = "labels_url" static let languageKey = "language" static let languagesUrlKey = "languages_url" static let mergesUrlKey = "merges_url" static let milestonesUrlKey = "milestones_url" static let mirrorUrlKey = "mirror_url" static let nameKey = "name" static let notificationsUrlKey = "notifications_url" static let openIssuesKey = "open_issues" static let openIssuesCountKey = "open_issues_count" static let ownerKey = "owner" static let starOwnerKey = "star_owner" static let permissionsKey = "permissions" static let privateKey = "private" static let pullsUrlKey = "pulls_url" static let pushedAtKey = "pushed_at" static let releasesUrlKey = "releases_url" static let sizeKey = "size" static let sshUrley = "ssh_url" static let stargazersCountKey = "stargazers_count" static let stargazersUrlKey = "stargazers_url" static let statusesUrlKey = "statuses_url" static let subscribersUrlKey = "subscribers_url" static let subscriptionUrlKey = "subscription_url" static let svnUrlKey = "svn_url" static let tagsUrlKey = "tags_url" static let teamsUrlKey = "teams_url" static let treesUrlKey = "trees_url:" static let updatedAtKey = "updated_at" static let urlKey = "url" static let watchersKey = "watchers" static let watchersCountKey = "watchers_count" static let subscribersCountKey = "subscribers_count" static let starTagsKey = "star_tags" static let starListKey = "star_lists" static let watchedKey = "watched" static let scoreKey = "score" static let starred_atKey = "starred_at" static let trending_star_textKey = "trending_star_text" static let trending_fork_textKey = "trending_fork_text" static let trending_star_interval_textKey = "trending_star_interval_text" static let trending_showcase_update_textKey = "trending_showcase_update_text" } // MARK: init and mapping required public init?(map: Map) { } override init() { super.init() } public func mapping(map: Map) { // super.mapping(map) archive_url <- map[ReposKey.archiveUrlKey] assignees_url <- map[ReposKey.assigneesUrlKey] blobs_url <- map[ReposKey.blobsUrlKey] branches_url <- map[ReposKey.branchesUrlKey] clone_url <- map[ReposKey.cloneUrlKey] collaborators_url <- map[ReposKey.collaboratorsUrlKey] comments_url <- map[ReposKey.commentsUrlKey] commits_url <- map[ReposKey.commitsUrlKey] compare_url <- map[ReposKey.compareUrlKey] contents_url <- map[ReposKey.contentsUrlKey] contributors_url <- map[ReposKey.contributorsUrlKey] created_at <- map[ReposKey.createdAtKey] default_branch <- map[ReposKey.defaultBranchKey] deployments_url <- map[ReposKey.deploymentsUrlKey] cdescription <- map[ReposKey.descriptionKey] downloads_url <- map[ReposKey.downloadsUrlKey] events_url <- map[ReposKey.eventsUrlKey] fork <- map[ReposKey.forkKey] forks <- map[ReposKey.forksKey] forks_count <- map[ReposKey.forksCountKey] forks_url <- map[ReposKey.forksUrlKey] full_name <- map[ReposKey.fullNameKey] git_commits_url <- map[ReposKey.gitCommitsUrlKey] git_refs_url <- map[ReposKey.gitRefsUrlKey] git_tags_url <- map[ReposKey.gitTagsUrlKey] git_url <- map[ReposKey.gitUrlKey] has_downloads <- map[ReposKey.hasDownloadsKey] has_projects <- map[ReposKey.hasProjects] has_issues <- map[ReposKey.hasIssuesKey] has_pages <- map[ReposKey.hasPagesKey] has_wiki <- map[ReposKey.hasWikiKey] homepage <- map[ReposKey.homepageKey] hooks_url <- map[ReposKey.hooksUrlKey] html_url <- map[ReposKey.htmlUrlKey] id <- map[ReposKey.idKey] issue_comment_url <- map[ReposKey.issueCommentUrlKey] issue_events_url <- map[ReposKey.issueEventsUrlKey] issues_url <- map[ReposKey.issuesUrlKey] keys_url <- map[ReposKey.keysUrlKey] labels_url <- map[ReposKey.labelsUrlKey] language <- map[ReposKey.languageKey] languages_url <- map[ReposKey.languagesUrlKey] merges_url <- map[ReposKey.mergesUrlKey] milestones_url <- map[ReposKey.milestonesUrlKey] mirror_url <- map[ReposKey.mirrorUrlKey] name <- map[ReposKey.nameKey] notifications_url <- map[ReposKey.notificationsUrlKey] open_issues <- map[ReposKey.openIssuesKey] open_issues_count <- map[ReposKey.openIssuesCountKey] owner <- map[ReposKey.ownerKey] star_owner <- map[ReposKey.starOwnerKey] permissions <- map[ReposKey.permissionsKey] cprivate <- map[ReposKey.privateKey] pulls_url <- map[ReposKey.pullsUrlKey] pushed_at <- map[ReposKey.pushedAtKey] releases_url <- map[ReposKey.releasesUrlKey] size <- map[ReposKey.sizeKey] ssh_url <- map[ReposKey.sshUrley] stargazers_count <- map[ReposKey.stargazersCountKey] stargazers_url <- map[ReposKey.stargazersUrlKey] statuses_url <- map[ReposKey.statusesUrlKey] subscribers_url <- map[ReposKey.subscribersUrlKey] subscription_url <- map[ReposKey.subscriptionUrlKey] svn_url <- map[ReposKey.svnUrlKey] tags_url <- map[ReposKey.gitTagsUrlKey] teams_url <- map[ReposKey.teamsUrlKey] trees_url <- map[ReposKey.treesUrlKey] updated_at <- map[ReposKey.updatedAtKey] url <- map[ReposKey.urlKey] watchers <- map[ReposKey.watchersKey] watchers_count <- map[ReposKey.watchersCountKey] subscribers_count <- map[ReposKey.subscribersCountKey] score <- map[ReposKey.scoreKey] starred_at <- map[ReposKey.starred_atKey] star_tags <- map[ReposKey.starTagsKey] star_lists <- map[ReposKey.starListKey] trending_fork_text <- map[ReposKey.trending_fork_textKey] trending_star_text <- map[ReposKey.trending_star_textKey] trending_star_interval_text <- map[ReposKey.trending_star_interval_textKey] trending_showcase_update_text <- map[ReposKey.trending_showcase_update_textKey] } }
mit
x331275955/-
xiong-练习微博(视频)/xiong-练习微博(视频)/Models/UserAccount.swift
1
4079
// // UserAccount.swift // xiong-练习微博(视频) // // Created by 王晨阳 on 15/9/14. // Copyright © 2015年 IOS. All rights reserved. // import UIKit class UserAccount: NSObject, NSCoding { // MARK: - 成员属性: // 用于调用access_token,接口获取授权后的access token。 var access_token : String? // 授权过期时间 var expiresDate : NSDate? // 当前授权用户的UID。 var uid : String? // 友好显示名称 var name : String? // 用户的头像(大图180*180) var avatar_large : String? // access_token的生命周期,单位是秒数。 var expires_in : NSTimeInterval = 0 // 用户是否登录 class var userLogon: Bool { return UserAccount.loadAccount() != nil } // MARK:- KVC字典转模型 init(dict:[String:AnyObject]){ // 调用父类的init方法 super.init() setValuesForKeysWithDictionary(dict) expiresDate = NSDate(timeIntervalSinceNow: expires_in) UserAccount.userAccount = self } override func setValue(value: AnyObject?, forUndefinedKey key: String) {} // MARK:- 获取:对象描述信息. override var description: String { let properties = ["access_token","expires_in","uid","expiresDate", "name", "avatar_large"] return "\(dictionaryWithValuesForKeys(properties))" } // 保存用户账号 private func saveAccount(){ NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath) } //MARK:- 加载用户信息 func loadUserInfo(finished:(error: NSError?) -> ()){ NetworkTools.sharedTools.loadUserInfo(uid!) { (result, error) -> () in if let dict = result{ // 设置用户信息 self.name = dict["name"] as? String self.avatar_large = dict["avatar_large"] as? String // TODO: 保存用户信息 print("5.(UserAccount)保存用户信息",self.name,self.avatar_large) // 保存用户信息 self.saveAccount() } finished(error: nil) } } // MARK:- 载入用户信息, 先判断账户是否为空,是否过期 // 静态的用户账户属性 private static var userAccount: UserAccount? class func loadAccount() -> UserAccount? { // 如果账户为空从本地加载 if userAccount == nil{ userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount } // 判断是否过期 if let date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending{ // 如果过期,设置为空 userAccount = nil } return userAccount } // MARK:- 归档和解档的方法 /// 保存归档文件的路径 static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true).last!.stringByAppendingString("/account.Plist") // 归档 func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(access_token, forKey: "access_token") aCoder.encodeDouble(expires_in, forKey: "expires_in") aCoder.encodeObject(expiresDate, forKey: "expiresDate") aCoder.encodeObject(uid, forKey: "uid") aCoder.encodeObject(name, forKey: "name") aCoder.encodeObject(avatar_large, forKey: "avatar_large") } // 解档 required init?(coder aDecoder: NSCoder) { access_token = aDecoder.decodeObjectForKey("access_token") as? String expires_in = aDecoder.decodeDoubleForKey("expires_in") expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate uid = aDecoder.decodeObjectForKey("uid") as? String name = aDecoder.decodeObjectForKey("name") as? String avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String } }
mit
EZ-NET/CodePiece
ESTwitter/Data/Entity/MediaEntity.swift
1
1149
// // Media.swift // CodePiece // // Created by Tomohiro Kumagai on H27/11/15. // Copyright © 平成27年 EasyStyle G.K. All rights reserved. // public struct MediaEntity : HasIndices { public struct Size { public var width: Int public var height: Int public var resize: String } public var idStr: String public var mediaUrlHttps: TwitterUrl public var expandedUrl: TwitterUrl public var id: UInt64 public var sizes: [String : Size] public var displayUrl: String public var type: String public var indices: Indices public var mediaUrl: TwitterUrl public var url: TwitterUrl } extension MediaEntity : EntityUnit { var displayText: String { displayUrl } } extension MediaEntity : Decodable { enum CodingKeys : String, CodingKey { case idStr = "id_str" case mediaUrlHttps = "media_url_https" case expandedUrl = "expanded_url" case id case sizes case displayUrl = "display_url" case type case indices case mediaUrl = "media_url" case url } } extension MediaEntity.Size : Decodable { enum CodingKeys : String, CodingKey { case width = "w" case height = "h" case resize } }
gpl-3.0
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/CheckoutCompleteFreePayload.swift
1
5694
// // CheckoutCompleteFreePayload.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// Return type for `checkoutCompleteFree` mutation. open class CheckoutCompleteFreePayloadQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = CheckoutCompleteFreePayload /// The updated checkout object. @discardableResult open func checkout(alias: String? = nil, _ subfields: (CheckoutQuery) -> Void) -> CheckoutCompleteFreePayloadQuery { let subquery = CheckoutQuery() subfields(subquery) addField(field: "checkout", aliasSuffix: alias, subfields: subquery) return self } /// The list of errors that occurred from executing the mutation. @discardableResult open func checkoutUserErrors(alias: String? = nil, _ subfields: (CheckoutUserErrorQuery) -> Void) -> CheckoutCompleteFreePayloadQuery { let subquery = CheckoutUserErrorQuery() subfields(subquery) addField(field: "checkoutUserErrors", aliasSuffix: alias, subfields: subquery) return self } /// The list of errors that occurred from executing the mutation. @available(*, deprecated, message:"Use `checkoutUserErrors` instead.") @discardableResult open func userErrors(alias: String? = nil, _ subfields: (UserErrorQuery) -> Void) -> CheckoutCompleteFreePayloadQuery { let subquery = UserErrorQuery() subfields(subquery) addField(field: "userErrors", aliasSuffix: alias, subfields: subquery) return self } } /// Return type for `checkoutCompleteFree` mutation. open class CheckoutCompleteFreePayload: GraphQL.AbstractResponse, GraphQLObject { public typealias Query = CheckoutCompleteFreePayloadQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "checkout": if value is NSNull { return nil } guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CheckoutCompleteFreePayload.self, field: fieldName, value: fieldValue) } return try Checkout(fields: value) case "checkoutUserErrors": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: CheckoutCompleteFreePayload.self, field: fieldName, value: fieldValue) } return try value.map { return try CheckoutUserError(fields: $0) } case "userErrors": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: CheckoutCompleteFreePayload.self, field: fieldName, value: fieldValue) } return try value.map { return try UserError(fields: $0) } default: throw SchemaViolationError(type: CheckoutCompleteFreePayload.self, field: fieldName, value: fieldValue) } } /// The updated checkout object. open var checkout: Storefront.Checkout? { return internalGetCheckout() } func internalGetCheckout(alias: String? = nil) -> Storefront.Checkout? { return field(field: "checkout", aliasSuffix: alias) as! Storefront.Checkout? } /// The list of errors that occurred from executing the mutation. open var checkoutUserErrors: [Storefront.CheckoutUserError] { return internalGetCheckoutUserErrors() } func internalGetCheckoutUserErrors(alias: String? = nil) -> [Storefront.CheckoutUserError] { return field(field: "checkoutUserErrors", aliasSuffix: alias) as! [Storefront.CheckoutUserError] } /// The list of errors that occurred from executing the mutation. @available(*, deprecated, message:"Use `checkoutUserErrors` instead.") open var userErrors: [Storefront.UserError] { return internalGetUserErrors() } func internalGetUserErrors(alias: String? = nil) -> [Storefront.UserError] { return field(field: "userErrors", aliasSuffix: alias) as! [Storefront.UserError] } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { var response: [GraphQL.AbstractResponse] = [] objectMap.keys.forEach { switch($0) { case "checkout": if let value = internalGetCheckout() { response.append(value) response.append(contentsOf: value.childResponseObjectMap()) } case "checkoutUserErrors": internalGetCheckoutUserErrors().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } case "userErrors": internalGetUserErrors().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } default: break } } return response } } }
mit
matthew-compton/Photorama
Photorama/Photo.swift
1
825
// // Photo.swift // Photorama // // Created by Matthew Compton on 10/22/15. // Copyright © 2015 Big Nerd Ranch. All rights reserved. // import UIKit import CoreData class Photo: NSManagedObject { // Insert code here to add functionality to your managed object subclass var image: UIImage? override func awakeFromInsert() { super.awakeFromInsert() title = "" photoID = "" remoteURL = NSURL() photoKey = NSUUID().UUIDString dateTaken = NSDate() } func addTagObject(tag: NSManagedObject) { let currentTags = mutableSetValueForKey("tags") currentTags.addObject(tag) } func removeTagObject(tag: NSManagedObject) { let currentTags = mutableSetValueForKey("tags") currentTags.removeObject(tag) } }
apache-2.0
DoubleSha/BitcoinSwift
BitcoinSwift/Models/BlockHeader.swift
1
4719
// // BlockHeader.swift // BitcoinSwift // // Created by Kevin Greene on 9/28/14. // Copyright (c) 2014 DoubleSha. All rights reserved. // import Foundation public func ==(left: BlockHeader, right: BlockHeader) -> Bool { return left.version == right.version && left.previousBlockHash == right.previousBlockHash && left.merkleRoot == right.merkleRoot && left.timestamp == right.timestamp && left.compactDifficulty == right.compactDifficulty && left.nonce == right.nonce } public protocol BlockHeaderParameters { var blockVersion: UInt32 { get } } public struct BlockHeader: Equatable { public let version: UInt32 public let previousBlockHash: SHA256Hash public let merkleRoot: SHA256Hash public let timestamp: NSDate public let compactDifficulty: UInt32 public let nonce: UInt32 static private let largestDifficulty = BigInteger(1) << 256 private var cachedHash: SHA256Hash? public init(params: BlockHeaderParameters, previousBlockHash: SHA256Hash, merkleRoot: SHA256Hash, timestamp: NSDate, compactDifficulty: UInt32, nonce: UInt32) { self.init(version: params.blockVersion, previousBlockHash: previousBlockHash, merkleRoot: merkleRoot, timestamp: timestamp, compactDifficulty: compactDifficulty, nonce: nonce) } public init(version: UInt32, previousBlockHash: SHA256Hash, merkleRoot: SHA256Hash, timestamp: NSDate, compactDifficulty: UInt32, nonce: UInt32) { self.version = version self.previousBlockHash = previousBlockHash self.merkleRoot = merkleRoot self.timestamp = timestamp self.compactDifficulty = compactDifficulty self.nonce = nonce } /// Calculated from the information in the block header. It does not include the transactions. /// https://en.bitcoin.it/wiki/Block_hashing_algorithm public var hash: SHA256Hash { // TODO: Don't recalculate this every time. return SHA256Hash(data: bitcoinData.SHA256Hash().SHA256Hash().reversedData) } /// The difficulty used to create this block. This is the uncompressed form of the /// compactDifficulty property. public var difficulty: BigInteger { let compactDifficultyData = NSMutableData() compactDifficultyData.appendUInt32(compactDifficulty, endianness: .BigEndian) return BigInteger(compactData: compactDifficultyData) } /// The work represented by this block. /// Work is defined as the number of tries needed to solve a block in the average case. /// Consider a difficulty target that covers 5% of all possible hash values. Then the work of the /// block will be 20. As the difficulty gets lower, the amount of work goes up. public var work: BigInteger { return BlockHeader.largestDifficulty / (difficulty + BigInteger(1)) } } extension BlockHeader: BitcoinSerializable { public var bitcoinData: NSData { let data = NSMutableData() data.appendUInt32(version) data.appendData(previousBlockHash.bitcoinData) data.appendData(merkleRoot.bitcoinData) data.appendDateAs32BitUnixTimestamp(timestamp) data.appendUInt32(compactDifficulty) data.appendUInt32(nonce) return data } public static func fromBitcoinStream(stream: NSInputStream) -> BlockHeader? { let version = stream.readUInt32() if version == nil { Logger.warn("Failed to parse version from BlockHeader") return nil } let previousBlockHash = SHA256Hash.fromBitcoinStream(stream) if previousBlockHash == nil { Logger.warn("Failed to parse previousBlockHash from BlockHeader") return nil } let merkleRoot = SHA256Hash.fromBitcoinStream(stream) if merkleRoot == nil { Logger.warn("Failed to parse merkleRoot from BlockHeader") return nil } let timestamp = stream.readDateFrom32BitUnixTimestamp() if timestamp == nil { Logger.warn("Failed to parse timestamp from BlockHeader") return nil } let compactDifficulty = stream.readUInt32() if compactDifficulty == nil { Logger.warn("Failed to parse compactDifficulty from BlockHeader") return nil } let nonce = stream.readUInt32() if nonce == nil { Logger.warn("Failed to parse nonce from BlockHeader") return nil } return BlockHeader(version: version!, previousBlockHash: previousBlockHash!, merkleRoot: merkleRoot!, timestamp: timestamp!, compactDifficulty: compactDifficulty!, nonce: nonce!) } }
apache-2.0
lemberg/connfa-ios
Pods/SwiftDate/Sources/SwiftDate/Formatters/RelativeFormatter/languages/lang_cy.swift
1
7311
// // lang_cy.swift // SwiftDate // // Created by Daniele Margutti on 13/06/2018. // Copyright © 2018 SwiftDate. All rights reserved. // import Foundation // swiftlint:disable type_name public class lang_cy: RelativeFormatterLang { /// Locales.welsh public static let identifier: String = "cy" public required init() {} public func quantifyKey(forValue value: Double) -> RelativeFormatter.PluralForm? { switch value { case 0: return .zero case 1: return .one case 2: return .two case 3: return .few case 6: return .many default: return .other } } public var flavours: [String: Any] { return [ RelativeFormatter.Flavour.long.rawValue: self._long, RelativeFormatter.Flavour.narrow.rawValue: self._narrow, RelativeFormatter.Flavour.short.rawValue: self._short ] } private var _short: [String: Any] { return [ "year": [ "previous": "llynedd", "current": "eleni", "next": "blwyddyn nesaf", "past": [ "one": "blwyddyn yn ôl", "two": "{0} flynedd yn ôl", "few": "{0} blynedd yn ôl", "many": "{0} blynedd yn ôl", "other": "{0} o flynyddoedd yn ôl" ], "future": [ "one": "ymhen blwyddyn", "two": "ymhen {0} flynedd", "few": "ymhen {0} blynedd", "many": "ymhen {0} blynedd", "other": "ymhen {0} mlynedd" ] ], "quarter": [ "previous": "chwarter olaf", "current": "chwarter hwn", "next": "chwarter nesaf", "past": [ "one": "{0} chwarter yn ôl", "two": "{0} chwarter yn ôl", "few": "{0} chwarter yn ôl", "many": "{0} chwarter yn ôl", "other": "{0} o chwarteri yn ôl" ], "future": "ymhen {0} chwarter" ], "month": [ "previous": "mis diwethaf", "current": "y mis hwn", "next": "mis nesaf", "past": [ "two": "deufis yn ôl", "other": "{0} mis yn ôl" ], "future": [ "one": "ymhen mis", "two": "ymhen deufis", "other": "ymhen {0} mis" ] ], "week": [ "previous": "wythnos ddiwethaf", "current": "yr wythnos hon", "next": "wythnos nesaf", "past": [ "two": "pythefnos yn ôl", "other": "{0} wythnos yn ôl" ], "future": [ "one": "ymhen wythnos", "two": "ymhen pythefnos", "other": "ymhen {0} wythnos" ] ], "day": [ "previous": "ddoe", "current": "heddiw", "next": "yfory", "past": [ "two": "{0} ddiwrnod yn ôl", "other": "{0} diwrnod yn ôl" ], "future": [ "one": "ymhen diwrnod", "two": "ymhen deuddydd", "other": "ymhen {0} diwrnod" ] ], "hour": [ "current": "yr awr hon", "past": [ "one": "awr yn ôl", "other": "{0} awr yn ôl" ], "future": [ "one": "ymhen awr", "other": "ymhen {0} awr" ] ], "minute": [ "current": "y funud hon", "past": [ "two": "{0} fun. yn ôl", "other": "{0} munud yn ôl" ], "future": [ "one": "ymhen {0} mun.", "two": "ymhen {0} fun.", "other": "ymhen {0} munud" ] ], "second": [ "current": "nawr", "past": "{0} eiliad yn ôl", "future": "ymhen {0} eiliad" ], "now": "nawr" ] } private var _narrow: [String: Any] { return [ "year": [ "previous": "llynedd", "current": "eleni", "next": "blwyddyn nesaf", "past": [ "one": "blwyddyn yn ôl", "two": "{0} flynedd yn ôl", "few": "{0} blynedd yn ôl", "many": "{0} blynedd yn ôl", "other": "{0} o flynyddoedd yn ôl" ], "future": [ "one": "ymhen blwyddyn", "two": "ymhen {0} flynedd", "few": "ymhen {0} blynedd", "many": "ymhen {0} blynedd", "other": "ymhen {0} mlynedd" ] ], "quarter": [ "previous": "chwarter olaf", "current": "chwarter hwn", "next": "chwarter nesaf", "past": [ "one": "{0} chwarter yn ôl", "two": "{0} chwarter yn ôl", "few": "{0} chwarter yn ôl", "many": "{0} chwarter yn ôl", "other": "{0} o chwarteri yn ôl" ], "future": "ymhen {0} chwarter" ], "month": [ "previous": "mis diwethaf", "current": "y mis hwn", "next": "mis nesaf", "past": [ "two": "{0} fis yn ôl", "other": "{0} mis yn ôl" ], "future": [ "one": "ymhen mis", "two": "ymhen deufis", "other": "ymhen {0} mis" ] ], "week": [ "previous": "wythnos ddiwethaf", "current": "yr wythnos hon", "next": "wythnos nesaf", "past": [ "two": "pythefnos yn ôl", "other": "{0} wythnos yn ôl" ], "future": "ymhen {0} wythnos" ], "day": [ "previous": "ddoe", "current": "heddiw", "next": "yfory", "past": [ "two": "{0} ddiwrnod yn ôl", "other": "{0} diwrnod yn ôl" ], "future": "ymhen {0} diwrnod" ], "hour": [ "current": "yr awr hon", "past": "{0} awr yn ôl", "future": "ymhen {0} awr" ], "minute": [ "current": "y funud hon", "past": "{0} mun. yn ôl", "future": "ymhen {0} mun." ], "second": [ "current": "nawr", "past": "{0} eiliad yn ôl", "future": "ymhen {0} eiliad" ], "now": "nawr" ] } private var _long: [String: Any] { return [ "year": [ "previous": "llynedd", "current": "eleni", "next": "blwyddyn nesaf", "past": [ "one": "blwyddyn yn ôl", "two": "{0} flynedd yn ôl", "few": "{0} blynedd yn ôl", "many": "{0} blynedd yn ôl", "other": "{0} o flynyddoedd yn ôl" ], "future": [ "one": "ymhen blwyddyn", "two": "ymhen {0} flynedd", "few": "ymhen {0} blynedd", "many": "ymhen {0} blynedd", "other": "ymhen {0} mlynedd" ] ], "quarter": [ "previous": "chwarter olaf", "current": "chwarter hwn", "next": "chwarter nesaf", "past": [ "one": "{0} chwarter yn ôl", "two": "{0} chwarter yn ôl", "few": "{0} chwarter yn ôl", "many": "{0} chwarter yn ôl", "other": "{0} o chwarteri yn ôl" ], "future": "ymhen {0} chwarter" ], "month": [ "previous": "mis diwethaf", "current": "y mis hwn", "next": "mis nesaf", "past": [ "two": "{0} fis yn ôl", "other": "{0} mis yn ôl" ], "future": [ "one": "ymhen mis", "two": "ymhen deufis", "other": "ymhen {0} mis" ] ], "week": [ "previous": "wythnos ddiwethaf", "current": "yr wythnos hon", "next": "wythnos nesaf", "past": "{0} wythnos yn ôl", "future": [ "one": "ymhen wythnos", "two": "ymhen pythefnos", "other": "ymhen {0} wythnos" ] ], "day": [ "previous": "ddoe", "current": "heddiw", "next": "yfory", "past": [ "two": "{0} ddiwrnod yn ôl", "other": "{0} diwrnod yn ôl" ], "future": [ "one": "ymhen diwrnod", "two": "ymhen deuddydd", "other": "ymhen {0} diwrnod" ] ], "hour": [ "current": "yr awr hon", "past": "{0} awr yn ôl", "future": [ "one": "ymhen awr", "other": "ymhen {0} awr" ] ], "minute": [ "current": "y funud hon", "past": "{0} munud yn ôl", "future": "ymhen {0} munud" ], "second": [ "current": "nawr", "past": "{0} eiliad yn ôl", "future": "ymhen {0} eiliad" ], "now": "nawr" ] } }
apache-2.0
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Views/ViewExtensions.swift
2
919
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation extension UITabBarItem { convenience init(title: String, img: String, selImage: String) { let unselectedIcon = ActorSDK.sharedActor().style.tabUnselectedIconColor let unselectedText = ActorSDK.sharedActor().style.tabUnselectedTextColor let selectedIcon = ActorSDK.sharedActor().style.tabSelectedIconColor let selectedText = ActorSDK.sharedActor().style.tabSelectedTextColor self.init(title: AALocalized(title), image: UIImage.tinted(img, color: unselectedIcon), selectedImage: UIImage.tinted(selImage, color: selectedIcon)) setTitleTextAttributes([NSForegroundColorAttributeName: unselectedText], forState: UIControlState.Normal) setTitleTextAttributes([NSForegroundColorAttributeName: selectedText], forState: UIControlState.Selected) } }
agpl-3.0
iException/CSStickyHeaderFlowLayout
Project/SwiftDemo/SwiftDemo/CollectionParallaxHeader.swift
2
977
// // CollectionParallaxHeader.swift // SwiftDemo // // Created by James Tang on 16/7/15. // Copyright © 2015 James Tang. All rights reserved. // import UIKit class CollectionParallaxHeader: UICollectionReusableView { private var imageView : UIImageView? override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.lightGrayColor() self.clipsToBounds = true let bounds = CGRectMake(0, 0, CGRectGetMaxX(frame), CGRectGetMaxY(frame)) let imageView = UIImageView(frame: bounds) imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.image = UIImage(named: "success-baby") self.imageView = imageView self.addSubview(imageView) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() self.imageView?.frame = self.bounds } }
mit
milseman/swift
validation-test/compiler_crashers_fixed/01089-llvm-foldingset-swift-tupletype-nodeequals.swift
65
556
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func f<o>() -> (o, o -> o) -> o { m o m.i = { } { o) { p } } protocol f { class func i() } class m: f{ class func i {} protocol p { } class o: p { class ni
apache-2.0
ApplePride/PIDOR
Examples/Swift/PIDOR/Decorator.swift
1
2018
// // Decorator.swift // PIDOR // // Created by Alexander on 3/1/17. // Copyright © 2017 ApplePride. All rights reserved. // import UIKit class Decorator: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var firstOption: UIButton! @IBOutlet weak var secondOption: UIButton! @IBOutlet weak var resultLabelCenter: NSLayoutConstraint! weak var handler: GayventHandler? override func viewDidLoad() { super.viewDidLoad() resultLabelCenter.constant = -self.view.frame.width handler?.viewDidLoad() } @IBAction func topButtonTapped(_ sender: Any) { handler?.topButtonPressed() } @IBAction func bottomButtonPressed(_ sender: Any) { handler?.bottomButtonPressed() } } extension Decorator: Decoratable { func setImages(_ names:[String]) { UIView.animate(withDuration: 0.25, animations: { self.firstOption.alpha = 0 self.secondOption.alpha = 0 }) { (finished) in self.firstOption.setImage(UIImage(named: names[0]), for: .normal) self.secondOption.setImage(UIImage(named: names[1]), for: .normal) UIView.animate(withDuration: 0.25, animations: { self.firstOption.alpha = 1 self.secondOption.alpha = 1 }) } } func showResults(is pidor: Bool) { UIView.animate(withDuration: 0.5, animations: { self.firstOption.alpha = 0 self.secondOption.alpha = 0 }) { (completed) in if !pidor { self.resultLabel.text = "LOH, NE PIDOR" } else { self.resultLabel.text = "WAY 2 GO BRUH" } UIView.animate(withDuration: 4) { self.resultLabelCenter.constant = self.view.frame.width self.view.layoutIfNeeded() } } } }
mit
PopcornTimeTV/PopcornTimeTV
PopcornTime/UI/iOS/Extensions/MoviesViewController+iOS.swift
1
4867
import Foundation import PopcornKit extension MoviesViewController:UISearchBarDelegate,PCTPlayerViewControllerDelegate,UIViewControllerTransitioningDelegate{ func playerViewControllerPresentCastPlayer(_ playerViewController: PCTPlayerViewController) { func playerViewControllerPresentCastPlayer(_ playerViewController: PCTPlayerViewController) { dismiss(animated: true) // Close player view controller first. let castPlayerViewController = storyboard?.instantiateViewController(withIdentifier: "CastPlayerViewController") as! CastPlayerViewController castPlayerViewController.media = playerViewController.media castPlayerViewController.localPathToMedia = playerViewController.localPathToMedia castPlayerViewController.directory = playerViewController.directory castPlayerViewController.url = playerViewController.url castPlayerViewController.startPosition = TimeInterval(playerViewController.progressBar.progress) present(castPlayerViewController, animated: true) } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { if searchBar.text?.isEmpty == true { self.showExternalTorrentWindow(self) return } var magnetLink = searchBar.text! // get magnet link that is inserted as a link tag from the website magnetLink = magnetLink.removingPercentEncoding! let userTorrent = Torrent.init(health: .excellent, url: magnetLink, quality: "1080p", seeds: 100, peers: 100, size: nil) var title = magnetLink if let startIndex = title.range(of: "dn="){ title = String(title[startIndex.upperBound...]) title = String(title[title.startIndex ... title.range(of: "&tr")!.lowerBound]) } let magnetTorrentMedia = Movie.init(title: title, id: "34", tmdbId: nil, slug: "magnet-link", summary: "", torrents: [userTorrent], subtitles: [:], largeBackgroundImage: nil, largeCoverImage: nil) let storyboard = UIStoryboard.main let loadingViewController = storyboard.instantiateViewController(withIdentifier: "PreloadTorrentViewController") as! PreloadTorrentViewController loadingViewController.transitioningDelegate = self loadingViewController.loadView() loadingViewController.titleLabel.text = title self.present(loadingViewController, animated: true) //Movie completion Blocks let error: (String) -> Void = { (errorMessage) in if self.presentedViewController != nil { self.dismiss(animated: false) } let vc = UIAlertController(title: "Error".localized, message: errorMessage, preferredStyle: .alert) vc.addAction(UIAlertAction(title: "OK".localized, style: .cancel, handler: nil)) vc.show(animated: true) } let finishedLoading: (PreloadTorrentViewController, UIViewController) -> Void = { (loadingVc, playerVc) in let flag = UIDevice.current.userInterfaceIdiom != .tv self.dismiss(animated: flag) self.present(playerVc, animated: flag) } let selectTorrent: (Array<String>) -> Int32 = { (torrents) in var selected = -1 let torrentSelection = UIAlertController(title: "Select file to play", message: nil, preferredStyle: .actionSheet) for torrent in torrents{ torrentSelection.addAction(UIAlertAction(title: torrent, style: .default, handler: { _ in selected = torrents.distance(from: torrents.startIndex, to: torrents.firstIndex(of: torrent)!) })) } DispatchQueue.main.sync { torrentSelection.show(animated: true) } while selected == -1{ print("hold")} return Int32(selected) } //Movie player view controller calls let playViewController = storyboard.instantiateViewController(withIdentifier: "PCTPlayerViewController") as! PCTPlayerViewController playViewController.delegate = self magnetTorrentMedia.play(fromFileOrMagnetLink: magnetLink, nextEpisodeInSeries: nil, loadingViewController: loadingViewController, playViewController: playViewController, progress: 0, errorBlock: error, finishedLoadingBlock: finishedLoading, selectingTorrentBlock: selectTorrent) } override func viewDidLoad() { self.magnetLinkTextField.delegate = self super.viewDidLoad() } }
gpl-3.0
alreadyRight/Swift-algorithm
自定义cell编辑状态/自定义cell编辑状态/PrefixHeader.swift
1
299
// // PrefixHeader.swift // 自定义cell编辑状态 // // Created by 周冰烽 on 2017/12/12. // Copyright © 2017年 周冰烽. All rights reserved. // import UIKit import SnapKit let kScreenWidth = UIScreen.main.bounds.size.width let kScreenHeight = UIScreen.main.bounds.size.height
mit
yuhaifei123/EmoticonKey
EmoticonKey/EmoticonKey/SnapKit/mode/EmoticonPackage.swift
1
6800
// // EmoticonPackage.swift // EmoticonKey // // Created by 虞海飞 on 2017/2/1. // Copyright © 2017年 虞海飞. All rights reserved. // import UIKit /* 结构: 1. 加载emoticons.plist拿到每组表情的路径 emoticons.plist(字典) 存储了所有组表情的数据 |----packages(字典数组) |-------id(存储了对应组表情对应的文件夹) 2. 根据拿到的路径加载对应组表情的info.plist info.plist(字典) |----id(当前组表情文件夹的名称) |----group_name_cn(组的名称) |----emoticons(字典数组, 里面存储了所有表情) |----chs(表情对应的文字) |----png(表情对应的图片) |----code(emoji表情对应的十六进制字符串) */ class EmoticonPackage: NSObject { //变成单例,这样可以降低性能 static let staticLoadPackages : [EmoticonPackage] = loadPackages(); /// 当前组表情文件夹的名称 var id: String? /// 组的名称 var group_name_cn : String? /// 当前组所有的表情对象 var emoticons: [Emoticon]? /// 获取所有组的表情数组 // 浪小花 -> 一组 -> 所有的表情模型(emoticons) // 默认 -> 一组 -> 所有的表情模型(emoticons) // emoji -> 一组 -> 所有的表情模型(emoticons) private class func loadPackages() -> [EmoticonPackage] { //创建数据 var packages = [EmoticonPackage](); //添加最近组 let pk = EmoticonPackage(id: ""); pk.group_name_cn = "最近"; pk.emoticons = [Emoticon](); pk.appendEmtyEmoticons(); packages.append(pk); let path = Bundle.main.path(forResource: "emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle") // 1.加载emoticons.plist let dict = NSDictionary(contentsOfFile: path!)! // 2.或emoticons中获取packages let dictArray = dict["packages"] as! [[String:AnyObject]] // 3.遍历packages数组 for d in dictArray{ // 4.取出ID, 创建对应的组 let package = EmoticonPackage(id: d["id"]! as! String) packages.append(package) package.loadEmoticons(); package.appendEmtyEmoticons(); } return packages } /// 加载每一组中所有的表情 func loadEmoticons() { let emoticonDict = NSDictionary(contentsOfFile: infoPath(fileName: "info.plist"))! group_name_cn = emoticonDict["group_name_cn"] as? String let dictArray = emoticonDict["emoticons"] as! [[String: String]] emoticons = [Emoticon](); //每个21就加删除按钮 var nub = 0; for dict in dictArray{ if nub == 20{ emoticons!.append(Emoticon.init(removButton: true)); nub = 0; } emoticons!.append(Emoticon(dict: dict, id: id!)) nub = nub+1; } } /// 添加删除按钮 func appendEmtyEmoticons(){ if let num = emoticons{ let count = num.count % 21; for _ in count ..< 20 { //添加空,不是删除按钮 emoticons!.append(Emoticon.init(removButton: false)); } //最后加上删除按钮 emoticons!.append(Emoticon.init(removButton: true)); } } /// 添加个人喜欢 func appendEmoticon(emotion : Emoticon){ //判断是不是删除按钮 if emotion.removButton { return; } let contains = emoticons?.contains(emotion); //判断里面是不是包含这个图形 if contains == false { //删除『删除按钮』 最后一个 emoticons?.removeLast(); //添加一个图标 emoticons?.append(emotion); } var result = emoticons!.sorted { (e1, e2) -> Bool in return e1.times > e2.times; } //判断里面是不是包含这个图形,包含的,把多余的图形删除,添加删除按钮 if contains == false { //删除最后一个数据 result.removeLast(); //添加删除按钮 result.append(Emoticon.init(removButton: true)); } emoticons = result; } /** 获取指定文件的全路径 :param: fileName 文件的名称 :returns: 全路径 */ func infoPath(fileName: String) -> String { return (EmoticonPackage.emoticonPath().appendingPathComponent(id!) as NSString).appendingPathComponent(fileName) } /// 获取微博表情的主路径 class func emoticonPath() -> NSString{ return (Bundle.main.bundlePath as NSString).appendingPathComponent("Emoticons.bundle") as NSString } init(id: String) { self.id = id } } class Emoticon: NSObject { /// 表情对应的文字 var chs: String? /// 表情对应的图片 var png: String?; /// emoji表情对应的十六进制字符串 var code: String?; //emoji 表情 var emojiStr: String?; /// 当前表情对应的文件夹 var id: String? /// 删除按钮 var removButton : Bool = false; /// 点击次数 var times : Int = 0; /// 表情图片的全路径 var imagePath: String? init(removButton : Bool) { super.init(); self.removButton = removButton; } init(dict: [String: String], id: String){ super.init(); self.id = id self.chs = dict["chs"]; self.png = dict["png"]; self.code = dict["code"]; self.emojiStr = dict["emojiStr"]; //setValuesForKeys(dict); if self.png != nil { self.imagePath = (EmoticonPackage.emoticonPath().appendingPathComponent(id) as NSString).appendingPathComponent(png!) } //十六进制转化 if dict["code"] != nil { // 1.从字符串中取出十六进制的数 // 创建一个扫描器, 扫描器可以从字符串中提取我们想要的数据 let scanner = Scanner(string: dict["code"]!) // 2.将十六进制转换为字符串 var result:UInt32 = 0 scanner.scanHexInt32(&result) // 3.将十六进制转换为emoji字符串 emojiStr = "\(Character(UnicodeScalar(result)!))" } } override func setValuesForKeys(_ keyedValues: [String : Any]) { } }
apache-2.0
Stitch7/mclient
mclient/PrivateMessages/_MessageInputBar/Protocols/InputPlugin.swift
1
1616
/* MIT License Copyright (c) 2017-2018 MessageKit 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 /// `InputPlugin` is a protocol that makes integrating plugins to the `MessageInputBar` easy. public protocol InputPlugin: AnyObject { /// Should reload the state if the `InputPlugin` func reloadData() /// Should remove any content that the `InputPlugin` is managing func invalidate() /// Should handle the input of data types that an `InputPlugin` manages /// /// - Parameter object: The object to input func handleInput(of object: AnyObject) -> Bool }
mit
apple/swift-async-algorithms
Sources/AsyncAlgorithms/Zip/ZipStateMachine.swift
1
20055
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Async Algorithms open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// /// State machine for zip struct ZipStateMachine< Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence >: Sendable where Base1: Sendable, Base2: Sendable, Base3: Sendable, Base1.Element: Sendable, Base2.Element: Sendable, Base3.Element: Sendable { typealias DownstreamContinuation = UnsafeContinuation<Result<( Base1.Element, Base2.Element, Base3.Element? )?, Error>, Never> private enum State: Sendable { /// Small wrapper for the state of an upstream sequence. struct Upstream<Element: Sendable>: Sendable { /// The upstream continuation. var continuation: UnsafeContinuation<Void, Error>? /// The produced upstream element. var element: Element? } /// The initial state before a call to `next` happened. case initial(base1: Base1, base2: Base2, base3: Base3?) /// The state while we are waiting for downstream demand. case waitingForDemand( task: Task<Void, Never>, upstreams: (Upstream<Base1.Element>, Upstream<Base2.Element>, Upstream<Base3.Element>) ) /// The state while we are consuming the upstream and waiting until we get a result from all upstreams. case zipping( task: Task<Void, Never>, upstreams: (Upstream<Base1.Element>, Upstream<Base2.Element>, Upstream<Base3.Element>), downstreamContinuation: DownstreamContinuation ) /// The state once one upstream sequences finished/threw or the downstream consumer stopped, i.e. by dropping all references /// or by getting their `Task` cancelled. case finished /// Internal state to avoid CoW. case modifying } private var state: State private let numberOfUpstreamSequences: Int /// Initializes a new `StateMachine`. init( base1: Base1, base2: Base2, base3: Base3? ) { self.state = .initial( base1: base1, base2: base2, base3: base3 ) if base3 == nil { self.numberOfUpstreamSequences = 2 } else { self.numberOfUpstreamSequences = 3 } } /// Actions returned by `iteratorDeinitialized()`. enum IteratorDeinitializedAction { /// Indicates that the `Task` needs to be cancelled and /// the upstream continuations need to be resumed with a `CancellationError`. case cancelTaskAndUpstreamContinuations( task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) } mutating func iteratorDeinitialized() -> IteratorDeinitializedAction? { switch self.state { case .initial: // Nothing to do here. No demand was signalled until now return .none case .zipping: // An iterator was deinitialized while we have a suspended continuation. preconditionFailure("Internal inconsistency current state \(self.state) and received iteratorDeinitialized()") case .waitingForDemand(let task, let upstreams): // The iterator was dropped which signals that the consumer is finished. // We can transition to finished now and need to clean everything up. self.state = .finished return .cancelTaskAndUpstreamContinuations( task: task, upstreamContinuations: [upstreams.0.continuation, upstreams.1.continuation, upstreams.2.continuation].compactMap { $0 } ) case .finished: // We are already finished so there is nothing left to clean up. // This is just the references dropping afterwards. return .none case .modifying: preconditionFailure("Invalid state") } } mutating func taskIsStarted( task: Task<Void, Never>, downstreamContinuation: DownstreamContinuation ) { switch self.state { case .initial: // The user called `next` and we are starting the `Task` // to consume the upstream sequences self.state = .zipping( task: task, upstreams: (.init(), .init(), .init()), downstreamContinuation: downstreamContinuation ) case .zipping, .waitingForDemand, .finished: // We only allow a single task to be created so this must never happen. preconditionFailure("Internal inconsistency current state \(self.state) and received taskStarted()") case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `childTaskSuspended()`. enum ChildTaskSuspendedAction { /// Indicates that the continuation should be resumed which will lead to calling `next` on the upstream. case resumeContinuation( upstreamContinuation: UnsafeContinuation<Void, Error> ) /// Indicates that the continuation should be resumed with an Error because another upstream sequence threw. case resumeContinuationWithError( upstreamContinuation: UnsafeContinuation<Void, Error>, error: Error ) } mutating func childTaskSuspended(baseIndex: Int, continuation: UnsafeContinuation<Void, Error>) -> ChildTaskSuspendedAction? { switch self.state { case .initial: // Child tasks are only created after we transitioned to `zipping` preconditionFailure("Internal inconsistency current state \(self.state) and received childTaskSuspended()") case .waitingForDemand(let task, var upstreams): self.state = .modifying switch baseIndex { case 0: upstreams.0.continuation = continuation case 1: upstreams.1.continuation = continuation case 2: upstreams.2.continuation = continuation default: preconditionFailure("Internal inconsistency current state \(self.state) and received childTaskSuspended() with base index \(baseIndex)") } self.state = .waitingForDemand( task: task, upstreams: upstreams ) return .none case .zipping(let task, var upstreams, let downstreamContinuation): // We are currently zipping. If we have a buffered element from the base // already then we store the continuation otherwise we just go ahead and resume it switch baseIndex { case 0: if upstreams.0.element == nil { return .resumeContinuation(upstreamContinuation: continuation) } else { self.state = .modifying upstreams.0.continuation = continuation self.state = .zipping( task: task, upstreams: upstreams, downstreamContinuation: downstreamContinuation ) return .none } case 1: if upstreams.1.element == nil { return .resumeContinuation(upstreamContinuation: continuation) } else { self.state = .modifying upstreams.1.continuation = continuation self.state = .zipping( task: task, upstreams: upstreams, downstreamContinuation: downstreamContinuation ) return .none } case 2: if upstreams.2.element == nil { return .resumeContinuation(upstreamContinuation: continuation) } else { self.state = .modifying upstreams.2.continuation = continuation self.state = .zipping( task: task, upstreams: upstreams, downstreamContinuation: downstreamContinuation ) return .none } default: preconditionFailure("Internal inconsistency current state \(self.state) and received childTaskSuspended() with base index \(baseIndex)") } case .finished: // Since cancellation is cooperative it might be that child tasks are still getting // suspended even though we already cancelled them. We must tolerate this and just resume // the continuation with an error. return .resumeContinuationWithError( upstreamContinuation: continuation, error: CancellationError() ) case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `elementProduced()`. enum ElementProducedAction { /// Indicates that the downstream continuation should be resumed with the element. case resumeContinuation( downstreamContinuation: DownstreamContinuation, result: Result<(Base1.Element, Base2.Element, Base3.Element?)?, Error> ) } mutating func elementProduced(_ result: (Base1.Element?, Base2.Element?, Base3.Element?)) -> ElementProducedAction? { switch self.state { case .initial: // Child tasks that are producing elements are only created after we transitioned to `zipping` preconditionFailure("Internal inconsistency current state \(self.state) and received elementProduced()") case .waitingForDemand: // We are only issuing demand when we get signalled by the downstream. // We should never receive an element when we are waiting for demand. preconditionFailure("Internal inconsistency current state \(self.state) and received elementProduced()") case .zipping(let task, var upstreams, let downstreamContinuation): self.state = .modifying switch result { case (.some(let first), .none, .none): precondition(upstreams.0.element == nil) upstreams.0.element = first case (.none, .some(let second), .none): precondition(upstreams.1.element == nil) upstreams.1.element = second case (.none, .none, .some(let third)): precondition(upstreams.2.element == nil) upstreams.2.element = third default: preconditionFailure("Internal inconsistency current state \(self.state) and received elementProduced()") } // Implementing this for the two arities without variadic generics is a bit awkward sadly. if let first = upstreams.0.element, let second = upstreams.1.element, let third = upstreams.2.element { // We got an element from each upstream so we can resume the downstream now self.state = .waitingForDemand( task: task, upstreams: ( .init(continuation: upstreams.0.continuation), .init(continuation: upstreams.1.continuation), .init(continuation: upstreams.2.continuation) ) ) return .resumeContinuation( downstreamContinuation: downstreamContinuation, result: .success((first, second, third)) ) } else if let first = upstreams.0.element, let second = upstreams.1.element, self.numberOfUpstreamSequences == 2 { // We got an element from each upstream so we can resume the downstream now self.state = .waitingForDemand( task: task, upstreams: ( .init(continuation: upstreams.0.continuation), .init(continuation: upstreams.1.continuation), .init(continuation: upstreams.2.continuation) ) ) return .resumeContinuation( downstreamContinuation: downstreamContinuation, result: .success((first, second, nil)) ) } else { // We are still waiting for one of the upstreams to produce an element self.state = .zipping( task: task, upstreams: ( .init(continuation: upstreams.0.continuation, element: upstreams.0.element), .init(continuation: upstreams.1.continuation, element: upstreams.1.element), .init(continuation: upstreams.2.continuation, element: upstreams.2.element) ), downstreamContinuation: downstreamContinuation ) return .none } case .finished: // Since cancellation is cooperative it might be that child tasks // are still producing elements after we finished. // We are just going to drop them since there is nothing we can do return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `upstreamFinished()`. enum UpstreamFinishedAction { /// Indicates that the downstream continuation should be resumed with `nil` and /// the task and the upstream continuations should be cancelled. case resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: DownstreamContinuation, task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) } mutating func upstreamFinished() -> UpstreamFinishedAction? { switch self.state { case .initial: preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamFinished()") case .waitingForDemand: // This can't happen. We are only issuing demand for a single element each time. // There must never be outstanding demand to an upstream while we have no demand ourselves. preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamFinished()") case .zipping(let task, let upstreams, let downstreamContinuation): // One of our upstreams finished. We need to transition to finished ourselves now // and resume the downstream continuation with nil. Furthermore, we need to cancel all of // the upstream work. self.state = .finished return .resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: downstreamContinuation, task: task, upstreamContinuations: [upstreams.0.continuation, upstreams.1.continuation, upstreams.2.continuation].compactMap { $0 } ) case .finished: // This is just everything finishing up, nothing to do here return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `upstreamThrew()`. enum UpstreamThrewAction { /// Indicates that the downstream continuation should be resumed with the `error` and /// the task and the upstream continuations should be cancelled. case resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations( downstreamContinuation: DownstreamContinuation, error: Error, task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) } mutating func upstreamThrew(_ error: Error) -> UpstreamThrewAction? { switch self.state { case .initial: preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamThrew()") case .waitingForDemand: // This can't happen. We are only issuing demand for a single element each time. // There must never be outstanding demand to an upstream while we have no demand ourselves. preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamThrew()") case .zipping(let task, let upstreams, let downstreamContinuation): // One of our upstreams threw. We need to transition to finished ourselves now // and resume the downstream continuation with the error. Furthermore, we need to cancel all of // the upstream work. self.state = .finished return .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations( downstreamContinuation: downstreamContinuation, error: error, task: task, upstreamContinuations: [upstreams.0.continuation, upstreams.1.continuation, upstreams.2.continuation].compactMap { $0 } ) case .finished: // This is just everything finishing up, nothing to do here return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `cancelled()`. enum CancelledAction { /// Indicates that the downstream continuation needs to be resumed and /// task and the upstream continuations should be cancelled. case resumeDownstreamContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: DownstreamContinuation, task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that the task and the upstream continuations should be cancelled. case cancelTaskAndUpstreamContinuations( task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) } mutating func cancelled() -> CancelledAction? { switch self.state { case .initial: preconditionFailure("Internal inconsistency current state \(self.state) and received cancelled()") case .waitingForDemand(let task, let upstreams): // The downstream task got cancelled so we need to cancel our upstream Task // and resume all continuations. We can also transition to finished. self.state = .finished return .cancelTaskAndUpstreamContinuations( task: task, upstreamContinuations: [upstreams.0.continuation, upstreams.1.continuation, upstreams.2.continuation].compactMap { $0 } ) case .zipping(let task, let upstreams, let downstreamContinuation): // The downstream Task got cancelled so we need to cancel our upstream Task // and resume all continuations. We can also transition to finished. self.state = .finished return .resumeDownstreamContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: downstreamContinuation, task: task, upstreamContinuations: [upstreams.0.continuation, upstreams.1.continuation, upstreams.2.continuation].compactMap { $0 } ) case .finished: // We are already finished so nothing to do here: self.state = .finished return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `next()`. enum NextAction { /// Indicates that a new `Task` should be created that consumes the sequence. case startTask(Base1, Base2, Base3?) case resumeUpstreamContinuations( upstreamContinuation: [UnsafeContinuation<Void, Error>] ) /// Indicates that the downstream continuation should be resumed with `nil`. case resumeDownstreamContinuationWithNil(DownstreamContinuation) } mutating func next(for continuation: DownstreamContinuation) -> NextAction { switch self.state { case .initial(let base1, let base2, let base3): // This is the first time we get demand singalled so we have to start the task // The transition to the next state is done in the taskStarted method return .startTask(base1, base2, base3) case .zipping: // We already got demand signalled and have suspended the downstream task // Getting a second next calls means the iterator was transferred across Tasks which is not allowed preconditionFailure("Internal inconsistency current state \(self.state) and received next()") case .waitingForDemand(let task, var upstreams): // We got demand signalled now and can transition to zipping. // We also need to resume all upstream continuations now self.state = .modifying let upstreamContinuations = [upstreams.0.continuation, upstreams.1.continuation, upstreams.2.continuation].compactMap { $0 } upstreams.0.continuation = nil upstreams.1.continuation = nil upstreams.2.continuation = nil self.state = .zipping( task: task, upstreams: upstreams, downstreamContinuation: continuation ) return .resumeUpstreamContinuations( upstreamContinuation: upstreamContinuations ) case .finished: // We are already finished so we are just returning `nil` return .resumeDownstreamContinuationWithNil(continuation) case .modifying: preconditionFailure("Invalid state") } } }
apache-2.0
dan-huang/Music-Player
Music Player/AppDelegate.swift
1
2233
// // AppDelegate.swift // Music Player // // Created by polat on 19/08/14. // Copyright (c) 2014 polat. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { var vc : ViewController = window?.rootViewController as! ViewController vc.correctProgressValueWhenLocked() // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
unlicense
BrunoMazzo/CocoaHeadsApp
CocoaHeadsApp/Classes/Base/Utils/NibDesignable.swift
3
2201
import UIKit /** A NibDesignable is a view wrapper tha loads a XIB with the same name of the class and add it to itself. You should use mainly in storyboards, to avoid modifying views inside the storyboard */ @IBDesignable public class NibDesignable: UIView { // MARK: - Initializer override public init(frame: CGRect) { super.init(frame: frame) self.setupNib() } // MARK: - NSCoding required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib() } // MARK: - Nib loading /** Called in init(frame:) and init(aDecoder:) to load the nib and add it as a subview. */ internal func setupNib() { let view = self.loadNib() self.addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false let bindings = ["view": view] self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: bindings)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: bindings)) viewDidLoad() } public func viewDidLoad() { } /** Called to load the nib in setupNib(). - returns: UIView instance loaded from a nib file. */ public func loadNib() -> UIView { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: self.nibName(), bundle: bundle) guard let view = nib.instantiateWithOwner(self, options: nil).first as? UIView else { fatalError("You're trying to load a NibDesignable without the respective nib file") } return view } /** Called in the default implementation of loadNib(). Default is class name. - returns: Name of a single view nib file. */ public func nibName() -> String { guard let name = self.dynamicType.description().componentsSeparatedByString(".").last else { fatalError("Invalid module name") } return name } }
mit
lokinfey/MyPerfectframework
PerfectLib/MimeReader.swift
1
12166
// // MimeReader.swift // PerfectLib // // Created by Kyle Jessup on 7/6/15. // Copyright (C) 2015 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // #if os(Linux) import SwiftGlibc import LinuxBridge let S_IRUSR = __S_IREAD let S_IROTH = (S_IRGRP >> 3) let S_IWOTH = (S_IWGRP >> 3) #else import Darwin #endif enum MimeReadState { case StateNone case StateBoundary // next thing to be read will be a boundry case StateHeader // read header lines until data starts case StateFieldValue // read a simple value; name has already been set case StateFile // read file data until boundry case StateDone } let kMultiPartForm = "multipart/form-data" let kBoundary = "boundary" let kContentDisposition = "Content-Disposition" let kContentType = "Content-Type" let kPerfectTempPrefix = "perfect_upload_" let mime_cr = UInt8(13) let mime_lf = UInt8(10) let mime_dash = UInt8(45) /// This class is responsible for reading multi-part POST form data, including handling file uploads. /// Data can be given for parsing in little bits at a time by calling the `addTobuffer` function. /// Any file uploads which are encountered will be written to the temporary directory indicated when the `MimeReader` is created. /// Temporary files will be deleted when this object is deinitialized. public class MimeReader { /// Array of BodySpecs representing each part that was parsed. public var bodySpecs = [BodySpec]() var maxFileSize = -1 var (multi, gotFile) = (false, false) var buffer = [UInt8]() let tempDirectory: String var state: MimeReadState = .StateNone /// The boundary identifier. public var boundary = "" /// This class represents a single part of a multi-part POST submission public class BodySpec { /// The name of the form field. public var fieldName = "" /// The value for the form field. /// Having a fieldValue and a file are mutually exclusive. public var fieldValue = "" var fieldValueTempBytes: [UInt8]? /// The content-type for the form part. public var contentType = "" /// The client-side file name as submitted by the form. public var fileName = "" /// The size of the file which was submitted. public var fileSize = 0 /// The name of the temporary file which stores the file upload on the server-side. public var tmpFileName = "" /// The File object for the local temporary file. public var file: File? init() { } /// Clean up the BodySpec, possibly closing and deleting any associated temporary file. public func cleanup() { if let f = self.file { if f.exists() { f.delete() } self.file = nil } } deinit { self.cleanup() } } /// Initialize given a Content-type header line. /// - parameter contentType: The Content-type header line. /// - parameter tempDir: The path to the directory in which to store temporary files. Defaults to "/tmp/". public init(_ contentType: String, tempDir: String = "/tmp/") { self.tempDirectory = tempDir if contentType.rangeOf(kMultiPartForm) != nil { self.multi = true if let range = contentType.rangeOf(kBoundary) { var startIndex = range.startIndex.successor() for _ in 1...kBoundary.characters.count { startIndex = startIndex.successor() } let endIndex = contentType.endIndex let boundaryString = contentType.substringWith(Range(start: startIndex, end: endIndex)) self.boundary.appendContentsOf("--") self.boundary.appendContentsOf(boundaryString) self.state = .StateBoundary } } } // not implimented // public func setMaxFileSize(size: Int) { // self.maxFileSize = size // } func openTempFile(spec: BodySpec) { spec.file = File(tempFilePrefix: self.tempDirectory + kPerfectTempPrefix) spec.tmpFileName = spec.file!.path() } func isBoundaryStart(bytes: [UInt8], start: Array<UInt8>.Index) -> Bool { var gen = self.boundary.utf8.generate() var pos = start var next = gen.next() while let char = next { if pos == bytes.endIndex || char != bytes[pos] { return false } pos = pos.successor() next = gen.next() } return next == nil // got to the end is success } func isField(name: String, bytes: [UInt8], start: Array<UInt8>.Index) -> Array<UInt8>.Index { var check = start let end = bytes.endIndex var gen = name.utf8.generate() while check != end { if bytes[check] == 58 { // : return check } let gened = gen.next() if gened == nil { break } if tolower(Int32(gened!)) != tolower(Int32(bytes[check])) { break } check = check.successor() } return end } func pullValue(name: String, from: String) -> String { var accum = "" if let nameRange = from.rangeOf(name + "=", ignoreCase: true) { var start = nameRange.endIndex let end = from.endIndex if from[start] == "\"" { start = start.successor() } while start < end { if from[start] == "\"" || from[start] == ";" { break; } accum.append(from[start]) start = start.successor() } } return accum } func internalAddToBuffer(bytes: [UInt8]) -> MimeReadState { var clearBuffer = true var position = bytes.startIndex let end = bytes.endIndex while position != end { switch self.state { case .StateDone, .StateNone: return .StateNone case .StateBoundary: if position.distanceTo(end) < self.boundary.characters.count + 2 { self.buffer = Array(bytes[position..<end]) clearBuffer = false position = end } else { position = position.advancedBy(self.boundary.characters.count) if bytes[position] == mime_dash && bytes[position.successor()] == mime_dash { self.state = .StateDone position = position.advancedBy(2) } else { self.state = .StateHeader self.bodySpecs.append(BodySpec()) } if self.state != .StateDone { position = position.advancedBy(2) // line end } else { position = end } } case .StateHeader: var eolPos = position while eolPos.distanceTo(end) > 1 { let b1 = bytes[eolPos] let b2 = bytes[eolPos.successor()] if b1 == mime_cr && b2 == mime_lf { break } eolPos = eolPos.successor() } if eolPos.distanceTo(end) <= 1 { // no eol self.buffer = Array(bytes[position..<end]) clearBuffer = false position = end } else { let spec = self.bodySpecs.last! if eolPos != position { let check = isField(kContentDisposition, bytes: bytes, start: position) if check != end { // yes, content-disposition let line = UTF8Encoding.encode(bytes[check.advancedBy(2)..<eolPos]) let name = pullValue("name", from: line) let fileName = pullValue("filename", from: line) spec.fieldName = name spec.fileName = fileName } else { let check = isField(kContentType, bytes: bytes, start: position) if check != end { // yes, content-type spec.contentType = UTF8Encoding.encode(bytes[check.advancedBy(2)..<eolPos]) } } position = eolPos.advancedBy(2) } if (eolPos == position || position != end) && position.distanceTo(end) > 1 && bytes[position] == mime_cr && bytes[position.successor()] == mime_lf { position = position.advancedBy(2) if spec.fileName.characters.count > 0 { openTempFile(spec) self.state = .StateFile } else { self.state = .StateFieldValue spec.fieldValueTempBytes = [UInt8]() } } } case .StateFieldValue: let spec = self.bodySpecs.last! while position != end { if bytes[position] == mime_cr { if position.distanceTo(end) == 1 { self.buffer = Array(bytes[position..<end]) clearBuffer = false position = end continue } if bytes[position.successor()] == mime_lf { if isBoundaryStart(bytes, start: position.advancedBy(2)) { position = position.advancedBy(2) self.state = .StateBoundary spec.fieldValue = UTF8Encoding.encode(spec.fieldValueTempBytes!) spec.fieldValueTempBytes = nil break } else if position.distanceTo(end) - 2 < self.boundary.characters.count { // we are at the eol, but check to see if the next line may be starting a boundary if position.distanceTo(end) < 4 || (bytes[position.advancedBy(2)] == mime_dash && bytes[position.advancedBy(3)] == mime_dash) { self.buffer = Array(bytes[position..<end]) clearBuffer = false position = end continue } } } } spec.fieldValueTempBytes!.append(bytes[position]) position = position.successor() } case .StateFile: let spec = self.bodySpecs.last! while position != end { if bytes[position] == mime_cr { if position.distanceTo(end) == 1 { self.buffer = Array(bytes[position..<end]) clearBuffer = false position = end continue } if bytes[position.successor()] == mime_lf { if isBoundaryStart(bytes, start: position.advancedBy(2)) { position = position.advancedBy(2) self.state = .StateBoundary // end of file data spec.file!.close() chmod(spec.file!.path(), mode_t(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)) break } else if position.distanceTo(end) - 2 < self.boundary.characters.count { // we are at the eol, but check to see if the next line may be starting a boundary if position.distanceTo(end) < 4 || (bytes[position.advancedBy(2)] == mime_dash && bytes[position.advancedBy(3)] == mime_dash) { self.buffer = Array(bytes[position..<end]) clearBuffer = false position = end continue } } } } // write as much data as we reasonably can var writeEnd = position while writeEnd < end { if bytes[writeEnd] == mime_cr { if writeEnd.distanceTo(end) < 2 { break } if bytes[writeEnd.successor()] == mime_lf { if isBoundaryStart(bytes, start: writeEnd.advancedBy(2)) { break } else if writeEnd.distanceTo(end) - 2 < self.boundary.characters.count { // we are at the eol, but check to see if the next line may be starting a boundary if writeEnd.distanceTo(end) < 4 || (bytes[writeEnd.advancedBy(2)] == mime_dash && bytes[writeEnd.advancedBy(3)] == mime_dash) { break } } } } writeEnd = writeEnd.successor() } do { let length = position.distanceTo(writeEnd) spec.fileSize += try spec.file!.writeBytes(bytes, dataPosition: position, length: length) } catch let e { print("Exception while writing file upload data: \(e)") self.state = .StateNone break } if (writeEnd == end) { self.buffer.removeAll() } position = writeEnd self.gotFile = true } } } if clearBuffer { self.buffer.removeAll() } return self.state } /// Add data to be parsed. /// - parameter bytes: The array of UInt8 to be parsed. public func addToBuffer(bytes: [UInt8]) { if isMultiPart() { if self.buffer.count != 0 { self.buffer.appendContentsOf(bytes) internalAddToBuffer(self.buffer) } else { internalAddToBuffer(bytes) } } else { self.buffer.appendContentsOf(bytes) } } /// Returns true of the content type indicated a multi-part form. public func isMultiPart() -> Bool { return self.multi } }
apache-2.0
SusanDoggie/Doggie
Sources/DoggieGeometry/Exported.swift
1
1262
// // Exported.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @_exported import DoggieCore @_exported import DoggieMath
mit
NghiaTranUIT/Himotoki
Himotoki/ArgumentsBuilder.swift
5
12533
// // ArgumentsBuilder.swift // Himotoki // // Created by Syo Ikeda on 5/11/15. // Copyright (c) 2015 Syo Ikeda. All rights reserved. // // MARK: Arguments builder public func build<A>(a: A?) -> (A)? { if let a = a { return (a) } return nil } public func build<A, B>(a: A?, @autoclosure b: () -> B?) -> (A, B)? { if let a = a, b = b() { return (a, b) } return nil } public func build<A, B, C>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?) -> (A, B, C)? { if let a = a, b = b(), c = c() { return (a, b, c) } return nil } public func build<A, B, C, D>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?) -> (A, B, C, D)? { if let a = a, b = b(), c = c(), d = d() { return (a, b, c, d) } return nil } public func build<A, B, C, D, E>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?) -> (A, B, C, D, E)? { if let a = a, b = b(), c = c(), d = d(), e = e() { return (a, b, c, d, e) } return nil } public func build<A, B, C, D, E, F>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?) -> (A, B, C, D, E, F)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f() { return (a, b, c, d, e, f) } return nil } public func build<A, B, C, D, E, F, G>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?) -> (A, B, C, D, E, F, G)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g() { return (a, b, c, d, e, f, g) } return nil } public func build<A, B, C, D, E, F, G, H>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?) -> (A, B, C, D, E, F, G, H)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h() { return (a, b, c, d, e, f, g, h) } return nil } public func build<A, B, C, D, E, F, G, H, I>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?) -> (A, B, C, D, E, F, G, H, I)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i() { return (a, b, c, d, e, f, g, h, i) } return nil } public func build<A, B, C, D, E, F, G, H, I, J>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?) -> (A, B, C, D, E, F, G, H, I, J)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j() { return (a, b, c, d, e, f, g, h, i, j) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?) -> (A, B, C, D, E, F, G, H, I, J, K)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k() { return (a, b, c, d, e, f, g, h, i, j, k) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?) -> (A, B, C, D, E, F, G, H, I, J, K, L)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l() { return (a, b, c, d, e, f, g, h, i, j, k, l) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m() { return (a, b, c, d, e, f, g, h, i, j, k, l, m) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?, @autoclosure q: () -> Q?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p(), q = q() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?, @autoclosure q: () -> Q?, @autoclosure r: () -> R?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p(), q = q(), r = r() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?, @autoclosure q: () -> Q?, @autoclosure r: () -> R?, @autoclosure s: () -> S?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p(), q = q(), r = r(), s = s() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?, @autoclosure q: () -> Q?, @autoclosure r: () -> R?, @autoclosure s: () -> S?, @autoclosure t: () -> T?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p(), q = q(), r = r(), s = s(), t = t() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?, @autoclosure q: () -> Q?, @autoclosure r: () -> R?, @autoclosure s: () -> S?, @autoclosure t: () -> T?, @autoclosure u: () -> U?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p(), q = q(), r = r(), s = s(), t = t(), u = u() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?, @autoclosure q: () -> Q?, @autoclosure r: () -> R?, @autoclosure s: () -> S?, @autoclosure t: () -> T?, @autoclosure u: () -> U?, @autoclosure v: () -> V?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p(), q = q(), r = r(), s = s(), t = t(), u = u(), v = v() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v) } return nil }
mit
SodiumFRP/sodium-swift
Sodium/String-Extension.swift
1
311
/** # String-Extension.swift - Author: Andrew Bradnan - Date: 5/6/16 - Copyright: © 2016 Whirlygig Ventures. All rights reserved. */ extension String { var isUpperCase: Bool { return self == self.uppercased() } var isLowerCase: Bool { return self == self.lowercased() } }
bsd-3-clause
dtop/SwiftFilter
SwiftFilter/Filters/ReplaceFilter.swift
1
1963
// // ReplaceFilter.swift // SwiftFilter // // Created by Danilo Topalovic on 18.03.16. // Copyright © 2016 nerdsee. All rights reserved. // import Foundation public class ReplaceFilter: FilterProtocol { public enum ReplaceType { case ReplaceString(searchStr: String, replacementStr: String) case ReplaceRange(advStart: Int, advEnd: Int, replacementStr: String) } /// Holds the actual replacement type public var replaceType: ReplaceType! /** Easy init - parameter initialize: the initializer func */ required public init(@noescape _ initialize: (ReplaceFilter) -> Void = { _ in }) { initialize(self) } /// should return the input when filter fails otherwise nil public var returnInputOnFailure: Bool = true /** Filters a value - parameter value: the value - parameter context: some context - throws: filter errors - returns: the filtered value */ public func filter<I: Any, O: Any>(value: I?, _ context: [String: AnyObject]?) throws -> O? { guard let rType: ReplaceType = self.replaceType else { throw NSError(domain: swiftFilterErrorDomain, code: 1, userInfo: [NSLocalizedDescriptionKey: "No replacementType given in ReplaceFilter"]) } guard var inStr: String = value as? String else { return nil } switch rType { case let .ReplaceString(searchString, replacementStr): return inStr.stringByReplacingOccurrencesOfString(searchString, withString: replacementStr) as? O case let .ReplaceRange(advStart, advEnd, replacementStr): inStr.replaceRange(Range<String.Index>(start: inStr.startIndex.advancedBy(advStart), end: inStr.startIndex.advancedBy(advEnd)), with: replacementStr) return inStr as? O } } }
mit
darvin/Poker-Swift
Poker/GameViewController.swift
1
2134
// // GameViewController.swift // Poker // // Created by Sergey Klimov on 4/22/15. // Copyright (c) 2015 Sergey Klimov. All rights reserved. // import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : String) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { let sceneData = try! NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe) let archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return UIInterfaceOrientationMask.AllButUpsideDown } else { return UIInterfaceOrientationMask.All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
mit
hikelee/hotel
Sources/Common/Models/User.swift
1
1353
import Vapor import Fluent import HTTP public final class User: RestModel { public static var entity: String { return "common_user" } public var id: Node? public var name: String? public var salt:String? public var password: String? public var title: String? public var exists: Bool = false //used in fluent public convenience init(node: Node, in context: Context) throws { try self.init(node:node) } public init(node: Node) throws { id = try? node.extract("id") title = try? node.extract("title") name = try? node.extract("name") salt = try? node.extract("salt") password = try? node.extract("password") } public func makeNode() throws -> Node { return try Node.init( node:[ "id": id, "title": title, "name": name, "salt": salt, "password": password, ] ) } public func validate(isCreate: Bool) throws ->[String:String] { var result:[String:String]=[:] if name?.isEmpty ?? true {result["name"] = "必填项"} if isCreate { if password?.isEmpty ?? true {result["password"] = "必填项"} } if title?.isEmpty ?? true {result["title"] = "必填项"} return result } }
mit
TonyReet/AutoSQLite.swift
AutoSQLite.swift/AutoSQLite.swift/ViewController.swift
1
301
// // ViewController.swift // AutoSQLite.swift // // Created by QJ Technology on 2017/5/11. // Copyright © 2017年 TonyReet. All rights reserved. // import UIKit class ViewController: UIViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { } }
mit
superman-coder/pakr
pakr/pakr/WebService/Authentication/Manager/GoogleAuth.swift
1
1493
// // GoogleAuth.swift // pakr // // Created by Huynh Quang Thao on 4/17/16. // Copyright © 2016 Pakr. All rights reserved. // import Foundation import UIKit import Google class GoogleAuth: SocialAuth { class var sharedInstance : GoogleAuth { struct Static { static var token : dispatch_once_t = 0 static var instance : GoogleAuth? = nil } dispatch_once(&Static.token) { Static.instance = GoogleAuth() } return Static.instance! } static func getInstance() -> GIDSignIn { GIDSignIn.sharedInstance().shouldFetchBasicProfile = true return GIDSignIn.sharedInstance() } static func isLogin() -> Bool { return getInstance().hasAuthInKeychain() } static func signOut() { getInstance().signOut() } static func getLoginedUser(googler: GIDGoogleUser) -> User! { let user = User(userId: "", role: Role.UserAuth, email: googler.profile.email, dateCreated: NSDate(), name: googler.profile.name, avatarUrl: googler.profile.imageURLWithDimension(120).absoluteString) return user } static func loginSuccess() { NSUserDefaults.standardUserDefaults().setLoginMechanism(LoginMechanism.GOOGLE) } static func isValidatedWithUrl(url: NSURL) -> Bool { return url.scheme.hasPrefix(NSBundle.mainBundle().bundleIdentifier!) || url.scheme.hasPrefix("com.googleusercontent.apps.") } }
apache-2.0
Bunn/firefox-ios
XCUITests/DisplaySettingsTests.swift
1
2453
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import XCTest class DisplaySettingTests: BaseTestCase { override func tearDown() { navigator.goto(DisplaySettings) waitForExistence(app.switches["DisplaySwitchValue"]) if (app.switches["DisplaySwitchValue"].value! as! String == "1") { app.switches["DisplaySwitchValue"].tap() } super.tearDown() } func testCheckDisplaySettingsDefault() { navigator.goto(DisplaySettings) waitForExistence(app.navigationBars["Theme"]) XCTAssertTrue(app.tables["DisplayTheme.Setting.Options"].exists) let switchValue = app.switches["DisplaySwitchValue"].value! XCTAssertEqual(switchValue as! String, "0") XCTAssertTrue(app.tables.cells.staticTexts["Light"].exists) XCTAssertTrue(app.tables.cells.staticTexts["Dark"].exists) } func testModifySwitchAutomatically() { navigator.goto(DisplaySettings) waitForExistence(app.switches["DisplaySwitchValue"]) navigator.performAction(Action.SelectAutomatically) waitForExistence(app.sliders["0%"]) XCTAssertFalse(app.tables.cells.staticTexts["Dark"].exists) // Going back to Settings and Display settings keeps the value navigator.goto(SettingsScreen) navigator.goto(DisplaySettings) waitForExistence(app.switches["DisplaySwitchValue"]) let switchValue = app.switches["DisplaySwitchValue"].value! XCTAssertEqual(switchValue as! String, "1") XCTAssertFalse(app.tables.cells.staticTexts["Dark"].exists) // Unselect the Automatic mode navigator.performAction(Action.SelectAutomatically) waitForExistence(app.tables.cells.staticTexts["Light"]) XCTAssertTrue(app.tables.cells.staticTexts["Dark"].exists) } func testChangeMode() { // From XCUI there is now way to check the Mode, but at least we test it can be changed if iPad() { navigator.goto(SettingsScreen) } navigator.goto(DisplaySettings) waitForExistence(app.cells.staticTexts["Dark"], timeout: 5) navigator.performAction(Action.SelectDarkMode) navigator.goto(SettingsScreen) navigator.performAction(Action.SelectLightMode) } }
mpl-2.0
Bunn/firefox-ios
Client/Frontend/Settings/SettingsContentViewController.swift
1
6041
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import SnapKit import UIKit import WebKit let DefaultTimeoutTimeInterval = 10.0 // Seconds. We'll want some telemetry on load times in the wild. private var TODOPageLoadErrorString = NSLocalizedString("Could not load page.", comment: "Error message that is shown in settings when there was a problem loading") /** * A controller that manages a single web view and provides a way for * the user to navigate back to Settings. */ class SettingsContentViewController: UIViewController, WKNavigationDelegate { let interstitialBackgroundColor: UIColor var settingsTitle: NSAttributedString? var url: URL! var timer: Timer? var isLoaded: Bool = false { didSet { if isLoaded { UIView.transition(from: interstitialView, to: settingsWebView, duration: 0.5, options: .transitionCrossDissolve, completion: { finished in self.interstitialView.removeFromSuperview() self.interstitialSpinnerView.stopAnimating() }) } } } fileprivate var isError: Bool = false { didSet { if isError { interstitialErrorView.isHidden = false UIView.transition(from: interstitialSpinnerView, to: interstitialErrorView, duration: 0.5, options: .transitionCrossDissolve, completion: { finished in self.interstitialSpinnerView.removeFromSuperview() self.interstitialSpinnerView.stopAnimating() }) } } } // The view shown while the content is loading in the background web view. fileprivate var interstitialView: UIView! fileprivate var interstitialSpinnerView: UIActivityIndicatorView! fileprivate var interstitialErrorView: UILabel! // The web view that displays content. var settingsWebView: WKWebView! fileprivate func startLoading(_ timeout: Double = DefaultTimeoutTimeInterval) { if self.isLoaded { return } if timeout > 0 { self.timer = Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(didTimeOut), userInfo: nil, repeats: false) } else { self.timer = nil } self.settingsWebView.load(PrivilegedRequest(url: url) as URLRequest) self.interstitialSpinnerView.startAnimating() } init(backgroundColor: UIColor = UIColor.Photon.White100, title: NSAttributedString? = nil) { interstitialBackgroundColor = backgroundColor settingsTitle = title super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // This background agrees with the web page background. // Keeping the background constant prevents a pop of mismatched color. view.backgroundColor = interstitialBackgroundColor self.settingsWebView = makeWebView() view.addSubview(settingsWebView) self.settingsWebView.snp.remakeConstraints { make in make.edges.equalTo(self.view) } // Destructuring let causes problems. let ret = makeInterstitialViews() self.interstitialView = ret.0 self.interstitialSpinnerView = ret.1 self.interstitialErrorView = ret.2 view.addSubview(interstitialView) self.interstitialView.snp.remakeConstraints { make in make.edges.equalTo(self.view) } startLoading() } func makeWebView() -> WKWebView { let config = TabManager.makeWebViewConfig(isPrivate: true, blockPopups: true) let webView = WKWebView( frame: CGRect(width: 1, height: 1), configuration: config ) webView.allowsLinkPreview = false webView.navigationDelegate = self // This is not shown full-screen, use mobile UA webView.customUserAgent = UserAgent.mobileUserAgent() return webView } fileprivate func makeInterstitialViews() -> (UIView, UIActivityIndicatorView, UILabel) { let view = UIView() // Keeping the background constant prevents a pop of mismatched color. view.backgroundColor = interstitialBackgroundColor let spinner = UIActivityIndicatorView(style: .gray) view.addSubview(spinner) let error = UILabel() if let _ = settingsTitle { error.text = TODOPageLoadErrorString error.textColor = UIColor.theme.tableView.errorText error.textAlignment = .center } error.isHidden = true view.addSubview(error) spinner.snp.makeConstraints { make in make.center.equalTo(view) return } error.snp.makeConstraints { make in make.center.equalTo(view) make.left.equalTo(view.snp.left).offset(20) make.right.equalTo(view.snp.right).offset(-20) make.height.equalTo(44) return } return (view, spinner, error) } @objc func didTimeOut() { self.timer = nil self.isError = true } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { didTimeOut() } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { didTimeOut() } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { self.timer?.invalidate() self.timer = nil self.isLoaded = true } }
mpl-2.0
doronkatz/firefox-ios
StorageTests/TestSQLiteBookmarks.swift
2
37393
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared @testable import Storage import XCTest private func getBrowserDB(_ filename: String, files: FileAccessor) -> BrowserDB? { let db = BrowserDB(filename: filename, files: files) db.attachDB(filename: "metadata.db", as: AttachedDatabaseMetadata) // BrowserTable exists only to perform create/update etc. operations -- it's not // a queryable thing that needs to stick around. if db.createOrUpdate(BrowserTable()) != .success { return nil } return db } extension SQLiteBookmarks { var testFactory: SQLiteBookmarksModelFactory { return SQLiteBookmarksModelFactory(bookmarks: self, direction: .local) } } // MARK: - Tests. class TestSQLiteBookmarks: XCTestCase { let files = MockFiles() fileprivate func remove(_ path: String) { do { try self.files.remove(path) } catch {} } override func tearDown() { self.remove("TSQLBtestBookmarks.db") self.remove("TSQLBtestBufferStorage.db") self.remove("TSQLBtestLocalAndMirror.db") self.remove("TSQLBtestRecursiveAndURLDelete.db") self.remove("TSQLBtestUnrooted.db") self.remove("TSQLBtestTreeBuilding.db") super.tearDown() } func testBookmarks() { guard let db = getBrowserDB("TSQLBtestBookmarks.db", files: self.files) else { XCTFail("Unable to create browser DB.") return } let bookmarks = SQLiteBookmarks(db: db) let factory = bookmarks.testFactory let url = "http://url1/" let u = url.asURL! bookmarks.addToMobileBookmarks(u, title: "Title", favicon: nil).succeeded() let model = factory.modelForFolder(BookmarkRoots.MobileFolderGUID).value.successValue XCTAssertEqual((model?.current[0] as? BookmarkItem)?.url, url) XCTAssertTrue(factory.isBookmarked(url).value.successValue ?? false) factory.removeByURL("").succeeded() // Grab that GUID and move it into desktop bookmarks. let guid = (model?.current[0] as! BookmarkItem).guid // Desktop bookmarks. XCTAssertFalse(factory.hasDesktopBookmarks().value.successValue ?? true) let toolbar = BookmarkRoots.ToolbarFolderGUID XCTAssertTrue(bookmarks.db.run([ "UPDATE \(TableBookmarksLocal) SET parentid = '\(toolbar)' WHERE guid = '\(guid)'", "UPDATE \(TableBookmarksLocalStructure) SET parent = '\(toolbar)' WHERE child = '\(guid)'", ]).value.isSuccess) XCTAssertTrue(factory.hasDesktopBookmarks().value.successValue ?? true) } fileprivate func createStockMirrorTree(_ db: BrowserDB) { // Set up a mirror tree. let mirrorQuery = "INSERT INTO \(TableBookmarksMirror) (guid, type, bmkUri, title, parentid, parentName, description, tags, keyword, is_overridden, server_modified, pos) " + "VALUES " + "(?, \(BookmarkNodeType.folder.rawValue), NULL, ?, ?, '', '', '', '', 0, \(Date.now()), NULL), " + "(?, \(BookmarkNodeType.folder.rawValue), NULL, ?, ?, '', '', '', '', 0, \(Date.now()), NULL), " + "(?, \(BookmarkNodeType.folder.rawValue), NULL, ?, ?, '', '', '', '', 0, \(Date.now()), NULL), " + "(?, \(BookmarkNodeType.separator.rawValue), NULL, NULL, ?, '', '', '', '', 0, \(Date.now()), 0), " + "(?, \(BookmarkNodeType.bookmark.rawValue), ?, ?, ?, '', '', '', '', 0, \(Date.now()), NULL), " + "(?, \(BookmarkNodeType.bookmark.rawValue), ?, ?, ?, '', '', '', '', 0, \(Date.now()), NULL), " + "(?, \(BookmarkNodeType.bookmark.rawValue), ?, ?, ?, '', '', '', '', 0, \(Date.now()), NULL), " + "(?, \(BookmarkNodeType.bookmark.rawValue), ?, ?, ?, '', '', '', '', 0, \(Date.now()), NULL), " + "(?, \(BookmarkNodeType.bookmark.rawValue), ?, ?, ?, '', '', '', '', 0, \(Date.now()), NULL) " let mirrorArgs: Args = [ "folderAAAAAA", "AAA", BookmarkRoots.ToolbarFolderGUID, "folderBBBBBB", "BBB", BookmarkRoots.MenuFolderGUID, "folderCCCCCC", "CCC", "folderBBBBBB", "separator101", "folderAAAAAA", "bookmark1001", "http://example.org/1", "Bookmark 1", "folderAAAAAA", "bookmark1002", "http://example.org/1", "Bookmark 1 Again", "folderAAAAAA", "bookmark2001", "http://example.org/2", "Bookmark 2", "folderAAAAAA", "bookmark2002", "http://example.org/2", "Bookmark 2 Again", "folderCCCCCC", "bookmark3001", "http://example.org/3", "Bookmark 3", "folderBBBBBB", ] let structureQuery = "INSERT INTO \(TableBookmarksMirrorStructure) (parent, child, idx) VALUES " + "(?, ?, ?), " + "(?, ?, ?), " + "(?, ?, ?), " + "(?, ?, ?), " + "(?, ?, ?), " + "(?, ?, ?), " + "(?, ?, ?), " + "(?, ?, ?), " + "(?, ?, ?) " let structureArgs: Args = [ BookmarkRoots.ToolbarFolderGUID, "folderAAAAAA", 0, BookmarkRoots.MenuFolderGUID, "folderBBBBBB", 0, "folderAAAAAA", "bookmark1001", 0, "folderAAAAAA", "separator101", 1, "folderAAAAAA", "bookmark1002", 2, "folderAAAAAA", "bookmark2001", 3, "folderBBBBBB", "bookmark3001", 0, "folderBBBBBB", "folderCCCCCC", 1, "folderCCCCCC", "bookmark2002", 0, ] db.moveLocalToMirrorForTesting() // So we have the roots. db.run([ (sql: mirrorQuery, args: mirrorArgs), (sql: structureQuery, args: structureArgs), ]).succeeded() } fileprivate func isUnknown(_ folder: BookmarkTreeNode, withGUID: GUID) { switch folder { case .unknown(let guid): XCTAssertEqual(withGUID, guid) default: XCTFail("Not an unknown with GUID \(withGUID).") } } fileprivate func isNonFolder(_ folder: BookmarkTreeNode, withGUID: GUID) { switch folder { case .nonFolder(let guid): XCTAssertEqual(withGUID, guid) default: XCTFail("Not a non-folder with GUID \(withGUID).") } } fileprivate func isFolder(_ folder: BookmarkTreeNode, withGUID: GUID) { switch folder { case .folder(let record): XCTAssertEqual(withGUID, record.guid) default: XCTFail("Not a folder with GUID \(withGUID).") } } fileprivate func areFolders(_ folders: [BookmarkTreeNode], withGUIDs: [GUID]) { folders.zip(withGUIDs).forEach { (node, guid) in self.isFolder(node, withGUID: guid) } } fileprivate func assertTreeIsEmpty(_ treeMaybe: Maybe<BookmarkTree>) { guard let tree = treeMaybe.successValue else { XCTFail("Couldn't get tree!") return } XCTAssertTrue(tree.orphans.isEmpty) XCTAssertTrue(tree.deleted.isEmpty) XCTAssertTrue(tree.isEmpty) } fileprivate func assertTreeContainsOnlyRoots(_ treeMaybe: Maybe<BookmarkTree>) { guard let tree = treeMaybe.successValue else { XCTFail("Couldn't get tree!") return } XCTAssertTrue(tree.orphans.isEmpty) XCTAssertTrue(tree.deleted.isEmpty) XCTAssertFalse(tree.isEmpty) XCTAssertEqual(1, tree.subtrees.count) if case let .folder(guid, children) = tree.subtrees[0] { XCTAssertEqual(guid, "root________") XCTAssertEqual(4, children.count) children.forEach { child in guard case let .folder(_, lower) = child, lower.isEmpty else { XCTFail("Child \(child) wasn't empty!") return } } } else { XCTFail("Tree didn't contain root.") } } func testUnrootedBufferRowsDontAppearInTrees() { guard let db = getBrowserDB("TSQLBtestUnrooted.db", files: self.files) else { XCTFail("Unable to create browser DB.") return } let bookmarks = SQLiteBookmarks(db: db) self.assertTreeContainsOnlyRoots(bookmarks.treeForMirror().value) self.assertTreeIsEmpty(bookmarks.treeForBuffer().value) self.assertTreeContainsOnlyRoots(bookmarks.treeForLocal().value) let args: Args = [ "unrooted0001", BookmarkNodeType.bookmark.rawValue, 0, "somefolder01", "Some Folder", "I have no folder", "http://example.org/", "rooted000002", BookmarkNodeType.bookmark.rawValue, 0, "somefolder02", "Some Other Folder", "I have a folder", "http://example.org/", "somefolder02", BookmarkNodeType.folder.rawValue, 0, BookmarkRoots.MobileFolderGUID, "Mobile Bookmarks", "Some Other Folder", ] let now = Date.now() let bufferSQL = "INSERT INTO \(TableBookmarksBuffer) (server_modified, guid, type, is_deleted, parentid, parentName, title, bmkUri) VALUES " + "(\(now), ?, ?, ?, ?, ?, ?, ?), " + "(\(now), ?, ?, ?, ?, ?, ?, ?), " + "(\(now), ?, ?, ?, ?, ?, ?, NULL)" let bufferStructureSQL = "INSERT INTO \(TableBookmarksBufferStructure) (parent, child, idx) VALUES ('somefolder02', 'rooted000002', 0)" db.run(bufferSQL, withArgs: args).succeeded() db.run(bufferStructureSQL).succeeded() let tree = bookmarks.treeForBuffer().value.successValue! XCTAssertFalse(tree.orphans.contains("somefolder02")) // Folders are never orphans; they appear in subtrees instead. XCTAssertFalse(tree.orphans.contains("rooted000002")) // This tree contains its parent, so it's not an orphan. XCTAssertTrue(tree.orphans.contains("unrooted0001")) XCTAssertEqual(Set(tree.subtrees.map { $0.recordGUID }), Set(["somefolder02"])) } func testTreeBuilding() { guard let db = getBrowserDB("TSQLBtestTreeBuilding.db", files: self.files) else { XCTFail("Unable to create browser DB.") return } let bookmarks = SQLiteBookmarks(db: db) self.assertTreeContainsOnlyRoots(bookmarks.treeForMirror().value) self.assertTreeIsEmpty(bookmarks.treeForBuffer().value) self.assertTreeContainsOnlyRoots(bookmarks.treeForLocal().value) self.createStockMirrorTree(db) self.assertTreeIsEmpty(bookmarks.treeForBuffer().value) // Local was emptied when we moved the roots to the mirror. self.assertTreeIsEmpty(bookmarks.treeForLocal().value) guard let tree = bookmarks.treeForMirror().value.successValue else { XCTFail("Couldn't get tree!") return } // Mirror is no longer empty. XCTAssertFalse(tree.isEmpty) // There's one root. XCTAssertEqual(1, tree.subtrees.count) if case let .folder(guid, children) = tree.subtrees[0] { XCTAssertEqual("root________", guid) XCTAssertEqual(4, children.count) self.areFolders(children, withGUIDs: BookmarkRoots.RootChildren) } else { XCTFail("Root should be a folder.") } // Every GUID is in the tree's nodes. ["folderAAAAAA", "folderBBBBBB", "folderCCCCCC"].forEach { isFolder(tree.lookup[$0]!, withGUID: $0) } ["separator101", "bookmark1001", "bookmark1002", "bookmark2001", "bookmark2002", "bookmark3001"].forEach { isNonFolder(tree.lookup[$0]!, withGUID: $0) } let expectedCount = BookmarkRoots.RootChildren.count + 1 + // The roots. 6 + // Non-folders. 3 // Folders. XCTAssertEqual(expectedCount, tree.lookup.count) // There are no orphans and no deletions. XCTAssertTrue(tree.orphans.isEmpty) XCTAssertTrue(tree.deleted.isEmpty) // root________ // menu________ // folderBBBBBB // bookmark3001 if case let .folder(guidR, rootChildren) = tree.subtrees[0] { XCTAssertEqual(guidR, "root________") if case let .folder(guidM, menuChildren) = rootChildren[0] { XCTAssertEqual(guidM, "menu________") if case let .folder(guidB, bbbChildren) = menuChildren[0] { XCTAssertEqual(guidB, "folderBBBBBB") // BBB contains bookmark3001. if case let .nonFolder(guidBM) = bbbChildren[0] { XCTAssertEqual(guidBM, "bookmark3001") } else { XCTFail("First child of BBB should be bookmark3001.") } // BBB contains folderCCCCCC. if case let .folder(guidBF, _) = bbbChildren[1] { XCTAssertEqual(guidBF, "folderCCCCCC") } else { XCTFail("Second child of BBB should be folderCCCCCC.") } } else { XCTFail("First child of menu should be BBB.") } } else { XCTFail("First child of root should be menu________") } } else { XCTFail("First root should be root________") } // Add a bookmark. It'll override the folder. bookmarks.insertBookmark("https://foo.com/".asURL!, title: "Foo", favicon: nil, intoFolder: "folderBBBBBB", withTitle: "BBB").succeeded() let newlyInserted = db.getRecordByURL("https://foo.com/", fromTable: TableBookmarksLocal).guid guard let local = bookmarks.treeForLocal().value.successValue else { XCTFail("Couldn't get local tree!") return } XCTAssertFalse(local.isEmpty) XCTAssertEqual(4, local.lookup.count) // Folder, new bookmark, original two children. XCTAssertEqual(1, local.subtrees.count) if case let .folder(guid, children) = local.subtrees[0] { XCTAssertEqual("folderBBBBBB", guid) // We have shadows of the original two children. XCTAssertEqual(3, children.count) self.isUnknown(children[0], withGUID: "bookmark3001") self.isUnknown(children[1], withGUID: "folderCCCCCC") self.isNonFolder(children[2], withGUID: newlyInserted) } else { XCTFail("Root should be folderBBBBBB.") } // Insert partial data into the buffer. // We insert: let bufferArgs: Args = [ // * A folder whose parent isn't present in the structure. "ihavenoparent", BookmarkNodeType.folder.rawValue, 0, "myparentnoexist", "No Exist", "No Parent", // * A folder with no children. "ihavenochildren", BookmarkNodeType.folder.rawValue, 0, "ihavenoparent", "No Parent", "No Children", // * A folder that meets both criteria. "xhavenoparent", BookmarkNodeType.folder.rawValue, 0, "myparentnoexist", "No Exist", "No Parent And No Children", // * A changed bookmark with no parent. "changedbookmark", BookmarkNodeType.bookmark.rawValue, 0, "folderCCCCCC", "CCC", "I changed", "http://change.org/", // * A deleted record. "iwasdeleted", BookmarkNodeType.bookmark.rawValue, ] let now = Date.now() let bufferSQL = "INSERT INTO \(TableBookmarksBuffer) (server_modified, guid, type, is_deleted, parentid, parentName, title, bmkUri) VALUES " + "(\(now), ?, ?, ?, ?, ?, ?, NULL), " + "(\(now), ?, ?, ?, ?, ?, ?, NULL), " + "(\(now), ?, ?, ?, ?, ?, ?, NULL), " + "(\(now), ?, ?, ?, ?, ?, ?, ?), " + "(\(now), ?, ?, 1, NULL, NULL, NULL, NULL) " let bufferStructureSQL = "INSERT INTO \(TableBookmarksBufferStructure) (parent, child, idx) VALUES (?, ?, ?)" let bufferStructureArgs: Args = ["ihavenoparent", "ihavenochildren", 0] db.run([(bufferSQL, bufferArgs), (bufferStructureSQL, bufferStructureArgs)]).succeeded() // Now build the tree. guard let partialBuffer = bookmarks.treeForBuffer().value.successValue else { XCTFail("Couldn't get buffer tree!") return } XCTAssertEqual(partialBuffer.deleted, Set<GUID>(["iwasdeleted"])) XCTAssertEqual(partialBuffer.orphans, Set<GUID>(["changedbookmark"])) XCTAssertEqual(partialBuffer.subtreeGUIDs, Set<GUID>(["ihavenoparent", "xhavenoparent"])) if case let .folder(_, children) = partialBuffer.lookup["ihavenochildren"]! { XCTAssertTrue(children.isEmpty) } else { XCTFail("Couldn't look up childless folder.") } } func testRecursiveAndURLDelete() { guard let db = getBrowserDB("TSQLBtestRecursiveAndURLDelete.db", files: self.files) else { XCTFail("Unable to create browser DB.") return } let bookmarks = SQLiteBookmarks(db: db) self.createStockMirrorTree(db) let menuOverridden = BookmarkRoots.MenuFolderGUID XCTAssertFalse(db.isOverridden(menuOverridden) ?? true) func getMenuChildren() -> [GUID] { return db.getChildrenOfFolder(BookmarkRoots.MenuFolderGUID) } XCTAssertEqual(["folderBBBBBB"], getMenuChildren()) // Locally add an item to the menu. This'll override the menu folder. bookmarks.insertBookmark(URL(string: "http://example.com/2")!, title: "Bookmark 2 added locally", favicon: nil, intoFolder: BookmarkRoots.MenuFolderGUID, withTitle: "Bookmarks Menu").succeeded() XCTAssertTrue(db.isOverridden(BookmarkRoots.MenuFolderGUID) ?? false) let menuChildrenBeforeRecursiveDelete = getMenuChildren() XCTAssertEqual(2, menuChildrenBeforeRecursiveDelete.count) XCTAssertEqual("folderBBBBBB", menuChildrenBeforeRecursiveDelete[0]) let locallyAddedBookmark2 = menuChildrenBeforeRecursiveDelete[1] // It's local, so it's not overridden. // N.B., these tests all use XCTAssertEqual instead of XCTAssert{True,False} because // the former plays well with optionals. XCTAssertNil(db.isOverridden(locallyAddedBookmark2)) XCTAssertEqual(false, db.isLocallyDeleted(locallyAddedBookmark2)) // Now let's delete folder B and check that things that weren't deleted now are. XCTAssertEqual(false, db.isOverridden("folderBBBBBB")) XCTAssertNil(db.isLocallyDeleted("folderBBBBBB")) XCTAssertEqual(false, db.isOverridden("folderCCCCCC")) XCTAssertNil(db.isLocallyDeleted("folderCCCCCC")) XCTAssertEqual(false, db.isOverridden("bookmark2002")) XCTAssertNil(db.isLocallyDeleted("bookmark2002")) XCTAssertEqual(false, db.isOverridden("bookmark3001")) XCTAssertNil(db.isLocallyDeleted("bookmark3001")) bookmarks.testFactory.removeByGUID("folderBBBBBB").succeeded() XCTAssertEqual(true, db.isOverridden("folderBBBBBB")) XCTAssertEqual(true, db.isLocallyDeleted("folderBBBBBB")) XCTAssertEqual(true, db.isOverridden("folderCCCCCC")) XCTAssertEqual(true, db.isLocallyDeleted("folderCCCCCC")) XCTAssertEqual(true, db.isOverridden("bookmark2002")) XCTAssertEqual(true, db.isLocallyDeleted("bookmark2002")) XCTAssertEqual(true, db.isOverridden("bookmark3001")) XCTAssertEqual(true, db.isLocallyDeleted("bookmark3001")) // Still there. XCTAssertNil(db.isOverridden(locallyAddedBookmark2)) XCTAssertFalse(db.isLocallyDeleted(locallyAddedBookmark2) ?? true) let menuChildrenAfterRecursiveDelete = getMenuChildren() XCTAssertEqual(1, menuChildrenAfterRecursiveDelete.count) XCTAssertEqual(locallyAddedBookmark2, menuChildrenAfterRecursiveDelete[0]) // Now let's delete by URL. XCTAssertEqual(false, db.isOverridden("bookmark1001")) XCTAssertNil(db.isLocallyDeleted("bookmark1001")) XCTAssertEqual(false, db.isOverridden("bookmark1002")) XCTAssertNil(db.isLocallyDeleted("bookmark1002")) bookmarks.testFactory.removeByURL("http://example.org/1").succeeded() // To conclude, check the entire hierarchy. // Menu: overridden, only the locally-added bookmark 2. // B, 3001, C, 2002: locally deleted. // A: overridden, children [separator101, 2001]. // No bookmarks with URL /1. XCTAssertEqual(true, db.isOverridden(BookmarkRoots.MenuFolderGUID)) XCTAssertEqual(true, db.isOverridden("folderBBBBBB")) XCTAssertEqual(true, db.isLocallyDeleted("folderBBBBBB")) XCTAssertEqual(true, db.isOverridden("folderCCCCCC")) XCTAssertEqual(true, db.isLocallyDeleted("folderCCCCCC")) XCTAssertEqual(true, db.isOverridden("bookmark2002")) XCTAssertEqual(true, db.isLocallyDeleted("bookmark2002")) XCTAssertEqual(true, db.isOverridden("bookmark3001")) XCTAssertEqual(true, db.isLocallyDeleted("bookmark3001")) XCTAssertEqual(true, db.isOverridden("bookmark1001")) XCTAssertEqual(true, db.isLocallyDeleted("bookmark1001")) XCTAssertEqual(true, db.isOverridden("bookmark1002")) XCTAssertEqual(true, db.isLocallyDeleted("bookmark1002")) let menuChildrenAfterURLDelete = getMenuChildren() XCTAssertEqual(1, menuChildrenAfterURLDelete.count) XCTAssertEqual(locallyAddedBookmark2, menuChildrenAfterURLDelete[0]) XCTAssertEqual(["separator101", "bookmark2001"], db.getChildrenOfFolder("folderAAAAAA")) } func testLocalAndMirror() { guard let db = getBrowserDB("TSQLBtestLocalAndMirror.db", files: self.files) else { XCTFail("Unable to create browser DB.") return } // Preconditions. let rootGUIDs = [ BookmarkRoots.RootGUID, BookmarkRoots.MobileFolderGUID, BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, ] let positioned = [ BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, BookmarkRoots.MobileFolderGUID, ] XCTAssertEqual(rootGUIDs, db.getGUIDs("SELECT guid FROM \(TableBookmarksLocal) ORDER BY id")) XCTAssertEqual(positioned, db.getGUIDs("SELECT child FROM \(TableBookmarksLocalStructure) ORDER BY idx")) XCTAssertEqual([], db.getGUIDs("SELECT guid FROM \(TableBookmarksMirror)")) XCTAssertEqual([], db.getGUIDs("SELECT child FROM \(TableBookmarksMirrorStructure)")) // Add a local bookmark. let bookmarks = SQLiteBookmarks(db: db) bookmarks.insertBookmark("http://example.org/".asURL!, title: "Example", favicon: nil, intoFolder: BookmarkRoots.MobileFolderGUID, withTitle: "The Mobile").succeeded() let rowA = db.getRecordByURL("http://example.org/", fromTable: TableBookmarksLocal) XCTAssertEqual(rowA.bookmarkURI, "http://example.org/") XCTAssertEqual(rowA.title, "Example") XCTAssertEqual(rowA.parentName, "The Mobile") XCTAssertEqual(rootGUIDs + [rowA.guid], db.getGUIDs("SELECT guid FROM \(TableBookmarksLocal) ORDER BY id")) XCTAssertEqual([rowA.guid], db.getGUIDs("SELECT child FROM \(TableBookmarksLocalStructure) WHERE parent = '\(BookmarkRoots.MobileFolderGUID)' ORDER BY idx")) XCTAssertEqual(SyncStatus.new, db.getSyncStatusForGUID(rowA.guid)) // Add another. Order should be maintained. bookmarks.insertBookmark("https://reddit.com/".asURL!, title: "Reddit", favicon: nil, intoFolder: BookmarkRoots.MobileFolderGUID, withTitle: "Mobile").succeeded() let rowB = db.getRecordByURL("https://reddit.com/", fromTable: TableBookmarksLocal) XCTAssertEqual(rowB.bookmarkURI, "https://reddit.com/") XCTAssertEqual(rowB.title, "Reddit") XCTAssertEqual(rootGUIDs + [rowA.guid, rowB.guid], db.getGUIDs("SELECT guid FROM \(TableBookmarksLocal) ORDER BY id")) XCTAssertEqual([rowA.guid, rowB.guid], db.getGUIDs("SELECT child FROM \(TableBookmarksLocalStructure) WHERE parent = '\(BookmarkRoots.MobileFolderGUID)' ORDER BY idx")) XCTAssertEqual(SyncStatus.new, db.getSyncStatusForGUID(rowA.guid)) XCTAssertEqual(SyncStatus.new, db.getSyncStatusForGUID(rowB.guid)) // The indices should be 0, 1. let positions = db.getPositionsForChildrenOfParent(BookmarkRoots.MobileFolderGUID, fromTable: TableBookmarksLocalStructure) XCTAssertEqual(positions.count, 2) XCTAssertEqual(positions[rowA.guid], 0) XCTAssertEqual(positions[rowB.guid], 1) // Delete the first. sync_status was New, so the row was immediately deleted. bookmarks.testFactory.removeByURL("http://example.org/").succeeded() XCTAssertEqual(rootGUIDs + [rowB.guid], db.getGUIDs("SELECT guid FROM \(TableBookmarksLocal) ORDER BY id")) XCTAssertEqual([rowB.guid], db.getGUIDs("SELECT child FROM \(TableBookmarksLocalStructure) WHERE parent = '\(BookmarkRoots.MobileFolderGUID)' ORDER BY idx")) let positionsAfterDelete = db.getPositionsForChildrenOfParent(BookmarkRoots.MobileFolderGUID, fromTable: TableBookmarksLocalStructure) XCTAssertEqual(positionsAfterDelete.count, 1) XCTAssertEqual(positionsAfterDelete[rowB.guid], 0) // Manually shuffle all of these into the mirror, as if we were fully synchronized. db.moveLocalToMirrorForTesting() XCTAssertEqual([], db.getGUIDs("SELECT guid FROM \(TableBookmarksLocal) ORDER BY id")) XCTAssertEqual([], db.getGUIDs("SELECT child FROM \(TableBookmarksLocalStructure)")) XCTAssertEqual(rootGUIDs + [rowB.guid], db.getGUIDs("SELECT guid FROM \(TableBookmarksMirror) ORDER BY id")) XCTAssertEqual([rowB.guid], db.getGUIDs("SELECT child FROM \(TableBookmarksMirrorStructure) WHERE parent = '\(BookmarkRoots.MobileFolderGUID)' ORDER BY idx")) let mirrorPositions = db.getPositionsForChildrenOfParent(BookmarkRoots.MobileFolderGUID, fromTable: TableBookmarksMirrorStructure) XCTAssertEqual(mirrorPositions.count, 1) XCTAssertEqual(mirrorPositions[rowB.guid], 0) // Now insert a new mobile bookmark. bookmarks.insertBookmark("https://letsencrypt.org/".asURL!, title: "Let's Encrypt", favicon: nil, intoFolder: BookmarkRoots.MobileFolderGUID, withTitle: "Mobile").succeeded() // The mobile bookmarks folder is overridden. XCTAssertEqual(true, db.isOverridden(BookmarkRoots.MobileFolderGUID)) // Our previous inserted bookmark is not. XCTAssertEqual(false, db.isOverridden(rowB.guid)) let rowC = db.getRecordByURL("https://letsencrypt.org/", fromTable: TableBookmarksLocal) // We have the old structure in the mirror. XCTAssertEqual(rootGUIDs + [rowB.guid], db.getGUIDs("SELECT guid FROM \(TableBookmarksMirror) ORDER BY id")) XCTAssertEqual([rowB.guid], db.getGUIDs("SELECT child FROM \(TableBookmarksMirrorStructure) WHERE parent = '\(BookmarkRoots.MobileFolderGUID)' ORDER BY idx")) // We have the new structure in the local table. XCTAssertEqual(Set([BookmarkRoots.MobileFolderGUID, rowC.guid]), Set(db.getGUIDs("SELECT guid FROM \(TableBookmarksLocal) ORDER BY id"))) XCTAssertEqual([rowB.guid, rowC.guid], db.getGUIDs("SELECT child FROM \(TableBookmarksLocalStructure) WHERE parent = '\(BookmarkRoots.MobileFolderGUID)' ORDER BY idx")) // Parent is changed. The new record is New. The unmodified and deleted records aren't present. XCTAssertNil(db.getSyncStatusForGUID(rowA.guid)) XCTAssertNil(db.getSyncStatusForGUID(rowB.guid)) XCTAssertEqual(SyncStatus.new, db.getSyncStatusForGUID(rowC.guid)) XCTAssertEqual(SyncStatus.changed, db.getSyncStatusForGUID(BookmarkRoots.MobileFolderGUID)) // If we delete the old record, we mark it as changed, and it's no longer in the structure. bookmarks.testFactory.removeByGUID(rowB.guid).succeeded() XCTAssertEqual(SyncStatus.changed, db.getSyncStatusForGUID(rowB.guid)) XCTAssertEqual([rowC.guid], db.getGUIDs("SELECT child FROM \(TableBookmarksLocalStructure) WHERE parent = '\(BookmarkRoots.MobileFolderGUID)' ORDER BY idx")) // Add a duplicate to test multi-deletion (unstar). bookmarks.insertBookmark("https://letsencrypt.org/".asURL!, title: "Let's Encrypt", favicon: nil, intoFolder: BookmarkRoots.MobileFolderGUID, withTitle: "Mobile").succeeded() let guidD = db.getGUIDs("SELECT child FROM \(TableBookmarksLocalStructure) WHERE parent = '\(BookmarkRoots.MobileFolderGUID)' ORDER BY idx").last! XCTAssertNotEqual(rowC.guid, guidD) XCTAssertEqual(SyncStatus.new, db.getSyncStatusForGUID(guidD)) XCTAssertEqual(SyncStatus.changed, db.getSyncStatusForGUID(BookmarkRoots.MobileFolderGUID)) // Delete by URL. // If we delete the new records, they just go away -- there's no server version to delete. bookmarks.testFactory.removeByURL(rowC.bookmarkURI!).succeeded() XCTAssertNil(db.getSyncStatusForGUID(rowC.guid)) XCTAssertNil(db.getSyncStatusForGUID(guidD)) XCTAssertEqual([], db.getGUIDs("SELECT child FROM \(TableBookmarksLocalStructure) WHERE parent = '\(BookmarkRoots.MobileFolderGUID)' ORDER BY idx")) // The mirror structure is unchanged after all this. XCTAssertEqual(rootGUIDs + [rowB.guid], db.getGUIDs("SELECT guid FROM \(TableBookmarksMirror) ORDER BY id")) XCTAssertEqual([rowB.guid], db.getGUIDs("SELECT child FROM \(TableBookmarksMirrorStructure) WHERE parent = '\(BookmarkRoots.MobileFolderGUID)' ORDER BY idx")) } /* // This is dead test code after we eliminated the merged view. // Expect this to be ported to reflect post-sync state. func testBookmarkStructure() { guard let db = getBrowserDB("TSQLBtestBufferStorage.db", files: self.files) else { XCTFail("Unable to create browser DB.") return } let bookmarks = MergedSQLiteBookmarks(db: db) guard let model = bookmarks.modelForRoot().value.successValue else { XCTFail("Unable to get root.") return } let root = model.current // The root isn't useful. The merged bookmark implementation doesn't use it. XCTAssertEqual(root.guid, BookmarkRoots.RootGUID) XCTAssertEqual(0, root.count) // Specifically fetching the fake desktop folder works, though. guard let desktopModel = bookmarks.modelForFolder(BookmarkRoots.FakeDesktopFolderGUID).value.successValue else { XCTFail("Unable to get desktop bookmarks.") return } // It contains the toolbar. let desktopFolder = desktopModel.current XCTAssertEqual(desktopFolder.guid, BookmarkRoots.FakeDesktopFolderGUID) XCTAssertEqual(1, desktopFolder.count) guard let toolbarModel = desktopModel.selectFolder(BookmarkRoots.ToolbarFolderGUID).value.successValue else { XCTFail("Unable to get toolbar.") return } // The toolbar is the child, and it has the two bookmarks as entries. let toolbarFolder = toolbarModel.current XCTAssertEqual(toolbarFolder.guid, BookmarkRoots.ToolbarFolderGUID) XCTAssertEqual(2, toolbarFolder.count) guard let first = toolbarModel.current[0] else { XCTFail("Expected to get AAA.") return } guard let second = toolbarModel.current[1] else { XCTFail("Expected to get BBB.") return } XCTAssertEqual(first.guid, "aaaaaaaaaaaa") XCTAssertEqual(first.title, "AAA") XCTAssertEqual((first as? BookmarkItem)?.url, "http://getfirefox.com") XCTAssertEqual(second.guid, "bbbbbbbbbbbb") XCTAssertEqual(second.title, "BBB") XCTAssertEqual((second as? BookmarkItem)?.url, "http://getfirefox.com") let del: [BookmarkMirrorItem] = [BookmarkMirrorItem.deleted(BookmarkNodeType.Bookmark, guid: "aaaaaaaaaaaa", modified: Date.now())] bookmarks.applyRecords(del, withMaxVars: 1) guard let newToolbar = bookmarks.modelForFolder(BookmarkRoots.ToolbarFolderGUID).value.successValue else { XCTFail("Unable to get toolbar.") return } XCTAssertEqual(newToolbar.current.count, 1) XCTAssertEqual(newToolbar.current[0]?.guid, "bbbbbbbbbbbb") } */ func testBufferStorage() { guard let db = getBrowserDB("TSQLBtestBufferStorage.db", files: self.files) else { XCTFail("Unable to create browser DB.") return } let bookmarks = SQLiteBookmarkBufferStorage(db: db) let record1 = BookmarkMirrorItem.bookmark("aaaaaaaaaaaa", modified: Date.now(), hasDupe: false, parentID: BookmarkRoots.ToolbarFolderGUID, parentName: "Bookmarks Toolbar", title: "AAA", description: "AAA desc", URI: "http://getfirefox.com", tags: "[]", keyword: nil) let record2 = BookmarkMirrorItem.bookmark("bbbbbbbbbbbb", modified: Date.now() + 10, hasDupe: false, parentID: BookmarkRoots.ToolbarFolderGUID, parentName: "Bookmarks Toolbar", title: "BBB", description: "BBB desc", URI: "http://getfirefox.com", tags: "[]", keyword: nil) let toolbar = BookmarkMirrorItem.folder("toolbar", modified: Date.now(), hasDupe: false, parentID: "places", parentName: "", title: "Bookmarks Toolbar", description: "Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar", children: ["aaaaaaaaaaaa", "bbbbbbbbbbbb"]) let recordsA: [BookmarkMirrorItem] = [record1, toolbar, record2] bookmarks.applyRecords(recordsA, withMaxVars: 3).succeeded() // Insert mobile bookmarks as produced by Firefox 40-something on desktop. // swiftlint:disable line_length let children = ["M87np9Vfh_2s", "-JxRyqNte-ue", "6lIQzUtbjE8O", "eOg3jPSslzXl", "1WJIi9EjQErp", "z5uRo45Rvfbd", "EK3lcNd0sUFN", "gFD3GTljgu12", "eRZGsbN1ew9-", "widfEdgGn9de", "l7eTOR4Uf6xq", "vPbxG-gpN4Rb", "4dwJ8CototFe", "zK-kw9Ii6ScW", "eDmDU-gtEFW6", "lKjqWQaL_syt", "ETVDvWgGT31Q", "3Z_bMIHPSZQ8", "Fqu4_bJOk7fT", "Uo_5K1QrA67j", "gDTXNg4m1AJZ", "zpds8P-9xews", "87zjNtVGPtEp", "ZJru8Sn3qhW7", "txVnzBBBOgLP", "JTnRqFaj_oNa", "soaMlfmM4kjR", "g8AcVBjo6IRf", "uPUDaiG4q637", "rfq2bUud_w4d", "XBGxsiuUG2UD", "-VQRnJlyAvMs", "6wu7TScKdTU7", "ZeFji2hLVpLj", "HpCn_TVizMWX", "IPR5HZwRdlwi", "00JFOGuWnhWB", "P1jb3qKt32Vg", "D6MQJ43V1Ir5", "qWSoXFteRfsq", "o2avfYqEdomL", "xRS0U0YnjK9G", "VgOgzE_xfP4w", "SwP3rMJGvoO3", "Hf2jEgI_-PWa", "AyhmBi7Cv598", "-PaMuzTJXxVk", "JMhYrg8SlY5K", "SQeySEjzyplL", "GTAwd2UkEQEe", "x3RsZj5Ilebr", "sRZWZqPi74FP", "amHR50TpygA6", "XSk782ceVNN6", "ipiMyYQzeypI", "ph2k3Nqfhau4", "m5JKC3hAEQ0H", "yTVerkmQbNxk", "7taA6FbbbUbH", "PZvpbSRuJLPs", "C8atoa25U94F", "KOfNJk_ISLc6", "Bt74lBG9tJq6", "BuHoY2rUhuKA", "XTmoWKnwfIPl", "ZATwa3oTD1m0", "e8TczN5It6Am", "6kCUYs8hQtKg", "jDD8s5aiKoex", "QmpmcrYwLU29", "nCRcekynuJ08", "resttaI4J9tu", "EKSX3HV55VU3", "2-yCz0EIsVls", "sSeeGw3VbBY-", "qfpCrU34w9y0", "RKDgzPWecD6m", "5SgXEKu_dICW", "R143WAeB5E5r", "8Ns4-NiKG62r", "4AHuZDvop5XX", "YCP1OsO1goFF", "CYYaU1mQ_N6t", "UGkzEOMK8cuU", "1RzZOarkzQBa", "qSW2Z3cZSI9c", "ooPlKEAfQsnn", "jIUScoKLiXQt", "bjNTKugzRRL1", "hR24ZVnHUZcs", "3j2IDAZgUyYi", "xnWcy-sQDJRu", "UCcgJqGk3bTV", "WSSRWeptH9tq", "4ugv47OGD2E2", "XboCZgUx-x3x", "HrmWqiqsuLrm", "OjdxvRJ3Jb6j"] // swiftlint:enable line_length let mA = BookmarkMirrorItem.bookmark("jIUScoKLiXQt", modified: Date.now(), hasDupe: false, parentID: "mobile", parentName: "mobile", title: "Join the Engineering Leisure Class — Medium", description: nil, URI: "https://medium.com/@chrisloer/join-the-engineering-leisure-class-b3083c09a78e", tags: "[]", keyword: nil) let mB = BookmarkMirrorItem.folder("UjAHxFOGEqU8", modified: Date.now(), hasDupe: false, parentID: "places", parentName: "", title: "mobile", description: nil, children: children) bookmarks.applyRecords([mA, mB]).succeeded() func childCount(_ parent: GUID) -> Int? { let sql = "SELECT COUNT(*) AS childCount FROM \(TableBookmarksBufferStructure) WHERE parent = ?" let args: Args = [parent] return db.runQuery(sql, args: args, factory: { $0["childCount"] as! Int }).value.successValue?[0] } // We have children. XCTAssertEqual(children.count, childCount("UjAHxFOGEqU8")) // Insert an empty mobile bookmarks folder, so we can verify that the structure table is wiped. let mBEmpty = BookmarkMirrorItem.folder("UjAHxFOGEqU8", modified: Date.now() + 1, hasDupe: false, parentID: "places", parentName: "", title: "mobile", description: nil, children: []) bookmarks.applyRecords([mBEmpty]).succeeded() // We no longer have children. XCTAssertEqual(0, childCount("UjAHxFOGEqU8")) } }
mpl-2.0
allbto/ios-swiftility
Swiftility/Sources/Type Safety/Storyboard.swift
2
1710
// // Storyboard.swift // Swiftility // // Created by Allan Barbato on 10/21/15. // Copyright © 2015 Allan Barbato. All rights reserved. // import Foundation import UIKit // MARK: - Storyboard extension UIStoryboard { public struct Name { var name: String var bundle: Bundle? public init(name: String, bundle: Bundle? = nil) { self.name = name self.bundle = bundle } } } extension UIStoryboard { public convenience init(name: UIStoryboard.Name) { self.init(name: name.name, bundle: name.bundle) } } // MARK: - FromStoryboard public protocol FromStoryboard { static var storyboardName: UIStoryboard.Name { get } } // MARK: - Type safe instantiate view controller extension UIStoryboard { public func instantiateInitialViewController<T: UIViewController>() -> T { guard let vc = self.instantiateInitialViewController() as? T else { fatalError("\(String(describing: T.self)) could not be instantiated because it was not found in storyboard: \(self)") } return vc } public func instantiateViewController<T: UIViewController>() -> T { var vc: UIViewController? = nil do { try ObjC.catchException { vc = self.instantiateViewController(withIdentifier: String(describing: T.self)) } } catch { vc = nil } guard let typedVc = vc as? T else { fatalError("\(String(describing: T.self)) could not be instantiated because it was not found in storyboard: \(self)") } return typedVc } }
mit
FengDeng/SwiftNet
SwiftNetDemo/SwiftNetDemo/User.swift
1
593
// // File.swift // SwiftNetDemo // // Created by 邓锋 on 16/3/8. // Copyright © 2016年 fengdeng. All rights reserved. // import Foundation class User : ModelJSONType{ var username = "" var avatar_url = "" required init(){} static func from(json: AnyObject?) throws -> Self { guard let json = json as? [String:AnyObject] else{ throw NSError(domain: "json 解析出错", code: -1, userInfo: nil) } let user = User() user.avatar_url = (json["avatar_url"] as? String) ?? "" return autocast(user) } }
mit
jixuhui/HJPlayArchitecture
HJDemo/Steed/Task.swift
2
856
// // Task.swift // HJDemo // // Created by Hubbert on 15/11/14. // Copyright © 2015年 Hubbert. All rights reserved. // import Foundation class SDURLTask : NSObject{ var ID:String var reqType:String var reqURLPath:String var reqParameters:Dictionary<String,String> var operation:AFHTTPRequestOperation? override init() { ID = "" reqType = "" reqURLPath = "" reqParameters = Dictionary<String,String>(minimumCapacity: 5) super.init() } } class SDURLPageTask : SDURLTask { var pageIndex:Int var pageSize:Int var hasMoreData:Bool var pageIndexKey:String var pageSizeKey:String override init() { pageIndex = 0 pageSize = 20 hasMoreData = false pageIndexKey = "" pageSizeKey = "" super.init() } }
mit
kirayamato1989/KYPhotoBrowser
Demo/ViewController.swift
1
1499
// // ViewController.swift // KYPhotoBrowser // // Created by 郭帅 on 2016/11/8. // Copyright © 2016年 郭帅. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func tap(_ sender: Any) { let path1 = Bundle.main.path(forResource: "1", ofType: "jpg") let path2 = Bundle.main.path(forResource: "2", ofType: "jpg") let photoItems = [path1!, path2!].map { (path) -> KYPhotoItem in let item = KYPhotoItem(url: URL(fileURLWithPath: path), placeholder: nil, image: nil, des: nil) return item } let vc = KYPhotoBrowser(photos: photoItems, initialIndex: 1) vc.eventMonitor = { let event = $1 _ = $0 switch event { case .oneTap: print("单击了\(event.index)") break case .longPress: print("长按了\(event.index)") break case .displayPageChanged: print("图片改变\(event.index)") break default: break } } DispatchQueue.main.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: 2), execute: { self.present(vc, animated: true, completion: nil) }) } }
mit
DarrenKong/firefox-ios
ReadingList/ReadingListClient.swift
2
10292
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Alamofire enum ReadingListDeleteRecordResult { case success(ReadingListRecordResponse) case preconditionFailed(ReadingListResponse) case notFound(ReadingListResponse) case failure(ReadingListResponse) case error(NSError) } enum ReadingListGetRecordResult { case success(ReadingListRecordResponse) case notModified(ReadingListResponse) // TODO Should really call this NotModified for clarity case notFound(ReadingListResponse) case failure(ReadingListResponse) case error(NSError) } enum ReadingListGetAllRecordsResult { case success(ReadingListRecordsResponse) case notModified(ReadingListResponse) // TODO Should really call this NotModified for clarity case failure(ReadingListResponse) case error(NSError) } enum ReadingListPatchRecordResult { } enum ReadingListAddRecordResult { case success(ReadingListRecordResponse) case failure(ReadingListResponse) case conflict(ReadingListResponse) case error(NSError) } enum ReadingListBatchAddRecordsResult { case success(ReadingListBatchRecordResponse) case failure(ReadingListResponse) case error(NSError) } private let ReadingListClientUnknownError = NSError(domain: "org.mozilla.ios.Fennec.ReadingListClient", code: -1, userInfo: nil) class ReadingListClient { var serviceURL: URL var authenticator: ReadingListAuthenticator var articlesURL: URL! var articlesBaseURL: URL! var batchURL: URL! func getRecordWithGuid(_ guid: String, ifModifiedSince: ReadingListTimestamp?, completion: @escaping (ReadingListGetRecordResult) -> Void) { if let url = URL(string: guid, relativeTo: articlesBaseURL) { SessionManager.default.request(createRequest("GET", url, ifModifiedSince: ifModifiedSince)).responseJSON(options: [], completionHandler: { response -> Void in if let json = response.result.value as? [String: Any], let response = response.response { switch response.statusCode { case 200: completion(.success(ReadingListRecordResponse(response: response, json: json)!)) case 304: completion(.notModified(ReadingListResponse(response: response, json: json)!)) case 404: completion(.notFound(ReadingListResponse(response: response, json: json)!)) default: completion(.failure(ReadingListResponse(response: response, json: json)!)) } } else { completion(.error(response.result.error as NSError? ?? ReadingListClientUnknownError)) } }) } else { // TODO ??? } } func getRecordWithGuid(_ guid: String, completion: @escaping (ReadingListGetRecordResult) -> Void) { getRecordWithGuid(guid, ifModifiedSince: nil, completion: completion) } func getAllRecordsWithFetchSpec(_ fetchSpec: ReadingListFetchSpec, ifModifiedSince: ReadingListTimestamp?, completion: @escaping (ReadingListGetAllRecordsResult) -> Void) { if let url = fetchSpec.getURL(serviceURL: serviceURL, path: "/v1/articles") { SessionManager.default.request(createRequest("GET", url)).responseJSON(options: [], completionHandler: { response -> Void in if let json = response.result.value as? [String: Any], let response = response.response { switch response.statusCode { case 200: completion(.success(ReadingListRecordsResponse(response: response, json: json)!)) case 304: completion(.notModified(ReadingListResponse(response: response, json: json)!)) default: completion(.failure(ReadingListResponse(response: response, json: json)!)) } } else { completion(.error(response.result.error as NSError? ?? ReadingListClientUnknownError)) } }) } else { // TODO ??? } } func getAllRecordsWithFetchSpec(_ fetchSpec: ReadingListFetchSpec, completion: @escaping (ReadingListGetAllRecordsResult) -> Void) { getAllRecordsWithFetchSpec(fetchSpec, ifModifiedSince: nil, completion: completion) } func patchRecord(_ record: ReadingListClientRecord, completion: (ReadingListPatchRecordResult) -> Void) { } func addRecord(_ record: ReadingListClientRecord, completion: @escaping (ReadingListAddRecordResult) -> Void) { SessionManager.default.request(createRequest("POST", articlesURL, json: record.json)).responseJSON(options: [], completionHandler: { response in if let json = response.result.value as? [String: Any], let response = response.response { switch response.statusCode { case 200, 201: // TODO Should we have different results for these? Do we care about 200 vs 201? completion(.success(ReadingListRecordResponse(response: response, json: json)!)) case 303: completion(.conflict(ReadingListResponse(response: response, json: json)!)) default: completion(.failure(ReadingListResponse(response: response, json: json)!)) } } else { completion(.error(response.result.error as NSError? ?? ReadingListClientUnknownError)) } }) } /// Build the JSON body for POST /v1/batch { defaults: {}, request: [ {body: {} } ] } fileprivate func recordsToBatchJSON(_ records: [ReadingListClientRecord]) -> AnyObject { return [ "defaults": ["method": "POST", "path": "/v1/articles", "headers": ["Content-Type": "application/json"]], "requests": records.map { ["body": $0.json] } ] as NSDictionary } func batchAddRecords(_ records: [ReadingListClientRecord], completion: @escaping (ReadingListBatchAddRecordsResult) -> Void) { SessionManager.default.request(createRequest("POST", batchURL, json: recordsToBatchJSON(records))).responseJSON(options: [], completionHandler: { response in if let json = response.result.value as? [String: Any], let response = response.response { switch response.statusCode { case 200: completion(.success(ReadingListBatchRecordResponse(response: response, json: json)!)) default: completion(.failure(ReadingListResponse(response: response, json: json)!)) } } else { completion(.error(response.result.error as NSError? ?? ReadingListClientUnknownError)) } }) } func deleteRecordWithGuid(_ guid: String, ifUnmodifiedSince: ReadingListTimestamp?, completion: @escaping (ReadingListDeleteRecordResult) -> Void) { if let url = URL(string: guid, relativeTo: articlesBaseURL) { SessionManager.default.request(createRequest("DELETE", url, ifUnmodifiedSince: ifUnmodifiedSince)).responseJSON(options: [], completionHandler: { response in if let json = response.result.value as? [String: Any], let response = response.response { switch response.statusCode { case 200: completion(.success(ReadingListRecordResponse(response: response, json: json)!)) case 412: completion(.preconditionFailed(ReadingListResponse(response: response, json: json)!)) case 404: completion(.notFound(ReadingListResponse(response: response, json: json)!)) default: completion(.failure(ReadingListResponse(response: response, json: json)!)) } } else { completion(.error(response.result.error as NSError? ?? ReadingListClientUnknownError)) } }) } else { // TODO ??? } } func deleteRecordWithGuid(_ guid: String, completion: @escaping (ReadingListDeleteRecordResult) -> Void) { deleteRecordWithGuid(guid, ifUnmodifiedSince: nil, completion: completion) } func createRequest(_ method: String, _ url: URL, ifUnmodifiedSince: ReadingListTimestamp? = nil, ifModifiedSince: ReadingListTimestamp? = nil, json: AnyObject? = nil) -> URLRequest { let request = NSMutableURLRequest(url: url) request.httpMethod = method if let ifUnmodifiedSince = ifUnmodifiedSince { request.setValue(String(ifUnmodifiedSince), forHTTPHeaderField: "If-Unmodified-Since") } if let ifModifiedSince = ifModifiedSince { request.setValue(String(ifModifiedSince), forHTTPHeaderField: "If-Modified-Since") } for (headerField, value) in authenticator.headers { request.setValue(value, forHTTPHeaderField: headerField) } request.addValue("application/json", forHTTPHeaderField: "Accept") if let json = json { request.addValue("application/json", forHTTPHeaderField: "Content-Type") do { request.httpBody = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) } catch _ { request.httpBody = nil } // TODO Handle errors here } return request as URLRequest } init(serviceURL: URL, authenticator: ReadingListAuthenticator) { self.serviceURL = serviceURL self.authenticator = authenticator self.articlesURL = URL(string: "/v1/articles", relativeTo: self.serviceURL) self.articlesBaseURL = URL(string: "/v1/articles/", relativeTo: self.serviceURL) self.batchURL = URL(string: "/v1/batch", relativeTo: self.serviceURL) } }
mpl-2.0
blstream/TOZ_iOS
TOZ_iOS/PasswordChecker.swift
1
626
// // PasswordChecker.swift // TOZ_iOS // // Copyright © 2017 intive. All rights reserved. // import Foundation class PasswordChecker: TextChecker { weak var confirmView: TextInputView? func check(text: String) -> CheckResult { if text.count == 0 { return .invalid(error: "Pole wymagane") } else if text.count > 30 || text.count < 6 { return .invalid(error: "Niepoprawne hasło") } if let confirmView = confirmView, confirmView.text != text { return .invalid(error: "Wprowadzone hasła są różne") } return .valid } }
apache-2.0
keyOfVv/KEYExtension
KEYExtension/sources/UIEdgeInsets.swift
1
316
// // UIEdgeInsets.swift // KEYExtension // // Created by Ke Yang on 15/02/2017. // Copyright © 2017 com.keyofvv. All rights reserved. // import Foundation // MARK: - extension UIEdgeInsets { public init(eachDirection inset: CGFloat) { self.init(top: inset, left: inset, bottom: inset, right: inset) } }
mit
gokselkoksal/Lightning
Lightning/Sources/Components/StringMask.swift
1
1416
// // StringMask.swift // Lightning // // Created by Göksel Köksal on 20/12/2016. // Copyright © 2016 GK. All rights reserved. // import Foundation public final class StringMask { public let ranges: [NSRange] public let character: Character public init(ranges: [NSRange], character: Character = "*") { self.ranges = ranges self.character = character } public func mask(_ string: String) -> String { guard string.count > 0 else { return string } let stringRanges = ranges.compactMap { string.zap_rangeIntersection(with: $0) } func shouldMaskIndex(_ index: String.Index) -> Bool { for range in stringRanges { if range.contains(index) { return true } } return false } var result = "" var index = string.startIndex for char in string { result += String(shouldMaskIndex(index) ? character : char) index = string.index(after: index) } return result } } public struct StringMaskStorage { public var mask: StringMask { didSet { update() } } public var original: String? { didSet { update() } } public private(set) var masked: String? public init(mask: StringMask) { self.mask = mask } private mutating func update() { if let original = original { masked = mask.mask(original) } else { masked = nil } } }
mit
wscqs/FMDemo-
FMDemo/Classes/Model/SaveMaterialsModel.swift
1
1411
// // SaveMaterialsModel.swift // // Created by mba on 17/2/23 // Copyright (c) . All rights reserved. // import Foundation import ObjectMapper public class SaveMaterialsModel: BaseModel { // MARK: Declaration for string constants to be used to decode and also serialize. private let kSaveMaterialsModelStateKey: String = "state" private let kSaveMaterialsModelMidKey: String = "mid" // MARK: Properties public var state: String? public var mid: String? // MARK: ObjectMapper Initalizers /** Map a JSON object to this class using ObjectMapper - parameter map: A mapping from ObjectMapper */ public required init?(map: Map) { super.init(map: map) } /** Map a JSON object to this class using ObjectMapper - parameter map: A mapping from ObjectMapper */ public override func mapping(map: Map) { super.mapping(map: map) state <- map[kSaveMaterialsModelStateKey] mid <- map[kSaveMaterialsModelMidKey] } /** Generates description of the object in the form of a NSDictionary. - returns: A Key value pair containing all valid values in the object. */ public func dictionaryRepresentation() -> [String: Any] { var dictionary: [String: Any] = [:] if let value = state { dictionary[kSaveMaterialsModelStateKey] = value } if let value = mid { dictionary[kSaveMaterialsModelMidKey] = value } return dictionary } }
apache-2.0
Knowinnovation/kitime
KITime/KITimerCell.swift
1
337
// // KITimerCell.swift // KITime // // Created by Drew Dunne on 6/12/15. // Copyright (c) 2015 Know Innovation. All rights reserved. // import UIKit class KITimerCell: UITableViewCell { @IBOutlet weak var timerNameLabel: UILabel! @IBOutlet weak var controllerNameLabel: UILabel! @IBOutlet var indicatorView: UIView! }
gpl-2.0
mxcl/swift-package-manager
Sources/PackageLoading/ModuleMapGenerator.swift
1
7304
/* This source file is part of the Swift.org open source project Copyright 2015 - 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 Swift project authors */ import Basic import Utility import PackageModel public let moduleMapFilename = "module.modulemap" /// A protocol for modules which might have a modulemap. protocol ModuleMapProtocol { var moduleMapPath: AbsolutePath { get } var moduleMapDirectory: AbsolutePath { get } } extension CModule: ModuleMapProtocol { var moduleMapDirectory: AbsolutePath { return path } public var moduleMapPath: AbsolutePath { return moduleMapDirectory.appending(component: moduleMapFilename) } } extension ClangModule: ModuleMapProtocol { var moduleMapDirectory: AbsolutePath { return includeDir } public var moduleMapPath: AbsolutePath { return moduleMapDirectory.appending(component: moduleMapFilename) } } /// A modulemap generator for clang modules. /// /// Modulemap is generated under the following rules provided it is not already present in include directory: /// /// * "include/foo/foo.h" exists and `foo` is the only directory under include directory. /// Generates: `umbrella header "/path/to/include/foo/foo.h"` /// * "include/foo.h" exists and include contains no other directory. /// Generates: `umbrella header "/path/to/include/foo.h"` /// * Otherwise in all other cases. /// Generates: `umbrella "path/to/include"` public struct ModuleMapGenerator { /// The clang module to operate on. private let module: ClangModule /// The file system to be used. private var fileSystem: FileSystem /// Stream on which warnings will be emitted. private let warningStream: OutputByteStream public init(for module: ClangModule, fileSystem: FileSystem = localFileSystem, warningStream: OutputByteStream = stdoutStream) { self.module = module self.fileSystem = fileSystem self.warningStream = warningStream } /// A link-declaration specifies a library or framework /// against which a program should be linked. /// More info: http://clang.llvm.org/docs/Modules.html#link-declaration /// A `library` modulemap style uses `link` flag for link-declaration where /// as a `framework` uses `link framework` flag and a framework module. public enum ModuleMapStyle { case library case framework /// Link declaration flag to be used in modulemap. var linkDeclFlag: String { switch self { case .library: return "link" case .framework: return "link framework" } } var moduleDeclQualifier: String? { switch self { case .library: return nil case .framework: return "framework" } } } public enum ModuleMapError: Swift.Error { case unsupportedIncludeLayoutForModule(String) } /// Create the synthesized module map, if necessary. /// Note: modulemap is not generated for test modules. // // FIXME: We recompute the generated modulemap's path when building swift // modules in `XccFlags(prefix: String)` there shouldn't be need to redo // this there but is difficult in current architecture. public mutating func generateModuleMap(inDir wd: AbsolutePath, modulemapStyle: ModuleMapStyle = .library) throws { // Don't generate modulemap for a Test module. guard !module.isTest else { return } ///Return if module map is already present guard !fileSystem.isFile(module.moduleMapPath) else { return } let includeDir = module.includeDir // Warn and return if no include directory. guard fileSystem.isDirectory(includeDir) else { warningStream <<< "warning: No include directory found for module '\(module.name)'. A library can not be imported without any public headers." warningStream.flush() return } let walked = try fileSystem.getDirectoryContents(includeDir).map{ includeDir.appending(component: $0) } let files = walked.filter{ fileSystem.isFile($0) && $0.suffix == ".h" } let dirs = walked.filter{ fileSystem.isDirectory($0) } let umbrellaHeaderFlat = includeDir.appending(component: module.c99name + ".h") if fileSystem.isFile(umbrellaHeaderFlat) { guard dirs.isEmpty else { throw ModuleMapError.unsupportedIncludeLayoutForModule(module.name) } try createModuleMap(inDir: wd, type: .header(umbrellaHeaderFlat), modulemapStyle: modulemapStyle) return } diagnoseInvalidUmbrellaHeader(includeDir) let umbrellaHeader = includeDir.appending(components: module.c99name, module.c99name + ".h") if fileSystem.isFile(umbrellaHeader) { guard dirs.count == 1 && files.isEmpty else { throw ModuleMapError.unsupportedIncludeLayoutForModule(module.name) } try createModuleMap(inDir: wd, type: .header(umbrellaHeader), modulemapStyle: modulemapStyle) return } diagnoseInvalidUmbrellaHeader(includeDir.appending(component: module.c99name)) try createModuleMap(inDir: wd, type: .directory(includeDir), modulemapStyle: modulemapStyle) } /// Warn user if in case module name and c99name are different and there is a /// `name.h` umbrella header. private func diagnoseInvalidUmbrellaHeader(_ path: AbsolutePath) { let umbrellaHeader = path.appending(component: module.c99name + ".h") let invalidUmbrellaHeader = path.appending(component: module.name + ".h") if module.c99name != module.name && fileSystem.isFile(invalidUmbrellaHeader) { warningStream <<< "warning: \(invalidUmbrellaHeader.asString) should be renamed to \(umbrellaHeader.asString) to be used as an umbrella header" warningStream.flush() } } private enum UmbrellaType { case header(AbsolutePath) case directory(AbsolutePath) } private mutating func createModuleMap(inDir wd: AbsolutePath, type: UmbrellaType, modulemapStyle: ModuleMapStyle) throws { let stream = BufferedOutputByteStream() if let qualifier = modulemapStyle.moduleDeclQualifier { stream <<< qualifier <<< " " } stream <<< "module \(module.c99name) {\n" switch type { case .header(let header): stream <<< " umbrella header \"\(header.asString)\"\n" case .directory(let path): stream <<< " umbrella \"\(path.asString)\"\n" } stream <<< " \(modulemapStyle.linkDeclFlag) \"\(module.c99name)\"\n" stream <<< " export *\n" stream <<< "}\n" // FIXME: This doesn't belong here. try fileSystem.createDirectory(wd, recursive: true) let file = wd.appending(component: moduleMapFilename) try fileSystem.writeFileContents(file, bytes: stream.bytes) } }
apache-2.0
FabrizioBrancati/SwiftyBot
Sources/Assistant/Response/Example/OptionInfoKey.swift
1
1561
// // OptionInfoKey.swift // SwiftyBot // // The MIT License (MIT) // // Copyright (c) 2016 - 2019 Fabrizio Brancati. // // 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 /// Carousel Item Option Info Keys. public enum OptionInfoKey: String { /// Queuer option info key. case queuer = "QUEUER" /// BFKit-Swift option info key. case bfkitSwift = "BFKIT_SWIFT" /// BFKit option info key. case bfkit = "BFKIT" /// SwiftBot option info key. case swiftybot = "SWIFTYBOT" }
mit
benzguo/MusicKit
MusicKit/Accidental.swift
1
784
// Copyright (c) 2015 Ben Guo. All rights reserved. import Foundation public enum Accidental: Float, CustomStringConvertible { case doubleFlat = -2 case flat = -1 case natural = 0 case sharp = 1 case doubleSharp = 2 public func description(_ stripNatural: Bool) -> String { switch self { case .natural: return stripNatural ? "" : description default: return description } } public var description: String { switch self { case .doubleFlat: return "𝄫" case .flat: return "♭" case .natural: return "♮" case .sharp: return "♯" case .doubleSharp: return "𝄪" } } }
mit
seongkyu-sim/BaseVCKit
BaseVCKit/Classes/extensions/ArrayExtensions.swift
1
292
// // ArrayExtensions.swift // BaseVCKit // // Created by frank on 2017. 5. 31.. // Copyright © 2016년 colavo. All rights reserved. // import Foundation public extension Array { subscript (safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } }
mit
dvor/run-swift
tests/recursive_import/include.swift
2
69
#!import include2.swift print("import_preprocessing: include.swift")
mit
citysite102/kapi-kaffeine
kapi-kaffeine/kapi-kaffeine/KPViewController.swift
1
846
// // KPViewController.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/5/17. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit class KPViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // modalPresentationCapturesStatusBarAppearance = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .fade } } extension UINavigationController { override open var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
mit
nathantannar4/Parse-Dashboard-for-iOS-Pro
Parse Dashboard for iOS/Views/FormerInputAccessoryView.swift
1
6225
// // FormerInputAccessoryView.swift // Parse Dashboard for iOS // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 8/30/17. // import UIKit import Former final class FormerInputAccessoryView: UIToolbar { private weak var former: Former? private weak var leftArrow: UIBarButtonItem! private weak var rightArrow: UIBarButtonItem! init(former: Former) { super.init(frame: CGRect(origin: CGPoint(), size: CGSize(width: 0, height: 44))) self.former = former configure() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update() { leftArrow.isEnabled = former?.canBecomeEditingPrevious() ?? false rightArrow.isEnabled = former?.canBecomeEditingNext() ?? false } private func configure() { barTintColor = .white tintColor = .logoTint clipsToBounds = true isUserInteractionEnabled = true let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let leftArrow = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem(rawValue: 105)!, target: self, action: #selector(FormerInputAccessoryView.handleBackButton)) let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) space.width = 20 let rightArrow = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem(rawValue: 106)!, target: self, action: #selector(FormerInputAccessoryView.handleForwardButton)) let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(FormerInputAccessoryView.handleDoneButton)) let rightSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) setItems([leftArrow, space, rightArrow, flexible, doneButton, rightSpace], animated: false) self.leftArrow = leftArrow self.rightArrow = rightArrow let topLineView = UIView() topLineView.backgroundColor = UIColor(white: 0, alpha: 0.3) topLineView.translatesAutoresizingMaskIntoConstraints = false addSubview(topLineView) let bottomLineView = UIView() bottomLineView.backgroundColor = UIColor(white: 0, alpha: 0.3) bottomLineView.translatesAutoresizingMaskIntoConstraints = false addSubview(bottomLineView) let leftLineView = UIView() leftLineView.backgroundColor = UIColor(white: 0, alpha: 0.3) leftLineView.translatesAutoresizingMaskIntoConstraints = false addSubview(leftLineView) let rightLineView = UIView() rightLineView.backgroundColor = UIColor(white: 0, alpha: 0.3) rightLineView.translatesAutoresizingMaskIntoConstraints = false addSubview(rightLineView) let constraints = [ NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[topLine(0.5)]", options: [], metrics: nil, views: ["topLine": topLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "V:[bottomLine(0.5)]-0-|", options: [], metrics: nil, views: ["bottomLine": bottomLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "V:|-10-[leftLine]-10-|", options: [], metrics: nil, views: ["leftLine": leftLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "V:|-10-[rightLine]-10-|", options: [], metrics: nil, views: ["rightLine": rightLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "H:|-0-[topLine]-0-|", options: [], metrics: nil, views: ["topLine": topLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "H:|-0-[bottomLine]-0-|", options: [], metrics: nil, views: ["bottomLine": bottomLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "H:|-84-[leftLine(0.5)]", options: [], metrics: nil, views: ["leftLine": leftLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "H:[rightLine(0.5)]-74-|", options: [], metrics: nil, views: ["rightLine": rightLineView] ) ] addConstraints(constraints.flatMap { $0 }) } @objc private dynamic func handleBackButton() { update() former?.becomeEditingPrevious() } @objc private dynamic func handleForwardButton() { update() former?.becomeEditingNext() } @objc private dynamic func handleDoneButton() { former?.endEditing() } }
mit
blockchain/My-Wallet-V3-iOS
Modules/FeatureSettings/Sources/FeatureSettingsUI/SettingsServices/Biometry/LabelContent/BiometryLabelContentInteractor.swift
1
947
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import PlatformKit import PlatformUIKit import RxRelay import RxSwift final class BiometryLabelContentInteractor: LabelContentInteracting { typealias InteractionState = LabelContent.State.Interaction let stateRelay = BehaviorRelay<InteractionState>(value: .loading) var state: Observable<InteractionState> { stateRelay.asObservable() } // MARK: - Private Accessors init(biometryProviding: BiometryProviding) { var title = LocalizationConstants.Settings.enableTouchID switch biometryProviding.supportedBiometricsType { case .faceID: title = LocalizationConstants.Settings.enableFaceID case .touchID: title = LocalizationConstants.Settings.enableTouchID case .none: break } stateRelay.accept(.loaded(next: .init(text: title))) } }
lgpl-3.0
huonw/swift
test/SourceKit/CursorInfo/cursor_callargs.swift
57
1095
class C1 { init(passInt: Int, andThis: Float) {} func meth(_ x: Int, passFloat: Float) {} } var c1 = C1(passInt: 0, andThis: 0) c1.meth(0, passFloat: 0) // RUN: %sourcekitd-test -req=cursor -pos=6:11 %s -- %s | %FileCheck -check-prefix=CHECK-CLASS %s // CHECK-CLASS: source.lang.swift.ref.class (2:7-2:9) // RUN: %sourcekitd-test -req=cursor -pos=6:17 %s -- %s | %FileCheck -check-prefix=CHECK-INIT %s // RUN: %sourcekitd-test -req=cursor -pos=6:31 %s -- %s | %FileCheck -check-prefix=CHECK-INIT %s // CHECK-INIT: source.lang.swift.ref.function.constructor (3:3-3:37) // RUN: %sourcekitd-test -req=cursor -pos=7:6 %s -- %s | %FileCheck -check-prefix=CHECK-METH %s // RUN: %sourcekitd-test -req=cursor -pos=7:14 %s -- %s | %FileCheck -check-prefix=CHECK-METH %s // CHECK-METH: source.lang.swift.ref.function.method.instance (4:8-4:40) // Make sure we don't highlight all "meth" occurrences when pointing at "withFloat:". // RUN: %sourcekitd-test -req=related-idents -pos=7:15 %s -- %s | %FileCheck -check-prefix=CHECK-IDS %s // CHECK-IDS: START RANGES // CHECK-IDS-NEXT: END RANGES
apache-2.0
alexandresoliveira/IosSwiftExamples
Projeto/ProjetoTests/ProjetoTests.swift
1
976
// // ProjetoTests.swift // ProjetoTests // // Created by padrao on 5/31/16. // Copyright © 2016 Alexandre Oliveira. All rights reserved. // import XCTest @testable import Projeto class ProjetoTests: 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. } } }
gpl-3.0
juliensagot/JSNavigationController
Example/Example/SecondViewController.swift
1
6594
import AppKit import JSNavigationController private extension Selector { static let pushToThirdVC = #selector(SecondViewController.pushToThirdViewController(_:)) static let popVC = #selector(SecondViewController.popVC) } class SecondViewController: NSViewController, JSNavigationBarViewControllerProvider { weak var navigationController: JSNavigationController? fileprivate let navigationBarVC = BasicNavigationBarViewController() // MARK: - Initializers init() { super.init(nibName: "SecondViewController", bundle: Bundle.main) } required init?(coder: NSCoder) { fatalError("\(#function) has not been implemented") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() view.translatesAutoresizingMaskIntoConstraints = false view.wantsLayer = true if let view = view as? NSVisualEffectView { view.material = .mediumLight } } override func viewDidAppear() { super.viewDidAppear() view.superview?.addConstraints(viewConstraints()) // NavigationBar navigationBarVC.backButton?.action = .popVC navigationBarVC.backButton?.target = self navigationBarVC.titleLabel?.stringValue = "Second VC" navigationBarVC.nextButton?.action = .pushToThirdVC navigationBarVC.nextButton?.target = self } override func viewDidDisappear() { view.superview?.removeConstraints(viewConstraints()) } // MARK: - Layout fileprivate func viewConstraints() -> [NSLayoutConstraint] { let left = NSLayoutConstraint( item: view, attribute: .left, relatedBy: .equal, toItem: view.superview, attribute: .left, multiplier: 1.0, constant: 0.0 ) let right = NSLayoutConstraint( item: view, attribute: .right, relatedBy: .equal, toItem: view.superview, attribute: .right, multiplier: 1.0, constant: 0.0 ) let top = NSLayoutConstraint( item: view, attribute: .top, relatedBy: .equal, toItem: view.superview, attribute: .top, multiplier: 1.0, constant: 0.0 ) let bottom = NSLayoutConstraint( item: view, attribute: .bottom, relatedBy: .equal, toItem: view.superview, attribute: .bottom, multiplier: 1.0, constant: 0.0 ) return [left, right, top, bottom] } // MARK: - NavigationBar func navigationBarViewController() -> NSViewController { return navigationBarVC } // MARK: - Actions @IBAction func pushToThirdViewController(_: AnyObject?) { let thirdVC = ThirdViewController() navigationController?.push(viewController: thirdVC, animated: true) } @IBAction func pushWithCustomAnimations(_: AnyObject?) { let thirdVC = ThirdViewController() let contentAnimation: AnimationBlock = { [weak self] (_, _) in let viewBounds = self?.view.bounds ?? .zero let slideToBottomTransform = CATransform3DMakeTranslation(0, -viewBounds.height, 0) let slideToBottomAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform)) slideToBottomAnimation.fromValue = NSValue(caTransform3D: CATransform3DIdentity) slideToBottomAnimation.toValue = NSValue(caTransform3D: slideToBottomTransform) slideToBottomAnimation.duration = 0.25 slideToBottomAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) slideToBottomAnimation.fillMode = CAMediaTimingFillMode.forwards slideToBottomAnimation.isRemovedOnCompletion = false let slideFromTopTransform = CATransform3DMakeTranslation(0, viewBounds.height, 0) let slideFromTopAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform)) slideFromTopAnimation.fromValue = NSValue(caTransform3D: slideFromTopTransform) slideFromTopAnimation.toValue = NSValue(caTransform3D: CATransform3DIdentity) slideFromTopAnimation.duration = 0.25 slideFromTopAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) slideFromTopAnimation.fillMode = CAMediaTimingFillMode.forwards slideFromTopAnimation.isRemovedOnCompletion = false return ([slideToBottomAnimation], [slideFromTopAnimation]) } let navigationBarAnimation: AnimationBlock = { [weak self] (_, _) in let viewBounds = self?.navigationController?.navigationBarController?.contentView?.bounds ?? .zero let slideToBottomTransform = CATransform3DMakeTranslation(0, -viewBounds.height / 2, 0) let slideToBottomAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform)) slideToBottomAnimation.fromValue = NSValue(caTransform3D: CATransform3DIdentity) slideToBottomAnimation.toValue = NSValue(caTransform3D: slideToBottomTransform) slideToBottomAnimation.duration = 0.25 slideToBottomAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) slideToBottomAnimation.fillMode = CAMediaTimingFillMode.forwards slideToBottomAnimation.isRemovedOnCompletion = false let slideFromTopTransform = CATransform3DMakeTranslation(0, viewBounds.height / 2, 0) let slideFromTopAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform)) slideFromTopAnimation.fromValue = NSValue(caTransform3D: slideFromTopTransform) slideFromTopAnimation.toValue = NSValue(caTransform3D: CATransform3DIdentity) slideFromTopAnimation.duration = 0.25 slideFromTopAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) slideFromTopAnimation.fillMode = CAMediaTimingFillMode.forwards slideFromTopAnimation.isRemovedOnCompletion = false let fadeInAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity)) fadeInAnimation.fromValue = 0.0 fadeInAnimation.toValue = 1.0 fadeInAnimation.duration = 0.25 fadeInAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) fadeInAnimation.fillMode = CAMediaTimingFillMode.forwards fadeInAnimation.isRemovedOnCompletion = false let fadeOutAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity)) fadeOutAnimation.fromValue = 1.0 fadeOutAnimation.toValue = 0.0 fadeOutAnimation.duration = 0.25 fadeOutAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) fadeOutAnimation.fillMode = CAMediaTimingFillMode.forwards fadeOutAnimation.isRemovedOnCompletion = false return ([fadeOutAnimation, slideToBottomAnimation], [fadeInAnimation, slideFromTopAnimation]) } navigationController?.push(viewController: thirdVC, contentAnimation: contentAnimation, navigationBarAnimation: navigationBarAnimation) } @IBAction func popToRootVC(_: AnyObject?) { navigationController?.popToRootViewController(animated: true) } @objc func popVC() { navigationController?.popViewController(animated: true) } }
mit
vanyaland/Tagger
Tagger/Sources/Model/Entities/Image/CategoryImage+CoreDataProperties.swift
1
1251
/** * Copyright (c) 2016 Ivan Magda * * 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 import CoreData extension CategoryImage { @NSManaged var data: Data? @NSManaged var category: Category }
mit
Caiflower/SwiftWeiBo
花菜微博/花菜微博/Classes/View(视图和控制器)/ComposeView(发微博)/CFComposeView.swift
1
10369
// // CFComposeView.swift // 花菜微博 // // Created by 花菜Caiflower on 2017/1/7. // Copyright © 2017年 花菜ChrisCai. All rights reserved. // import UIKit import pop /// 按钮大小 fileprivate let kComposeTypeButtonSize = CGSize(width: 100, height: 100) /// 列间距 fileprivate let composeButtonColumnMargin: CGFloat = (UIScreen.main.cf_screenWidth - 3 * kComposeTypeButtonSize.width) * 0.25 /// 行间距 fileprivate let composeButtonRowMargin: CGFloat = (224 - 2 * kComposeTypeButtonSize.width) * 0.5 class CFComposeView: UIView { var completion: ((_ className: String?) -> ())? @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var scorllView: UIScrollView! @IBOutlet weak var returnButton: UIButton! /// 返回按钮中心点X约束 @IBOutlet weak var returnButtonCenterXContraint: NSLayoutConstraint! /// 关闭按钮中心点X约束 @IBOutlet weak var closeButtonCenterXContraint: NSLayoutConstraint! /// 按钮数据数组 fileprivate let buttonsInfo = [["imageName": "tabbar_compose_idea", "title": "文字", "className": "CFComposeTypeViewController"], ["imageName": "tabbar_compose_photo", "title": "照片/视频"], ["imageName": "tabbar_compose_weibo", "title": "长微博"], ["imageName": "tabbar_compose_lbs", "title": "签到"], ["imageName": "tabbar_compose_review", "title": "点评"], ["imageName": "tabbar_compose_more", "title": "更多", "actionName": "clickMore"], ["imageName": "tabbar_compose_friend", "title": "好友圈"], ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"], ["imageName": "tabbar_compose_music", "title": "音乐"], ["imageName": "tabbar_compose_shooting", "title": "拍摄"] ] class func composeView() -> CFComposeView { let nib = UINib(nibName: "CFComposeView", bundle: nil) let composeView = nib.instantiate(withOwner: nil, options: nil)[0] as! CFComposeView return composeView } override func awakeFromNib() { frame = UIScreen.main.bounds // 初始化子视图 setupOwerViews() } /// 显示发微博视图 func show(completion: @escaping (_ className: String?) -> ()) { self.completion = completion CFMainViewController.shared.view .addSubview(self) // 添加动画 showCurrentView() } /// 关闭按钮点击事件 @IBAction func dismissAction() { // 隐藏当前显示的所有按钮 hideButtons() } /// 返回按钮点击事件 @IBAction func returnButtonAction() { // 还原返回按钮和关闭按钮的位置 returnButtonCenterXContraint.constant = 0 closeButtonCenterXContraint.constant = 0 scorllView.setContentOffset(CGPoint.zero, animated: true) UIView.animate(withDuration: 0.25, animations: { self.layoutIfNeeded() self.returnButton.alpha = 0 }) } } // MARK: - 动画相关扩展 fileprivate extension CFComposeView { // MARK: - 显示动画 func showCurrentView() { // 创建动画 let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) // 设置属性 anim.fromValue = 0 anim.toValue = 1 anim.duration = 0.5 // 添加动画 pop_add(anim, forKey: nil) // 按钮动画 showButtons() } // MARK: - 显示按钮动画 func showButtons() { // 获取做动画的按钮 let v = scorllView.subviews[0] for (i , btn) in v.subviews.enumerated() { // 创建弹力动画 let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY) anim.fromValue = btn.center.y + 400 anim.toValue = btn.center.y // 弹力速度 anim.springSpeed = 8 // 弹力系数 0 ~ 20 默认是4 anim.springBounciness = 8 // 动画开始时间 anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025 // 添加动画 btn.layer.pop_add(anim, forKey: nil) } } // MARK: - 隐藏按钮动画 func hideButtons() { // 获取当前显示的子视图 let page = Int(scorllView.contentOffset.x / scorllView.bounds.width) if page < scorllView.subviews.count { let v = scorllView.subviews[page] // 倒数遍历 for (i, btn) in v.subviews.enumerated().reversed() { // 创建动画 let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY) anim.fromValue = btn.center.y anim.toValue = btn.center.y + 400 anim.springBounciness = 8 anim.springSpeed = 8 anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025 btn.layer.pop_add(anim, forKey: nil) // 监听第0个动画完成 if i == 0 { anim.completionBlock = { (_ , _) in // 隐藏当前视图 self.hideCurrentView() } } } } } // MARK: - 隐藏当前视图 func hideCurrentView() { let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) anim.toValue = 0 anim.fromValue = 1 anim.duration = 0.25 pop_add(anim, forKey: nil) // 监听动画完成 anim.completionBlock = { (_, _) in // 从父视图移除 self.removeFromSuperview() } } } fileprivate extension CFComposeView { func setupOwerViews() { // 强制布局 layoutIfNeeded() let rect = scorllView.bounds // 添加子控件 for i in 0..<2 { let v = UIView() v.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0) addButtons(view: v, index: i * 6) scorllView.addSubview(v) } // 配置scorllView scorllView.contentSize = CGSize(width: rect.width * 2, height: 0) scorllView.showsVerticalScrollIndicator = false scorllView.showsHorizontalScrollIndicator = false scorllView.bounces = false scorllView.isScrollEnabled = false } func addButtons(view: UIView, index: Int) { // 添加子控件 // 每次添加按钮的个数 let onceAddCount = 6 // 每行显示的按钮个数 let numberOfCountInColumn = 3 for i in index..<index + onceAddCount { // 越界结束循环 if i >= buttonsInfo.count { break } let dict = buttonsInfo[i] guard let imageName = dict["imageName"], let title = dict["title"] else { continue } // 创建按钮 let btn = CFComposeTypeButton(imageName: imageName, title: title) // 添加父视图 view.addSubview(btn) // 添加点击事件 if let actionName = dict["actionName"] { btn.addTarget(self, action: Selector(actionName), for: .touchUpInside); } else { btn.addTarget(self, action: #selector(btnClick(selectButton:)), for: .touchUpInside) } btn.className = dict["className"] } // 设置frame for (i , btn) in view.subviews.enumerated() { // 计算行/列 let row = i / numberOfCountInColumn let col = i % 3 // 根据行列计算x/y let x = CGFloat(col + 1) * composeButtonColumnMargin + CGFloat(col) * kComposeTypeButtonSize.width let y: CGFloat = CGFloat(row) * (kComposeTypeButtonSize.height + composeButtonRowMargin) btn.frame = CGRect(origin: CGPoint(x: x, y: y), size: kComposeTypeButtonSize) } } } // MARK: - 各个按钮的点击事件 fileprivate extension CFComposeView { @objc func btnClick(selectButton:CFComposeTypeButton) { print("点击了按钮") guard let view = selectButton.superview else { return } // 被选中的放大, 未被选中的缩小 for (i, button) in view.subviews.enumerated() { // 创建缩放动画 let scaleAnim = POPBasicAnimation(propertyNamed: kPOPViewScaleXY) // 设置缩放系数 let scale = (button == selectButton) ? 1.5 : 0.2 scaleAnim?.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale)) scaleAnim?.duration = 0.5 button.pop_add(scaleAnim, forKey: nil) // 创建透明度动画 let alphaAnim = POPBasicAnimation(propertyNamed: kPOPViewAlpha) alphaAnim?.toValue = 0.2 alphaAnim?.duration = 0.5 button.pop_add(alphaAnim, forKey: nil) // 监听动画完成 if i == 0 { alphaAnim?.completionBlock = { (_, _) in print("动画完毕,显示需要展示的控制器") self.completion?(selectButton.className) } } } } @objc func clickMore() { // 更新scorllView偏移量 scorllView.setContentOffset(CGPoint(x: scorllView.bounds.width, y: 0), animated: true) // 更新返回按钮和关闭按钮的位置 self.returnButtonCenterXContraint.constant -= UIScreen.main.cf_screenWidth / 6 self.closeButtonCenterXContraint.constant += UIScreen.main.cf_screenWidth / 6 // 添加动画效果显示返回按钮 UIView.animate(withDuration: 0.25) { self.layoutIfNeeded() self.returnButton.alpha = 1 } } }
apache-2.0
SECH-Tag-EEXCESS-Browser/iOSX-App
Team UI/Browser/Browser/HtmlManager.swift
1
3719
// // Regex.swift // Browser // // Created by Brian Mairhörmann on 04.11.15. // Copyright © 2015 SECH-Tag-EEXCESS-Browser. All rights reserved. // import Foundation class RegexForSech { func findSechTags(inString string : String) -> [String]{ let pattern = "</?search-[^>]*>" let regex = makeRegEx(withPattern: pattern) for item in getStringArrayWithRegex(string, regex: regex){ print(item) } return getStringArrayWithRegex(string, regex: regex) } func isSechSectionClosing(inString string : String) -> Bool { let pattern = "</search-section" let regex = makeRegEx(withPattern: pattern) let range = NSMakeRange(0, string.characters.count) return regex.firstMatchInString(string, options: NSMatchingOptions(), range: range) != nil } func isSechLinkClosing(inString string : String) -> Bool { let pattern = "</search-link" let regex = makeRegEx(withPattern: pattern) let range = NSMakeRange(0, string.characters.count) return regex.firstMatchInString(string, options: NSMatchingOptions(), range: range) != nil } func isSechSection(inString string : String) -> Bool { let pattern = "<search-section" let regex = makeRegEx(withPattern: pattern) let range = NSMakeRange(0, string.characters.count) return regex.firstMatchInString(string, options: NSMatchingOptions(), range: range) != nil } func isSechLink(inString string : String) -> Bool { let pattern = "<search-link" let regex = makeRegEx(withPattern: pattern) let range = NSMakeRange(0, string.characters.count) return regex.firstMatchInString(string, options: NSMatchingOptions(), range: range) != nil } func getAttributes(inString string : String) -> [String: String]{ // Attributes: topic, type, mediaType, provider, licence let attributeNames = ["topic", "type", "mediaType", "provider", "licence"] var attributes = [String: String]() for attributeName in attributeNames { let regex = makeRegEx(withPattern: attributeName) let range = NSMakeRange(0, string.characters.count) if regex.firstMatchInString(string, options: NSMatchingOptions(), range: range) != nil { let regexAttribute = makeRegEx(withPattern: "(?<=\(attributeName)=\")([#-~ !§°`´äöüÄÖÜß]*)(?=\")") let match = getStringArrayWithRegex(string, regex: regexAttribute) if (match.isEmpty != true){ attributes[attributeName] = match[0] } }else{ attributes[attributeName] = "" } } return attributes } // Private Methods //################################################################################################# private func makeRegEx(withPattern pattern : String) -> NSRegularExpression{ let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive) return regex } private func getStringArrayWithRegex(string : String, regex : NSRegularExpression) -> [String]{ let range = NSMakeRange(0, string.characters.count) let matches = regex.matchesInString(string, options: NSMatchingOptions(), range: range) return matches.map { let range = $0.range return (string as NSString).substringWithRange(range) } } }
mit
jekahy/Grocr
Grocr/Controls/TextField.swift
1
273
// // TextField.swift // Grocr // // Created by Eugene on 26.05.17. // Copyright © 2017 Razeware LLC. All rights reserved. // import Foundation import UIKit @IBDesignable class TextField: UITextField, ErrorBorder { @IBOutlet weak var nextResp:UIResponder? }
mit
cfdrake/lobsters-reader
Source/UI/Helpers/UITableViewController+ScrollToTop.swift
1
412
// // UITableView+ScrollToTop.swift // LobstersReader // // Created by Colin Drake on 6/25/17. // Copyright © 2017 Colin Drake. All rights reserved. // import UIKit extension UITableViewController { /// Scrolls the embedded table view to top. func scrollToTop() { let topRect = CGRect(x: 0, y: 0, width: 1, height: 1) tableView.scrollRectToVisible(topRect, animated: true) } }
mit
sora0077/iTunesMusic
Demo/Views/GenresViewController.swift
1
2118
// // GenresViewController.swift // iTunesMusic // // Created by 林達也 on 2016/06/26. // Copyright © 2016年 jp.sora0077. All rights reserved. // import UIKit import iTunesMusic import RxSwift import SnapKit class GenresViewController: UIViewController { fileprivate let genres = Model.Genres() fileprivate let tableView = UITableView() override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") tableView.delegate = self tableView.dataSource = self tableView.backgroundColor = .clear tableView.tableFooterView = UIView() tableView.snp.makeConstraints { make in make.edges.equalTo(0) } genres.changes .subscribe(tableView.rx.itemUpdates()) .addDisposableTo(disposeBag) action(genres.refresh) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRow(at: indexPath, animated: true) } } } extension GenresViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return genres.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.selectionStyle = .blue cell.textLabel?.text = genres[indexPath.row].name cell.textLabel?.textColor = .white cell.textLabel?.backgroundColor = .clear cell.backgroundColor = UIColor(hex: 0x20201e, alpha: 0.95) return cell } } extension GenresViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = RssViewController(genre: genres[indexPath.row]) navigationController?.pushViewController(vc, animated: true) } }
mit
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/2-Element/LeftCenter.Individual.swift
1
1487
// // LeftCenter.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct LeftCenter { let left: LayoutElement.Horizontal let center: LayoutElement.Horizontal } } // MARK: - Set A Line - // MARK: Top extension IndividualProperty.LeftCenter: LayoutPropertyCanStoreTopType { public func storeTop(_ top: LayoutElement.Vertical) -> IndividualProperty.LeftCenterTop { let leftCenterTop = IndividualProperty.LeftCenterTop(left: self.left, center: self.center, top: top) return leftCenterTop } } // MARK: Middle extension IndividualProperty.LeftCenter: LayoutPropertyCanStoreMiddleType { public func storeMiddle(_ middle: LayoutElement.Vertical) -> IndividualProperty.LeftCenterMiddle { let leftCenterMiddle = IndividualProperty.LeftCenterMiddle(left: self.left, center: self.center, middle: middle) return leftCenterMiddle } } // MARK: Bottom extension IndividualProperty.LeftCenter: LayoutPropertyCanStoreBottomType { public func storeBottom(_ bottom: LayoutElement.Vertical) -> IndividualProperty.LeftCenterBottom { let leftCenterBottom = IndividualProperty.LeftCenterBottom(left: self.left, center: self.center, bottom: bottom) return leftCenterBottom } }
apache-2.0
stripe/stripe-ios
Tests/Tests/ConfirmButtonTests.swift
1
2845
// // ConfirmButtonTests.swift // StripeiOS Tests // // Created by Ramon Torres on 10/6/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import XCTest @testable@_spi(STP) import Stripe @testable@_spi(STP) import StripeCore @testable@_spi(STP) import StripePaymentSheet @testable@_spi(STP) import StripePayments @testable@_spi(STP) import StripePaymentsUI class ConfirmButtonTests: XCTestCase { func testBuyButtonShouldAutomaticallyAdjustItsForegroundColor() { let testCases: [(background: UIColor, foreground: UIColor)] = [ // Dark backgrounds (background: .systemBlue, foreground: .white), (background: .black, foreground: .white), // Light backgrounds ( background: UIColor(red: 1.0, green: 0.87, blue: 0.98, alpha: 1.0), foreground: .black ), ( background: UIColor(red: 1.0, green: 0.89, blue: 0.35, alpha: 1.0), foreground: .black ), ] for (backgroundColor, expectedForeground) in testCases { let button = ConfirmButton.BuyButton() button.tintColor = backgroundColor button.update( status: .enabled, callToAction: .pay(amount: 900, currency: "usd"), animated: false ) XCTAssertEqual( // Test against `.cgColor` because any color set as `.backgroundColor` // will be automatically wrapped in `UIDynamicModifiedColor` (private subclass) by iOS. button.backgroundColor?.cgColor, backgroundColor.cgColor ) XCTAssertEqual( button.foregroundColor, expectedForeground, "The foreground color should contrast with the background color" ) } } func testUpdateShouldCallTheCompletionBlock() { let sut = ConfirmButton( style: .stripe, callToAction: .pay(amount: 1000, currency: "usd"), didTap: {} ) let expectation = XCTestExpectation(description: "Should call the completion block") sut.update(state: .disabled, animated: false) { expectation.fulfill() } wait(for: [expectation], timeout: 1) } func testUpdateShouldCallTheCompletionBlockWhenAnimated() { let sut = ConfirmButton( style: .stripe, callToAction: .pay(amount: 1000, currency: "usd"), didTap: {} ) let expectation = XCTestExpectation(description: "Should call the completion block") sut.update(state: .disabled, animated: true) { expectation.fulfill() } wait(for: [expectation], timeout: 3) } }
mit
dehlen/TRexAboutWindowController
AboutWindowFramework/AboutWindowControllerConfig.swift
1
2822
import Cocoa public struct AboutWindowControllerConfig { private(set) var name: String = "" private(set) var version: String = "" private(set) var copyright: NSAttributedString = NSAttributedString() private(set) var credits: NSAttributedString = NSAttributedString() private(set) var creditsButtonTitle: String = "Acknowledgments" private(set) var eula: NSAttributedString = NSAttributedString() private(set) var eulaButtonTitle: String = "License Agreement" private(set) var url: URL? = nil private(set) var hasShadow: Bool = true private var appName: String { return Bundle.main.appName ?? "" } private var appVersion: String { let version = Bundle.main.buildVersionNumber ?? "" let shortVersion = Bundle.main.releaseVersionNumber ?? "" return "Version \(shortVersion) (Build \(version))" } private var appCopyright: String { return Bundle.main.copyright ?? "" } private var appCredits: NSAttributedString { guard let creditsRtf = Bundle.main.url(forResource: "Credits", withExtension: "rtf") else { return NSAttributedString(string: "") } guard let attributedAppCredits = try? NSMutableAttributedString(url: creditsRtf, options: [:], documentAttributes: nil) else { return NSAttributedString(string: "") } let color = NSColor.textColor attributedAppCredits.apply(color: color) return attributedAppCredits } private var appEula: NSAttributedString { guard let eulaRtf = Bundle.main.url(forResource: "EULA", withExtension: "rtf") else { return NSAttributedString(string: "") } guard let attributedAppEula = try? NSMutableAttributedString(url: eulaRtf, options: [:], documentAttributes: nil) else { return NSAttributedString(string: "") } let color = NSColor.textColor attributedAppEula.apply(color: color) return attributedAppEula } public init(name: String? = nil, version: String? = nil, copyright: NSAttributedString? = nil, credits: NSAttributedString? = nil, creditsButtonTitle: String = "Acknowledgments", eula: NSAttributedString? = nil, eulaButtonTitle: String = "License Agreement", url: URL? = nil, hasShadow: Bool = true) { self.name = name ?? appName self.version = version ?? appVersion self.copyright = copyright ?? AttributedStringHandler.copyright(with: appCopyright) self.credits = credits ?? appCredits self.creditsButtonTitle = creditsButtonTitle self.eula = eula ?? appEula self.eulaButtonTitle = eulaButtonTitle self.url = url self.hasShadow = hasShadow } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/04253-swift-sourcemanager-getmessage.swift
11
428
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class a { struct A { func i() { protocol P { } typealias e : T: NSObject { let t: a { case c<T: BooleanType, A { println(f: c { typealias e : a { return "[1))"[Void{ typealias e : e : NSObject { } class a { class a { } let i: NSObject { } } class case c, } c
mit
Fig-leaves/curation
RSSReader/RadioViewController.swift
1
9171
// // RadioViewController.swift // RSSReader // // Created by 伊藤総一郎 on 9/8/15. // Copyright (c) 2015 susieyy. All rights reserved. // import UIKit class RadioViewController: UIViewController , UITableViewDataSource, UITableViewDelegate, AdstirMraidViewDelegate { var items = NSMutableArray() var refresh: UIRefreshControl! final let API_KEY = Constants.youtube.API_KEY final let WORD:String = Constants.youtube.RADIO var loading = false var nextPageToken:NSString! @IBOutlet weak var table: UITableView! var inter: AdstirInterstitial? = nil var click_count = 0; var adView: AdstirMraidView? = nil deinit { // デリゲートを解放します。解放を忘れるとクラッシュする可能性があります。 self.adView?.delegate = nil // 広告ビューを解放します。 self.adView = nil } override func viewDidLoad() { super.viewDidLoad() self.title = "さまぁ〜ず" self.inter = AdstirInterstitial() self.inter!.media = Constants.inter_ad.id self.inter!.spot = Constants.inter_ad.spot self.inter!.load() // 広告表示位置: タブバーの下でセンタリング、広告サイズ: 320,50 の場合 let originY = self.view.frame.height let originX = (self.view.frame.size.width - kAdstirAdSize320x50.size.width) / 2 let adView = AdstirMraidView(adSize: kAdstirAdSize320x50, origin: CGPointMake(originX, originY - 100), media: Constants.ad.id, spot:Constants.ad.spot) // リフレッシュ秒数を設定します。 adView.intervalTime = 5 // デリゲートを設定します。 adView.delegate = self // 広告ビューを親ビューに追加します。 self.view.addSubview(adView) self.adView = adView // NavigationControllerのタイトルバー(NavigationBar)の色の変更 self.navigationController?.navigationBar.barTintColor = UIColor.blackColor() // NavigationConrtollerの文字カラーの変更 self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] // NavigationControllerのNavigationItemの色 self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() items = NSMutableArray() let nibName = UINib(nibName: "YoutubeTableViewCell", bundle:nil) table.registerNib(nibName, forCellReuseIdentifier: "Cell") table.delegate = self table.dataSource = self self.refresh = UIRefreshControl() self.refresh.attributedTitle = NSAttributedString(string: Constants.message.UPDATING) self.refresh.addTarget(self, action: "viewWillAppear:", forControlEvents: UIControlEvents.ValueChanged) self.table.addSubview(refresh) // NADViewクラスを生成 // nadView = NADView(frame: CGRect(x: Constants.frame.X, // y: Constants.frame.Y, // width: Constants.frame.WIDTH, // height: Constants.frame.HEIGHT)) // // 広告枠のapikey/spotidを設定(必須) // nadView.setNendID(Constants.nend_id.API_ID, spotID: Constants.nend_id.SPOT_ID) // // nendSDKログ出力の設定(任意) // nadView.isOutputLog = true // // delegateを受けるオブジェクトを指定(必須) // nadView.delegate = self // 読み込み開始(必須) // nadView.load() // self.view.addSubview(nadView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) items = NSMutableArray() request(false) self.refresh?.endRefreshing() } func request(next: Bool) { let radioWord:String! = WORD.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) var urlString:String if(next) { urlString = "https://www.googleapis.com/youtube/v3/search?key=\(API_KEY)&q=\(radioWord)&part=snippet&pageToken=\(self.nextPageToken)&maxResults=20&orderby=published" } else { urlString = "https://www.googleapis.com/youtube/v3/search?key=\(API_KEY)&q=\(radioWord)&part=snippet&maxResults=20&orderby=published" } let url:NSURL! = NSURL(string:urlString) let urlRequest:NSURLRequest = NSURLRequest(URL:url) var data:NSData var dic: NSDictionary = NSDictionary() do { data = try NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil) dic = try NSJSONSerialization.JSONObjectWithData( data, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary } catch { print("ERROR") } if(dic.objectForKey("nextPageToken") != nil) { self.nextPageToken = dic.objectForKey("nextPageToken") as! String } else { self.nextPageToken = nil } let itemsArray: NSArray = dic.objectForKey("items") as! NSArray var content: Dictionary<String, String> = ["" : ""] itemsArray.enumerateObjectsUsingBlock({ object, index, stop in let snippet: NSDictionary = object.objectForKey("snippet") as! NSDictionary let ids: NSDictionary = object.objectForKey("id") as! NSDictionary let thumbnails: NSDictionary = snippet.objectForKey("thumbnails") as! NSDictionary let resolution: NSDictionary = thumbnails.objectForKey("high") as! NSDictionary let imageUrl: NSString = resolution.objectForKey("url") as! String if(ids["kind"] as! String == "youtube#video") { content[Constants.article_data.VIDEO_ID] = ids[Constants.article_data.VIDEO_ID] as? String content[Constants.article_data.TITLE] = snippet.objectForKey(Constants.article_data.TITLE) as? String content[Constants.article_data.IMAGE_URL] = imageUrl as String content[Constants.article_data.PUBLISH_AT] = snippet.objectForKey("publishedAt") as? String self.items.addObject(content) } }) self.table.reloadData() self.loading = false } func scrollViewDidScroll(scrollView: UIScrollView) { if(self.table.contentOffset.y >= (self.table.contentSize.height - self.table.bounds.size.height) && self.nextPageToken != nil && loading == false) { loading = true SVProgressHUD.showWithStatus(Constants.message.LOADING) dispatch_async(dispatch_get_main_queue(), { () -> Void in if(self.nextPageToken == nil) { } else { self.request(true) SVProgressHUD.dismiss() } }) } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.table.dequeueReusableCellWithIdentifier("Cell") as! YoutubeTableViewCell let item = self.items[indexPath.row] as! NSDictionary let date = item[Constants.article_data.PUBLISH_AT] as! String let length = date.characters.count var startIndex:String.Index var endIndex:String.Index startIndex = date.startIndex.advancedBy(0) endIndex = date.startIndex.advancedBy(length - 14) let newString = date.substringWithRange(Range(start:startIndex ,end:endIndex)) cell.movieTitleLabel.text = item[Constants.article_data.TITLE] as? String cell.movieTitleLabel.numberOfLines = 0; cell.movieTitleLabel.sizeToFit() cell.dateLabel.text = newString let imgURL: NSURL? = NSURL(string: item[Constants.article_data.IMAGE_URL] as! String) cell.movieImage.setImageWithURL(imgURL) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let item = self.items[indexPath.row] as! NSDictionary let con = KINWebBrowserViewController() let youtube_url = "https://www.youtube.com/watch?v=" + (item[Constants.article_data.VIDEO_ID] as! String) let URL = NSURL(string: youtube_url) con.loadURL(URL) if click_count % Constants.inter_ad.click_count == 1 { self.inter!.showTypeB(self) } click_count++; self.navigationController?.pushViewController(con, animated: true) } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/11631-swift-sourcemanager-getmessage.swift
11
245
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension g { class B { struct A { let d { for in a { func a { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/17800-no-stacktrace.swift
11
224
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { { class A { let f = [ { init( ) { class case ,
mit
mohamedrias/NYTPopularNews
NYTPopularNews/AppDelegate.swift
1
2203
// // AppDelegate.swift // NYTPopularNews // // Created by android on 8/4/17. // Copyright © 2017 com.mohamedrias.pocs.nytpopularnews. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
yoichitgy/Swinject
Tests/SwinjectTests/ContainerTests.Arguments.swift
2
4019
// // Copyright © 2021 Swinject Contributors. All rights reserved. // import XCTest @testable import Swinject class ContainerTests_Arguments: XCTestCase { var container: Container! override func setUpWithError() throws { container = Container() } func testContainierAccepts1Argument() { container.register(Animal.self) { _, arg1 in Cat(name: arg1) } let animal = container.resolve( Animal.self, argument: "1" ) XCTAssertEqual(animal?.name, "1") } func testContainierAccepts2Arguments() { container.register(Animal.self) { _, arg1, arg2 in Cat(name: arg1 + arg2) } let animal = container.resolve( Animal.self, arguments: "1", "2" ) XCTAssertEqual(animal?.name, "12") } func testContainierAccepts3Arguments() { container.register(Animal.self) { _, arg1, arg2, arg3 in Cat(name: arg1 + arg2 + arg3) } let animal = container.resolve( Animal.self, arguments: "1", "2", "3" ) XCTAssertEqual(animal?.name, "123") } func testContainierAccepts4Arguments() { container.register(Animal.self) { _, arg1, arg2, arg3, arg4 in Cat(name: arg1 + arg2 + arg3 + arg4) } let animal = container.resolve( Animal.self, arguments: "1", "2", "3", "4" ) XCTAssertEqual(animal?.name, "1234") } func testContainierAccepts5Arguments() { container.register(Animal.self) { (_, arg1: String, arg2: String, arg3: String, arg4: String, arg5: String) in // swiftlint:disable:this line_length Cat(name: arg1 + arg2 + arg3 + arg4 + arg5) } let animal = container.resolve( Animal.self, arguments: "1", "2", "3", "4", "5" ) XCTAssertEqual(animal?.name, "12345") } func testContainierAccepts6Arguments() { container.register(Animal.self) { (_, arg1: String, arg2: String, arg3: String, arg4: String, arg5: String, arg6: String) in // swiftlint:disable:this line_length Cat(name: arg1 + arg2 + arg3 + arg4 + arg5 + arg6) } let animal = container.resolve( Animal.self, arguments: "1", "2", "3", "4", "5", "6" ) XCTAssertEqual(animal?.name, "123456") } func testContainierAccepts7Arguments() { container.register(Animal.self) { (_, arg1: String, arg2: String, arg3: String, arg4: String, arg5: String, arg6: String, arg7: String) in // swiftlint:disable:this line_length Cat(name: arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7) } let animal = container.resolve( Animal.self, arguments: "1", "2", "3", "4", "5", "6", "7" ) XCTAssertEqual(animal?.name, "1234567") } func testContainierAccepts8Arguments() { container.register(Animal.self) { (_, arg1: String, arg2: String, arg3: String, arg4: String, arg5: String, arg6: String, arg7: String, arg8: String) in // swiftlint:disable:this line_length Cat(name: arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8) } let animal = container.resolve( Animal.self, arguments: "1", "2", "3", "4", "5", "6", "7", "8" ) XCTAssertEqual(animal?.name, "12345678") } func testContainierAccepts9Arguments() { container.register(Animal.self) { (_, arg1: String, arg2: String, arg3: String, arg4: String, arg5: String, arg6: String, arg7: String, arg8: String, arg9: String) in // swiftlint:disable:this line_length Cat(name: arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9) } let animal = container.resolve( Animal.self, arguments: "1", "2", "3", "4", "5", "6", "7", "8", "9" ) XCTAssertEqual(animal?.name, "123456789") } }
mit
tengyifei/wifts
Source/HTTPServer.swift
1
600
// // HTTPServer.swift // Wifts // // Created by Yifei Teng on 2/4/16. // // import Caramel public class HTTPServer { let host: String let server: TCPServer public init(host: String, port: UInt16) { self.host = host self.server = TCPServer(port: port) } public func start() throws { try server.listen { connection in connection.incoming.wait { result in var data = Data() data.append([UInt8]("Response: Hello".utf8)) connection.outgoing.write(data) } } } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/05708-swift-nominaltypedecl-getdeclaredtypeincontext.swift
11
325
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func c<T : d { protocol B { typealias e : A: d where T where A.init(a() -> : A { func a") class A<H : A: d where T -> : T where T where T where A>: A: b fu
mit
supp-f/kNetworking
kNetworking/Classes/KResponse.swift
1
652
// // KResponse.swift // KNetworking // // Created by Marat Shilibaev on 02/12/2016. // Copyright © 2016 KupiBilet. All rights reserved. // public protocol KResponse: Decodable { associatedtype DataType: Decodable var data: DataType? { get } var error: KError? { get } init(data: DataType?, error: KError?) } internal struct KEmptyResponseData: Decodable {} internal struct KEmptyResponse: KResponse { typealias DataType = KEmptyResponseData let data: KEmptyResponseData? let error: KError? init(data: KEmptyResponseData?, error: KError?) { self.data = nil self.error = nil } }
mit
LukaszLiberda/Swift-Design-Patterns
PatternProj/AppDelegate.swift
1
4611
// // AppDelegate.swift // PatternProj // // Created by lukasz on 05/07/15. // Copyright (c) 2015 lukasz. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. // MARK: Creation Pattern var testFactory = TestAbstractFactory() testFactory.test() testFactory.test2() var testBuilder = TestBuilder() testBuilder.test() testBuilder.test2() var testFactoryMethod = TestFactoryMethods() testFactoryMethod.test() testFactoryMethod.test2() var testPrototype = TestPrototype() testPrototype.test() testPrototype.test2() // MARK: Structural Pattern var testAdapter = TestAdapter() testAdapter.test() testAdapter.test2() var testBridgePattern = TestBridge() testBridgePattern.test() testBridgePattern.test2() var testCompositePattern = TestComposite() testCompositePattern.test() testCompositePattern.test2() var testDecorator = TestDecorator() testDecorator.test() testDecorator.test2() var testFacade = TestFacade() testFacade.test() testFacade.test2() var testProxy = TestProxy() testProxy.test() testProxy.test2() testProxy.test3() // MARK: Behavioral Pattern var testChaninOfResponsibility = TestChainOfResponsibility() testChaninOfResponsibility.test() testChaninOfResponsibility.test2() testChaninOfResponsibility.test3() var testCommand = TestCommand() testCommand.test() testCommand.test2() var testInterp = TestInterpreter() testInterp.test() testInterp.test2() var testIterator = TestIterator() testIterator.test() testIterator.test2() var testMediator = TestMediator() testMediator.test() var testMemento = TestMemento() testMemento.test() testMemento.test2() var testObserver:TestObserver = TestObserver() testObserver.test() testObserver.test2() var testState: TestState = TestState() testState.test() testState.test2() testState.test3() var testStrategy: TestStrategy = TestStrategy() testStrategy.test() testStrategy.test2() var testVisitor: TestVisitor = TestVisitor() testVisitor.test() testVisitor.test2() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
gpl-2.0
nkirby/Humber
Humber/_src/Table View Cells/EditOverviewAddCell.swift
1
999
// ======================================================= // Humber // Nathaniel Kirby // ======================================================= import UIKit import HMCore import HMGithub // ======================================================= class EditOverviewAddCell: UITableViewCell { @IBOutlet var titleLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func prepareForReuse() { super.prepareForReuse() self.titleLabel.text = "" } // ======================================================= internal func render() { self.backgroundColor = Theme.color(type: .CellBackgroundColor) let titleAttrString = NSAttributedString(string: "Add", attributes: [ NSForegroundColorAttributeName: Theme.color(type: .TintColor), NSFontAttributeName: Theme.font(type: .Bold(14.0)) ]) self.titleLabel.attributedText = titleAttrString } }
mit
brave/browser-ios
ReadingListTests/ReadingListStorageTestCase.swift
7
8693
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @testable import ReadingList import Foundation import Shared import XCTest class ReadingListStorageTestCase: XCTestCase { var storage: ReadingListStorage! override func setUp() { let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! if NSFileManager.defaultManager().fileExistsAtPath("\(path)/ReadingList.db") { do { try NSFileManager.defaultManager().removeItemAtPath("\(path)/ReadingList.db") } catch _ { XCTFail("Cannot remove old \(path)/ReadingList.db") } } storage = ReadingListSQLStorage(path: "\(path)/ReadingList.db") } func testCreateRecord() { let result = storage.createRecordWithURL("http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance", title: "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma", addedBy: "Stefan's iPhone") switch result { case .Failure(let error): XCTFail(error.description) case .Success(let result): XCTAssertEqual(result.value.url, "http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance") XCTAssertEqual(result.value.title, "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma") XCTAssertEqual(result.value.addedBy, "Stefan's iPhone") XCTAssertEqual(result.value.unread, true) XCTAssertEqual(result.value.archived, false) XCTAssertEqual(result.value.favorite, false) } } func testGetRecordWithURL() { let result1 = storage.createRecordWithURL("http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance", title: "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma", addedBy: "Stefan's iPhone") switch result1 { case .Failure(let error): XCTFail(error.description) case .Success( _): break } let result2 = storage.getRecordWithURL("http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance") switch result2 { case .Failure(let error): XCTFail(error.description) case .Success( _): XCTAssert(result1.successValue == result2.successValue!) } } func testGetUnreadRecords() { // Create 3 records, mark the 2nd as read. createRecordWithURL("http://localhost/article1", title: "Test 1", addedBy: "Stefan's iPhone") let createResult2 = createRecordWithURL("http://localhost/article2", title: "Test 2", addedBy: "Stefan's iPhone") createRecordWithURL("http://localhost/article3", title: "Test 3", addedBy: "Stefan's iPhone") if let record = createResult2.successValue { updateRecord(record, unread: false) } // Get all unread records, make sure we only get the first and last let getUnreadResult = storage.getUnreadRecords() if let records = getUnreadResult.successValue { XCTAssertEqual(2, records.count) for record in records { XCTAssert(record.title == "Test 1" || record.title == "Test 3") XCTAssertEqual(record.unread, true) } } } func testGetAllRecords() { createRecordWithURL("http://localhost/article1", title: "Test 1", addedBy: "Stefan's iPhone") let createResult2 = createRecordWithURL("http://localhost/article2", title: "Test 2", addedBy: "Stefan's iPhone") createRecordWithURL("http://localhost/article3", title: "Test 3", addedBy: "Stefan's iPhone") if let record = createResult2.successValue { updateRecord(record, unread: false) } let getAllResult = storage.getAllRecords() if let records = getAllResult.successValue { XCTAssertEqual(3, records.count) } } func testGetNewRecords() { createRecordWithURL("http://localhost/article1", title: "Test 1", addedBy: "Stefan's iPhone") createRecordWithURL("http://localhost/article2", title: "Test 2", addedBy: "Stefan's iPhone") createRecordWithURL("http://localhost/article3", title: "Test 3", addedBy: "Stefan's iPhone") let getAllResult = getAllRecords() if let records = getAllResult.successValue { XCTAssertEqual(3, records.count) } // TODO When we are able to create records coming from the server, we can extend this test to see if we query correctly } func testDeleteRecord() { let result1 = storage.createRecordWithURL("http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance", title: "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma", addedBy: "Stefan's iPhone") switch result1 { case .Failure(let error): XCTFail(error.description) case .Success(_): break } let result2 = storage.deleteRecord(result1.successValue!) switch result2 { case .Failure(let error): XCTFail(error.description) case .Success: break } let result3 = storage.getRecordWithURL("http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance") switch result3 { case .Failure(let error): XCTFail(error.description) case .Success(let result): XCTAssert(result.value == nil) } } func testDeleteAllRecords() { createRecordWithURL("http://localhost/article1", title: "Test 1", addedBy: "Stefan's iPhone") createRecordWithURL("http://localhost/article2", title: "Test 2", addedBy: "Stefan's iPhone") createRecordWithURL("http://localhost/article3", title: "Test 3", addedBy: "Stefan's iPhone") let getAllResult1 = storage.getAllRecords() if let records = getAllResult1.successValue { XCTAssertEqual(3, records.count) } deleteAllRecords() let getAllResult2 = getAllRecords() if let records = getAllResult2.successValue { XCTAssertEqual(0, records.count) } } func testUpdateRecord() { let result = createRecordWithURL("http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance", title: "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma", addedBy: "Stefan's iPhone") if let record = result.successValue { XCTAssertEqual(record.url, "http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance") XCTAssertEqual(record.title, "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma") XCTAssertEqual(record.addedBy, "Stefan's iPhone") XCTAssertEqual(record.unread, true) XCTAssertEqual(record.archived, false) XCTAssertEqual(record.favorite, false) let result = updateRecord(record, unread: false) if let record = result.successValue! { XCTAssertEqual(record.url, "http://www.anandtech.com/show/9117/analyzing-intel-core-m-performance") XCTAssertEqual(record.title, "Analyzing Intel Core M Performance: How 5Y10 can beat 5Y71 & the OEMs' Dilemma") XCTAssertEqual(record.addedBy, "Stefan's iPhone") XCTAssertEqual(record.unread, false) XCTAssertEqual(record.archived, false) XCTAssertEqual(record.favorite, false) } } } // Helpers that croak if the storage call was not succesful func createRecordWithURL(url: String, title: String, addedBy: String) -> Maybe<ReadingListClientRecord> { let result = storage.createRecordWithURL(url, title: title, addedBy: addedBy) XCTAssertTrue(result.isSuccess) return result } func deleteAllRecords() -> Maybe<Void> { let result = storage.deleteAllRecords() XCTAssertTrue(result.isSuccess) return result } func getAllRecords() -> Maybe<[ReadingListClientRecord]> { let result = storage.getAllRecords() XCTAssertTrue(result.isSuccess) return result } func updateRecord(record: ReadingListClientRecord, unread: Bool) -> Maybe<ReadingListClientRecord?> { let result = storage.updateRecord(record, unread: unread) XCTAssertTrue(result.isSuccess) return result } }
mpl-2.0
wuchuwuyou/CoreTextDemo
CoreTextDemo/AppDelegate.swift
1
2139
// // AppDelegate.swift // CoreTextDemo // // Created by Tiny on 15/7/13. // Copyright (c) 2015年 Murphy. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
cnoon/swift-compiler-crashes
crashes-duplicates/04257-swift-sourcemanager-getmessage.swift
11
260
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let f = [Void{ func g<T { let t: b: BooleanType, A { let t: C { class case c, var d = { pr
mit
chanricle/NCKTextView
LEOTextView/Classes/LEOTextUtil.swift
3
5479
// // LEOTextUtil.swift // LEOTextView // // Created by Leonardo Hammer on 21/04/2017. // // import UIKit class LEOTextUtil: NSObject { static let markdownUnorderedListRegularExpression = try! NSRegularExpression(pattern: "^[-*••∙●] ", options: .caseInsensitive) static let markdownOrderedListRegularExpression = try! NSRegularExpression(pattern: "^\\d*\\. ", options: .caseInsensitive) static let markdownOrderedListAfterItemsRegularExpression = try! NSRegularExpression(pattern: "\\n\\d*\\. ", options: .caseInsensitive) class func isReturn(_ text: String) -> Bool { if text == "\n" { return true } else { return false } } class func isBackspace(_ text: String) -> Bool { if text == "" { return true } else { return false } } class func isSelectedTextWithTextView(_ textView: UITextView) -> Bool { let length = textView.selectedRange.length return length > 0 } class func objectLineAndIndexWithString(_ string: String, location: Int) -> (String, Int) { let ns_string = NSString(string: string) var objectIndex: Int = 0 var objectLine = ns_string.substring(to: location) let textSplits = objectLine.components(separatedBy: "\n") if textSplits.count > 0 { let currentObjectLine = textSplits[textSplits.count - 1] objectIndex = objectLine.length() - currentObjectLine.length() objectLine = currentObjectLine } return (objectLine, objectIndex) } class func objectLineWithString(_ string: String, location: Int) -> String { return objectLineAndIndexWithString(string, location: location).0 } class func lineEndIndexWithString(_ string: String, location: Int) -> Int { let remainText: NSString = NSString(string: string).substring(from: location) as NSString var nextLineBreakLocation = remainText.range(of: "\n").location nextLineBreakLocation = (nextLineBreakLocation == NSNotFound) ? string.length() : nextLineBreakLocation + location return nextLineBreakLocation } class func paragraphRangeOfString(_ string: String, location: Int) -> NSRange { let startLocation = objectLineAndIndexWithString(string, location: location).1 let endLocation = lineEndIndexWithString(string, location: location) return NSMakeRange(startLocation, endLocation - startLocation) } class func currentParagraphStringOfString(_ string: String, location: Int) -> String { return NSString(string: string).substring(with: paragraphRangeOfString(string, location: location)) } /** Just return ListTypes. */ class func paragraphTypeWithObjectLine(_ objectLine: String) -> LEOInputParagraphType { let objectLineRange = NSMakeRange(0, objectLine.length()) let unorderedListMatches = LEOTextUtil.markdownUnorderedListRegularExpression.matches(in: objectLine, options: [], range: objectLineRange) if unorderedListMatches.count > 0 { let firstChar = NSString(string: objectLine).substring(to: 1) if firstChar == "-" { return .dashedList } else { return .bulletedList } } let orderedListMatches = LEOTextUtil.markdownOrderedListRegularExpression.matches(in: objectLine, options: [], range: objectLineRange) if orderedListMatches.count > 0 { return .numberedList } return .body } class func isListParagraph(_ objectLine: String) -> Bool { let objectLineRange = NSMakeRange(0, objectLine.length()) let isCurrentOrderedList = LEOTextUtil.markdownOrderedListRegularExpression.matches(in: objectLine, options: [], range: objectLineRange).count > 0 if isCurrentOrderedList { return true } let isCurrentUnorderedList = LEOTextUtil.markdownUnorderedListRegularExpression.matches(in: objectLine, options: [], range: objectLineRange).count > 0 if isCurrentUnorderedList { return true } return false } class func isBoldFont(_ font: UIFont, boldFontName: String) -> Bool { if font.fontName == boldFontName { return true } let keywords = ["bold", "medium"] // At chinese language: PingFangSC-Light is normal, PingFangSC-Regular is bold return isSpecialFont(font, keywords: keywords) } class func isItalicFont(_ font: UIFont, italicFontName: String) -> Bool { if font.fontName == italicFontName { return true } let keywords = ["italic"] return isSpecialFont(font, keywords: keywords) } class func isSpecialFont(_ font: UIFont, keywords: [String]) -> Bool { let fontName = NSString(string: font.fontName) for keyword in keywords { if fontName.range(of: keyword, options: .caseInsensitive).location != NSNotFound { return true } } return false } class func keyboardWindow() -> UIWindow? { var keyboardWin: UIWindow? UIApplication.shared.windows.forEach { if String(describing: type(of: $0)) == "UITextEffectsWindow" { keyboardWin = $0 return } } return keyboardWin } }
mit
maximveksler/Developing-iOS-8-Apps-with-Swift
lesson-010/Smashtag/Smashtag/Twitter Swift 2.0/User.swift
4
2887
// // User.swift // Twitter // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import Foundation // container to hold data about a Twitter user public struct User: CustomStringConvertible { public let screenName: String public let name: String public let profileImageURL: NSURL? public let verified: Bool public let id: String? public var description: String { let v = verified ? " ✅" : ""; return "@\(screenName) (\(name))\(v)" } // MARK: - Private Implementation init?(data: NSDictionary?) { if let nameFromData = data?.valueForKeyPath(TwitterKey.Name) as? String { if let screenNameFromData = data?.valueForKeyPath(TwitterKey.ScreenName) as? String { name = nameFromData screenName = screenNameFromData id = data?.valueForKeyPath(TwitterKey.ID) as? String verified = data?.valueForKeyPath(TwitterKey.Verified)?.boolValue ?? false if let urlString = data?.valueForKeyPath(TwitterKey.ProfileImageURL) as? String { profileImageURL = NSURL(string: urlString) } else { profileImageURL = nil } // failable initializers are required to initialize all properties before returning failure // (this is probably just a (temporary?) limitation of the implementation of Swift) // however, it appears that (sometimes) you can "return" in the case of success like this // and it avoids the warning (although "return" is sort of weird in an initializer) // (this seems to work even though all the properties are NOT initialized for the "return nil" below) // hopefully in future versions of Swift this will all not be an issue // because you'll be allowed to fail without initializing all properties? return } } // it is possible we will get here without all properties being initialized // hopefully that won't cause a problem even though the compiler does not complain? :) return nil } var asPropertyList: AnyObject { var dictionary = Dictionary<String,String>() dictionary[TwitterKey.Name] = self.name dictionary[TwitterKey.ScreenName] = self.screenName dictionary[TwitterKey.ID] = self.id dictionary[TwitterKey.Verified] = verified ? "YES" : "NO" dictionary[TwitterKey.ProfileImageURL] = profileImageURL?.absoluteString return dictionary } struct TwitterKey { static let Name = "name" static let ScreenName = "screen_name" static let ID = "id_str" static let Verified = "verified" static let ProfileImageURL = "profile_image_url" } }
apache-2.0
shahabc/ProjectNexus
Mobile Buy SDK Sample Apps/Advanced App - ObjC/MessageExtension/BuildOutfitCollectionViewCell.swift
1
424
// // BuildOutfitCollectionViewCell.swift // Mobile Buy SDK Advanced Sample // // Created by Shahab Chaouche on 2017-01-03. // Copyright © 2017 Shopify. All rights reserved. // import UIKit class BuildOutfitCollectionViewCell: UICollectionViewCell { @IBOutlet weak var topsImageView: UIImageView! @IBOutlet weak var pantsImageView: UIImageView! @IBOutlet weak var shoesImageView: UIImageView! }
mit
kousun12/RxSwift
RxSwift/Subjects/BehaviorSubject.swift
4
3908
// // BehaviorSubject.swift // RxSwift // // Created by Krunoslav Zaher on 5/23/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Represents a value that changes over time. Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ public final class BehaviorSubject<Element> : Observable<Element> , SubjectType , ObserverType , LockOwnerType , SynchronizedOnType , SynchronizedSubscribeType , SynchronizedUnsubscribeType , Disposable { public typealias SubjectObserverType = BehaviorSubject<Element> typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType let _lock = NSRecursiveLock() // state private var _disposed = false private var _value: Element private var _observers = Bag<AnyObserver<Element>>() private var _stoppedEvent: Event<Element>? /** Indicates whether the subject has been disposed. */ public var disposed: Bool { return _disposed } /** Initializes a new instance of the subject that caches its last value and starts with the specified value. - parameter value: Initial value sent to observers when no other value has been received by the subject yet. */ public init(value: Element) { _value = value } /** Gets the current value or throws an error. - returns: Latest value. */ public func value() throws -> Element { _lock.lock(); defer { _lock.unlock() } // { if _disposed { throw RxError.DisposedError } if let error = _stoppedEvent?.error { // intentionally throw exception throw error } else { return _value } //} } /** Notifies all subscribed observers about next event. - parameter event: Event to send to the observers. */ public func on(event: Event<E>) { synchronizedOn(event) } func _synchronized_on(event: Event<E>) { if _stoppedEvent != nil || _disposed { return } switch event { case .Next(let value): _value = value case .Error, .Completed: _stoppedEvent = event } _observers.on(event) } /** Subscribes an observer to the subject. - parameter observer: Observer to subscribe to the subject. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ public override func subscribe<O : ObserverType where O.E == Element>(observer: O) -> Disposable { return synchronizedSubscribe(observer) } func _synchronized_subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable { if _disposed { observer.on(.Error(RxError.DisposedError)) return NopDisposable.instance } if let stoppedEvent = _stoppedEvent { observer.on(stoppedEvent) return NopDisposable.instance } let key = _observers.insert(observer.asObserver()) observer.on(.Next(_value)) return SubscriptionDisposable(owner: self, key: key) } func _synchronized_unsubscribe(disposeKey: DisposeKey) { if _disposed { return } _ = _observers.removeKey(disposeKey) } /** Returns observer interface for subject. */ public func asObserver() -> BehaviorSubject<Element> { return self } /** Unsubscribe all observers and release resources. */ public func dispose() { _lock.performLocked { _disposed = true _observers.removeAll() _stoppedEvent = nil } } }
mit
away4m/Vendors
Vendors/Extensions/Set.swift
1
243
// // Set.swift // Pods // // Created by Admin on 11/24/16. // // import Foundation import UIKit public extension Set { public func random() -> Element { return Array(self)[Int(arc4random_uniform(UInt32(self.count)))] } }
mit
karivalkama/Agricola-Scripture-Editor
TranslationEditor/NotesPost.swift
1
2088
// // NotesPost.swift // TranslationEditor // // Created by Mikko Hilpinen on 17.1.2017. // Copyright © 2017 SIL. All rights reserved. // import Foundation // A single post is one persons contribution to a certain notes thread final class NotesPost: Storable { // ATTRIBUTES ------------ static let type = "post" static let PROPERTY_THREAD = "thread" static let PROPERTY_CREATED = "created" let threadId: String let creatorId: String let created: TimeInterval let originalCommentId: String? var content: String // COMP. PROPERTIES -------- static var idIndexMap: IdIndexMap { return NotesThread.idIndexMap.makeChildPath(parentPathName: PROPERTY_THREAD, childPath: [PROPERTY_CREATED]) } var idProperties: [Any] { return [threadId, created] } var properties: [String : PropertyValue] { return ["creator": creatorId.value, "content": content.value, "original_comment": originalCommentId.value] } var collectionId: String { return ParagraphNotes.collectionId(fromId: threadId) } var chapterIndex: Int { return ParagraphNotes.chapterIndex(fromId: threadId) } var noteId: String { return NotesThread.noteId(fromId: threadId) } var threadCreated: TimeInterval { return NotesThread.created(fromId: threadId) } // INIT -------------------- init(threadId: String, creatorId: String, content: String, created: TimeInterval = Date().timeIntervalSince1970, originalCommentId: String? = nil) { self.threadId = threadId self.creatorId = creatorId self.content = content self.created = created self.originalCommentId = originalCommentId } static func create(from properties: PropertySet, withId id: Id) -> NotesPost { return NotesPost(threadId: id[PROPERTY_THREAD].string(), creatorId: properties["creator"].string(), content: properties["content"].string(), created: id[PROPERTY_CREATED].time(), originalCommentId: properties["original_comment"].string()) } // IMPLEMENTED METHODS ---- func update(with properties: PropertySet) { if let content = properties["content"].string { self.content = content } } }
mit
danpratt/On-the-Map
On the Map/OTMMapDataModel.swift
1
882
// // OTMMapDataModel.swift // On the Map // // Created by Daniel Pratt on 4/6/17. // Copyright © 2017 Daniel Pratt. All rights reserved. // import Foundation import MapKit // MARK: - OTMMapDataModel Class class OTMMapDataModel { // MARK: - Properties // Map Data var mapData: [OTMMapData]? = nil // Update info var mapPinDataUpdated: Bool = false var listDataUpdated: Bool = false // User specific info var userID: String? = nil var firstName: String? = nil var lastName: String? = nil var usersExistingObjectID: String? = nil var userLocation: CLLocationCoordinate2D? // MARK: Shared Instance class func mapModel() -> OTMMapDataModel { struct Singleton { static var sharedInstance = OTMMapDataModel() } return Singleton.sharedInstance } }
mit
melbrng/TrackApp
Track/Track/Footprint.swift
1
930
// // Footprint.swift // Track // // Created by Melissa Boring on 8/9/16. // Copyright © 2016 melbo. All rights reserved. // import MapKit class Footprint: NSObject, MKAnnotation { var coordinate: CLLocationCoordinate2D var image: UIImage? var title: String? var subtitle: String? var trackUID: String? var footprintUID: String? var imagePath: String? init(coordinate: CLLocationCoordinate2D, image: UIImage) { self.coordinate = coordinate self.image = image } init(coordinate: CLLocationCoordinate2D, trackUID: String, footUID: String, title: String, subtitle: String, image: UIImage, imagePath: String) { self.coordinate = coordinate self.trackUID = trackUID self.footprintUID = footUID self.title = title self.subtitle = subtitle self.image = image self.imagePath = imagePath } }
mit
niunaruto/DeDaoAppSwift
DeDaoSwift/DeDaoSwift/Home/Model/DDHomeSubjectModel.swift
1
1230
// // DDHomeSubjectModel.swift // DeDaoSwift // // Created by niuting on 2017/3/6. // Copyright © 2017年 niuNaruto. All rights reserved. // import UIKit import ObjectMapper class DDHomeSubjectListModel: Mappable { var m_type = 0 var m_title = "" var m_url = "" var m_img = "" var m_isSubscribe = 0 var m_id = "" var m_from = "" required init?(map : Map) { } func mapping(map:Map) { m_type <- map["m_type"] m_id <- map["m_id"] m_from <- map["m_from"] m_title <- map["m_title"] m_url <- map["m_url"] m_img <- map["m_img"] m_isSubscribe <- map["m_isSubscribe"] } } class DDHomeSubjectModel: Mappable { var count = 0 var title = "" var rightTitle = "" var list : Array<DDHomeSubjectListModel>? required init?(map : Map) { } func mapping(map:Map) { count <- map["count"] title <- map["title"] rightTitle <- map["rightTitle"] list <- map["list"] } }
mit
niunaruto/DeDaoAppSwift
testSwift/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift
20
6484
// // CombineLatest+Collection.swift // RxSwift // // Created by Krunoslav Zaher on 8/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) - parameter resultSelector: Function to invoke whenever any of the sources produces an element. - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ public static func combineLatest<Collection: Swift.Collection>(_ collection: Collection, resultSelector: @escaping ([Collection.Element.Element]) throws -> Element) -> Observable<Element> where Collection.Element: ObservableType { return CombineLatestCollectionType(sources: collection, resultSelector: resultSelector) } /** Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element. - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) - returns: An observable sequence containing the result of combining elements of the sources. */ public static func combineLatest<Collection: Swift.Collection>(_ collection: Collection) -> Observable<[Element]> where Collection.Element: ObservableType, Collection.Element.Element == Element { return CombineLatestCollectionType(sources: collection, resultSelector: { $0 }) } } final private class CombineLatestCollectionTypeSink<Collection: Swift.Collection, Observer: ObserverType> : Sink<Observer> where Collection.Element: ObservableConvertibleType { typealias Result = Observer.Element typealias Parent = CombineLatestCollectionType<Collection, Result> typealias SourceElement = Collection.Element.Element let _parent: Parent let _lock = RecursiveLock() // state var _numberOfValues = 0 var _values: [SourceElement?] var _isDone: [Bool] var _numberOfDone = 0 var _subscriptions: [SingleAssignmentDisposable] init(parent: Parent, observer: Observer, cancel: Cancelable) { self._parent = parent self._values = [SourceElement?](repeating: nil, count: parent._count) self._isDone = [Bool](repeating: false, count: parent._count) self._subscriptions = [SingleAssignmentDisposable]() self._subscriptions.reserveCapacity(parent._count) for _ in 0 ..< parent._count { self._subscriptions.append(SingleAssignmentDisposable()) } super.init(observer: observer, cancel: cancel) } func on(_ event: Event<SourceElement>, atIndex: Int) { self._lock.lock(); defer { self._lock.unlock() } // { switch event { case .next(let element): if self._values[atIndex] == nil { self._numberOfValues += 1 } self._values[atIndex] = element if self._numberOfValues < self._parent._count { let numberOfOthersThatAreDone = self._numberOfDone - (self._isDone[atIndex] ? 1 : 0) if numberOfOthersThatAreDone == self._parent._count - 1 { self.forwardOn(.completed) self.dispose() } return } do { let result = try self._parent._resultSelector(self._values.map { $0! }) self.forwardOn(.next(result)) } catch let error { self.forwardOn(.error(error)) self.dispose() } case .error(let error): self.forwardOn(.error(error)) self.dispose() case .completed: if self._isDone[atIndex] { return } self._isDone[atIndex] = true self._numberOfDone += 1 if self._numberOfDone == self._parent._count { self.forwardOn(.completed) self.dispose() } else { self._subscriptions[atIndex].dispose() } } // } } func run() -> Disposable { var j = 0 for i in self._parent._sources { let index = j let source = i.asObservable() let disposable = source.subscribe(AnyObserver { event in self.on(event, atIndex: index) }) self._subscriptions[j].setDisposable(disposable) j += 1 } if self._parent._sources.isEmpty { do { let result = try self._parent._resultSelector([]) self.forwardOn(.next(result)) self.forwardOn(.completed) self.dispose() } catch let error { self.forwardOn(.error(error)) self.dispose() } } return Disposables.create(_subscriptions) } } final private class CombineLatestCollectionType<Collection: Swift.Collection, Result>: Producer<Result> where Collection.Element: ObservableConvertibleType { typealias ResultSelector = ([Collection.Element.Element]) throws -> Result let _sources: Collection let _resultSelector: ResultSelector let _count: Int init(sources: Collection, resultSelector: @escaping ResultSelector) { self._sources = sources self._resultSelector = resultSelector self._count = self._sources.count } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
mit
lacyrhoades/SwiftSingleton
SingletonTests/SingletonBTests.swift
7
1494
// // SingletonBTests.swift // Singleton // // Created by Hermes Pique on 6/9/14. // Copyright (c) 2014 Hermes Pique. All rights reserved. // import XCTest import Singleton class SingletonBTests: XCTestCase { func testSharedInstance() { let instance = SingletonB.sharedInstance XCTAssertNotNil(instance, "") } func testSharedInstance_Unique() { let instance1 = SingletonB() let instance2 = SingletonB.sharedInstance XCTAssertFalse(instance1 === instance2) } func testSharedInstance_Twice() { let instance1 = SingletonB.sharedInstance let instance2 = SingletonB.sharedInstance XCTAssertTrue(instance1 === instance2) } func testSharedInstance_ThreadSafety() { var instance1 : SingletonB! var instance2 : SingletonB! let expectation1 = expectationWithDescription("Instance 1") dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { instance1 = SingletonB.sharedInstance expectation1.fulfill() } let expectation2 = expectationWithDescription("Instance 2") dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { instance2 = SingletonB.sharedInstance expectation2.fulfill() } waitForExpectationsWithTimeout(1.0) { (_) in XCTAssertTrue(instance1 === instance2) } } }
apache-2.0
gregomni/swift
test/Generics/minimal_conformances_compare_concrete.swift
3
1738
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on -disable-requirement-machine-concrete-contraction 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on -disable-requirement-machine-concrete-contraction -dump-requirement-machine 2>&1 | %FileCheck %s --check-prefix=RULE protocol P {} class Base : P {} class Derived : Base {} struct G<X> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=G // CHECK-NEXT: Generic signature: <X where X == Derived> extension G where X : Base, X : P, X == Derived {} // RULE: + superclass: τ_0_0 Base // RULE: + conforms_to: τ_0_0 P // RULE: + same_type: τ_0_0 Derived // RULE: Rewrite system: { // RULE-NEXT: - [P].[P] => [P] [permanent] // RULE-NEXT: - τ_0_0.[superclass: Base] => τ_0_0 [explicit] // RULE-NEXT: - τ_0_0.[P] => τ_0_0 [explicit] // RULE-NEXT: - τ_0_0.[concrete: Derived] => τ_0_0 [explicit] // RULE-NEXT: - τ_0_0.[layout: _NativeClass] => τ_0_0 // RULE-NEXT: - τ_0_0.[superclass: Derived] => τ_0_0 // RULE-NEXT: - τ_0_0.[concrete: Derived : P] => τ_0_0 // RULE-NEXT: - τ_0_0.[concrete: Base : P] => τ_0_0 // RULE-NEXT: } // Notes: // // - concrete contraction kills the 'X : P' requirement before building the // rewrite system so this test passes trivially. // // - without concrete contraction, we used to hit a problem where the sort // in the minimal conformances algorithm would hit the unordered concrete // conformances [concrete: Derived : P] vs [concrete: Base : P].
apache-2.0