repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
abdullahselek/Lighty
Sources/LightyLogger.swift
1
5454
// // LightyLogger.swift // Lighty // // Copyright © 2016 Abdullah Selek. 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 #if os(Linux) import Glibc #endif /** Message type for logging */ public enum LightyMessageType: String { case verbose = "💜 VERBOSE" case debug = "💙 DEBUG" case info = "💚 INFO" case warn = "💛 WARN" case error = "❤️ ERROR" } /** Main class for log mechanism */ open class LightyLogger { /** Singleton instance of LightyLogger */ public static let sharedInstance: LightyLogger = LightyLogger() /** DateFormatter used in logs to format log date and time */ open var dateFormatter: DateFormatter! /** String used to separate log message */ open var separator = " | " /** Enable/disable formatted date for logs */ open var enableDate = true /** Enable/disable logging */ open var enable = true internal init() { dateFormatter = createDateFormatter() } internal func createDateFormatter() -> DateFormatter { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .short dateFormatter.timeStyle = .medium return dateFormatter } internal func getFormattedDate() -> String { if enableDate { return dateFormatter.string(from: Date()) } return "" } internal func threadName() -> String { #if os(Linux) return "" #else if Thread.isMainThread { return "" } else { let threadName = Thread.current.name if let threadName = threadName, !threadName.isEmpty { return threadName } else { return String(format: "%@%p", separator, Thread.current) } } #endif } /** Main function print logs - parameter type: LightyMessageType - parameter message: Message string to log - parameter file: String internal parameter to detect class file which uses log function - parameter function: String internal parameter to detect function which uses log function - parameter line: Int string internal parameter to detect line number which uses log function */ open func log(type: LightyMessageType, message: String, file: String = #file, function: String = #function, line: Int = #line) { if enable { let fileUrl = URL(fileURLWithPath: file) let fileExtension = fileUrl.pathExtension let fileName = fileUrl.deletingPathExtension().lastPathComponent let trackedString = "\(fileName).\(fileExtension):\(line) \(function)" print(type.rawValue + " " + getFormattedDate() + separator + trackedString + separator + message + threadName()) } } /** Function for print debug logs - parameter type: LightyMessageType - parameter message: Message string to log - parameter file: String internal parameter to detect class file which uses log function - parameter function: String internal parameter to detect function which uses log function - parameter line: Int string internal parameter to detect line number which uses log function */ open func dlog(type: LightyMessageType, message: String, file: String = #file, function: String = #function, line: Int = #line) { #if DEBUG && enable let fileUrl = URL(fileURLWithPath: file) let fileExtension = fileUrl.pathExtension let fileName = fileUrl.deletingPathExtension().lastPathComponent let trackedString = "\(fileName).\(fileExtension):\(line) \(function)" print(type.rawValue + " " + getFormattedDate() + separator + trackedString + separator + message + threadName()) #endif } }
mit
217f9dfd6594bfe2411157427ccd8c6e
31.363095
99
0.595365
5.227885
false
false
false
false
aleufms/JeraUtils
JeraUtils/Form/MaterialCheckFormView.swift
1
2531
// // MaterialCheckFormView.swift // Glambox // // Created by Alessandro Nakamuta on 2/17/16. // Copyright © 2016 Glambox. All rights reserved. // import UIKit import Material import FontAwesome_swift //import Tactile import RxSwift public class MaterialCheckFormView: UIView { public class func instantiateFromNib() -> MaterialCheckFormView { let podBundle = NSBundle(forClass: self) if let bundleURL = podBundle.URLForResource("JeraUtils", withExtension: "bundle") { if let bundle = NSBundle(URL: bundleURL) { return bundle.loadNibNamed("MaterialCheckFormView", owner: nil, options: nil)!.first as! MaterialCheckFormView }else { assertionFailure("Could not load the bundle") } } assertionFailure("Could not create a path to the bundle") return MaterialCheckFormView() } @IBOutlet public weak var checkImageView: UIImageView! @IBOutlet public weak var textLabel: UILabel! let disposeBag = DisposeBag() public let rx_checked = Variable(false) public var checkedImage = UIImage.fontAwesomeIconWithName(FontAwesome.CheckSquareO, textColor: UIColor.grayColor(), size: CGSize(width: 36, height: 36)).imageWithRenderingMode(.AlwaysTemplate) { didSet { refreshCheckImageView() } } public var uncheckedImage = UIImage.fontAwesomeIconWithName(FontAwesome.SquareO, textColor: UIColor.grayColor(), size: CGSize(width: 36, height: 36)).imageWithRenderingMode(.AlwaysTemplate) { didSet { refreshCheckImageView() } } override public func awakeFromNib() { super.awakeFromNib() refreshCheckImageView() self.userInteractionEnabled = true self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(MaterialCheckFormView.toogleCheckedValue))) // self.tap { [weak self] (_) -> Void in // if let strongSelf = self { // strongSelf.rx_checked.value = !strongSelf.rx_checked.value // } // } rx_checked.asObservable().distinctUntilChanged().subscribeNext { [weak self] (_) -> Void in self?.refreshCheckImageView() }.addDisposableTo(disposeBag) } @objc private func toogleCheckedValue(){ rx_checked.value = !rx_checked.value } private func refreshCheckImageView() { checkImageView.image = rx_checked.value ? checkedImage : uncheckedImage } }
mit
8937ef9dda16ab40a14d87ccfc07d776
32.289474
198
0.662055
4.828244
false
false
false
false
qutheory/vapor
Sources/Vapor/Authentication/SessionAuthenticatable.swift
1
2955
/// Helper for creating authentication middleware in conjunction with `SessionsMiddleware`. public protocol SessionAuthenticator: Authenticator { associatedtype User: SessionAuthenticatable /// Authenticate a model with the supplied ID. func authenticate(sessionID: User.SessionID, for request: Request) -> EventLoopFuture<Void> } extension SessionAuthenticator { public func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> { // if the user has already been authenticated // by a previous middleware, continue if request.auth.has(User.self) { return next.respond(to: request) } let future: EventLoopFuture<Void> if let aID = request.session.authenticated(User.self) { // try to find user with id from session future = self.authenticate(sessionID: aID, for: request) } else { // no need to authenticate future = request.eventLoop.makeSucceededFuture(()) } // map the auth future to a resopnse return future.flatMap { _ in // respond to the request return next.respond(to: request).map { response in if let user = request.auth.get(User.self) { // if a user has been authed (or is still authed), store in the session request.session.authenticate(user) } else if request.hasSession { // if no user is authed, it's possible they've been unauthed. // remove from session. request.session.unauthenticate(User.self) } return response } } } } /// Models conforming to this protocol can have their authentication /// status cached using `SessionAuthenticator`. public protocol SessionAuthenticatable: Authenticatable { /// Session identifier type. associatedtype SessionID: LosslessStringConvertible /// Unique session identifier. var sessionID: SessionID { get } } private extension SessionAuthenticatable { static var sessionName: String { return "\(Self.self)" } } extension Session { /// Authenticates the model into the session. public func authenticate<A>(_ a: A) where A: SessionAuthenticatable { self.data["_" + A.sessionName + "Session"] = a.sessionID.description } /// Un-authenticates the model from the session. public func unauthenticate<A>(_ a: A.Type) where A: SessionAuthenticatable { self.data["_" + A.sessionName + "Session"] = nil } /// Returns the authenticatable type's ID if it exists /// in the session data. public func authenticated<A>(_ a: A.Type) -> A.SessionID? where A: SessionAuthenticatable { self.data["_" + A.sessionName + "Session"] .flatMap { A.SessionID.init($0) } } }
mit
32b9e44ace2c93b75cd2b3ac2522c80d
34.60241
103
0.626058
4.868204
false
false
false
false
WalterCreazyBear/Swifter30
UIElements/UIElements/ViewController.swift
1
2349
// // ViewController.swift // UIElements // // Created by Bear on 2017/6/20. // Copyright © 2017年 Bear. All rights reserved. // import UIKit class ViewController: UIViewController { let cellIdentify = "cellIdentify" let elements:[String] = { let eles = ["Label","Text","Gesture","Massive"] return eles }() let tableView :UITableView = { let tableView:UITableView = UITableView.init() return tableView }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.title = "UIElements" self.setupTableView() } fileprivate func setupTableView(){ self.tableView.frame = self.view.bounds self.tableView.delegate = self self.tableView.dataSource = self self.tableView.backgroundColor = UIColor.white self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentify) self.view.addSubview(self.tableView) } } extension ViewController:UITableViewDelegate,UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.elements.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentify) cell?.textLabel?.text = self.elements[indexPath.row] return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var vc:UIViewController?; if(elements[indexPath.row] == "Label") { vc = UILabelViewController() } else if(elements[indexPath.row] == "Text") { vc = UITextViewController() } else if(elements[indexPath.row] == "Gesture") { vc = GetureViewController() } else if(elements[indexPath.row] == "Massive") { vc = UIMassiveViewController() } guard vc != nil else { return; } self.navigationController?.pushViewController(vc!, animated: true) } }
mit
65b4d5f06106dabbac0a68d7bc1bf7ff
27.26506
100
0.614237
4.918239
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/ProjectNotificationCellViewModel.swift
1
3998
import KsApi import Prelude import ReactiveExtensions import ReactiveSwift public protocol ProjectNotificationCellViewModelInputs { /// Call with the initial cell notification value. func configureWith(notification: ProjectNotification) /// Call when the notification switch is tapped. func notificationTapped(on: Bool) } public protocol ProjectNotificationCellViewModelOutputs { /// Emits the project name. var name: Signal<String, Never> { get } /// Emits true when the notification is turned on, false otherwise. var notificationOn: Signal<Bool, Never> { get } /// Emits when an update error has occurred and a message should be displayed. var notifyDelegateOfSaveError: Signal<String, Never> { get } } public protocol ProjectNotificationCellViewModelType { var inputs: ProjectNotificationCellViewModelInputs { get } var outputs: ProjectNotificationCellViewModelOutputs { get } } public final class ProjectNotificationCellViewModel: ProjectNotificationCellViewModelType, ProjectNotificationCellViewModelInputs, ProjectNotificationCellViewModelOutputs { public init() { let notification = self.notificationProperty.signal.skipNil() .map(cached(notification:)) self.name = notification.map { $0.project.name } let toggledNotification = notification .takePairWhen(self.notificationTappedProperty.signal) .map { notification, on -> ProjectNotification in let n = (notification |> ProjectNotification.lens.email .~ on |> ProjectNotification.lens.mobile .~ on) return n } let updateEvent = toggledNotification .switchMap { AppEnvironment.current.apiService.updateProjectNotification($0) .ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler) .materialize() } self.notifyDelegateOfSaveError = updateEvent.errors() .map { env in env.errorMessages.first ?? Strings.profile_settings_error() } let previousNotificationOnError = notification .switchMap { .merge( SignalProducer(value: $0), SignalProducer(toggledNotification.skipRepeats()) ) } .combinePrevious() .takeWhen(self.notifyDelegateOfSaveError) .map { previous, _ in previous } Signal.merge(updateEvent.values(), previousNotificationOnError) .observeValues(cache(notification:)) self.notificationOn = Signal.merge( notification, toggledNotification, previousNotificationOnError ) .map { $0.email && $0.mobile } .skipRepeats() } fileprivate let notificationProperty = MutableProperty<ProjectNotification?>(nil) public func configureWith(notification: ProjectNotification) { self.notificationProperty.value = notification } fileprivate let notificationTappedProperty = MutableProperty(false) public func notificationTapped(on: Bool) { self.notificationTappedProperty.value = on } public let name: Signal<String, Never> public let notificationOn: Signal<Bool, Never> public let notifyDelegateOfSaveError: Signal<String, Never> public var inputs: ProjectNotificationCellViewModelInputs { return self } public var outputs: ProjectNotificationCellViewModelOutputs { return self } } private func cacheKey(forNotification notification: ProjectNotification) -> String { return "project_notification_view_model_notification_\(notification.id)" } private func cache(notification: ProjectNotification) { let key = cacheKey(forNotification: notification) AppEnvironment.current.cache[key] = notification.email && notification.mobile } private func cached(notification: ProjectNotification) -> ProjectNotification { let key = cacheKey(forNotification: notification) let on = AppEnvironment.current.cache[key] as? Bool return notification |> ProjectNotification.lens.email .~ (on ?? notification.email) |> ProjectNotification.lens.mobile .~ (on ?? notification.mobile) }
apache-2.0
f91d92583197b93eb60c22e4ffc3c443
33.465517
99
0.743122
4.917589
false
false
false
false
haranicle/RealmRelationsSample
Carthage/Checkouts/realm-cocoa/examples/ios/swift/TableView/TableViewController.swift
2
4219
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import UIKit import Realm class DemoObject: RLMObject { dynamic var title = "" dynamic var date = NSDate() } class Cell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: .Subtitle, reuseIdentifier: reuseIdentifier) } required init(coder: NSCoder) { fatalError("NSCoding not supported") } } class TableViewController: UITableViewController { var array = DemoObject.allObjects().sortedResultsUsingProperty("date", ascending: true) var notificationToken: RLMNotificationToken? override func viewDidLoad() { super.viewDidLoad() setupUI() // Set realm notification block notificationToken = RLMRealm.defaultRealm().addNotificationBlock { note, realm in self.tableView.reloadData() } tableView.reloadData() } // UI func setupUI() { tableView.registerClass(Cell.self, forCellReuseIdentifier: "cell") self.title = "TableView" self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "BG Add", style: .Plain, target: self, action: "backgroundAdd") self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "add") } // Table view data source override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { return Int(array.count) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as Cell let object = array[UInt(indexPath.row)] as DemoObject cell.textLabel?.text = object.title cell.detailTextLabel?.text = object.date.description return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let realm = RLMRealm.defaultRealm() realm.beginWriteTransaction() realm.deleteObject(array[UInt(indexPath.row)] as RLMObject) realm.commitWriteTransaction() } } // Actions func backgroundAdd() { let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) // Import many items in a background thread dispatch_async(queue) { // Get new realm and table since we are in a new thread let realm = RLMRealm.defaultRealm() realm.beginWriteTransaction() for index in 0..<5 { // Add row via dictionary. Order is ignored. DemoObject.createInRealm(realm, withObject: ["title": TableViewController.randomString(), "date": TableViewController.randomDate()]) } realm.commitWriteTransaction() } } func add() { let realm = RLMRealm.defaultRealm() realm.beginWriteTransaction() DemoObject.createInRealm(realm, withObject: [TableViewController.randomString(), TableViewController.randomDate()]) realm.commitWriteTransaction() } // Helpers class func randomString() -> String { return "Title \(arc4random())" } class func randomDate() -> NSDate { return NSDate(timeIntervalSince1970: NSTimeInterval(arc4random())) } }
mit
2cc4e5a5b36deace67f83a173a7567c7
33.300813
157
0.652287
5.347275
false
false
false
false
Catteno/SwiftyIO
SwiftyIO/BaseDataContext.swift
2
7377
// // BaseDataContext.swift // CoreDataContext // // Created by Rafael Veronezi on 9/30/14. // Copyright (c) 2014 Ravero. All rights reserved. // import Foundation import CoreData public class BaseDataContext : NSObject { // // MARK: - Properties var resourceName: String var allowAutomaticMigrations = false // // MARK: - Initializers public init(resourceName: String) { self.resourceName = resourceName } // // MARK: - Utilitarian Methods /** Clear the current database of this context. */ public func clearDatabase() -> Bool { if let persistentStore = self.persistentStore { // First tell the persistent store coordinator that the current store will be clear. do { try self.persistentStoreCoordinator?.removePersistentStore(persistentStore) } catch let error as NSError { NSLog("Error trying to remove Persistent Store: \(error.localizedDescription)\nError data: \(error)") return false } // Delete the data files if let path = storeUrl.path where NSFileManager.defaultManager().fileExistsAtPath(path) { do { try NSFileManager.defaultManager().removeItemAtURL(self.storeUrl) } catch let error as NSError { NSLog("Error trying to remove data files: \(error.localizedDescription)\nError data: \(error)") return false } } if let path = storeUrl_wal.path where NSFileManager.defaultManager().fileExistsAtPath(path) { do { try NSFileManager.defaultManager().removeItemAtURL(self.storeUrl_wal) } catch let error as NSError { NSLog("Error trying to remove WAL file: \(error.localizedDescription)\nError data: \(error)") return false } } if let path = storeUrl_shm.path where NSFileManager.defaultManager().fileExistsAtPath(path) { do { try NSFileManager.defaultManager().removeItemAtURL(self.storeUrl_shm) } catch let error as NSError { NSLog("Error trying to remove SHM file: \(error.localizedDescription)\nError data: \(error)") return false } } // Re-create the persistent store coordinator self.createPersistentStore(self.persistentStoreCoordinator!) return true } return false } /** A simple utilitarian method to print the path of the SQLite file of this instance. */ public func printDatabasePath() { print("SwiftyIO - Model '\(resourceName)' database path: \(self.storeUrl)") } // // MARK: - Core Data Stack private var persistentStore: NSPersistentStore? lazy private var storeUrl: NSURL = { return self.applicationDocumentsDirectory.URLByAppendingPathComponent("\(self.resourceName).sqlite") }() lazy private var storeUrl_wal: NSURL = { return self.applicationDocumentsDirectory.URLByAppendingPathComponent("\(self.resourceName).sqlite-wal") }() lazy private var storeUrl_shm: NSURL = { return self.applicationDocumentsDirectory.URLByAppendingPathComponent("\(self.resourceName).sqlite-shm") }() lazy private var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy private var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource(self.resourceName, withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy private var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) if let coordinator = coordinator { self.createPersistentStore(coordinator) } return coordinator }() lazy public var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // // MARK: - Support Methods private func createPersistentStore(coordinator: NSPersistentStoreCoordinator) { let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("\(self.resourceName).sqlite") let failureReason = "There was an error creating or loading the application's saved data." var options: [NSObject: AnyObject]? = nil if allowAutomaticMigrations { options = [ NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true ] } do { self.persistentStore = try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options) } catch let error as NSError { // Report any error we got. var dict = [NSObject: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error let customError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. fatalError("Unresolved error \(customError), \(customError.userInfo)") } } // // MARK: - Core Data Saving support public func saveContext() throws { try self.managedObjectContext?.save() } }
mit
a97a2d473c4e0cdd1a24ebe486397d66
41.641618
290
0.641182
6.002441
false
false
false
false
castial/Quick-Start-iOS
Pods/HYAlertController/HYAlertController/HYAlertView.swift
1
5241
// // HYAlertView.swift // Quick-Start-iOS // // Created by work on 2016/11/4. // Copyright © 2016年 hyyy. All rights reserved. // import UIKit protocol HYAlertViewDelegate { /// 点击事件 func clickAlertItemHandler() } class HYAlertView: UIView { lazy var alertTable: UITableView = { let tableView: UITableView = UITableView (frame: CGRect.zero, style: .plain) tableView.backgroundColor = UIColor.white tableView.isScrollEnabled = false return tableView }() lazy var titleView: HYTitleView = { let view: HYTitleView = HYTitleView (frame: CGRect.zero) return view }() var alertTitle: String = String () var alertMessage: String = String () var delegate: HYAlertViewDelegate? fileprivate var alertDataArray: NSArray = NSArray () fileprivate var cancelDataArray: NSArray = NSArray () override init(frame: CGRect) { super.init(frame: frame) initUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - LifeCycle extension HYAlertView { fileprivate func initUI() { self.alertTable.delegate = self self.alertTable.dataSource = self self.addSubview(self.alertTable) } override func layoutSubviews() { super.layoutSubviews() if self.alertTitle.characters.count > 0 || self.alertMessage.characters.count > 0 { self.titleView.refrenshTitleView(title: self.alertTitle, message: self.alertMessage) self.titleView.frame = CGRect (x: 0, y: 0, width: self.bounds.size.width, height: HYTitleView.titleViewHeight(title: self.alertTitle, message: self.alertMessage, width: self.bounds.size.width)) self.alertTable.tableHeaderView = self.titleView }else { self.alertTable.tableHeaderView = UIView () } self.alertTable.frame = self.bounds } } // MARK: - Public Methods extension HYAlertView { open func refreshDate(dataArray: NSArray, cancelArray: NSArray, title: String, message: String) { self.alertDataArray = dataArray self.cancelDataArray = cancelArray self.alertTable.reloadData() } } // MARK: - UITableViewDataSource extension HYAlertView: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return self.alertDataArray.count }else { return 1 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell: HYAlertCell = HYAlertCell.cellWithTableView(tableView: tableView) let action: HYAlertAction = self.alertDataArray.object(at: indexPath.row) as! HYAlertAction cell.titleLabel.text = action.title if action.style == .destructive { cell.titleLabel.textColor = UIColor.red } cell.cellIcon.image = action.image return cell }else { let cell: HYAlertCell = HYAlertCell.cellWithTableView(tableView: tableView) if self.cancelDataArray.count > 0 { let action: HYAlertAction = self.cancelDataArray.object(at: indexPath.row) as! HYAlertAction cell.titleLabel.text = action.title cell.cellIcon.image = action.image }else { cell.titleLabel.text = HY_Constants.defaultCancelText } return cell } } } // MARK: - UITableViewDelegate extension HYAlertView: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 1 { return 10 } return 0.1 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return HYAlertCell.cellHeight() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == 0 { let action: HYAlertAction = self.alertDataArray.object(at: indexPath.row) as! HYAlertAction action.myHandler(action) }else { if self.cancelDataArray.count > 0 { let action: HYAlertAction = self.cancelDataArray.object(at: indexPath.row) as! HYAlertAction action.myHandler(action) } } delegate?.clickAlertItemHandler() } }
mit
10f8614fa7542ef3fac36a217994169a
32.741935
110
0.59044
5.038536
false
false
false
false
blocktree/BitcoinSwift
BitcoinSwift/Sources/core/BTCOpcode.swift
1
14136
// // BTCOpcode.swift // BitcoinSwift // // Created by Chance on 2017/4/26. // // import Foundation //MARK: 脚本语言指令集 //https://en.bitcoin.it/wiki/Script#Constants public enum BTCOpcode: UInt8 { // 1. Operators pushing data on stack. // Push 1 byte 0x00 on the stack case OP_0 = 0x00 //case OP_FALSE = 0x00 // Any opcode with value < PUSHDATA1 is a length of the string to be pushed on the stack. // So opcode 0x01 is followed by 1 byte of data, 0x09 by 9 bytes and so on up to 0x4b (75 bytes) // PUSHDATA<N> opcode is followed by N-byte length of the string that follows. case OP_PUSHDATA1 = 0x4c // followed by a 1-byte length of the string to push (allows pushing 0..255 bytes). case OP_PUSHDATA2 = 0x4d // followed by a 2-byte length of the string to push (allows pushing 0..65535 bytes). case OP_PUSHDATA4 = 0x4e // followed by a 4-byte length of the string to push (allows pushing 0..4294967295 bytes). case OP_1NEGATE = 0x4f // pushes -1 number on the stack case OP_RESERVED = 0x50 // Not assigned. If executed, transaction is invalid. // OP_<N> pushes number <N> on the stack case OP_1 = 0x51 //case OP_TRUE = 0x51 case OP_2 = 0x52 case OP_3 = 0x53 case OP_4 = 0x54 case OP_5 = 0x55 case OP_6 = 0x56 case OP_7 = 0x57 case OP_8 = 0x58 case OP_9 = 0x59 case OP_10 = 0x5a case OP_11 = 0x5b case OP_12 = 0x5c case OP_13 = 0x5d case OP_14 = 0x5e case OP_15 = 0x5f case OP_16 = 0x60 // 2. Control flow operators case OP_NOP = 0x61 // Does nothing case OP_VER = 0x62 // Not assigned. If executed, transaction is invalid. // BitcoinQT executes all operators from OP_IF to OP_ENDIF even inside "non-executed" branch (to keep track of nesting). // Since OP_VERIF and OP_VERNOTIF are not assigned, even inside a non-executed branch they will fall in "default:" switch case // and cause the script to fail. Some other ops like OP_VER can be present inside non-executed branch because they'll be skipped. case OP_IF = 0x63 // If the top stack value is not 0, the statements are executed. The top stack value is removed. case OP_NOTIF = 0x64 // If the top stack value is 0, the statements are executed. The top stack value is removed. case OP_VERIF = 0x65 // Not assigned. Script is invalid with that opcode (even if inside non-executed branch). case OP_VERNOTIF = 0x66 // Not assigned. Script is invalid with that opcode (even if inside non-executed branch). case OP_ELSE = 0x67 // Executes code if the previous OP_IF or OP_NOTIF was not executed. case OP_ENDIF = 0x68 // Finishes if/else block case OP_VERIFY = 0x69 // Removes item from the stack if it's not 0x00 or 0x80 (negative zero). Otherwise, marks script as invalid. case OP_RETURN = 0x6a // Marks transaction as invalid. // Stack ops case OP_TOALTSTACK = 0x6b // Moves item from the stack to altstack case OP_FROMALTSTACK = 0x6c // Moves item from the altstack to stack case OP_2DROP = 0x6d case OP_2DUP = 0x6e case OP_3DUP = 0x6f case OP_2OVER = 0x70 case OP_2ROT = 0x71 case OP_2SWAP = 0x72 case OP_IFDUP = 0x73 case OP_DEPTH = 0x74 case OP_DROP = 0x75 case OP_DUP = 0x76 case OP_NIP = 0x77 case OP_OVER = 0x78 case OP_PICK = 0x79 case OP_ROLL = 0x7a case OP_ROT = 0x7b case OP_SWAP = 0x7c case OP_TUCK = 0x7d // Splice ops case OP_CAT = 0x7e // Disabled opcode. If executed, transaction is invalid. case OP_SUBSTR = 0x7f // Disabled opcode. If executed, transaction is invalid. case OP_LEFT = 0x80 // Disabled opcode. If executed, transaction is invalid. case OP_RIGHT = 0x81 // Disabled opcode. If executed, transaction is invalid. case OP_SIZE = 0x82 // Bit logic case OP_INVERT = 0x83 // Disabled opcode. If executed, transaction is invalid. case OP_AND = 0x84 // Disabled opcode. If executed, transaction is invalid. case OP_OR = 0x85 // Disabled opcode. If executed, transaction is invalid. case OP_XOR = 0x86 // Disabled opcode. If executed, transaction is invalid. case OP_EQUAL = 0x87 // Last two items are removed from the stack and compared. Result (true or false) is pushed to the stack. case OP_EQUALVERIFY = 0x88 // Same as OP_EQUAL, but removes the result from the stack if it's true or marks script as invalid. case OP_RESERVED1 = 0x89 // Disabled opcode. If executed, transaction is invalid. case OP_RESERVED2 = 0x8a // Disabled opcode. If executed, transaction is invalid. // Numeric case OP_1ADD = 0x8b // adds 1 to last item, pops it from stack and pushes result. case OP_1SUB = 0x8c // substracts 1 to last item, pops it from stack and pushes result. case OP_2MUL = 0x8d // Disabled opcode. If executed, transaction is invalid. case OP_2DIV = 0x8e // Disabled opcode. If executed, transaction is invalid. case OP_NEGATE = 0x8f // negates the number, pops it from stack and pushes result. case OP_ABS = 0x90 // replaces number with its absolute value case OP_NOT = 0x91 // replaces number with True if it's zero, False otherwise. case OP_0NOTEQUAL = 0x92 // replaces number with True if it's not zero, False otherwise. case OP_ADD = 0x93 // (x y -- x+y) case OP_SUB = 0x94 // (x y -- x-y) case OP_MUL = 0x95 // Disabled opcode. If executed, transaction is invalid. case OP_DIV = 0x96 // Disabled opcode. If executed, transaction is invalid. case OP_MOD = 0x97 // Disabled opcode. If executed, transaction is invalid. case OP_LSHIFT = 0x98 // Disabled opcode. If executed, transaction is invalid. case OP_RSHIFT = 0x99 // Disabled opcode. If executed, transaction is invalid. case OP_BOOLAND = 0x9a case OP_BOOLOR = 0x9b case OP_NUMEQUAL = 0x9c case OP_NUMEQUALVERIFY = 0x9d case OP_NUMNOTEQUAL = 0x9e case OP_LESSTHAN = 0x9f case OP_GREATERTHAN = 0xa0 case OP_LESSTHANOREQUAL = 0xa1 case OP_GREATERTHANOREQUAL = 0xa2 case OP_MIN = 0xa3 case OP_MAX = 0xa4 case OP_WITHIN = 0xa5 // Crypto case OP_RIPEMD160 = 0xa6 case OP_SHA1 = 0xa7 case OP_SHA256 = 0xa8 case OP_HASH160 = 0xa9 case OP_HASH256 = 0xaa case OP_CODESEPARATOR = 0xab // This opcode is rarely used because it's useless, but we need to support it anyway. case OP_CHECKSIG = 0xac case OP_CHECKSIGVERIFY = 0xad case OP_CHECKMULTISIG = 0xae case OP_CHECKMULTISIGVERIFY = 0xaf // Expansion case OP_NOP1 = 0xb0 case OP_NOP2 = 0xb1 case OP_NOP3 = 0xb2 case OP_NOP4 = 0xb3 case OP_NOP5 = 0xb4 case OP_NOP6 = 0xb5 case OP_NOP7 = 0xb6 case OP_NOP8 = 0xb7 case OP_NOP9 = 0xb8 case OP_NOP10 = 0xb9 case OP_INVALIDOPCODE = 0xff ///同值指令,使用静态常量定义 static let OP_FALSE = BTCOpcode.OP_0 static let OP_TRUE = BTCOpcode.OP_1 /// 命名字典 static let names: [String: BTCOpcode] = [ "OP_0": BTCOpcode.OP_0, "OP_FALSE": BTCOpcode.OP_FALSE, "OP_PUSHDATA1": BTCOpcode.OP_PUSHDATA1, "OP_PUSHDATA2": BTCOpcode.OP_PUSHDATA2, "OP_PUSHDATA4": BTCOpcode.OP_PUSHDATA4, "OP_1NEGATE": BTCOpcode.OP_1NEGATE, "OP_RESERVED": BTCOpcode.OP_RESERVED, "OP_1": BTCOpcode.OP_1, "OP_TRUE": BTCOpcode.OP_TRUE, "OP_2": BTCOpcode.OP_2, "OP_3": BTCOpcode.OP_3, "OP_4": BTCOpcode.OP_4, "OP_5": BTCOpcode.OP_5, "OP_6": BTCOpcode.OP_6, "OP_7": BTCOpcode.OP_7, "OP_8": BTCOpcode.OP_8, "OP_9": BTCOpcode.OP_9, "OP_10": BTCOpcode.OP_10, "OP_11": BTCOpcode.OP_11, "OP_12": BTCOpcode.OP_12, "OP_13": BTCOpcode.OP_13, "OP_14": BTCOpcode.OP_14, "OP_15": BTCOpcode.OP_15, "OP_16": BTCOpcode.OP_16, "OP_NOP": BTCOpcode.OP_NOP, "OP_VER": BTCOpcode.OP_VER, "OP_IF": BTCOpcode.OP_IF, "OP_NOTIF": BTCOpcode.OP_NOTIF, "OP_VERIF": BTCOpcode.OP_VERIF, "OP_VERNOTIF": BTCOpcode.OP_VERNOTIF, "OP_ELSE": BTCOpcode.OP_ELSE, "OP_ENDIF": BTCOpcode.OP_ENDIF, "OP_VERIFY": BTCOpcode.OP_VERIFY, "OP_RETURN": BTCOpcode.OP_RETURN, "OP_TOALTSTACK": BTCOpcode.OP_TOALTSTACK, "OP_FROMALTSTACK": BTCOpcode.OP_FROMALTSTACK, "OP_2DROP": BTCOpcode.OP_2DROP, "OP_2DUP": BTCOpcode.OP_2DUP, "OP_3DUP": BTCOpcode.OP_3DUP, "OP_2OVER": BTCOpcode.OP_2OVER, "OP_2ROT": BTCOpcode.OP_2ROT, "OP_2SWAP": BTCOpcode.OP_2SWAP, "OP_IFDUP": BTCOpcode.OP_IFDUP, "OP_DEPTH": BTCOpcode.OP_DEPTH, "OP_DROP": BTCOpcode.OP_DROP, "OP_DUP": BTCOpcode.OP_DUP, "OP_NIP": BTCOpcode.OP_NIP, "OP_OVER": BTCOpcode.OP_OVER, "OP_PICK": BTCOpcode.OP_PICK, "OP_ROLL": BTCOpcode.OP_ROLL, "OP_ROT": BTCOpcode.OP_ROT, "OP_SWAP": BTCOpcode.OP_SWAP, "OP_TUCK": BTCOpcode.OP_TUCK, "OP_CAT": BTCOpcode.OP_CAT, "OP_SUBSTR": BTCOpcode.OP_SUBSTR, "OP_LEFT": BTCOpcode.OP_LEFT, "OP_RIGHT": BTCOpcode.OP_RIGHT, "OP_SIZE": BTCOpcode.OP_SIZE, "OP_INVERT": BTCOpcode.OP_INVERT, "OP_AND": BTCOpcode.OP_AND, "OP_OR": BTCOpcode.OP_OR, "OP_XOR": BTCOpcode.OP_XOR, "OP_EQUAL": BTCOpcode.OP_EQUAL, "OP_EQUALVERIFY": BTCOpcode.OP_EQUALVERIFY, "OP_RESERVED1": BTCOpcode.OP_RESERVED1, "OP_RESERVED2": BTCOpcode.OP_RESERVED2, "OP_1ADD": BTCOpcode.OP_1ADD, "OP_1SUB": BTCOpcode.OP_1SUB, "OP_2MUL": BTCOpcode.OP_2MUL, "OP_2DIV": BTCOpcode.OP_2DIV, "OP_NEGATE": BTCOpcode.OP_NEGATE, "OP_ABS": BTCOpcode.OP_ABS, "OP_NOT": BTCOpcode.OP_NOT, "OP_0NOTEQUAL": BTCOpcode.OP_0NOTEQUAL, "OP_ADD": BTCOpcode.OP_ADD, "OP_SUB": BTCOpcode.OP_SUB, "OP_MUL": BTCOpcode.OP_MUL, "OP_DIV": BTCOpcode.OP_DIV, "OP_MOD": BTCOpcode.OP_MOD, "OP_LSHIFT": BTCOpcode.OP_LSHIFT, "OP_RSHIFT": BTCOpcode.OP_RSHIFT, "OP_BOOLAND": BTCOpcode.OP_BOOLAND, "OP_BOOLOR": BTCOpcode.OP_BOOLOR, "OP_NUMEQUAL": BTCOpcode.OP_NUMEQUAL, "OP_NUMEQUALVERIFY": BTCOpcode.OP_NUMEQUALVERIFY, "OP_NUMNOTEQUAL": BTCOpcode.OP_NUMNOTEQUAL, "OP_LESSTHAN": BTCOpcode.OP_LESSTHAN, "OP_GREATERTHAN": BTCOpcode.OP_GREATERTHAN, "OP_LESSTHANOREQUAL": BTCOpcode.OP_LESSTHANOREQUAL, "OP_GREATERTHANOREQUAL": BTCOpcode.OP_GREATERTHANOREQUAL, "OP_MIN": BTCOpcode.OP_MIN, "OP_MAX": BTCOpcode.OP_MAX, "OP_WITHIN": BTCOpcode.OP_WITHIN, "OP_RIPEMD160": BTCOpcode.OP_RIPEMD160, "OP_SHA1": BTCOpcode.OP_SHA1, "OP_SHA256": BTCOpcode.OP_SHA256, "OP_HASH160": BTCOpcode.OP_HASH160, "OP_HASH256": BTCOpcode.OP_HASH256, "OP_CODESEPARATOR": BTCOpcode.OP_CODESEPARATOR, "OP_CHECKSIG": BTCOpcode.OP_CHECKSIG, "OP_CHECKSIGVERIFY": BTCOpcode.OP_CHECKSIGVERIFY, "OP_CHECKMULTISIG": BTCOpcode.OP_CHECKMULTISIG, "OP_CHECKMULTISIGVERIFY": BTCOpcode.OP_CHECKMULTISIGVERIFY, "OP_NOP1": BTCOpcode.OP_NOP1, "OP_NOP2": BTCOpcode.OP_NOP2, "OP_NOP3": BTCOpcode.OP_NOP3, "OP_NOP4": BTCOpcode.OP_NOP4, "OP_NOP5": BTCOpcode.OP_NOP5, "OP_NOP6": BTCOpcode.OP_NOP6, "OP_NOP7": BTCOpcode.OP_NOP7, "OP_NOP8": BTCOpcode.OP_NOP8, "OP_NOP9": BTCOpcode.OP_NOP9, "OP_NOP10": BTCOpcode.OP_NOP10, "OP_INVALIDOPCODE": BTCOpcode.OP_INVALIDOPCODE, ] /// 通过命名查找指令定义 /// /// - Parameter name: 指令名字 /// - Returns: 指令定义 public static func opcode(for name: String) -> BTCOpcode { return BTCOpcode.names[name] ?? .OP_INVALIDOPCODE } /// 指令名字 public var name: String { var name = "OP_UNKNOWN" for (key, value) in BTCOpcode.names { if value == self { name = key break } } return name } }
mit
c32616827997389e7f42cecde053e9f6
44.303226
137
0.542652
3.402132
false
false
false
false
KevinZhouRafael/ActiveSQLite
ActiveSQLite/Classes/ASProtocol+Schame.swift
1
8755
// // ASProtocolSchame.swift // ActiveSQLite // // Created by Kevin Zhou on 08/06/2017. // Copyright © 2017 [email protected]. All rights reserved. // import Foundation import SQLite public protocol CreateColumnsProtocol { func createColumns(t:TableBuilder) } public extension ASProtocol where Self:ASModel{ internal func createTable()throws{ // type(of: self).createTable() do{ try getDB().run(getTable().create(ifNotExists: true) { t in if self is CreateColumnsProtocol { (self as! CreateColumnsProtocol).createColumns(t: t) }else{ autoCreateColumns(t) } // let s = recusionProperties(t) // (s["definitions"] as! [Expressible]).count // // let create1: Method = class_getClassMethod(self, #selector(ASModel.createTable)) // let create2: Method = class_getClassMethod(self, #selector(self.createTable)) // }) Log.i("Create Table \(nameOfTable) success") }catch let e{ Log.e("Create Table \(nameOfTable)failure:\(e.localizedDescription)") throw e } } static func createTable()throws{ try self.init().createTable() } internal func autoCreateColumns(_ t:TableBuilder){ for case let (attribute?,column?, value) in self.recursionProperties() { //check primaryKey if attribute == primaryKeyAttributeName { t.column(Expression<NSNumber>(column), primaryKey: .autoincrement) continue } let mir = Mirror(reflecting:value) switch mir.subjectType { case _ as String.Type: t.column(Expression<String>(column), defaultValue: "") case _ as String?.Type: t.column(Expression<String?>(column)) case _ as NSNumber.Type: if doubleTypes().contains(attribute) { t.column(Expression<Double>(column), defaultValue: 0.0) }else{ if attribute == primaryKeyAttributeName { t.column(Expression<NSNumber>(column), primaryKey: .autoincrement) }else{ t.column(Expression<NSNumber>(column), defaultValue: 0) } } case _ as NSNumber?.Type: if doubleTypes().contains(attribute) { t.column(Expression<Double?>(column)) }else{ t.column(Expression<NSNumber?>(column)) } case _ as NSDate.Type: t.column(Expression<NSDate>(column), defaultValue: NSDate(timeIntervalSince1970: 0)) case _ as NSDate?.Type: t.column(Expression<NSDate?>(column)) default: break } } } static func dropTable()throws{ do{ try getDB().run(getTable().drop(ifExists: true)) Log.i("Delete Table \(nameOfTable) success") }catch{ Log.e("Delete Table \(nameOfTable)failure:\(error.localizedDescription)") throw error } } //MARK: - Alter Table //MARK: - Rename Table static func renameTable(oldName:String, newName:String)throws{ do{ try getDB().run(Table(oldName).rename(Table(newName))) Log.i("alter name of table from \(oldName) to \(newName) success") }catch{ Log.e("alter name of table from \(oldName) to \(newName) failure:\(error.localizedDescription)") throw error } } //MARK: - Add Column static func addColumn(_ columnNames:[String])throws { do{ try getDB().savepoint("savepointname_\(nameOfTable)_addColumn_\(NSDate().timeIntervalSince1970 * 1000)", block: { // try self.db.transaction { let t = getTable() for columnName in columnNames { try self.getDB().run(self.init().addColumnReturnSQL(t: t, columnName: columnName)!) } // } }) Log.i("Add \(columnNames) columns to \(nameOfTable) table success") }catch{ Log.e("Add \(columnNames) columns to \(nameOfTable) table failure") throw error } } private func addColumnReturnSQL(t:Table,columnName newAttributeName:String)->String?{ for case let (attribute?,column?, value) in self.recursionProperties() { if newAttributeName != attribute { continue } let mir = Mirror(reflecting:value) switch mir.subjectType { case _ as String.Type: return t.addColumn(Expression<String>(column), defaultValue: "") case _ as String?.Type: return t.addColumn(Expression<String?>(column)) case _ as NSNumber.Type: if doubleTypes().contains(attribute) { return t.addColumn(Expression<Double>(column), defaultValue: 0.0) }else{ // if key == primaryKeyAttributeName { // return t.addColumn(Expression<NSNumber>(key), primaryKey: .autoincrement) // }else{ return t.addColumn(Expression<NSNumber>(column), defaultValue: 0) // } } case _ as NSNumber?.Type: if doubleTypes().contains(attribute) { return t.addColumn(Expression<Double?>(column)) }else{ return t.addColumn(Expression<NSNumber?>(column)) } case _ as NSDate.Type: return t.addColumn(Expression<NSDate>(column), defaultValue: NSDate(timeIntervalSince1970: 0)) case _ as NSDate?.Type: return t.addColumn(Expression<NSDate?>(column)) default: return nil } } return nil } // MARK: - CREATE INDEX static func createIndex(_ columns: Expressible...)throws { do{ try getDB().run(getTable().createIndexBrage(columns)) Log.i("Create \(columns) indexs on \(nameOfTable) table success") }catch{ Log.e("Create \(columns) indexs on \(nameOfTable) table failure") throw error } } static func createIndex(_ columns: [Expressible], unique: Bool = false, ifNotExists: Bool = false)throws { do{ try getDB().run(getTable().createIndexBrage(columns, unique: unique, ifNotExists: ifNotExists)) Log.i("Create \(columns) indexs on \(nameOfTable) table success") }catch{ Log.e("Create \(columns) indexs on \(nameOfTable) table failure") throw error } } // MARK: - DROP INDEX static func dropIndex(_ columns: Expressible...) -> Bool { do{ try getDB().run(getTable().dropIndexBrage(columns)) Log.i("Drop \(columns) indexs from \(nameOfTable) table success") return true }catch{ Log.e("Drop \(columns) indexs from \(nameOfTable) table failure") return false } } static func dropIndex(_ columns: [Expressible], ifExists: Bool = false) -> Bool { do{ try getDB().run(getTable().dropIndexBrage(columns, ifExists: ifExists)) Log.i("Drop \(columns) indexs from \(nameOfTable) table success") return true }catch{ Log.e("Drop \(columns) indexs from \(nameOfTable) table failure") return false } } }
mit
8a2d30947d1f61a818447f4525c245b4
33.171875
125
0.483768
5.324407
false
false
false
false
blg-andreasbraun/ProcedureKit
Sources/Testing/QueueTestDelegate.swift
2
3493
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import Foundation import ProcedureKit public class QueueTestDelegate: ProcedureQueueDelegate, OperationQueueDelegate { public typealias OperationQueueCheckType = (OperationQueue, Operation) public typealias ProcedureQueueCheckType = (ProcedureQueue, Operation) public typealias ProcedureQueueCheckTypeWithErrors = (ProcedureQueue, Operation, [Error]) public var operationQueueWillAddOperation: [OperationQueueCheckType] { get { return _operationQueueWillAddOperation.read { $0 } } } public var operationQueueWillFinishOperation: [OperationQueueCheckType] { get { return _operationQueueWillFinishOperation.read { $0 } } } public var operationQueueDidFinishOperation: [OperationQueueCheckType] { get { return _operationQueueDidFinishOperation.read { $0 } } } public var procedureQueueWillAddOperation: [ProcedureQueueCheckType] { get { return _procedureQueueWillAddOperation.read { $0 } } } public var procedureQueueWillProduceOperation: [ProcedureQueueCheckType] { get { return _procedureQueueWillProduceOperation.read { $0 } } } public var procedureQueueWillFinishOperation: [ProcedureQueueCheckTypeWithErrors] { get { return _procedureQueueWillFinishOperation.read { $0 } } } public var procedureQueueDidFinishOperation: [ProcedureQueueCheckTypeWithErrors] { get { return _procedureQueueDidFinishOperation.read { $0 } } } private var _operationQueueWillAddOperation = Protector([OperationQueueCheckType]()) private var _operationQueueWillFinishOperation = Protector([OperationQueueCheckType]()) private var _operationQueueDidFinishOperation = Protector([OperationQueueCheckType]()) private var _procedureQueueWillAddOperation = Protector([ProcedureQueueCheckType]()) private var _procedureQueueWillProduceOperation = Protector([ProcedureQueueCheckType]()) private var _procedureQueueWillFinishOperation = Protector([ProcedureQueueCheckTypeWithErrors]()) private var _procedureQueueDidFinishOperation = Protector([ProcedureQueueCheckTypeWithErrors]()) public func operationQueue(_ queue: OperationQueue, willAddOperation operation: Operation) { _operationQueueWillAddOperation.append((queue, operation)) } public func operationQueue(_ queue: OperationQueue, willFinishOperation operation: Operation) { _operationQueueWillFinishOperation.append((queue, operation)) } public func operationQueue(_ queue: OperationQueue, didFinishOperation operation: Operation) { _operationQueueDidFinishOperation.append((queue, operation)) } public func procedureQueue(_ queue: ProcedureQueue, willAddOperation operation: Operation) { _procedureQueueWillAddOperation.append((queue, operation)) } public func procedureQueue(_ queue: ProcedureQueue, willProduceOperation operation: Operation) { _procedureQueueWillProduceOperation.append((queue, operation)) } public func procedureQueue(_ queue: ProcedureQueue, willFinishOperation operation: Operation, withErrors errors: [Error]) { _procedureQueueWillFinishOperation.append((queue, operation, errors)) } public func procedureQueue(_ queue: ProcedureQueue, didFinishOperation operation: Operation, withErrors errors: [Error]) { _procedureQueueDidFinishOperation.append((queue, operation, errors)) } }
mit
e04247af18963cb87e2c8e94f6704f70
45.56
127
0.760882
5.507886
false
false
false
false
Qmerce/ios-sdk
Sources/EmbededUnit/AdProvider/GoogleAd/APEGADViewProvider.swift
1
4231
// // APEGADViewProvider.swift // ApesterKit // // Created by Hasan Sawaed Tabash on 06/10/2021. // Copyright © 2021 Apester. All rights reserved. // import Foundation extension APEUnitView { struct GADViewProvider { var view: GADBannerView? var delegate: GADViewDelegate? } } extension APEUnitView.GADViewProvider { struct Params: Hashable { let adUnitId: String let isCompanionVariant: Bool init?(from dictionary: [String: Any]) { guard let provider = dictionary[Constants.Monetization.adProvider] as? String, provider == Constants.Monetization.adMob, let adUnitId = dictionary[Constants.Monetization.adMobUnitId] as? String, let isCompanionVariant = dictionary[Constants.Monetization.isCompanionVariant] as? Bool else { return nil } self.adUnitId = adUnitId self.isCompanionVariant = isCompanionVariant } } } // MARK:- Google ADs extension APEUnitView { private func makeGADViewDelegate() -> GADViewDelegate { GADViewDelegate(containerViewController: containerViewController, receiveAdSuccessCompletion: { [weak self] in guard let self = self else { return } self.messageDispatcher.sendNativeAdEvent(to: self.unitWebView, Constants.Monetization.playerMonImpression) }, receiveAdErrorCompletion: { [weak self] error in guard let self = self else { return } self.messageDispatcher.sendNativeAdEvent(to: self.unitWebView, Constants.Monetization.playerMonLoadingImpressionFailed) print(error?.localizedDescription ?? "") }) } func setupGADView(params: GADViewProvider.Params) { var gADView = gADViewProviders[params]?.view if gADView == nil { GADMobileAds.sharedInstance().start(completionHandler: nil) self.messageDispatcher.sendNativeAdEvent(to: self.unitWebView, Constants.Monetization.playerMonLoadingPass) gADView = GADBannerView(adSize: kGADAdSizeBanner) gADView?.translatesAutoresizingMaskIntoConstraints = false let delegate = gADViewProviders[params]?.delegate ?? self.makeGADViewDelegate() gADView?.delegate = delegate self.gADViewProviders[params] = .init(view: gADView, delegate: delegate) } gADView?.adUnitID = params.adUnitId gADView?.load(GADRequest()) self.messageDispatcher.sendNativeAdEvent(to: self.unitWebView, Constants.Monetization.playerMonImpressionPending) showGADView() } func showGADView() { guard let containerView = unitWebView, let containerViewController = self.containerViewController else { return } gADViewProviders.forEach { params, provider in guard let gADView = provider.view else { return } containerView.addSubview(gADView) gADView.rootViewController = containerViewController gADView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate(gADViewLayoutConstraints(gADView, containerView: containerView, isCompanionVariant: params.isCompanionVariant)) } } private func gADViewLayoutConstraints(_ gADView: GADBannerView, containerView: UIView, isCompanionVariant: Bool) -> [NSLayoutConstraint] { var constraints = [ gADView.leadingAnchor.constraint(equalTo: unitWebView.leadingAnchor), gADView.trailingAnchor.constraint(equalTo: unitWebView.trailingAnchor) ] if isCompanionVariant { constraints.append(gADView.topAnchor.constraint(equalTo: unitWebView.bottomAnchor, constant: 0)) } else { constraints.append(gADView.bottomAnchor.constraint(equalTo: unitWebView.bottomAnchor, constant: 0)) } return constraints } }
mit
a5b675718deedaed9015f84f5e090f8c
43.526316
151
0.634279
5.041716
false
false
false
false
TheNounProject/CollectionView
CollectionViewTests/CVProxyTests.swift
1
14039
// // CVProxyTests.swift // CollectionViewTests // // Created by Wesley Byrne on 3/5/18. // Copyright © 2018 Noun Project. All rights reserved. // import XCTest @testable import CollectionView class CVProxyTests: XCTestCase, CollectionViewDataSource { lazy var collectionView: CollectionView = { let cv = CollectionView(frame: NSRect(x: 0, y: 0, width: 600, height: 600)) cv.collectionViewLayout = CollectionViewListLayout() cv.dataSource = self CollectionViewCell.register(in: cv) return cv }() private lazy var resultsController: MutableResultsController<Parent, Child> = { let rc = MutableResultsController<Parent, Child>(sectionKeyPath: nil, sortDescriptors: [SortDescriptor(\Child.rank)], sectionSortDescriptors: [SortDescriptor(\Parent.rank)]) rc.setSectionKeyPath(\Child.parent) return rc }() private lazy var provider: CollectionViewProvider = { return CollectionViewProvider(self.collectionView, resultsController: self.resultsController) }() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. provider.populateWhenEmpty = false provider.populateEmptySections = false provider.defaultCollapse = false resultsController.reset() collectionView.reloadData() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func numberOfSections(in collectionView: CollectionView) -> Int { return provider.numberOfSections } func collectionView(_ collectionView: CollectionView, numberOfItemsInSection section: Int) -> Int { return provider.numberOfItems(in: section) } func collectionView(_ collectionView: CollectionView, cellForItemAt indexPath: IndexPath) -> CollectionViewCell { return CollectionViewCell.deque(for: indexPath, in: collectionView) } func assertCounts(_ counts: [Int]) { XCTAssertEqual(provider.numberOfSections, counts.count) XCTAssertEqual(collectionView.numberOfSections, counts.count) for (s, count) in counts.enumerated() { XCTAssertEqual(provider.numberOfItems(in: s), count) XCTAssertEqual(collectionView.numberOfItems(in: s), count) } } // MARK: - Placeholders /*-------------------------------------------------------------------------------*/ func testEmptyPlaceholder() { provider.populateWhenEmpty = true collectionView.reloadData() self.assertCounts([1]) XCTAssertTrue(provider.showEmptyState) } func testEmptyPlaceholderReplaced() { // Start with empty placeholder and insert a section provider.populateWhenEmpty = true collectionView.reloadData() self.assertCounts([1]) resultsController.insert(section: Parent(rank: 0)) self.assertCounts([0]) XCTAssertFalse(provider.showEmptyState) } func testEmptySectionPlaceholder() { // Empty sections provider.populateEmptySections = true let p = Parent(rank: 0) resultsController.setContent([(p, [])]) collectionView.reloadData() self.assertCounts([1]) XCTAssertFalse(provider.showEmptyState) XCTAssertTrue(provider.showEmptySection(at: IndexPath.zero)) } func testReplaceEmptySectionPlaceholder() { // Empty sections provider.populateEmptySections = true let p = Parent(rank: 0) resultsController.setContent([(p, [])]) collectionView.reloadData() resultsController.beginEditing() for c in p.createChildren(5) { resultsController.insert(object: c) } resultsController.endEditing() XCTAssertFalse(provider.showEmptySection(at: IndexPath.zero)) self.assertCounts([5]) } // MARK: - Section Expanding /*-------------------------------------------------------------------------------*/ func testCollapseSection() { var children = [Child]() for n in 0..<3 { children.append(contentsOf: Parent(rank: n).createChildren(5)) } resultsController.setContent(objects: children) collectionView.reloadData() self.assertCounts([5, 5, 5]) provider.collapseSection(at: 1, animated: false) self.assertCounts([5, 0, 5]) } func testExpandSection() { var children = [Child]() for n in 0..<3 { children.append(contentsOf: Parent(rank: n).createChildren(5)) } resultsController.setContent(objects: children) collectionView.reloadData() provider.collapseSection(at: 1, animated: false) self.assertCounts([5, 0, 5]) provider.expandSection(at: 1, animated: false) self.assertCounts([5, 5, 5]) } func testMoveCollapseSection() { var children = [Child]() var parents = [Parent]() for n in 0..<3 { let p = Parent(rank: n) parents.append(p) children.append(contentsOf: p.createChildren(5)) } resultsController.setContent(objects: children) collectionView.reloadData() provider.collapseSection(at: 1, animated: false) self.assertCounts([5, 0, 5]) // Edit the data parents[0].rank = 1 parents[1].rank = 0 self.resultsController.beginEditing() self.resultsController.didUpdate(section: parents[0]) self.resultsController.didUpdate(section: parents[1]) self.resultsController.endEditing() XCTAssertTrue(provider.isSectionCollapsed(at: 0)) XCTAssertFalse(provider.isSectionCollapsed(at: 1)) self.assertCounts([0, 5, 5]) provider.expandSection(at: 0, animated: false) XCTAssertFalse(provider.isSectionCollapsed(at: 1)) self.assertCounts([5, 5, 5]) } func testMoveItemsFromCollapsedToExpanded() { let p0 = Parent(rank: 0) let p1 = Parent(rank: 1) let c0 = p0.createChildren(5) let c1 = p1.createChildren(5) let children = [c0, c1].flatMap { return $0 } resultsController.setContent(objects: children) collectionView.reloadData() provider.collapseSection(at: 0, animated: false) self.assertCounts([0, 5]) // Edit the data c0[0].parent = p1 self.resultsController.beginEditing() self.resultsController.didUpdate(object: c0[0]) self.resultsController.endEditing() self.assertCounts([0, 6]) provider.expandSection(at: 0, animated: false) self.assertCounts([4, 6]) } func testMoveItemsFromExpandedToCollapsed() { let p0 = Parent(rank: 0) let p1 = Parent(rank: 1) let c0 = p0.createChildren(5) let c1 = p1.createChildren(5) let children = [c0, c1].flatMap { return $0 } resultsController.setContent(objects: children) collectionView.reloadData() provider.collapseSection(at: 1, animated: false) self.assertCounts([5, 0]) // Edit the data c0[0].parent = p1 self.resultsController.beginEditing() self.resultsController.didUpdate(object: c0[0]) self.resultsController.endEditing() self.assertCounts([4, 0]) provider.expandSection(at: 1, animated: false) self.assertCounts([4, 6]) } func testDefaultCollapsed() { var children = [Child]() children.append(contentsOf: Parent(rank: 0).createChildren(5)) children.append(contentsOf: Parent(rank: 1).createChildren(5)) provider.defaultCollapse = true resultsController.setContent(objects: children) collectionView.reloadData() self.assertCounts([0, 0]) XCTAssertTrue(provider.isSectionCollapsed(at: 0)) XCTAssertTrue(provider.isSectionCollapsed(at: 1)) let c = Parent(rank: 2).createChildren(1) resultsController.insert(object: c[0]) self.assertCounts([0, 0, 0]) XCTAssertTrue(provider.isSectionCollapsed(at: 2)) } func testDefaultCollapsedOnInsert() { var children = [Child]() children.append(contentsOf: Parent(rank: 0).createChildren(5)) children.append(contentsOf: Parent(rank: 1).createChildren(5)) provider.defaultCollapse = true resultsController.setContent(objects: children) collectionView.reloadData() provider.expandSection(at: 0, animated: false) self.assertCounts([5, 0]) XCTAssertFalse(provider.isSectionCollapsed(at: 0)) XCTAssertTrue(provider.isSectionCollapsed(at: 1)) let c = Parent(rank: 2).createChildren(1) resultsController.insert(object: c[0]) self.assertCounts([5, 0, 0]) XCTAssertTrue(provider.isSectionCollapsed(at: 2)) } func testBreakingUseCase1() { // A reproduction of a previously breaking case from the demo app let _data: [(String, [String])] = [ ("ZSnKWisBqE", ["ueHNbNmzJE", "BLDDODjZeP", "eObJUPufpv", "dOwXZZpyif", "RIZOqeMoWM", "hGLYuDzKQi", "ZOAwicSMDE"]), ("WqoQBTNEaY", ["rsubjBxbVb", "zgxqrwEMEP", "RFMVhYUOBt", "TPtWHpAfhO", "vGNjxxuxds", "EEQzPOqFLm", "WqWAgYBpdk"]), ("KjqnrhLzeE", ["jmKARnCZQJ", "GkVzEtvFEp", "VWbpXXYeZH", "iiRlRTkGKi", "UOGPKdyFLd", "hRPjsirdxZ"]) ] let parentOrder = ["KjqnrhLzeE", "ZSnKWisBqE", "WqoQBTNEaY"] let deleted = ["zgxqrwEMEP"] let inserted = [("nCcfswhOXr", "KjqnrhLzeE", 0)] var children = [String: Child]() var parents = [String: Parent]() for p in _data.enumerated() { let id = p.element.0 let parent = Parent(rank: p.offset, name: id) for c in p.element.1.enumerated() { children[c.element] = Child(rank: c.offset, name: c.element, parent: parent) } parents[id] = parent } let changes = [ ("RIZOqeMoWM", "KjqnrhLzeE", 6), ("eObJUPufpv", "KjqnrhLzeE", 1), ("GkVzEtvFEp", "ZSnKWisBqE", 2), ("dOwXZZpyif", "WqoQBTNEaY", 4), ("ueHNbNmzJE", "KjqnrhLzeE", 5), ("UOGPKdyFLd", "KjqnrhLzeE", 4), ("RFMVhYUOBt", "WqoQBTNEaY", 0), ("iiRlRTkGKi", "WqoQBTNEaY", 5), ("TPtWHpAfhO", "ZSnKWisBqE", 5), ("VWbpXXYeZH", "WqoQBTNEaY", 3), ("WqWAgYBpdk", "ZSnKWisBqE", 3), ("hRPjsirdxZ", "WqoQBTNEaY", 1), ("rsubjBxbVb", "ZSnKWisBqE", 6), ("hGLYuDzKQi", "WqoQBTNEaY", 2), ("ZOAwicSMDE", "ZSnKWisBqE", 0), ("EEQzPOqFLm", "KjqnrhLzeE", 3), ("jmKARnCZQJ", "ZSnKWisBqE", 1), ("BLDDODjZeP", "ZSnKWisBqE", 4), ("vGNjxxuxds", "KjqnrhLzeE", 2) ] resultsController.setContent(objects: Array(children.values)) collectionView.reloadData() for change in changes { children[change.0]?.parent = parents[change.1] children[change.0]?.rank = change.2 } for p in parentOrder.enumerated() { let parent = parents[p.element]! parent.rank = p.offset } resultsController.beginEditing() for p in parentOrder.enumerated() { let parent = parents[p.element]! resultsController.didUpdate(section: parent) } for d in deleted { resultsController.delete(object: children[d]!) } for i in inserted { resultsController.insert(object: Child(rank: i.2, name: i.0, parent: parents[i.1]!)) } for change in changes { resultsController.didUpdate(object: children[change.0]!) } resultsController.endEditing() } } fileprivate class Child: ResultType, CustomStringConvertible { let id = UUID() var rank: Int var name: String var parent: Parent? init(rank: Int, name: String? = nil, parent: Parent) { self.rank = rank self.name = name ?? "Child \(rank)" self.parent = parent } func hash(into hasher: inout Hasher) { hasher.combine(self.id) } static func == (lhs: Child, rhs: Child) -> Bool { return lhs === rhs } var description: String { return "Child \(self.name) - [\(self.parent?.rank.description ?? "nil parent"), \(self.rank)]" } } fileprivate class Parent: SectionType, CustomStringConvertible { let id = UUID() var rank: Int var name: String func hash(into hasher: inout Hasher) { hasher.combine(self.id) } init(rank: Int, name: String? = nil) { self.rank = rank self.name = name ?? "Parent \(rank)" } static func == (lhs: Parent, rhs: Parent) -> Bool { return lhs === rhs } func createChildren(_ n: Int) -> [Child] { var _children = [Child]() for idx in 0..<n { _children.append(Child(rank: idx, name: "Child \(idx)", parent: self)) } return _children } var description: String { return "Parent \(self.name) - \(self.rank)" } }
mit
8f0077bcd289ede50ee38a2a032a6930
32.908213
127
0.577575
4.279878
false
false
false
false
SlackKit/SKServer
Sources/SKServer/Conformers/SwifterServer.swift
2
3325
// // SwifterServer.swift // // Copyright © 2017 Peter Zignego. 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 import Swifter class SwifterServer: SlackKitServer { let server = HttpServer() let port: in_port_t let forceIPV4: Bool init(port: in_port_t = 8080, forceIPV4: Bool = false, responder: SlackKitResponder) { self.port = port self.forceIPV4 = forceIPV4 for route in responder.routes { server[route.path] = { request in return route.middleware.respond(to: (request.request, Response())).1.httpResponse } } } public func start() { do { try server.start(port, forceIPv4: forceIPV4) } catch let error { print("Server failed to start with error: \(error)") } } deinit { server.stop() } } extension HttpRequest { public var request: RequestType { return try! Request( method: HTTPMethod.custom(named: method), path: path, body: String(bytes: body, encoding: .utf8) ?? "", headers: HTTPHeaders(headers: headers.map ({ Header(name: $0.key, value: $0.value) })) ) } } extension ResponseType { public var contentType: String? { return self.headers.first(where: {$0.name.lowercased() == "content-type"})?.value } public var httpResponse: HttpResponse { switch self.code { case 200 where contentType == nil: return .ok(.text(bodyString ?? "")) case 200 where contentType?.lowercased() == "application/json": do { let json = try JSONSerialization.jsonObject(with: body, options: []) #if os(Linux) //swiftlint:disable force_cast return .ok(.json(json as! AnyObject)) //swiftlint:enable force_cast #else return .ok(.json(json as AnyObject)) #endif } catch let error { return .badRequest(.text(error.localizedDescription)) } case 400: return .badRequest(.text("Bad request.")) default: return .ok(.text("ok")) } } }
mit
e549c2113603fa74bb9f224a58e67d35
33.989474
98
0.620036
4.547196
false
false
false
false
superman-coder/pakr
pakr/pakr/UserInterface/MapView/MapController.swift
1
8782
// // Created by Huynh Quang Thao on 4/7/16. // Copyright (c) 2016 Pakr. All rights reserved. // import Foundation import UIKit import MapKit import Parse let MAP_DEFAULT_RADIUS:CLLocationDistance = 800 class MapController: UIViewController { @IBOutlet weak var parkMapView: MKMapView! let locationManager = CLLocationManager() var parkingList: [Topic]! = [] var parkingDataLoadingRadius:Double = 0 var serviceAvailable = false // Rarely modified. // let centerPinLayer = CALayer() var pinImage: UIImage? // Center point on Map var currentCenterLocation: CLLocationCoordinate2D? // Center point that used to load data var currentDataCenterLocation: CLLocationCoordinate2D? var currentUserLocation: CLLocationCoordinate2D? // When user first time open app, we will wating for a valid current user location var startUpdatingParkingData = false // MARK: - Init controller override func viewDidLoad() { super.viewDidLoad() self.title = "Map" setupLocationManager() initMapView() } func setupLocationManager() { if CLLocationManager.authorizationStatus() == .NotDetermined { locationManager.requestWhenInUseAuthorization() } } func initMapView() { parkMapView.delegate = self let initialLocation = self.initialLocation() if let initialLocation = initialLocation { let region = MKCoordinateRegionMakeWithDistance(initialLocation, MAP_DEFAULT_RADIUS, MAP_DEFAULT_RADIUS) parkMapView.setRegion(region, animated: true) } let button = UIButton(type: .Custom) button.backgroundColor = UIColor.whiteColor() button.layer.cornerRadius = 8 button.addTarget(self, action: #selector(MapController.buttonMyLocationDidClick(_:)), forControlEvents: .TouchUpInside) button.translatesAutoresizingMaskIntoConstraints = false button.setImage(UIImage(named: "current-location")?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal) button.tintColor = UIColor.primaryColor() button.imageView?.contentMode = .ScaleAspectFit let views = ["button":button] self.parkMapView.addSubview(button) self.parkMapView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[button(48)]-(8)-|", options: [], metrics: nil, views: views)) self.parkMapView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[button(48)]-(8)-|", options: [], metrics: nil, views: views)) /* Realize that no need to add center pin - TIEN centerPinLayer.contents = UIImage(named: "pin-orange")?.CGImage centerPinLayer.bounds = CGRectMake(0, 0, 29, 42) let bounds = parkMapView.bounds centerPinLayer.position = CGPointMake(bounds.size.width / 2, bounds.size.height / 2) centerPinLayer.anchorPoint = CGPointMake(0.5, 1) parkMapView.layer.addSublayer(centerPinLayer) */ } func buttonMyLocationDidClick(sender:UIButton) { if let myLocation = self.currentUserLocation { let region = MKCoordinateRegionMakeWithDistance(myLocation, MAP_DEFAULT_RADIUS, MAP_DEFAULT_RADIUS) parkMapView.setRegion(region, animated: true) } } func reload() { fillAnnotationOnMap(self.createAnnotationList(self.parkingList)) } func fillAnnotationOnMap(listAnnotation:[ParkAnnotation]) { self.parkMapView.removeAnnotations(self.parkMapView.annotations) self.parkMapView.addAnnotations(listAnnotation) } func createAnnotationList(parkingList:[Topic]!) -> [ParkAnnotation] { var listAnnotation:[ParkAnnotation] = [] for i in 0..<parkingList.count { let topic = parkingList[i]; let parking = topic.parking let annotation = ParkAnnotation(title: parking.parkingName, subtitle: nil, coordinate: CLLocationCoordinate2DMake(parking.coordinate.latitude, parking.coordinate.longitude), tag: i) listAnnotation.append(annotation) } return listAnnotation } func initialLocation() -> CLLocationCoordinate2D? { return NSUserDefaults.standardUserDefaults().getLastSavedLocation() } // MARK: - func mapViewRadius() -> Double { let bottomrightScreenPoint = CGPointMake(CGRectGetMaxX(parkMapView.bounds), CGRectGetMaxY(parkMapView.bounds)) let topleftScreenPoint = CGPointZero let topleftLocation = self.parkMapView.convertPoint(topleftScreenPoint, toCoordinateFromView: self.parkMapView).CLLocationPoint() let bottomrightLocation = self.parkMapView.convertPoint(bottomrightScreenPoint, toCoordinateFromView: self.parkMapView).CLLocationPoint() let distance = bottomrightLocation.distanceFromLocation(topleftLocation) let radius = (distance > 0 ? distance : -distance) / 2 // print("Radius of data load \(radius)") return radius } func loadDataWithCenter(latitude:Double, longitude:Double, radius:Double) { // print("Load data with center: (\(latitude),\(longitude)) radius: \(radius)") WebServiceFactory.getAddressService().getNearByParkingLotByLocation(latitude, longitude: longitude, radius: radius, success: { topics in self.parkingList = topics self.reload() }) { error in } // parkingList = JSONUtils.dummyTopicList } } extension MapController: MKMapViewDelegate { func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) { currentCenterLocation = mapView.region.center let mapViewRadius = self.mapViewRadius() // Dont know why bounds of mapview become Zero, in that case, mapViewRadius is Zero too, // Here we will skip that case. if mapViewRadius == 0 { return } if DataServiceUtils.needToReloadParking(currentDataCenterLocation, newLocation: currentCenterLocation, lastDataLoadingRadius: parkingDataLoadingRadius, newMapViewRadius: mapViewRadius) { currentDataCenterLocation = currentCenterLocation parkingDataLoadingRadius = mapViewRadius * 1.5 self.loadDataWithCenter(currentDataCenterLocation!.latitude, longitude: currentDataCenterLocation!.longitude, radius: parkingDataLoadingRadius) } } func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) { self.currentUserLocation = userLocation.coordinate if (!serviceAvailable) { let region = MKCoordinateRegionMakeWithDistance(currentUserLocation!, MAP_DEFAULT_RADIUS, MAP_DEFAULT_RADIUS) parkMapView.setRegion(region, animated: true) serviceAvailable = true } } func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { if(annotation.isKindOfClass(MKUserLocation)) { return nil; } let reuseIdentifier = "pakr_annotation" var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseIdentifier) if (annotationView == nil) { annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier) } if pinImage == nil { pinImage = PakrImageUtils.resizeImage(UIImage(named: "pin-orange")!, toSize: CGSizeMake(29, 42)) } if let pakrAnnotation = annotation as? ParkAnnotation { annotationView?.tag = pakrAnnotation.tag } annotationView?.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure) annotationView?.canShowCallout = true annotationView?.image = pinImage return annotationView } func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { let tag = view.tag let topic = self.parkingList[tag]; let detailVc = DetailParkingController(nibName: "DetailParkingController", bundle: nil) detailVc.topic = topic self.navigationController?.pushViewController(detailVc, animated: true) } } extension MapController: CLLocationManagerDelegate { func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == .AuthorizedAlways || status == .AuthorizedWhenInUse { manager.startUpdatingLocation() } } }
apache-2.0
0e4d798ebaf7f68dbe037829509b2f08
38.558559
194
0.676156
5.328883
false
false
false
false
acevest/acecode
learn/AcePlay/AcePlay.playground/Pages/Closure.xcplaygroundpage/Contents.swift
1
7624
//: [Previous](@previous) import UIKit // //闭包采取如下三种形式之一: // 1. 全局函数是一个有名字但不会捕获任何值的闭包 // 2. 嵌套函数是一个有名字并可以捕获其封闭函数域内值的闭包 // 3. 闭包表达式是一个利用轻量级语法所写的可以捕获其上下文中变量或常量值的匿名闭包 // // //Swift闭包语法特点: // 1. 利用上下文推断参数和返回值类型 // 2. 隐式返回单表达式闭包,即单表达式闭包可以省略return关键字 // 3. 参数名称缩写 // 4. 尾随(Trailing)闭包语法 // /* The sort(_:) method accepts a closure that takes two arguments of the same type as the array’s contents, and returns a Bool value to say whether the first value should appear before or after the second value once the values are sorted. The sorting closure needs to return true if the first value should appear before the second value, and false otherwise. */ var company = ["Tencent", "Apple", "Facebook", "Google", "Twitter", "Amazon"] var sortedCompany: [String] = [] printLine("Sort") sortedCompany = company.sorted() print(sortedCompany) sortedCompany = [] printLine("Sort With Function A") func backwardsA(_ a: String, b: String) -> Bool { return a > b } sortedCompany = company.sorted(by: backwardsA) print(sortedCompany) sortedCompany = [] printLine("Sort With Backwards Closure A [Closure Expression Syntax]") sortedCompany = company.sorted(by: { (a: String, b: String) -> Bool in return a>b }) print(sortedCompany) sortedCompany = [] // 参数及返回类型自动推断 printLine("Sort With Backwards Closure B [Inferring Type From Context]") sortedCompany = company.sorted(by: { a, b in return a > b }) print(sortedCompany) sortedCompany = [] // 隐式返回表达式闭包,省略return printLine("Sort With Backwards Closure C [Implicit Returns from Single-Expression Closures]") sortedCompany = company.sorted(by: { a, b in a > b }) print(sortedCompany) sortedCompany = [] // 简写参数名 printLine("Sort With Backwards Closure D [Shorthand Argument Names]") sortedCompany = company.sorted(by: { $0 > $1 }) print(sortedCompany) sortedCompany = [] // 尾随闭包 // 尾随闭包是一个书写在`函数括号之后`的闭包表达式,函数支持将其作为最后一个参数调用 // 在使用尾随闭包时,不用写出它的参数标签 printLine("Trailing Closures") sortedCompany = company.sorted() { $0 > $1} print(sortedCompany) sortedCompany = [] // 如果闭包表达式是函数或方法的唯一参数,在使用尾随闭包时,可以把`()`省掉 sortedCompany = company.sorted { $0 > $1 } print(sortedCompany) sortedCompany = [] /* There’s actually an even shorter way to write the closure expression above. Swift’s String type defines its string-specific implementation of the greater-than operator (>) as a function that has two parameters of type String, and returns a value of type Bool. This exactly matches the function type needed by the sort(_:) method. Therefore, you can simply pass in the greater-than operator, and Swift will infer that you want to use its string-specific implementation: */ printLine("Sort With Backwards Closure E [Operator Functions]") sortedCompany = company.sorted(by: >) print(sortedCompany) sortedCompany = [] // Trailing Closure printLine("Sort With Backwards Closure F [Trailing Closure]") sortedCompany = company.sorted() { a, b in a > b} // 如果闭包参数是这个函数的最后一个参数,是可以采用尾随闭包写法 //sortedCompany = company.sort { a, b in a > b} // 如果闭包参数是这个函数的唯一一个参数,是可以不用写括号的 print(sortedCompany) sortedCompany = [] let digitNames = [ 0: "零", 1: "壹", 2: "贰", 3: "叁", 4: "肆", 5: "伍", 6: "陆", 7: "柒", 8: "捌", 9: "玖", ] let numbers = [9876543210, 1413, 110, 64] // map函数可能不用指定参数类型,但要指定返回值类型 let digitString = numbers.map() { (digit) -> String in var n = digit // 参数digit不能在函数体内被修改 var s = "" while n > 0 { s = digitNames[n % 10]! + s n /= 10 } return s } print(digitString) printLine("Captuare Value") // 捕获值 func makeIncrementer(_ step:Int) -> () -> Int { var total = 0 func inc() -> Int { total += step return total } return inc } // 闭包是引用类型 let closureFuncA = makeIncrementer(2) print("ClosureFuncA:", closureFuncA()) print("ClosureFuncA:", closureFuncA()) let closureFuncB = closureFuncA print("ClosureFunnB:", closureFuncB()) let closureFuncC = makeIncrementer(1) print("ClosureFuncC:", closureFuncC()) // 逃逸&非逃逸闭包 // 当一个闭包作为参数传到一个函数中,但是这个闭包在函数返回之后才被执行,则称该闭包从函数中逃逸 // 可以在定义参数时,在参数名前标注@escaping来指明这个闭包是允许逃逸出这个函数的 printLine("Noescaping & Escaping Closesure") func noescapingClosure(_ closure: () -> Void) { closure() } var closureHandler: Array<() -> Void> = [] func escapingClosure(_ closure: @escaping () -> Void) { // 此时参数前加@noescape会报错 closureHandler.append(closure) } class ClosureClass { var x = 10 func doSomethingAboutEscape() { noescapingClosure() { x = 200 } // 将参数标记为@noescape能在闭包中隐式地引用self escapingClosure() { self.x = 100 } // 将一个闭包参数标记为@escaping意味着必须在闭包中显式地引用self } } var closureInstance = ClosureClass() closureInstance.doSomethingAboutEscape() print(closureInstance.x) closureHandler[0]() // 两种调用逃逸闭包的方法 closureHandler.first?() print(closureInstance.x) // 自动闭包 printLine("AutoClosure") print("Now Company Items:", company) print("Company Item Count:", company.count) // autoClosureHanlerA的type是 () -> String 不是 String let autoClosureHandlerA = { company.remove(at: 0) } // an autoclosure lets you delay evaluation print("Company Item Count:", company.count) // 在自动闭包被调用前,值不会变 print("No Remove \(autoClosureHandlerA())") print("Company Item Count:", company.count) // autoclosure parameter printLine("AutoClosure Parameter") func autoClosureFuncParameterA(_ closure: () -> String) { print("AutoClosureFuncParameterA \(closure())!") } autoClosureFuncParameterA({ company.remove(at: 0) }) func autoClosureFuncParameterB(_ closure: @autoclosure () -> String) { print("AutoClosureFuncParameterB \(closure())!") } // 用@autoclosure修饰参数 可以在调用的时候少写一对`{}` // 过度使用@autoclosure会让代码变得难以理解 autoClosureFuncParameterB(company.remove(at: 0)) // @autoclosure 暗含了 noescape 特性 var autoClosureHanlder: [() -> String] = [] func autoClosureFuncParameterC(_ closure: @autoclosure () -> String) { //因为参数被@autoclosure修饰了,而@autoclosure暗含@noescape特性,因此以下语句会报错 //autoClosureHanlder.append(closure) } // 如果用了@autoclosure又要用escape特性,则用@autoclosure(escaping)修饰参数 func autoClosureFuncParameterD( _ closure: @autoclosure @escaping () ->String) { print("Called autoClosureFuncParameterD") autoClosureHanlder.append(closure) } autoClosureFuncParameterD(company.remove(at: 0)) autoClosureFuncParameterD(company.remove(at: 0)) for handler in autoClosureHanlder { print("autoClosure Handling \(handler())!") }
gpl-2.0
01cbb9082144cfc273527e915ca404cc
27.321429
469
0.714849
3.215408
false
false
false
false
BinaryDennis/SwiftPocketBible
Extensions/UIColor+Hex.swift
1
1126
import Foundation import UIKit extension UIColor { convenience init(hexString:String) { let hexString = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() let scanner = Scanner(string: hexString) if (hexString.hasPrefix("#")) { scanner.scanLocation = 1 } var color:UInt32 = 0 scanner.scanHexInt32(&color) let mask = 0x000000FF let r = Int(color >> 16) & mask let g = Int(color >> 8) & mask let b = Int(color) & mask let red = CGFloat(r) / 255.0 let green = CGFloat(g) / 255.0 let blue = CGFloat(b) / 255.0 self.init(red:red, green:green, blue:blue, alpha:1) } func toHexString() -> String { var r:CGFloat = 0 var g:CGFloat = 0 var b:CGFloat = 0 var a:CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0 return String(format:"#%06x", rgb) } }
mit
12e8eca85566a971d7a560918894f552
26.463415
106
0.517762
3.964789
false
false
false
false
dsoisson/SwiftLearning
SwiftLearning.playground/Pages/Functions.xcplaygroundpage/Contents.swift
2
13467
/*: [Table of Contents](@first) | [Previous](@previous) | [Next](@next) - - - # Functions * callout(Session Overview): Functions are statements of code grouped together to provide readability, reusability, and modularity within your program. The Swift Standard Library provides functions that we have already used within previous Playgrounds. Please visit The Swift Standard Library [Functions](https://developer.apple.com/library/prerelease/mac/documentation/Swift/Reference/Swift_StandardLibrary_Functions/index.html#//apple_ref/doc/uid/TP40016052) online resource to see the full list of global functions available to your programs. */ import Foundation /*: ## Calling Functions All functions have a name, that describes what the function will do when you *call* the function. The `print` function has a name *print* that informs the caller the function will print the parameters *passed* to the function. Functions are constructed using the following parts: - Name of the function - Parameters data type(s) that will be passed as arguments - Return type of the output */ let i = 4 let j = 5 let biggest = max(i, j) //: The above statements creates 2 Int constants, *calls* the function `max`, *passing* parameters i and j and *returns* an Int of which parameter is larger. //: > **Experiment**: Call the `min` function to determine which value is smaller. /*: ## Creating your own functions Calling functions created outside of your program is a very common task. There will be many instances that you will have to create your own function to accomplish a specific task. The process of creating a function is also known as defining a function. You start defining a function with the `func` keyword. */ func sayHiTeacher() { print("Hi Teach!"); } //: The above statement creates a function using the `func` keyword, with a name of *sayHiTeacher*, that doesn't accept parameters and doesn't return a value. //: > **Experiment**: Call the `sayHiTeacher` function. /*: ## Passing parameters Functions can be defined with no parameters or with many parameters. The above function `max` is defined with 2 parameters and the `print` function is defined without parameters. Parameters are data types such as `Int`s, `Bool`eans, `String`s and complex types such as [Enumerations](Enumerations), [Classes & Structures](Classes%20and%20Structures) explained in future sessions. */ /*: ### Functions Without Parameters The above function `sayHiTeacher` is and example of a function defined without parameters. */ //: > **Experiment**: Create and call a function to print your name. Define the function with a name of your choice, without parameters and no return value. /*: ### Functions With Multiple Parameters The above function `max` is and example of a function defined with multiple parameters. The `min` function is also a function defined with multiple parameters. */ func sayHiTeacher2(name: String, className: String) { print("Hi \(name), from my \(className) class"); } sayHiTeacher2("Mr. Sheets", className: "Swift") //: The above statement creates a function `sayHiTeacher2` defined with accepting 1 parameter of type String. //: > **Experiment**: Create and call a function to print your name and age. Define the function with a name of your choice, with a parameter of a `String` and `Int` data types and no return value. /*: ### Function Parameter Names There are two possible names you can give parameters when defining a function. The *local* parameter name is only available for use within the function body. The *external* parameter name is used by the caller to label arguments passed with calling a function. All functions have *local* parameter names name must be unique when defining the function. */ /*: ### Specifying External Parameter Names *External* parameter names are exposed to the caller of the function. *External* and *local* parameter names don't have to be the same and by default the first parameter doesn't have an external name and all subsequent *local* names are also the *external* names. The `sayHiTeacher2` function is an example of a function omitting the *external* name for the first parameter and using the default external name for the second parameter. */ func sayHiTeacher3(teacherName name: String, className: String) { print("Hi \(name), from my \(className) class"); } sayHiTeacher3(teacherName: "Mr. Sheets", className: "Swift") /*: ### Omitting External Parameter Names You can omit *external* names by using the underscore `_` in front of second or subsequent parameters. */ func sayHiTeacher4(name: String, _ className: String) { print("Hi \(name), from my \(className) class"); } sayHiTeacher4("Mr. Sheets", "Swift") /*: ### Default Parameter Values Function parameters can be set to a default value and omitted from a function call. It's recommended that you place all defaulted parameters at the end of the parameter list. */ func sayHiTeacher5(name: String = "Mr. Sheets", _ className: String = "Swift") { print("Hi \(name), from my \(className) class"); } sayHiTeacher5() /*: ### Variadic Parameters Functions can be defined with accepting a varying number of arguments (zero or more) when called. You used the three dot notation `...` after the parameter type name. A function can only have at most 1 variadic parameter. */ func sayHiTeacher6(name: String, classNames: String ...) { var classes = "" for className in classNames { classes += className + " " } print("Hi \(name), from my \(classes)classes"); } sayHiTeacher6("Mr. Sheets", classNames: "Swift 1", "Swift 2", "Swift 3") /*: ### Constant and Variable Parameters By default function parameters are defined as constants, meaning that you are not allowed to change the value. You can also define parameters as variable, providing you the ability to change the value and not define another variable with in your function. */ func sayHiTeacher7(var teacherName name: String, className: String) { if !name.hasPrefix("Mr.") { name = "Mr. " + name; } print("Hi \(name), from my \(className) class"); } sayHiTeacher7(teacherName: "Sheets", className: "Swift 1") //: The above variable parameter `name`'s value was changed within the function body but changing the value of variable parameters has no impact outside of the function. /*: ### In-Out Parameters As mentioned above, changing the value of a variable parameter doesn't change the value of the argument variable. If you want the changes to a variable parameter to be reflected outside of your function body, you can define the variable parameter with the `inout` keyword. You place an `&` in front of the varable argument to indicate that the function can modify the value. */ func sayHiTeacher8(inout name: String, _ className: String) { if !name.hasPrefix("Mr.") { name = "Mr. " + name; } print("Hi \(name), from my \(className) class"); } var teacherName = "Sheets"; sayHiTeacher8(&teacherName, "Swift 1") print(teacherName) //: The above variable `teacherName`'s value was changed within the function body and now has a new value. /*: ## Return values When defining a function, the part that describes the output of calling the function is called the `return` value. You indicate what you are *returning* from a function using the right arrow `->`. The return value from a function can be ignored when it is called. */ func getHello() -> String { return "Hello"; } let hello = getHello() getHello() /*: ### Functions Without Return Values As we have seen above, functions don't always have to return a value. A function without a return value (or omitting the function definition return syntax) is the same as including the return syntax of ` -> Void`. */ func sayHi() -> Void { print("Hi"); } sayHi() /*: ### Functions with Multiple Return Values There are instances where returning multiple values from a function is needed. Swift provides tuples as a return type enabling you to return multiple values grouped together in one return type. */ func ends(names: String ...) -> (first: String, last: String)? { if names.isEmpty { return nil } var first = "z" var last = "." for name in names[0..<names.count] { if name < first { first = name } else if name > last { last = name } } return (first, last) } let firstLastName = ends("Mathew", "Sam", "Jack", "Annie", "Oliver", "Hudson") if firstLastName != nil { print("first = \(firstLastName!.first), last = \(firstLastName!.last)") } let none = ends() if none != nil { print("first = \(none!.first), last = \(none!.last)") } //: The above function `ends` defines variadic parameter of `String`s and returns an optional tuple. /*: ## Function as Types We have already learned about data types such as `Int` and `String` in which you declare that a constant or variable stores a certain *type* of data. Functions are *types* as well. Function types are comprised of parameter types and the return type of the function. */ func twice(num: Int) -> Int { return 2 * num } //: The type of the `twice` function is `(Int) -> Int`. In the case of the `sayHiTeacher`, the function type is `() -> Void`. /*: Since functions are types, you can refer to the function in a constant or variable like: */ let doubleIt: (Int) -> Int = twice // or simply using type inference let doubleItAgain = twice print(doubleItAgain(4)) /*: ### Function Types as parameter types Function types can also be used as parameters, meaning that you can pass functions as arguments to another function. */ func printTwice(twiceFunction: (Int) -> Int, _ num: Int) { print(twiceFunction(num)) } printTwice(doubleItAgain, 8) /*: The `printTwice` function has two parameters. The first parameter `twiceFunction` is of type `(Int) -> Int` and the second parameter is an `Int`. You can pass any function type that conforms to `(Int) -> Int` to the `printTwice` function. The second parameter is used as an argument for the first parameter function type. */ /*: ### Function Types as a return type Function types can also be used as return types, meaning that you can return a functions within a function. Defining a function that returns a function is done by placing the function type after the defined function's return arrow `-> `. */ func sayHello(name: String) -> String { return "Hello " + name + "!" } func sayGoodBye(name: String) -> String { return "GoodBye " + name + "!" } func saySomething(justMet justMet: Bool) -> (String) -> String { return justMet ? sayHello : sayGoodBye; } print(saySomething(justMet: true)("Chris")) print(saySomething(justMet: false)("Jason")) /*: Here we have defined two functions, one that returns a `String` saying 'hello' to someone and another function that returns a `String` saying 'good bye' to someone. The third function defined `saySomething` accepts as an argument a `Boolean` if whether you just met someone and returns the appropriate function type to be called at a later time. The `firstTime` and `longTimeFriends` constants refer to different function on which you can call passing a `String` of a persons name as an argument. */ /*: ## Nesting Functions The function examples above are called *global functions*. A *global* function means that the function is visible from anywhere and anytime. Nested functions, functions within functions, are visible only to the function containing the nested function. */ func saySomethingNested(justMet justMet: Bool) -> (String) -> String { func hello(name: String) -> String { return "Hello " + name + "!" } func goodBye(name: String) -> String { return "GoodBye " + name + "!" } return justMet ? hello : goodBye; } print(saySomethingNested(justMet: true)("Chris")) print(saySomethingNested(justMet: false)("Jason")) /*: Above we rewrote the `saySomething` *global* function as `saySomethingNested`, *nesting* functions `hello` and `goodBye` and return the correct nested function. */ /*: - - - * callout(Exercise): Create a playground with pages with each playground page consisting of the previous four exercises. Refactor each exercise leveraging collection types and functions. **Constraints:** Create a swift file containing your functions for each exercise in the **Sources** directory. Make sure each function has the keyword `public` in front of the keyword `func`. * callout(Checkpoint): At this point, you should have a good understanding of calling and creating functions. Functions can be declared with or without parameters and with or without return values. Functions can also be used just like any other data type. You can assign functions to a constant or variable, pass functions as arguments to other functions and return functions from functions. **Keywords to remember:** - `func` = to create a function - `inout` = changing a value of a parameter will change the value of the argument - `return` = exiting a function passing to the caller a potential value * callout(Supporting Materials): Chapters and sections from the Guide and Vidoes from WWDC - [Guide: Functions](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html) - - - [Table of Contents](@first) | [Previous](@previous) | [Next](@next) */
mit
61c6184e0af243d36de238bd5c02a9e9
47.442446
546
0.726368
4.254976
false
false
false
false
skylib/SnapImagePicker
SnapImagePicker/AlbumSelector/View/AlbumSelectorViewController.swift
1
5724
import UIKit class AlbumSelectorViewController: UITableViewController { var eventHandler: AlbumSelectorEventHandler? fileprivate struct Header { static let Height = CGFloat(40) static let FontSize = CGFloat(18) static let Font = SnapImagePickerTheme.font?.withSize(FontSize) static let Indentation = CGFloat(8) } fileprivate struct Cell { static let FontSize = CGFloat(15) static let Font = SnapImagePickerTheme.font?.withSize(FontSize) } fileprivate var collections: [(title: String, albums: [Album])]? { didSet { tableView.reloadData() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) eventHandler?.viewWillAppear() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setupTitleButton() } fileprivate func setupTitleButton() { let button = UIButton() button.titleLabel?.font = SnapImagePickerTheme.font button.setTitle(L10n.generalCollectionName.string, for: UIControlState()) button.setTitleColor(UIColor.black, for: UIControlState()) button.setTitleColor(UIColor.init(red: 0xB8/0xFF, green: 0xB8/0xFF, blue: 0xB8/0xFF, alpha: 1), for: .highlighted) button.addTarget(self, action: #selector(titleButtonPressed), for: .touchUpInside) if let image = UIImage(named: "icon_s_arrow_up_gray", in: Bundle(for: SnapImagePickerViewController.self), compatibleWith: nil), let cgImage = image.cgImage { let rotatedImage = UIImage(cgImage: cgImage, scale: 1.0, orientation: .down) let highlightedImage = rotatedImage.setAlpha(0.3) if let mainCgImage = rotatedImage.cgImage, let highlightedCgImage = highlightedImage.cgImage, let navBarHeight = navigationController?.navigationBar.frame.height { let scale = image.findRoundedScale(image.size.height / (navBarHeight / 5)) let scaledMainImage = UIImage(cgImage: mainCgImage, scale: scale, orientation: .up) let scaledHighlightedImage = UIImage(cgImage: highlightedCgImage, scale: scale * 2, orientation: .up) button.setImage(scaledMainImage, for: UIControlState()) button.setImage(scaledHighlightedImage, for: .highlighted) button.frame = CGRect(x: 0, y: 0, width: scaledMainImage.size.width, height: scaledMainImage.size.height) button.rightAlignImage(scaledMainImage) } } navigationController?.navigationBar.topItem?.titleView = button } @IBAction func titleButtonPressed(_ sender: UIButton) { let _ = navigationController?.popViewController(animated: true) } override func numberOfSections(in tableView: UITableView) -> Int { return collections?.count ?? 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return collections?[section].albums.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Album Cell", for: indexPath) if let albumCell = cell as? AlbumCell { albumCell.album = collections?[(indexPath as NSIndexPath).section].albums[(indexPath as NSIndexPath).row] albumCell.displayFont = Cell.Font } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let collections = collections , (indexPath as NSIndexPath).section < collections.count && (indexPath as NSIndexPath).row < collections.count { eventHandler?.albumClicked(collections[(indexPath as NSIndexPath).section].albums[(indexPath as NSIndexPath).row].type, inNavigationController: self.navigationController) } } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? 0 : Header.Height } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() if section > 0 { view.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: Header.Height) view.backgroundColor = UIColor.white let label = UILabel() label.frame = CGRect(x: Header.Indentation, y: 0, width: tableView.frame.width, height: Header.Height) label.font = Header.Font if collections?[section].title == AlbumType.CollectionNames.General { label.text = L10n.generalCollectionName.string } else if collections?[section].title == AlbumType.CollectionNames.UserDefined { label.text = L10n.userDefinedAlbumsCollectionName.string } else if collections?[section].title == AlbumType.CollectionNames.SmartAlbums { label.text = L10n.smartAlbumsCollectionName.string } else { print("Fetched collection with invalid name!") label.text = nil } view.addSubview(label) } else { view.frame = CGRect(x: 0, y: 0, width: 0, height: 0) } return view } } extension AlbumSelectorViewController: AlbumSelectorViewControllerProtocol { func display(_ collections: [(title: String, albums: [Album])]) { self.collections = collections } }
bsd-3-clause
3f846104048bc097d767da1684850360
43.71875
182
0.646226
5.025461
false
false
false
false
mozilla-mobile/prox
Prox/Prox/Widgets/ReviewContainerView.swift
1
3322
/* 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 UIKit import QuartzCore private let verticalMargin: CGFloat = 6 class ReviewContainerView: UIView { private let getStarsFromScore: ProviderStarsForScore var score: Float = 0 { didSet { reviewScore.image = getStarsFromScore(score) } } lazy var reviewSiteLogo: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView }() let reviewScore: UIImageView = { let view = UIImageView() view.contentMode = .scaleAspectFit view.clipsToBounds = true return view }() lazy var numberOfReviewersLabel: UILabel = { let label = UILabel() label.textAlignment = .center return label }() init(score: Float = 0, getStarsFromScore: @escaping ProviderStarsForScore) { self.score = score self.getStarsFromScore = getStarsFromScore super.init(frame: .zero) setupSubviews() numberOfReviewersLabel.font = Fonts.detailsViewReviewerText numberOfReviewersLabel.textColor = Colors.detailsViewCardSecondaryText } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupSubviews() { for view in [reviewSiteLogo, reviewScore, numberOfReviewersLabel] as [UIView] { addSubview(view) } var constraints = [reviewSiteLogo.topAnchor.constraint(equalTo: self.topAnchor), reviewSiteLogo.leadingAnchor.constraint(equalTo: self.leadingAnchor), reviewSiteLogo.trailingAnchor.constraint(equalTo: self.trailingAnchor), reviewSiteLogo.heightAnchor.constraint(equalToConstant: 28)] constraints.append(contentsOf: [reviewScore.topAnchor.constraint(equalTo: reviewSiteLogo.bottomAnchor, constant: verticalMargin), reviewScore.leadingAnchor.constraint(equalTo: self.leadingAnchor), reviewScore.trailingAnchor.constraint(equalTo: self.trailingAnchor), reviewScore.heightAnchor.constraint(equalToConstant: 20),]) constraints.append(contentsOf: [numberOfReviewersLabel.topAnchor.constraint(equalTo: reviewScore.bottomAnchor, constant: verticalMargin), numberOfReviewersLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor), numberOfReviewersLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor), numberOfReviewersLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor)]) // Note: setting a height on the label may affect margins but, by not including it, // the view will collapse if no review score is present constraints += [bottomAnchor.constraint(equalTo: numberOfReviewersLabel.bottomAnchor)] NSLayoutConstraint.activate(constraints, translatesAutoresizingMaskIntoConstraints: false) } }
mpl-2.0
bca078d26ea189378c2b8f6928c9ad53
40.525
145
0.657435
5.392857
false
false
false
false
smashingboxes/BaseUrl-iOS
BaseUrl/BaseUrl.swift
1
3110
// // BaseUrl.swift // import UIKit /** Usage: 1. Implement BaseUrlDelegate in your app 2. `let baseUrl = BaseUrl(delegate: delegate)` 3. Use `baseUrl.url` 4. To show the switcher UI, call baseUrl.showDebugSwitcher(on: viewController) */ let BaseUrlKeys = ( urlProtocol: "com.BaseUrl.urlProtocol", domain: "com.BaseUrl.domain", previousUrlProtocol: "com.BaseUrl.previousUrlProtocol", previousDomain: "com.BaseUrl.previousDomain" ) public class BaseUrl { fileprivate weak var delegate: BaseUrlDelegate! fileprivate let defaults: UserDefaults required public init(delegate: BaseUrlDelegate, defaults: UserDefaults = UserDefaults.standard) { self.delegate = delegate self.defaults = defaults } public var url: String { get { return urlProtocol() + domain() } } public func urlProtocol() -> String { #if DEBUG || STAGING if let value = defaults.value(forKey: BaseUrlKeys.urlProtocol) as? String { return value } #endif return delegate.defaultProtocol() } public func domain() -> String { #if DEBUG || STAGING if let value = defaults.value(forKey: BaseUrlKeys.domain) as? String { return value } #endif return delegate.defaultDomain() } public func showDebugSwitcher(on viewController: UIViewController) { let switcher = BaseUrlDebugSwitcher(baseUrl: self) viewController.present(switcher, animated: true, completion: nil) } #if DEBUG || STAGING public func setDebug(domain: String?, urlProtocol: String?) { let needsRefresh = domain != self.domain() || urlProtocol != self.urlProtocol() storePrevious(domain: self.domain(), urlProtocol: self.urlProtocol()) set(value: domain, forKey: BaseUrlKeys.domain) set(value: urlProtocol, forKey: BaseUrlKeys.urlProtocol) if needsRefresh { delegate.baseUrlDidChange(newURL: url) } } internal func storePrevious(domain: String?, urlProtocol: String?) { set(value: domain, forKey: BaseUrlKeys.previousDomain) set(value: urlProtocol, forKey: BaseUrlKeys.previousUrlProtocol) } internal func retreivePrevious() -> (domain: String?, urlProtocol: String?) { return ( domain: defaults.string(forKey: BaseUrlKeys.previousDomain), urlProtocol: defaults.string(forKey: BaseUrlKeys.previousUrlProtocol) ) } private func set(value: String?, forKey key: String) { if value?.isEmpty ?? true { defaults.removeObject(forKey: key) } else { defaults.setValue(value, forKey: key) } } internal func reset() { defaults.removeObject(forKey: BaseUrlKeys.domain) defaults.removeObject(forKey: BaseUrlKeys.urlProtocol) defaults.removeObject(forKey: BaseUrlKeys.previousDomain) defaults.removeObject(forKey: BaseUrlKeys.previousUrlProtocol) } #endif }
mit
87b2abbfa2118f1cbdfe8383056c8df6
30.1
101
0.640836
4.540146
false
false
false
false
radubozga/Freedom
speech/Swift/Speech-gRPC-Streaming/Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorView/Presenter/NVActivityIndicatorPresenter.swift
6
10503
// // NVActivityIndicatorPresenter.swift // NVActivityIndicatorView // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit /// Class packages information used to display UI blocker. public final class ActivityData { /// Size of activity indicator view. let size: CGSize /// Message displayed under activity indicator view. let message: String? /// Font of message displayed under activity indicator view. let messageFont: UIFont /// Animation type. let type: NVActivityIndicatorType /// Color of activity indicator view. let color: UIColor /// Color of text. let textColor: UIColor /// Padding of activity indicator view. let padding: CGFloat /// Display time threshold to actually display UI blocker. let displayTimeThreshold: Int /// Minimum display time of UI blocker. let minimumDisplayTime: Int /// Background color of the UI blocker let backgroundColor: UIColor /** Create information package used to display UI blocker. Appropriate NVActivityIndicatorView.DEFAULT_* values are used for omitted params. - parameter size: size of activity indicator view. - parameter message: message displayed under activity indicator view. - parameter messageFont: font of message displayed under activity indicator view. - parameter type: animation type. - parameter color: color of activity indicator view. - parameter padding: padding of activity indicator view. - parameter displayTimeThreshold: display time threshold to actually display UI blocker. - parameter minimumDisplayTime: minimum display time of UI blocker. - parameter textColor: color of the text below the activity indicator view. Will match color parameter if not set, otherwise DEFAULT_TEXT_COLOR if color is not set. - returns: The information package used to display UI blocker. */ public init(size: CGSize? = nil, message: String? = nil, messageFont: UIFont? = nil, type: NVActivityIndicatorType? = nil, color: UIColor? = nil, padding: CGFloat? = nil, displayTimeThreshold: Int? = nil, minimumDisplayTime: Int? = nil, backgroundColor: UIColor? = nil, textColor: UIColor? = nil) { self.size = size ?? NVActivityIndicatorView.DEFAULT_BLOCKER_SIZE self.message = message ?? NVActivityIndicatorView.DEFAULT_BLOCKER_MESSAGE self.messageFont = messageFont ?? NVActivityIndicatorView.DEFAULT_BLOCKER_MESSAGE_FONT self.type = type ?? NVActivityIndicatorView.DEFAULT_TYPE self.color = color ?? NVActivityIndicatorView.DEFAULT_COLOR self.padding = padding ?? NVActivityIndicatorView.DEFAULT_PADDING self.displayTimeThreshold = displayTimeThreshold ?? NVActivityIndicatorView.DEFAULT_BLOCKER_DISPLAY_TIME_THRESHOLD self.minimumDisplayTime = minimumDisplayTime ?? NVActivityIndicatorView.DEFAULT_BLOCKER_MINIMUM_DISPLAY_TIME self.backgroundColor = backgroundColor ?? NVActivityIndicatorView.DEFAULT_BLOCKER_BACKGROUND_COLOR self.textColor = textColor ?? color ?? NVActivityIndicatorView.DEFAULT_TEXT_COLOR } } /// Presenter that displays NVActivityIndicatorView as UI blocker. public final class NVActivityIndicatorPresenter { private enum State { case waitingToShow case showed case waitingToHide case hidden } private let restorationIdentifier = "NVActivityIndicatorViewContainer" private let messageLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false return label }() private var state: State = .hidden private let startAnimatingGroup = DispatchGroup() /// Shared instance of `NVActivityIndicatorPresenter`. public static let sharedInstance = NVActivityIndicatorPresenter() private init() {} // MARK: - Public interface /** Display UI blocker. - parameter data: Information package used to display UI blocker. */ public final func startAnimating(_ data: ActivityData) { guard state == .hidden else { return } state = .waitingToShow startAnimatingGroup.enter() DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(data.displayTimeThreshold)) { guard self.state == .waitingToShow else { self.startAnimatingGroup.leave() return } self.show(with: data) self.startAnimatingGroup.leave() } } /** Remove UI blocker. */ public final func stopAnimating() { _hide() } /// Set message displayed under activity indicator view. /// /// - Parameter message: message displayed under activity indicator view. public final func setMessage(_ message: String?) { guard state == .showed else { startAnimatingGroup.notify(queue: DispatchQueue.main) { self.messageLabel.text = message } return } messageLabel.text = message } // MARK: - Helpers private func show(with activityData: ActivityData) { let containerView = UIView(frame: UIScreen.main.bounds) containerView.backgroundColor = activityData.backgroundColor containerView.restorationIdentifier = restorationIdentifier containerView.translatesAutoresizingMaskIntoConstraints = false let activityIndicatorView = NVActivityIndicatorView( frame: CGRect(x: 0, y: 0, width: activityData.size.width, height: activityData.size.height), type: activityData.type, color: activityData.color, padding: activityData.padding) activityIndicatorView.startAnimating() activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(activityIndicatorView) // Add constraints for `activityIndicatorView`. ({ let xConstraint = NSLayoutConstraint(item: containerView, attribute: .centerX, relatedBy: .equal, toItem: activityIndicatorView, attribute: .centerX, multiplier: 1, constant: 0) let yConstraint = NSLayoutConstraint(item: containerView, attribute: .centerY, relatedBy: .equal, toItem: activityIndicatorView, attribute: .centerY, multiplier: 1, constant: 0) containerView.addConstraints([xConstraint, yConstraint]) }()) messageLabel.font = activityData.messageFont messageLabel.textColor = activityData.textColor messageLabel.text = activityData.message containerView.addSubview(messageLabel) // Add constraints for `messageLabel`. ({ let leadingConstraint = NSLayoutConstraint(item: containerView, attribute: .leading, relatedBy: .equal, toItem: messageLabel, attribute: .leading, multiplier: 1, constant: -8) let trailingConstraint = NSLayoutConstraint(item: containerView, attribute: .trailing, relatedBy: .equal, toItem: messageLabel, attribute: .trailing, multiplier: 1, constant: 8) containerView.addConstraints([leadingConstraint, trailingConstraint]) }()) ({ let spacingConstraint = NSLayoutConstraint(item: messageLabel, attribute: .top, relatedBy: .equal, toItem: activityIndicatorView, attribute: .bottom, multiplier: 1, constant: 8) containerView.addConstraint(spacingConstraint) }()) guard let keyWindow = UIApplication.shared.keyWindow else { return } keyWindow.addSubview(containerView) state = .showed // Add constraints for `containerView`. ({ let leadingConstraint = NSLayoutConstraint(item: keyWindow, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1, constant: 0) let trailingConstraint = NSLayoutConstraint(item: keyWindow, attribute: .trailing, relatedBy: .equal, toItem: containerView, attribute: .trailing, multiplier: 1, constant: 0) let topConstraint = NSLayoutConstraint(item: keyWindow, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint(item: keyWindow, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1, constant: 0) keyWindow.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint]) }()) DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(activityData.minimumDisplayTime)) { self._hide() } } private func _hide() { if state == .waitingToHide { hide() } else if state != .hidden { state = .waitingToHide } } private func hide() { guard let keyWindow = UIApplication.shared.keyWindow else { return } for item in keyWindow.subviews where item.restorationIdentifier == restorationIdentifier { item.removeFromSuperview() } state = .hidden } }
apache-2.0
842c5cc8bb7ee59b7f97e07146635fef
39.709302
189
0.680663
5.470313
false
false
false
false
BabyShung/SplashWindow
ZHExtensions/ZHExtensions/ZHExtensions/NSAttributedStringExtension.swift
1
652
import UIKit public extension NSAttributedString { /// Set indentation (left padding) of self /// /// - Parameters: /// - text: text /// - val: padding value /// - Returns: new attributed string class func indentString(text: String, val: CGFloat) -> NSAttributedString { let style = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle style.alignment = .justified style.firstLineHeadIndent = val style.headIndent = val style.tailIndent = -val return NSAttributedString(string: text, attributes: [NSAttributedStringKey.paragraphStyle: style]) } }
mit
6001692aaa6960ab02b6c9ff720b72d7
31.6
106
0.659509
5.133858
false
false
false
false
sschiau/swift
stdlib/public/core/BridgeObjectiveC.swift
2
26640
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A Swift Array or Dictionary of types conforming to /// `_ObjectiveCBridgeable` can be passed to Objective-C as an NSArray or /// NSDictionary, respectively. The elements of the resulting NSArray /// or NSDictionary will be the result of calling `_bridgeToObjectiveC` /// on each element of the source container. public protocol _ObjectiveCBridgeable { associatedtype _ObjectiveCType: AnyObject /// Convert `self` to Objective-C. func _bridgeToObjectiveC() -> _ObjectiveCType /// Bridge from an Objective-C object of the bridged class type to a /// value of the Self type. /// /// This bridging operation is used for forced downcasting (e.g., /// via as), and may defer complete checking until later. For /// example, when bridging from `NSArray` to `Array<Element>`, we can defer /// the checking for the individual elements of the array. /// /// - parameter result: The location where the result is written. The optional /// will always contain a value. static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout Self? ) /// Try to bridge from an Objective-C object of the bridged class /// type to a value of the Self type. /// /// This conditional bridging operation is used for conditional /// downcasting (e.g., via as?) and therefore must perform a /// complete conversion to the value type; it cannot defer checking /// to a later time. /// /// - parameter result: The location where the result is written. /// /// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant /// information is provided for the convenience of the runtime's `dynamic_cast` /// implementation, so that it need not look into the optional representation /// to determine success. @discardableResult static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout Self? ) -> Bool /// Bridge from an Objective-C object of the bridged class type to a /// value of the Self type. /// /// This bridging operation is used for unconditional bridging when /// interoperating with Objective-C code, either in the body of an /// Objective-C thunk or when calling Objective-C code, and may /// defer complete checking until later. For example, when bridging /// from `NSArray` to `Array<Element>`, we can defer the checking /// for the individual elements of the array. /// /// \param source The Objective-C object from which we are /// bridging. This optional value will only be `nil` in cases where /// an Objective-C method has returned a `nil` despite being marked /// as `_Nonnull`/`nonnull`. In most such cases, bridging will /// generally force the value immediately. However, this gives /// bridging the flexibility to substitute a default value to cope /// with historical decisions, e.g., an existing Objective-C method /// that returns `nil` to for "empty result" rather than (say) an /// empty array. In such cases, when `nil` does occur, the /// implementation of `Swift.Array`'s conformance to /// `_ObjectiveCBridgeable` will produce an empty array rather than /// dynamically failing. @_effects(readonly) static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> Self } #if _runtime(_ObjC) @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) @available(*, deprecated) @_cdecl("_SwiftCreateBridgedArray") @usableFromInline internal func _SwiftCreateBridgedArray( values: UnsafePointer<AnyObject>, numValues: Int ) -> Unmanaged<AnyObject> { let bufPtr = UnsafeBufferPointer(start: values, count: numValues) let bridged = Array(bufPtr)._bridgeToObjectiveCImpl() return Unmanaged<AnyObject>.passRetained(bridged) } @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) @available(*, deprecated) @_cdecl("_SwiftCreateBridgedMutableArray") @usableFromInline internal func _SwiftCreateBridgedMutableArray( values: UnsafePointer<AnyObject>, numValues: Int ) -> Unmanaged<AnyObject> { let bufPtr = UnsafeBufferPointer(start: values, count: numValues) let bridged = _SwiftNSMutableArray(Array(bufPtr)) return Unmanaged<AnyObject>.passRetained(bridged) } @_silgen_name("swift_stdlib_connectNSBaseClasses") internal func _connectNSBaseClasses() -> Bool private let _bridgeInitializedSuccessfully = _connectNSBaseClasses() internal var _orphanedFoundationSubclassesReparented: Bool = false /// Reparents the SwiftNativeNS*Base classes to be subclasses of their respective /// Foundation types, or is false if they couldn't be reparented. Must be run /// in order to bridge Swift Strings, Arrays, Dictionarys, Sets, or Enumerators to ObjC. internal func _connectOrphanedFoundationSubclassesIfNeeded() -> Void { let bridgeWorks = _bridgeInitializedSuccessfully _debugPrecondition(bridgeWorks) _orphanedFoundationSubclassesReparented = true } //===--- Bridging for metatypes -------------------------------------------===// /// A stand-in for a value of metatype type. /// /// The language and runtime do not yet support protocol conformances for /// structural types like metatypes. However, we can use a struct that contains /// a metatype, make it conform to _ObjectiveCBridgeable, and its witness table /// will be ABI-compatible with one that directly provided conformance to the /// metatype type itself. public struct _BridgeableMetatype: _ObjectiveCBridgeable { internal var value: AnyObject.Type internal init(value: AnyObject.Type) { self.value = value } public typealias _ObjectiveCType = AnyObject public func _bridgeToObjectiveC() -> AnyObject { return value } public static func _forceBridgeFromObjectiveC( _ source: AnyObject, result: inout _BridgeableMetatype? ) { result = _BridgeableMetatype(value: source as! AnyObject.Type) } public static func _conditionallyBridgeFromObjectiveC( _ source: AnyObject, result: inout _BridgeableMetatype? ) -> Bool { if let type = source as? AnyObject.Type { result = _BridgeableMetatype(value: type) return true } result = nil return false } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?) -> _BridgeableMetatype { var result: _BridgeableMetatype? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } //===--- Bridging facilities written in Objective-C -----------------------===// // Functions that must discover and possibly use an arbitrary type's // conformance to a given protocol. See ../runtime/Casting.cpp for // implementations. //===----------------------------------------------------------------------===// /// Bridge an arbitrary value to an Objective-C object. /// /// - If `T` is a class type, it is always bridged verbatim, the function /// returns `x`; /// /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`, /// returns the result of `x._bridgeToObjectiveC()`; /// /// - otherwise, we use **boxing** to bring the value into Objective-C. /// The value is wrapped in an instance of a private Objective-C class /// that is `id`-compatible and dynamically castable back to the type of /// the boxed value, but is otherwise opaque. /// // COMPILER_INTRINSIC @inlinable public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject { if _fastPath(_isClassOrObjCExistential(T.self)) { return unsafeBitCast(x, to: AnyObject.self) } return _bridgeAnythingNonVerbatimToObjectiveC(x) } @_silgen_name("") public // @testable func _bridgeAnythingNonVerbatimToObjectiveC<T>(_ x: __owned T) -> AnyObject /// Convert a purportedly-nonnull `id` value from Objective-C into an Any. /// /// Since Objective-C APIs sometimes get their nullability annotations wrong, /// this includes a failsafe against nil `AnyObject`s, wrapping them up as /// a nil `AnyObject?`-inside-an-`Any`. /// // COMPILER_INTRINSIC public func _bridgeAnyObjectToAny(_ possiblyNullObject: AnyObject?) -> Any { if let nonnullObject = possiblyNullObject { return nonnullObject // AnyObject-in-Any } return possiblyNullObject as Any } /// Convert `x` from its Objective-C representation to its Swift /// representation. /// /// - If `T` is a class type: /// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged /// verbatim, the function returns `x`; /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`: /// + if the dynamic type of `x` is not `T._ObjectiveCType` /// or a subclass of it, trap; /// + otherwise, returns the result of `T._forceBridgeFromObjectiveC(x)`; /// - otherwise, trap. @inlinable public func _forceBridgeFromObjectiveC<T>(_ x: AnyObject, _: T.Type) -> T { if _fastPath(_isClassOrObjCExistential(T.self)) { return x as! T } var result: T? _bridgeNonVerbatimFromObjectiveC(x, T.self, &result) return result! } /// Convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> ( _ x: T._ObjectiveCType, _: T.Type ) -> T { var result: T? T._forceBridgeFromObjectiveC(x, result: &result) return result! } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. /// /// - If `T` is a class type: /// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged /// verbatim, the function returns `x`; /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`: /// + otherwise, if the dynamic type of `x` is not `T._ObjectiveCType` /// or a subclass of it, the result is empty; /// + otherwise, returns the result of /// `T._conditionallyBridgeFromObjectiveC(x)`; /// - otherwise, the result is empty. @inlinable public func _conditionallyBridgeFromObjectiveC<T>( _ x: AnyObject, _: T.Type ) -> T? { if _fastPath(_isClassOrObjCExistential(T.self)) { return x as? T } var result: T? _ = _bridgeNonVerbatimFromObjectiveCConditional(x, T.self, &result) return result } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>( _ x: T._ObjectiveCType, _: T.Type ) -> T? { var result: T? T._conditionallyBridgeFromObjectiveC (x, result: &result) return result } @_silgen_name("") @usableFromInline internal func _bridgeNonVerbatimFromObjectiveC<T>( _ x: AnyObject, _ nativeType: T.Type, _ result: inout T? ) /// Helper stub to upcast to Any and store the result to an inout Any? /// on the C++ runtime's behalf. @_silgen_name("_bridgeNonVerbatimFromObjectiveCToAny") internal func _bridgeNonVerbatimFromObjectiveCToAny( _ x: AnyObject, _ result: inout Any? ) { result = x as Any } /// Helper stub to upcast to Optional on the C++ runtime's behalf. @_silgen_name("_bridgeNonVerbatimBoxedValue") internal func _bridgeNonVerbatimBoxedValue<NativeType>( _ x: UnsafePointer<NativeType>, _ result: inout NativeType? ) { result = x.pointee } /// Runtime optional to conditionally perform a bridge from an object to a value /// type. /// /// - parameter result: Will be set to the resulting value if bridging succeeds, and /// unchanged otherwise. /// /// - Returns: `true` to indicate success, `false` to indicate failure. @_silgen_name("") public func _bridgeNonVerbatimFromObjectiveCConditional<T>( _ x: AnyObject, _ nativeType: T.Type, _ result: inout T? ) -> Bool /// Determines if values of a given type can be converted to an Objective-C /// representation. /// /// - If `T` is a class type, returns `true`; /// - otherwise, returns whether `T` conforms to `_ObjectiveCBridgeable`. public func _isBridgedToObjectiveC<T>(_: T.Type) -> Bool { if _fastPath(_isClassOrObjCExistential(T.self)) { return true } return _isBridgedNonVerbatimToObjectiveC(T.self) } @_silgen_name("") public func _isBridgedNonVerbatimToObjectiveC<T>(_: T.Type) -> Bool /// A type that's bridged "verbatim" does not conform to /// `_ObjectiveCBridgeable`, and can have its bits reinterpreted as an /// `AnyObject`. When this function returns true, the storage of an /// `Array<T>` can be `unsafeBitCast` as an array of `AnyObject`. @inlinable // FIXME(sil-serialize-all) public func _isBridgedVerbatimToObjectiveC<T>(_: T.Type) -> Bool { return _isClassOrObjCExistential(T.self) } /// Retrieve the Objective-C type to which the given type is bridged. @inlinable // FIXME(sil-serialize-all) public func _getBridgedObjectiveCType<T>(_: T.Type) -> Any.Type? { if _fastPath(_isClassOrObjCExistential(T.self)) { return T.self } return _getBridgedNonVerbatimObjectiveCType(T.self) } @_silgen_name("") public func _getBridgedNonVerbatimObjectiveCType<T>(_: T.Type) -> Any.Type? // -- Pointer argument bridging /// A mutable pointer addressing an Objective-C reference that doesn't own its /// target. /// /// `Pointee` must be a class type or `Optional<C>` where `C` is a class. /// /// This type has implicit conversions to allow passing any of the following /// to a C or ObjC API: /// /// - `nil`, which gets passed as a null pointer, /// - an inout argument of the referenced type, which gets passed as a pointer /// to a writeback temporary with autoreleasing ownership semantics, /// - an `UnsafeMutablePointer<Pointee>`, which is passed as-is. /// /// Passing pointers to mutable arrays of ObjC class pointers is not /// directly supported. Unlike `UnsafeMutablePointer<Pointee>`, /// `AutoreleasingUnsafeMutablePointer<Pointee>` must reference storage that /// does not own a reference count to the referenced /// value. UnsafeMutablePointer's operations, by contrast, assume that /// the referenced storage owns values loaded from or stored to it. /// /// This type does not carry an owner pointer unlike the other C*Pointer types /// because it only needs to reference the results of inout conversions, which /// already have writeback-scoped lifetime. @frozen public struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */> : _Pointer { public let _rawValue: Builtin.RawPointer @_transparent public // COMPILER_INTRINSIC init(_ _rawValue: Builtin.RawPointer) { self._rawValue = _rawValue } /// Retrieve or set the `Pointee` instance referenced by `self`. /// /// `AutoreleasingUnsafeMutablePointer` is assumed to reference a value with /// `__autoreleasing` ownership semantics, like `NSFoo **` declarations in /// ARC. Setting the pointee autoreleases the new value before trivially /// storing it in the referenced memory. /// /// - Precondition: the pointee has been initialized with an instance of type /// `Pointee`. @inlinable public var pointee: Pointee { @_transparent get { // The memory addressed by this pointer contains a non-owning reference, // therefore we *must not* point an `UnsafePointer<AnyObject>` to // it---otherwise we would allow the compiler to assume it has a +1 // refcount, enabling some optimizations that wouldn't be valid. // // Instead, we need to load the pointee as a +0 unmanaged reference. For // an extra twist, `Pointee` is allowed (but not required) to be an // optional type, so we actually need to load it as an optional, and // explicitly handle the nil case. let unmanaged = UnsafePointer<Optional<Unmanaged<AnyObject>>>(_rawValue).pointee return _unsafeReferenceCast( unmanaged?.takeUnretainedValue(), to: Pointee.self) } @_transparent nonmutating set { // Autorelease the object reference. let object = _unsafeReferenceCast(newValue, to: Optional<AnyObject>.self) Builtin.retain(object) Builtin.autorelease(object) // Convert it to an unmanaged reference and trivially assign it to the // memory addressed by this pointer. let unmanaged: Optional<Unmanaged<AnyObject>> if let object = object { unmanaged = Unmanaged.passUnretained(object) } else { unmanaged = nil } UnsafeMutablePointer<Optional<Unmanaged<AnyObject>>>(_rawValue).pointee = unmanaged } } /// Access the `i`th element of the raw array pointed to by /// `self`. /// /// - Precondition: `self != nil`. @inlinable // unsafe-performance public subscript(i: Int) -> Pointee { @_transparent get { return self.advanced(by: i).pointee } } /// Explicit construction from an UnsafeMutablePointer. /// /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @_transparent public init<U>(_ from: UnsafeMutablePointer<U>) { self._rawValue = from._rawValue } /// Explicit construction from an UnsafeMutablePointer. /// /// Returns nil if `from` is nil. /// /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @_transparent public init?<U>(_ from: UnsafeMutablePointer<U>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } /// Explicit construction from a UnsafePointer. /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @usableFromInline @_transparent internal init<U>(_ from: UnsafePointer<U>) { self._rawValue = from._rawValue } /// Explicit construction from a UnsafePointer. /// /// Returns nil if `from` is nil. /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @usableFromInline @_transparent internal init?<U>(_ from: UnsafePointer<U>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } } extension UnsafeMutableRawPointer { /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. @_transparent public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) { _rawValue = other._rawValue } /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. If `other` is `nil`, the /// result is `nil`. @_transparent public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) { guard let unwrapped = other else { return nil } self.init(unwrapped) } } extension UnsafeRawPointer { /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. @_transparent public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) { _rawValue = other._rawValue } /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. If `other` is `nil`, the /// result is `nil`. @_transparent public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) { guard let unwrapped = other else { return nil } self.init(unwrapped) } } internal struct _CocoaFastEnumerationStackBuf { // Clang uses 16 pointers. So do we. internal var _item0: UnsafeRawPointer? internal var _item1: UnsafeRawPointer? internal var _item2: UnsafeRawPointer? internal var _item3: UnsafeRawPointer? internal var _item4: UnsafeRawPointer? internal var _item5: UnsafeRawPointer? internal var _item6: UnsafeRawPointer? internal var _item7: UnsafeRawPointer? internal var _item8: UnsafeRawPointer? internal var _item9: UnsafeRawPointer? internal var _item10: UnsafeRawPointer? internal var _item11: UnsafeRawPointer? internal var _item12: UnsafeRawPointer? internal var _item13: UnsafeRawPointer? internal var _item14: UnsafeRawPointer? internal var _item15: UnsafeRawPointer? @_transparent internal var count: Int { return 16 } internal init() { _item0 = nil _item1 = _item0 _item2 = _item0 _item3 = _item0 _item4 = _item0 _item5 = _item0 _item6 = _item0 _item7 = _item0 _item8 = _item0 _item9 = _item0 _item10 = _item0 _item11 = _item0 _item12 = _item0 _item13 = _item0 _item14 = _item0 _item15 = _item0 _internalInvariant(MemoryLayout.size(ofValue: self) >= MemoryLayout<Optional<UnsafeRawPointer>>.size * count) } } /// Get the ObjC type encoding for a type as a pointer to a C string. /// /// This is used by the Foundation overlays. The compiler will error if the /// passed-in type is generic or not representable in Objective-C @_transparent public func _getObjCTypeEncoding<T>(_ type: T.Type) -> UnsafePointer<Int8> { // This must be `@_transparent` because `Builtin.getObjCTypeEncoding` is // only supported by the compiler for concrete types that are representable // in ObjC. return UnsafePointer(Builtin.getObjCTypeEncoding(type)) } #endif //===--- Bridging without the ObjC runtime --------------------------------===// #if !_runtime(_ObjC) /// Convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> ( _ x: T._ObjectiveCType, _: T.Type ) -> T { var result: T? T._forceBridgeFromObjectiveC(x, result: &result) return result! } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>( _ x: T._ObjectiveCType, _: T.Type ) -> T? { var result: T? T._conditionallyBridgeFromObjectiveC (x, result: &result) return result } public // SPI(Foundation) protocol _NSSwiftValue: class { init(_ value: Any) var value: Any { get } static var null: AnyObject { get } } @usableFromInline internal class __SwiftValue { @usableFromInline let value: Any @usableFromInline init(_ value: Any) { self.value = value } @usableFromInline static let null = __SwiftValue(Optional<Any>.none as Any) } // Internal stdlib SPI @_silgen_name("swift_unboxFromSwiftValueWithType") public func swift_unboxFromSwiftValueWithType<T>( _ source: inout AnyObject, _ result: UnsafeMutablePointer<T> ) -> Bool { if source === _nullPlaceholder { if let unpacked = Optional<Any>.none as? T { result.initialize(to: unpacked) return true } } if let box = source as? __SwiftValue { if let value = box.value as? T { result.initialize(to: value) return true } } else if let box = source as? _NSSwiftValue { if let value = box.value as? T { result.initialize(to: value) return true } } return false } // Internal stdlib SPI @_silgen_name("swift_swiftValueConformsTo") public func _swiftValueConformsTo<T>(_ type: T.Type) -> Bool { if let foundationType = _foundationSwiftValueType { return foundationType is T.Type } else { return __SwiftValue.self is T.Type } } @_silgen_name("_swift_extractDynamicValue") public func _extractDynamicValue<T>(_ value: T) -> AnyObject? @_silgen_name("_swift_bridgeToObjectiveCUsingProtocolIfPossible") public func _bridgeToObjectiveCUsingProtocolIfPossible<T>(_ value: T) -> AnyObject? internal protocol _Unwrappable { func _unwrap() -> Any? } extension Optional: _Unwrappable { internal func _unwrap() -> Any? { return self } } private let _foundationSwiftValueType = _typeByName("Foundation.__SwiftValue") as? _NSSwiftValue.Type @usableFromInline internal var _nullPlaceholder: AnyObject { if let foundationType = _foundationSwiftValueType { return foundationType.null } else { return __SwiftValue.null } } @usableFromInline func _makeSwiftValue(_ value: Any) -> AnyObject { if let foundationType = _foundationSwiftValueType { return foundationType.init(value) } else { return __SwiftValue(value) } } /// Bridge an arbitrary value to an Objective-C object. /// /// - If `T` is a class type, it is always bridged verbatim, the function /// returns `x`; /// /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`, /// returns the result of `x._bridgeToObjectiveC()`; /// /// - otherwise, we use **boxing** to bring the value into Objective-C. /// The value is wrapped in an instance of a private Objective-C class /// that is `id`-compatible and dynamically castable back to the type of /// the boxed value, but is otherwise opaque. /// // COMPILER_INTRINSIC public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject { var done = false var result: AnyObject! let source: Any = x if let dynamicSource = _extractDynamicValue(x) { result = dynamicSource as AnyObject done = true } if !done, let wrapper = source as? _Unwrappable { if let value = wrapper._unwrap() { result = value as AnyObject } else { result = _nullPlaceholder } done = true } if !done { if type(of: source) as? AnyClass != nil { result = unsafeBitCast(x, to: AnyObject.self) } else if let object = _bridgeToObjectiveCUsingProtocolIfPossible(source) { result = object } else { result = _makeSwiftValue(source) } } return result } #endif // !_runtime(_ObjC)
apache-2.0
691f9cf180b065554a3bf064776077bb
31.807882
101
0.691742
4.282958
false
false
false
false
wordpress-mobile/AztecEditor-iOS
Aztec/Classes/TextKit/LayoutManager.swift
2
15689
import Foundation import UIKit import QuartzCore // MARK: - Aztec Layout Manager // class LayoutManager: NSLayoutManager { /// Blockquote's Left Border Color /// Set the array with how many colors you like, they appear in the order they are set in the array. var blockquoteBorderColors = [UIColor.systemGray] /// Blockquote's Background Color /// var blockquoteBackgroundColor: UIColor? = UIColor(red: 0.91, green: 0.94, blue: 0.95, alpha: 1.0) /// HTML Pre Background Color /// var preBackgroundColor: UIColor? = UIColor(red: 243.0/255.0, green: 246.0/255.0, blue: 248.0/255.0, alpha: 1.0) /// Closure that is expected to return the TypingAttributes associated to the Extra Line Fragment /// var extraLineFragmentTypingAttributes: (() -> [NSAttributedString.Key: Any])? /// Blockquote's Left Border width /// var blockquoteBorderWidth: CGFloat = 2 /// Draws the background, associated to a given Text Range /// override func drawBackground(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) { super.drawBackground(forGlyphRange: glyphsToShow, at: origin) drawBlockquotes(forGlyphRange: glyphsToShow, at: origin) drawHTMLPre(forGlyphRange: glyphsToShow, at: origin) drawLists(forGlyphRange: glyphsToShow, at: origin) } } // MARK: - Blockquote Helpers // private extension LayoutManager { /// Draws a Blockquote associated to a Range + Graphics Origin. /// func drawBlockquotes(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) { guard let textStorage = textStorage else { return } guard let context = UIGraphicsGetCurrentContext() else { preconditionFailure("When drawBackgroundForGlyphRange is called, the graphics context is supposed to be set by UIKit") } let characterRange = self.characterRange(forGlyphRange: glyphsToShow, actualGlyphRange: nil) // Draw: Blockquotes textStorage.enumerateAttribute(.paragraphStyle, in: characterRange, options: []) { (object, range, stop) in guard let paragraphStyle = object as? ParagraphStyle, !paragraphStyle.blockquotes.isEmpty else { return } let blockquoteGlyphRange = glyphRange(forCharacterRange: range, actualCharacterRange: nil) enumerateLineFragments(forGlyphRange: blockquoteGlyphRange) { (rect, usedRect, textContainer, glyphRange, stop) in let startIndent = paragraphStyle.indentToFirst(Blockquote.self) - Metrics.listTextIndentation let lineRange = self.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil) let lineCharacters = textStorage.attributedSubstring(from: lineRange).string let lineEndsParagraph = lineCharacters.isEndOfParagraph(before: lineCharacters.endIndex) let blockquoteRect = self.blockquoteRect(origin: origin, lineRect: rect, blockquoteIndent: startIndent, lineEndsParagraph: lineEndsParagraph) self.drawBlockquoteBackground(in: blockquoteRect.integral, with: context) let nestDepth = paragraphStyle.blockquoteNestDepth for index in 0...nestDepth { let indent = paragraphStyle.indent(to: index, of: Blockquote.self) - Metrics.listTextIndentation let nestRect = self.blockquoteRect(origin: origin, lineRect: rect, blockquoteIndent: indent, lineEndsParagraph: lineEndsParagraph) self.drawBlockquoteBorder(in: nestRect.integral, with: context, at: index) } } } // Draw: Extra Line Fragment guard extraLineFragmentRect.height != 0, let typingAttributes = extraLineFragmentTypingAttributes?() else { return } guard let paragraphStyle = typingAttributes[.paragraphStyle] as? ParagraphStyle, !paragraphStyle.blockquotes.isEmpty else { return } let extraIndent = paragraphStyle.indentToLast(Blockquote.self) let extraRect = blockquoteRect(origin: origin, lineRect: extraLineFragmentRect, blockquoteIndent: extraIndent, lineEndsParagraph: false) drawBlockquoteBackground(in: extraRect.integral, with: context) drawBlockquoteBorder(in: extraRect.integral, with: context, at: 0) } /// Returns the Rect in which the Blockquote should be rendered. /// /// - Parameters: /// - origin: Origin of coordinates /// - lineRect: Line Fragment's Rect /// - blockquoteIndent: Blockquote Indentation Level for the current lineFragment /// - lineEndsParagraph: Indicates if the current blockquote line is the end of a Paragraph /// /// - Returns: Rect in which we should render the blockquote. /// private func blockquoteRect(origin: CGPoint, lineRect: CGRect, blockquoteIndent: CGFloat, lineEndsParagraph: Bool) -> CGRect { var blockquoteRect = lineRect.offsetBy(dx: origin.x, dy: origin.y) let paddingWidth = blockquoteIndent blockquoteRect.origin.x += paddingWidth blockquoteRect.size.width -= paddingWidth // Ref. Issue #645: Cheking if we this a middle line inside a blockquote paragraph if lineEndsParagraph { blockquoteRect.size.height -= Metrics.paragraphSpacing * 0.5 } return blockquoteRect } private func drawBlockquoteBorder(in rect: CGRect, with context: CGContext, at depth: Int) { let quoteCount = blockquoteBorderColors.count let index = min(depth, quoteCount-1) guard quoteCount > 0 && index < quoteCount else { return } let borderColor = blockquoteBorderColors[index] let borderRect = CGRect(origin: rect.origin, size: CGSize(width: blockquoteBorderWidth, height: rect.height)) borderColor.setFill() context.fill(borderRect) } /// Draws a single Blockquote Line Fragment, in the specified Rectangle, using a given Graphics Context. /// private func drawBlockquoteBackground(in rect: CGRect, with context: CGContext) { guard let color = blockquoteBackgroundColor else {return} color.setFill() context.fill(rect) } } // MARK: - PreFormatted Helpers // private extension LayoutManager { /// Draws a HTML Pre associated to a Range + Graphics Origin. /// func drawHTMLPre(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) { guard let textStorage = textStorage else { return } guard let context = UIGraphicsGetCurrentContext() else { preconditionFailure("When drawBackgroundForGlyphRange is called, the graphics context is supposed to be set by UIKit") } let characterRange = self.characterRange(forGlyphRange: glyphsToShow, actualGlyphRange: nil) //draw html pre paragraphs textStorage.enumerateAttribute(.paragraphStyle, in: characterRange, options: []){ (object, range, stop) in guard let paragraphStyle = object as? ParagraphStyle, paragraphStyle.htmlPre != nil else { return } let preGlyphRange = glyphRange(forCharacterRange: range, actualCharacterRange: nil) enumerateLineFragments(forGlyphRange: preGlyphRange) { (rect, usedRect, textContainer, glyphRange, stop) in let lineRect = rect.offsetBy(dx: origin.x, dy: origin.y) self.drawHTMLPre(in: lineRect.integral, with: context) } } } /// Draws a single HTML Pre Line Fragment, in the specified Rectangle, using a given Graphics Context. /// private func drawHTMLPre(in rect: CGRect, with context: CGContext) { guard let preBackgroundColor = preBackgroundColor else { return } preBackgroundColor.setFill() context.fill(rect) } } // MARK: - Lists Helpers // private extension LayoutManager { /// Draws a TextList associated to a Range + Graphics Origin. /// func drawLists(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) { guard let textStorage = textStorage else { return } let characterRange = self.characterRange(forGlyphRange: glyphsToShow, actualGlyphRange: nil) textStorage.enumerateParagraphRanges(spanning: characterRange) { (range, enclosingRange) in guard textStorage.string.isStartOfNewLine(atUTF16Offset: enclosingRange.location), let paragraphStyle = textStorage.attribute(.paragraphStyle, at: enclosingRange.location, effectiveRange: nil) as? ParagraphStyle, let list = paragraphStyle.lists.last else { return } let attributes = textStorage.attributes(at: enclosingRange.location, effectiveRange: nil) let glyphRange = self.glyphRange(forCharacterRange: enclosingRange, actualCharacterRange: nil) let markerRect = rectForItem(range: glyphRange, origin: origin, paragraphStyle: paragraphStyle) var markerNumber = textStorage.itemNumber(in: list, at: enclosingRange.location) var start = list.start ?? 1 if list.reversed { markerNumber = -markerNumber if list.start == nil { start = textStorage.numberOfItems(in: list, at: enclosingRange.location) } } markerNumber += start let markerString = list.style.markerText(forItemNumber: markerNumber) drawItem(markerString, in: markerRect, styled: attributes, at: enclosingRange.location) } } /// Returns the Rect for the MarkerItem at the specified Range + Origin, within a given ParagraphStyle. /// /// - Parameters: /// - range: List Item's Range /// - origin: List Origin /// - paragraphStyle: Container Style /// /// - Returns: CGRect in which we should render the MarkerItem. /// private func rectForItem(range: NSRange, origin: CGPoint, paragraphStyle: ParagraphStyle) -> CGRect { var paddingY = CGFloat(0) var effectiveLineRange = NSRange.zero // Since only the first line in a paragraph can have a bullet, we only need the first line fragment. let lineFragmentRect = self.lineFragmentRect(forGlyphAt: range.location, effectiveRange: &effectiveLineRange) // Whenever we're rendering an Item with multiple lines, within a Blockquote, we need to account for the // paragraph spacing. Otherwise the Marker will show up slightly off. // // Ref. #645 // if effectiveLineRange.length < range.length && paragraphStyle.blockquotes.isEmpty == false { paddingY = Metrics.paragraphSpacing } return lineFragmentRect.offsetBy(dx: origin.x, dy: origin.y + paddingY) } /// Draws the specified List Item Number, at a given location. /// /// - Parameters: /// - markerText: Marker String of the item to be drawn /// - rect: Visible Rect in which the Marker should be rendered /// - styled: Paragraph attributes associated to the list /// - location: Text Location that should get the marker rendered. /// private func drawItem(_ markerText: String, in rect: CGRect, styled paragraphAttributes: [NSAttributedString.Key: Any], at location: Int) { guard let style = paragraphAttributes[.paragraphStyle] as? ParagraphStyle else { return } let markerAttributes = markerAttributesBasedOnParagraph(attributes: paragraphAttributes) let markerAttributedText = NSAttributedString(string: markerText, attributes: markerAttributes) var yOffset = CGFloat(0) var xOffset = CGFloat(0) let indentWidth = style.indentToLast(TextList.self) let markerWidth = markerAttributedText.size().width * 1.5 if location > 0 { yOffset += style.paragraphSpacingBefore } // If the marker width is larger than the indent available let's offset the area to draw to the left if markerWidth > indentWidth { xOffset = indentWidth - markerWidth } var markerRect = rect.offsetBy(dx: xOffset, dy: yOffset) markerRect.size.width = max(indentWidth, markerWidth) markerAttributedText.draw(in: markerRect) } /// Returns the Marker Text Attributes, based on a collection that defines Regular Text Attributes. /// private func markerAttributesBasedOnParagraph(attributes: [NSAttributedString.Key: Any]) -> [NSAttributedString.Key: Any] { var resultAttributes = attributes let indent: CGFloat = CGFloat(Metrics.tabStepInterval) resultAttributes[.paragraphStyle] = markerParagraphStyle(indent: indent) resultAttributes.removeValue(forKey: .underlineStyle) resultAttributes.removeValue(forKey: .strikethroughStyle) resultAttributes.removeValue(forKey: .link) if let font = resultAttributes[.font] as? UIFont { resultAttributes[.font] = fixFontForMarkerAttributes(font: font) } return resultAttributes } /// Returns the Marker Paragraph Attributes /// private func markerParagraphStyle(indent: CGFloat) -> NSParagraphStyle { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .right paragraphStyle.tailIndent = -indent paragraphStyle.lineBreakMode = .byClipping return paragraphStyle } /// Fixes a UIFont Instance for List Marker Usage: /// /// - Emoji Font is replaced by the System's font, of matching size /// - Bold and Italic styling is neutralized /// private func fixFontForMarkerAttributes(font: UIFont) -> UIFont { guard !font.isAppleEmojiFont else { return UIFont.systemFont(ofSize: font.pointSize) } var traits = font.fontDescriptor.symbolicTraits traits.remove(.traitBold) traits.remove(.traitItalic) if let descriptor = font.fontDescriptor.withSymbolicTraits(traits) { return UIFont(descriptor: descriptor, size: font.pointSize) } else { // Don't touch the font if we cannot remove the symbolic traits. return font } } } extension LayoutManager { override func underlineGlyphRange(_ glyphRange: NSRange, underlineType underlineVal: NSUnderlineStyle, lineFragmentRect lineRect: CGRect, lineFragmentGlyphRange lineGlyphRange: NSRange, containerOrigin: CGPoint) { guard let textStorage = textStorage else { return } let underlinedString = textStorage.attributedSubstring(from: glyphRange).string var updatedGlyphRange = glyphRange if glyphRange.endLocation == lineGlyphRange.endLocation, underlinedString.hasSuffix(String.init(.paragraphSeparator)) || underlinedString.hasSuffix(String.init(.lineSeparator)) || underlinedString.hasSuffix(String.init(.carriageReturn)) || underlinedString.hasSuffix(String.init(.lineFeed)) { updatedGlyphRange = NSRange(location: glyphRange.location, length: glyphRange.length - 1) } drawUnderline(forGlyphRange: updatedGlyphRange, underlineType: underlineVal, baselineOffset: 0, lineFragmentRect: lineRect, lineFragmentGlyphRange: lineGlyphRange, containerOrigin: containerOrigin) } }
mpl-2.0
d2c2efd417972fd1b0a86980e89649d4
40.395778
245
0.667602
5.044695
false
false
false
false
Piwigo/Piwigo-Mobile
piwigo/Upload/Upload Queue/UploadQueueHeaderView.swift
1
1862
// // UploadQueueHeaderView.swift // piwigo // // Created by Eddy Lelièvre-Berna on 09/08/2020. // Copyright © 2020 Piwigo.org. All rights reserved. // import Foundation class UploadQueueHeaderView: UIView { private let label = UILabel(frame: .zero) private let margin: CGFloat = 32.0 override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .piwigoColorOrange() label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 0 label.font = .piwigoFontSemiBold() label.baselineAdjustment = .alignCenters label.lineBreakMode = .byWordWrapping label.textAlignment = .center addSubview(label) NSLayoutConstraint.activate([ label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin), label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -margin), label.topAnchor.constraint(equalTo: topAnchor), label.bottomAnchor.constraint(equalTo: bottomAnchor), ]) } func configure(width: CGFloat, text: String) { let context = NSStringDrawingContext() context.minimumScaleFactor = 1.0 let titleAttributes = [NSAttributedString.Key.font: UIFont.piwigoFontSmall()] var titleRect = text.boundingRect(with: CGSize(width: width - 2 * margin, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: titleAttributes, context: context) titleRect.size.height += 16 self.frame = titleRect label.text = text } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
970ef56947d75c65c8067b5ee42cfcab
34.769231
96
0.627957
5.329513
false
false
false
false
gowansg/firefox-ios
Client/Frontend/Home/HomePanels.swift
10
2305
/* 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 UIKit /** * Data for identifying and constructing a HomePanel. */ struct HomePanelDescriptor { let makeViewController: (profile: Profile) -> UIViewController let imageName: String let accessibilityLabel: String } class HomePanels { let enabledPanels = [ HomePanelDescriptor( makeViewController: { profile in let controller = TopSitesPanel() controller.profile = profile return controller }, imageName: "TopSites", accessibilityLabel: NSLocalizedString("Top sites", comment: "Panel accessibility label")), HomePanelDescriptor( makeViewController: { profile in let controller = BookmarksPanel() controller.profile = profile return controller }, imageName: "Bookmarks", accessibilityLabel: NSLocalizedString("Bookmarks", comment: "Panel accessibility label")), HomePanelDescriptor( makeViewController: { profile in let controller = HistoryPanel() controller.profile = profile return controller }, imageName: "History", accessibilityLabel: NSLocalizedString("History", comment: "Panel accessibility label")), HomePanelDescriptor( makeViewController: { profile in let controller = RemoteTabsPanel() controller.profile = profile return controller }, imageName: "SyncedTabs", accessibilityLabel: NSLocalizedString("Synced tabs", comment: "Panel accessibility label")), HomePanelDescriptor( makeViewController: { profile in let controller = ReadingListPanel() controller.profile = profile return controller }, imageName: "ReadingList", accessibilityLabel: NSLocalizedString("Reading list", comment: "Panel accessibility label")), ] }
mpl-2.0
bbdfde51f36a2a9a5b657d20e7dbb9a1
35.015625
105
0.603905
6.315068
false
false
false
false
jad6/CV
Swift/Jad's CV/Sections/References/RefereeCollectionViewCell.swift
1
6580
// // RefereeCollectionViewCell.swift // Jad's CV // // Created by Jad Osseiran on 25/07/2014. // Copyright (c) 2014 Jad. All rights reserved. // import UIKit class RefereeCollectionViewCell: DynamicTypeCollectionViewCell { //MARK:- Constants private struct LayoutConstants { struct Padding { static let top: CGFloat = 15.0 static let side: CGFloat = 15.0 static let bottom: CGFloat = 15.0 static let sideSmall: CGFloat = 4.0 static let betweenHorizontal: CGFloat = 10.0 static let betweenVerticalSmall: CGFloat = 3.0 static let betweenVerticalLarge: CGFloat = 4.0 static let betweenInfoAndContact: CGFloat = 8.0 } struct Separator { static let height: CGFloat = 1.0 static let widthFactor: CGFloat = 0.66 } static let photoImageViewSize = CGSize(width: 70.0, height: 70.0) } //MARK:- Properties let photoImageView = UIImageView() let fullNameLabel = UILabel() let positionLabel = UILabel() let locationlabel = UILabel() let connectionLabel = UILabel() let phoneButton = UIButton() let emailButton = UIButton() private let cardBackgroundImageView = UIImageView() private let separatorView = UIView() //MARK:- Init required init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) let cardImage = UIImage(named: "conatct-card").resizableImageWithCapInsets(UIEdgeInsets(top: 2.0, left: 4.0, bottom: 6.0, right: 4.0)) self.cardBackgroundImageView.image = cardImage self.contentView.addSubview(self.cardBackgroundImageView) self.separatorView.backgroundColor = UIColor.lightGrayColor() self.contentView.addSubview(self.separatorView) self.contentView.addSubview(self.photoImageView) self.fullNameLabel.numberOfLines = 2 self.contentView.addSubview(self.fullNameLabel) self.positionLabel.numberOfLines = 2 self.contentView.addSubview(self.positionLabel) self.locationlabel.numberOfLines = 2 self.contentView.addSubview(self.locationlabel) self.connectionLabel.numberOfLines = 3 self.contentView.addSubview(self.connectionLabel) self.emailButton.setTitleColor((UIDevice.canEmail() ? UIColor.defaultBlueColor() : UIColor.darkGrayColor()), forState: .Normal) self.contentView.addSubview(self.emailButton) self.phoneButton.setTitleColor((UIDevice.canCall() ? UIColor.defaultBlueColor() : UIColor.darkGrayColor()), forState: .Normal) self.contentView.addSubview(self.phoneButton) } //MARK:- Layout override func layoutSubviews() { super.layoutSubviews() photoImageView.frame.size = LayoutConstants.photoImageViewSize photoImageView.frame.origin.x = LayoutConstants.Padding.side photoImageView.frame.origin.y = LayoutConstants.Padding.top photoImageView.maskToCircle() let labelXOrigin = photoImageView.frame.maxX + LayoutConstants.Padding.betweenHorizontal let boundingLabelWidth = bounds.size.width - labelXOrigin - LayoutConstants.Padding.sideSmall let boundingLabelSize = CGSize(width: boundingLabelWidth, height: bounds.size.height) fullNameLabel.frame.size = fullNameLabel.sizeThatFits(boundingLabelSize).ceilSize fullNameLabel.frame.origin.x = labelXOrigin fullNameLabel.frame.origin.y = LayoutConstants.Padding.top positionLabel.frame.size = positionLabel.sizeThatFits(boundingLabelSize).ceilSize positionLabel.frame.origin.x = labelXOrigin positionLabel.frame.origin.y = fullNameLabel.frame.maxY + LayoutConstants.Padding.betweenVerticalSmall locationlabel.frame.size = locationlabel.sizeThatFits(boundingLabelSize).ceilSize locationlabel.frame.origin.x = labelXOrigin locationlabel.frame.origin.y = positionLabel.frame.maxY + LayoutConstants.Padding.betweenVerticalSmall connectionLabel.frame.size = connectionLabel.sizeThatFits(boundingLabelSize).ceilSize connectionLabel.frame.origin.x = labelXOrigin connectionLabel.frame.origin.y = locationlabel.frame.maxY + LayoutConstants.Padding.betweenVerticalSmall phoneButton.frame.size = phoneButton.sizeThatFits(bounds.size).ceilSize phoneButton.frame.origin.y = max(connectionLabel.frame.maxY, photoImageView.frame.maxY) + LayoutConstants.Padding.betweenInfoAndContact phoneButton.centerHorizontallyWithReferenceRect(self.contentView.bounds) separatorView.frame.size.width = floor(bounds.size.width * LayoutConstants.Separator.widthFactor) separatorView.frame.size.height = LayoutConstants.Separator.height separatorView.frame.origin.y = phoneButton.frame.maxY + LayoutConstants.Padding.betweenVerticalLarge separatorView.centerHorizontallyWithReferenceRect(self.contentView.bounds) emailButton.frame.size = emailButton.sizeThatFits(bounds.size).ceilSize emailButton.frame.origin.y = separatorView.frame.maxY + LayoutConstants.Padding.betweenVerticalLarge emailButton.centerHorizontallyWithReferenceRect(self.contentView.bounds) cardBackgroundImageView.frame = bounds } //MARK:- Dynamic type override func reloadDynamicTypeContent() { fullNameLabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleHeadline) positionLabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleCaption2) locationlabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleCaption2) connectionLabel.font = DynamicTypeFont.preferredFontForTextStyle(CVFontTextStyleCaption2Italic) emailButton.titleLabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleBody) phoneButton.titleLabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleBody) } override func optimalCellSize() -> CGSize { let minY = min(fullNameLabel.frame.minY, photoImageView.frame.minY) let Δ: CGFloat = emailButton.frame.maxY - minY let height = Δ + (2 * LayoutConstants.Padding.top) return CGSize(width: frame.size.width, height: height) } }
bsd-3-clause
6d29ffb50f046d2bf2643485ab7a2fcb
42.853333
143
0.702645
5.009901
false
false
false
false
StYaphet/firefox-ios
Storage/Rust/RustLogins.swift
2
15339
/* 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 @_exported import MozillaAppServices private let log = Logger.syncLogger public extension LoginRecord { convenience init(credentials: URLCredential, protectionSpace: URLProtectionSpace) { let hostname: String if let _ = protectionSpace.`protocol` { hostname = protectionSpace.urlString() } else { hostname = protectionSpace.host } let httpRealm = protectionSpace.realm let username = credentials.user let password = credentials.password self.init(fromJSONDict: [ "hostname": hostname, "httpRealm": httpRealm as Any, "username": username ?? "", "password": password ?? "" ]) } var credentials: URLCredential { return URLCredential(user: username, password: password, persistence: .forSession) } var protectionSpace: URLProtectionSpace { return URLProtectionSpace.fromOrigin(hostname) } var hasMalformedHostname: Bool { let hostnameURL = hostname.asURL guard let _ = hostnameURL?.host else { return true } return false } var isValid: Maybe<()> { // Referenced from https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginManager.js?rev=f76692f0fcf8&mark=280-281#271 // Logins with empty hostnames are not valid. if hostname.isEmpty { return Maybe(failure: LoginRecordError(description: "Can't add a login with an empty hostname.")) } // Logins with empty passwords are not valid. if password.isEmpty { return Maybe(failure: LoginRecordError(description: "Can't add a login with an empty password.")) } // Logins with both a formSubmitURL and httpRealm are not valid. if let _ = formSubmitURL, let _ = httpRealm { return Maybe(failure: LoginRecordError(description: "Can't add a login with both a httpRealm and formSubmitURL.")) } // Login must have at least a formSubmitURL or httpRealm. if (formSubmitURL == nil) && (httpRealm == nil) { return Maybe(failure: LoginRecordError(description: "Can't add a login without a httpRealm or formSubmitURL.")) } // All good. return Maybe(success: ()) } } public class LoginRecordError: MaybeErrorType { public let description: String public init(description: String) { self.description = description } } public class RustLogins { let databasePath: String let encryptionKey: String let salt: String let queue: DispatchQueue let storage: LoginsStorage fileprivate(set) var isOpen: Bool = false private var didAttemptToMoveToBackup = false public init(databasePath: String, encryptionKey: String, salt: String) { self.databasePath = databasePath self.encryptionKey = encryptionKey self.salt = salt self.queue = DispatchQueue(label: "RustLogins queue: \(databasePath)", attributes: []) self.storage = LoginsStorage(databasePath: databasePath) } // Migrate and return the salt, or create a new salt // Also, in the event of an error, returns a new salt. public static func setupPlaintextHeaderAndGetSalt(databasePath: String, encryptionKey: String) -> String { do { if FileManager.default.fileExists(atPath: databasePath) { let db = LoginsStorage(databasePath: databasePath) let salt = try db.getDbSaltForKey(key: encryptionKey) try db.migrateToPlaintextHeader(key: encryptionKey, salt: salt) return salt } } catch { print(error) Sentry.shared.send(message: "setupPlaintextHeaderAndGetSalt failed", tag: SentryTag.rustLogins, severity: .error, description: error.localizedDescription) } let saltOf32Chars = UUID().uuidString.replacingOccurrences(of: "-", with: "") return saltOf32Chars } // Open the db, and if it fails, it moves the db and creates a new db file and opens it. private func open() -> NSError? { do { try storage.unlockWithKeyAndSalt(key: encryptionKey, salt: salt) isOpen = true return nil } catch let err as NSError { if let loginsStoreError = err as? LoginsStoreError { switch loginsStoreError { // The encryption key is incorrect, or the `databasePath` // specified is not a valid database. This is an unrecoverable // state unless we can move the existing file to a backup // location and start over. case .invalidKey(let message): log.error(message) if !didAttemptToMoveToBackup { RustShared.moveDatabaseFileToBackupLocation(databasePath: databasePath) didAttemptToMoveToBackup = true return open() } case .panic(let message): Sentry.shared.sendWithStacktrace(message: "Panicked when opening Rust Logins database", tag: SentryTag.rustLogins, severity: .error, description: message) default: Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when opening Rust Logins database", tag: SentryTag.rustLogins, severity: .error, description: loginsStoreError.localizedDescription) } } else { Sentry.shared.sendWithStacktrace(message: "Unknown error when opening Rust Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription) } return err } } private func close() -> NSError? { do { try storage.lock() isOpen = false return nil } catch let err as NSError { Sentry.shared.sendWithStacktrace(message: "Unknown error when closing Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription) return err } } public func reopenIfClosed() -> NSError? { var error: NSError? queue.sync { guard !isOpen else { return } error = open() } return error } public func interrupt() { do { try storage.interrupt() } catch let err as NSError { Sentry.shared.sendWithStacktrace(message: "Error interrupting Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription) } } public func forceClose() -> NSError? { var error: NSError? interrupt() queue.sync { guard isOpen else { return } error = close() } return error } public func sync(unlockInfo: SyncUnlockInfo) -> Success { let deferred = Success() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { try _ = self.storage.sync(unlockInfo: unlockInfo) deferred.fill(Maybe(success: ())) } catch let err as NSError { if let loginsStoreError = err as? LoginsStoreError { switch loginsStoreError { case .panic(let message): Sentry.shared.sendWithStacktrace(message: "Panicked when syncing Logins database", tag: SentryTag.rustLogins, severity: .error, description: message) default: Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when syncing Logins database", tag: SentryTag.rustLogins, severity: .error, description: loginsStoreError.localizedDescription) } } deferred.fill(Maybe(failure: err)) } } return deferred } public func get(id: String) -> Deferred<Maybe<LoginRecord?>> { let deferred = Deferred<Maybe<LoginRecord?>>() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { let record = try self.storage.get(id: id) deferred.fill(Maybe(success: record)) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } public func searchLoginsWithQuery(_ query: String?) -> Deferred<Maybe<Cursor<LoginRecord>>> { return list().bind({ result in if let error = result.failureValue { return deferMaybe(error) } guard let records = result.successValue else { return deferMaybe(ArrayCursor(data: [])) } guard let query = query?.lowercased(), !query.isEmpty else { return deferMaybe(ArrayCursor(data: records)) } let filteredRecords = records.filter({ $0.hostname.lowercased().contains(query) || $0.username.lowercased().contains(query) }) return deferMaybe(ArrayCursor(data: filteredRecords)) }) } public func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace, withUsername username: String? = nil) -> Deferred<Maybe<Cursor<LoginRecord>>> { return list().bind({ result in if let error = result.failureValue { return deferMaybe(error) } guard let records = result.successValue else { return deferMaybe(ArrayCursor(data: [])) } let filteredRecords: [LoginRecord] if let username = username { filteredRecords = records.filter({ $0.username == username && ( $0.hostname == protectionSpace.urlString() || $0.hostname == protectionSpace.host ) }) } else { filteredRecords = records.filter({ $0.hostname == protectionSpace.urlString() || $0.hostname == protectionSpace.host }) } return deferMaybe(ArrayCursor(data: filteredRecords)) }) } public func hasSyncedLogins() -> Deferred<Maybe<Bool>> { return list().bind({ result in if let error = result.failureValue { return deferMaybe(error) } return deferMaybe((result.successValue?.count ?? 0) > 0) }) } public func list() -> Deferred<Maybe<[LoginRecord]>> { let deferred = Deferred<Maybe<[LoginRecord]>>() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { let records = try self.storage.list() deferred.fill(Maybe(success: records)) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } public func add(login: LoginRecord) -> Deferred<Maybe<String>> { let deferred = Deferred<Maybe<String>>() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { let id = try self.storage.add(login: login) deferred.fill(Maybe(success: id)) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } public func use(login: LoginRecord) -> Success { login.timesUsed += 1 login.timeLastUsed = Int64(Date.nowMicroseconds()) return update(login: login) } public func update(login: LoginRecord) -> Success { let deferred = Success() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { try self.storage.update(login: login) deferred.fill(Maybe(success: ())) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } public func delete(ids: [String]) -> Deferred<[Maybe<Bool>]> { return all(ids.map({ delete(id: $0) })) } public func delete(id: String) -> Deferred<Maybe<Bool>> { let deferred = Deferred<Maybe<Bool>>() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { let existed = try self.storage.delete(id: id) deferred.fill(Maybe(success: existed)) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } public func reset() -> Success { let deferred = Success() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { try self.storage.reset() deferred.fill(Maybe(success: ())) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } public func wipeLocal() -> Success { let deferred = Success() queue.async { guard self.isOpen else { let error = LoginsStoreError.unspecified(message: "Database is closed") deferred.fill(Maybe(failure: error as MaybeErrorType)) return } do { try self.storage.wipeLocal() deferred.fill(Maybe(success: ())) } catch let err as NSError { deferred.fill(Maybe(failure: err)) } } return deferred } }
mpl-2.0
8f73aa37d46ae14a0b0589219e99a258
33.162584
222
0.569789
5.182095
false
false
false
false
Nick11/SwiftGen
Tests/Storyboard/StoryboardTests.swift
4
2033
// // StoryboardTests.swift // SwiftGen // // Created by Olivier Halligon on 01/08/2015. // Copyright © 2015 AliSoftware. All rights reserved. // import XCTest /** * Important: In order for the "*.storyboard" files in fixtures/ to be copied as-is in the test bundle * (as opposed to being compiled when the test bundle is compiled), a custom "Build Rule" has been added to the target. * See Project -> Target "swiftgen-storyboard-tests" -> Build Rules -> « Files "*.storyboard" using PBXCp » */ class StoryboardTests: XCTestCase { func testMessageWithDefaults() { let enumBuilder = SwiftGenStoryboardEnumBuilder() enumBuilder.addStoryboardAtPath(self.fixturePath("Message.storyboard")) let result = enumBuilder.build() let expected = self.fixtureString("MessageWithDefaults.swift.out") XCTDiffStrings(result, expected) } func testAllWithDefaults() { let enumBuilder = SwiftGenStoryboardEnumBuilder() enumBuilder.parseDirectory(self.fixturesDir) let result = enumBuilder.build() let expected = self.fixtureString("AllWithDefaults.swift.out") XCTDiffStrings(result, expected) } func testMessageWithCustomNames() { let enumBuilder = SwiftGenStoryboardEnumBuilder() enumBuilder.addStoryboardAtPath(self.fixturePath("Message.storyboard")) let result = enumBuilder.build(scenesStructName: "XCTAllScenes", seguesStructName: "XCTAllSegues") let expected = self.fixtureString("MessageWithCustomNames.swift.out") XCTDiffStrings(result, expected) } func testMessageWithCustomIndentation() { let enumBuilder = SwiftGenStoryboardEnumBuilder() enumBuilder.addStoryboardAtPath(self.fixturePath("Message.storyboard")) let result = enumBuilder.build(indentation: .Spaces(3)) let expected = self.fixtureString("MessageWithCustomIndentation.swift.out") XCTDiffStrings(result, expected) } }
mit
f91ab44340b960e7068b0c9f1e414912
36.592593
119
0.696059
4.72093
false
true
false
false
hakeemsyd/twitter
twitter/TweetDetailViewController.swift
1
3499
// // TweetDetailViewController.swift // twitter // // Created by Syed Hakeem Abbas on 9/28/17. // Copyright © 2017 codepath. All rights reserved. // import UIKit class TweetDetailViewController: UIViewController { @IBOutlet weak var favButtonView: UIButton! @IBOutlet weak var retweetIcon: UIImageView! @IBOutlet weak var retweetUserName: UILabel! @IBOutlet weak var retweetButtonView: UIButton! var tweetId: Int = 0 @IBOutlet weak var numFavView: UILabel! @IBOutlet weak var numRetweetsView: UILabel! @IBOutlet weak var tweetTextView: UITextView! @IBOutlet weak var aliasView: UILabel! @IBOutlet weak var nameView: UILabel! @IBOutlet weak var profileImage: UIImageView! var tweet: Tweet? override func viewDidLoad() { super.viewDidLoad() update() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func onClose(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } @IBAction func close(_ sender: UIButton) { dismiss(animated: true, completion: nil) } @IBAction func onFavorite(_ sender: Any) { TwitterClient.sharedInstance.fav(tweetId: tweetId, val: !(tweet?.favourited)!,success: { (tweet: Tweet) in self.tweetId = tweet.id! self.update() }) { (error: Error) in print("\(error.localizedDescription)") } } @IBAction func onRetweet(_ sender: UIButton) { TwitterClient.sharedInstance.retweet(tweetId: tweetId, val: !(tweet?.retweeted)!, success: { (tweet: Tweet) in //self.tweetId = tweet.id! self.update() }) { (error: Error) in print("\(error.localizedDescription)") } } @IBAction func onReply(_ sender: UIButton) { } private func update(){ if(tweetId > 0) { TwitterClient.sharedInstance.getTweet(id: tweetId, success: { (tweet: Tweet) in self.tweet = tweet self.tweetTextView.text = tweet.text self.aliasView.text = tweet.user?.screenname self.nameView.text = tweet.user?.name self.numRetweetsView.text = "\(tweet.retweetCount) RETWEETS" self.numFavView.text = "\(tweet.favoriteCount) FAVORITES" self.favButtonView.setImage(tweet.getFavIcon(), for: []) self.retweetButtonView.setImage(tweet.getRetweetedIcon(), for: []) Helper.loadPhoto(withUrl: (tweet.user?.profileImageUrl)!, into: self.profileImage) if let rUser = tweet.retweetUser { self.retweetUserName.text = "\(rUser.screenname ?? "") Retweeted" self.retweetUserName.isHidden = false self.retweetIcon.isHidden = false } else { self.retweetUserName.isHidden = true self.retweetIcon.isHidden = true } }, failure: { (error: Error) in }) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
4bed0da68a24e0d249b02c931044e31a
35.061856
118
0.603774
4.752717
false
false
false
false
vinod1988/Cartography
CartographyTests/SizeSpec.swift
15
1464
import Cartography import Nimble import Quick class SizeSpec: QuickSpec { override func spec() { var superview: View! var view: View! beforeEach { superview = TestView(frame: CGRectMake(0, 0, 400, 400)) view = TestView(frame: CGRectZero) superview.addSubview(view) } describe("LayoutProxy.size") { it("should support relative equalities") { layout(view) { view in view.size == view.superview!.size } expect(view.frame.size).to(equal(CGSizeMake(400, 400))) } it("should support relative inequalities") { layout(view) { view in view.size <= view.superview!.size view.size >= view.superview!.size } expect(view.frame.size).to(equal(CGSizeMake(400, 400))) } it("should support multiplication") { layout(view) { view in view.size == view.superview!.size * 2 } expect(view.frame.size).to(equal(CGSizeMake(800, 800))) } it("should support division") { layout(view) { view in view.size == view.superview!.size / 2 } expect(view.frame.size).to(equal(CGSizeMake(200, 200))) } } } }
mit
d0635444a2d6823fca6b29cc186023b7
26.622642
71
0.482923
4.88
false
false
false
false
edmw/Volumio_ios
Volumio/PluginDetailViewController.swift
1
1681
// // PluginDetailViewController.swift // Volumio // // Created by Federico Sintucci on 12/10/16. // Copyright © 2016 Federico Sintucci. All rights reserved. // import UIKit import Eureka class PluginDetailViewController: FormViewController { var plugin: PluginObject! override func viewDidLoad() { super.viewDidLoad() self.title = plugin.prettyName form +++ Section("") <<< LabelRow { $0.title = localizedVersionTitle $0.value = plugin.version } <<< SwitchRow { $0.title = localizedStatusTitle $0.value = plugin.enabled == 1 }.onChange { [weak self] (row) in guard let plugin = self?.plugin else { return } guard let name = plugin.name, let category = plugin.category else { return } VolumioIOManager.shared.togglePlugin( name: name, category: category, action: (row.value ?? false) ? "enable" : "disable" ) } } } // MARK: - Localization extension PluginDetailViewController { fileprivate func localize() { navigationItem.title = NSLocalizedString("PLUGIN", comment: "plugin view title" ) } fileprivate var localizedVersionTitle: String { return NSLocalizedString("PLUGIN_VERSION", comment: "volumio player’s plugin version") } fileprivate var localizedStatusTitle: String { return NSLocalizedString("PLUGIN_STATUS", comment: "volumio player’s plugin status") } }
gpl-3.0
5617205cca28cab3798804f974997b3c
25.1875
94
0.568616
4.747875
false
false
false
false
ello/ello-ios
Sources/Controllers/Home/HomeViewController.swift
1
4414
//// /// HomeViewController.swift // class HomeViewController: BaseElloViewController, HomeScreenDelegate { override func trackerName() -> String? { return nil } var visibleViewController: UIViewController? var editorialsViewController: EditorialsViewController! var artistInvitesViewController: ArtistInvitesViewController! var followingViewController: FollowingViewController! var discoverViewController: CategoryViewController! enum Usage { case loggedOut case loggedIn } private let usage: Usage init(usage: Usage) { self.usage = usage super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var _mockScreen: HomeScreenProtocol? var screen: HomeScreenProtocol { set(screen) { _mockScreen = screen } get { return fetchScreen(_mockScreen) } } override func didSetCurrentUser() { super.didSetCurrentUser() editorialsViewController?.currentUser = currentUser artistInvitesViewController?.currentUser = currentUser followingViewController?.currentUser = currentUser discoverViewController?.currentUser = currentUser } override func loadView() { let screen = HomeScreen() screen.delegate = self view = screen } override func viewDidLoad() { super.viewDidLoad() setupControllers() } } extension HomeViewController: HomeResponder { func showEditorialsViewController() { showController(editorialsViewController) } func showArtistInvitesViewController() { showController(artistInvitesViewController) } func showFollowingViewController() { showController(followingViewController) } func showDiscoverViewController() { showController(discoverViewController) } private func setupControllers() { let editorialsViewController = EditorialsViewController(usage: usage) editorialsViewController.currentUser = currentUser addChild(editorialsViewController) editorialsViewController.didMove(toParent: self) self.editorialsViewController = editorialsViewController let artistInvitesViewController = ArtistInvitesViewController(usage: usage) artistInvitesViewController.currentUser = currentUser addChild(artistInvitesViewController) artistInvitesViewController.didMove(toParent: self) self.artistInvitesViewController = artistInvitesViewController let followingViewController = FollowingViewController() followingViewController.currentUser = currentUser addChild(followingViewController) followingViewController.didMove(toParent: self) self.followingViewController = followingViewController let discoverViewController = CategoryViewController( currentUser: currentUser, usage: .largeNav ) addChild(discoverViewController) discoverViewController.didMove(toParent: self) self.discoverViewController = discoverViewController showController(editorialsViewController) } private func showController(_ viewController: UIViewController) { guard visibleViewController != viewController else { return } viewController.view.frame = screen.controllerContainer.bounds viewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] viewController.view.layoutIfNeeded() if let visibleViewController = visibleViewController { screen.controllerContainer.insertSubview( viewController.view, aboveSubview: visibleViewController.view ) visibleViewController.view.removeFromSuperview() } else { screen.controllerContainer.addSubview(viewController.view) } visibleViewController = viewController } } let drawerAnimator = DrawerAnimator() extension HomeViewController: DrawerResponder { func showDrawerViewController() { let drawer = DrawerViewController() drawer.currentUser = currentUser drawer.transitioningDelegate = drawerAnimator drawer.modalPresentationStyle = .custom self.present(drawer, animated: true, completion: nil) } }
mit
dc6fd806500e7edcfc31fb80aa3c513c
29.652778
83
0.705483
6.105118
false
false
false
false
jmont/Mustachio
Mustachio/MustachioTests/ArrayExtensionsTests.swift
1
973
// // ArrayExtensionsTests.swift // Mustachio // // Created by Montemayor Elosua, Juan Carlos on 8/31/14. // Copyright (c) 2014 jmont. All rights reserved. // import UIKit import XCTest import Mustachio class ArrayExtensionTests: 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 testDropWhile() { var resultArray = Array("{{name}}").dropWhile({(char: Character) -> Bool in char == "{" }) var result = String(seq: resultArray) XCTAssertEqual(result, "name}}") } func testTrimWhitespace() { var result = " all this whitespace ".trimWhitespace() XCTAssertEqual(result, "all this whitespace") } }
mit
ecf1432e60e845ceca1d7e9e4ca545e6
26.8
111
0.645427
4.230435
false
true
false
false
blackbear/OpenHumansUpload
OpenHumansUpload/OpenHumansUpload/ViewController.swift
1
4171
// // ViewController.swift // OpenHumansUpload // // Created by James Turner on 4/28/16. // Copyright © 2016 Open Humans. All rights reserved. // import UIKit import HealthKit import Foundation import Crashlytics class ViewController: UIViewController { @IBOutlet weak var actionButton: UIButton! @IBOutlet weak var instructions: UILabel! var healthStore : HKHealthStore! var accessToken = "" var fileList : JSONArray = JSONArray() enum AppState { case Start, Checking, Prelogin, Postlogin } var currentState = AppState.Start func logUser(userId : String) { // TODO: Use the current user's information // You can call any combination of these three methods Crashlytics.sharedInstance().setUserIdentifier(userId) } override func viewDidLoad() { super.viewDidLoad() instructions.hidden = true actionButton.hidden = true let oauth = OH_OAuth2.sharedInstance(); if oauth.hasCachedToken() { instructions.text = "Logging in..." instructions.hidden = false OH_OAuth2.sharedInstance().authenticateOAuth2(self, allowLogin: false, handler: { (status : AuthorizationStatus) -> Void in if (status == AuthorizationStatus.AUTHORIZED) { OH_OAuth2.sharedInstance().getMemberInfo({ (memberId, messagePermission, usernameShared, username, files) in self.logUser(memberId) self.fileList = files dispatch_async(dispatch_get_main_queue(), { self.performSegueWithIdentifier("startupToMain", sender: self) }) }, onFailure: { dispatch_async(dispatch_get_main_queue(), { self.authenticateRequiresLogin() }) }) } else { self.authenticateRequiresLogin() } }); } else { self.authenticateRequiresLogin() } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "startupToMain") { let vc = segue.destinationViewController as! MainMenu vc.fileList = fileList } } func authenticateRequiresLogin() { instructions.text = "Welcome to the Open Humans HealthKit Uploader. This tool will allow you to upload your HealthKit data (visible in the Health app) to your Open Humans account so that researchers can access the information you have recorded on your device.\n\nTo begin, you need to authenticate your identity with the Open Humans Web Site." actionButton.setTitle("Go to Open Humans website", forState: .Normal) instructions.hidden = false actionButton.hidden = false } func uploadSucceeded(res: String) { print(res); } func memberInfoFailed() { } func authenticateFailed() -> Void { authenticateRequiresLogin() } func authenticateCanceled() -> Void { authenticateRequiresLogin() } override func viewDidAppear(animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func validateToken(token: String) -> Void { } @IBAction func nextAction(sender: AnyObject) { OH_OAuth2.sharedInstance().authenticateOAuth2(self, allowLogin: true, handler: { (status : AuthorizationStatus) -> Void in OH_OAuth2.sharedInstance().getMemberInfo({ (memberId, messagePermission, usernameShared, username, files) in self.logUser(memberId) self.performSegueWithIdentifier("startupToMain", sender: self) }, onFailure: { self.authenticateRequiresLogin() }) }); } }
mit
a7a1fc5be57f38b81b4a8515cc62178a
31.578125
351
0.586811
5.401554
false
false
false
false
bastianX6/swift-serializer
src/Serializable.swift
1
6525
/* Converts A class to a dictionary, used for serializing dictionaries to JSON Supported objects: - Serializable derived classes (sub classes) - Arrays of Serializable - NSData - String, Numeric, and all other NSJSONSerialization supported objects */ import Foundation public class Serializable: NSObject { private class SortedDictionary: NSMutableDictionary { var dictionary = [String: AnyObject]() override var count: Int { return dictionary.count } override func keyEnumerator() -> NSEnumerator { let sortedKeys: NSArray = dictionary.keys.sort() return sortedKeys.objectEnumerator() } override func setValue(value: AnyObject?, forKey key: String) { dictionary[key] = value } override func objectForKey(aKey: AnyObject) -> AnyObject? { if let key = aKey as? String { return dictionary[key] } return nil } } public func formatKey(key: String) -> String { return key } public func formatValue(value: AnyObject?, forKey: String) -> AnyObject? { return value } func setValue(dictionary: NSDictionary, value: AnyObject?, forKey: String) { dictionary.setValue(formatValue(value, forKey: forKey), forKey: formatKey(forKey)) } /** Converts the class to a dictionary. - returns: The class as an NSDictionary. */ public func toDictionary() -> NSDictionary { let propertiesDictionary = SortedDictionary() let mirror = Mirror(reflecting: self) for (propName, propValue) in mirror.children { if let propValue: AnyObject = self.unwrap(propValue) as? AnyObject, propName = propName { if let serializablePropValue = propValue as? Serializable { setValue(propertiesDictionary, value: serializablePropValue.toDictionary(), forKey: propName) } else if let arrayPropValue = propValue as? [Serializable] { let subArray = arrayPropValue.toNSDictionaryArray() setValue(propertiesDictionary, value: subArray, forKey: propName) } else if propValue is Int || propValue is Double || propValue is Float || propValue is Bool { setValue(propertiesDictionary, value: propValue, forKey: propName) } else if let dataPropValue = propValue as? NSData { setValue(propertiesDictionary, value: dataPropValue.base64EncodedStringWithOptions(.Encoding64CharacterLineLength), forKey: propName) } else if let datePropValue = propValue as? NSDate { setValue(propertiesDictionary, value: self.dateToSringJSON(datePropValue), forKey: propName) } else { setValue(propertiesDictionary, value: propValue, forKey: propName) } } else if let propValue: Int8 = propValue as? Int8 { setValue(propertiesDictionary, value: NSNumber(char: propValue), forKey: propName!) } else if let propValue: Int16 = propValue as? Int16 { setValue(propertiesDictionary, value: NSNumber(short: propValue), forKey: propName!) } else if let propValue: Int32 = propValue as? Int32 { setValue(propertiesDictionary, value: NSNumber(int: propValue), forKey: propName!) } else if let propValue: Int64 = propValue as? Int64 { setValue(propertiesDictionary, value: NSNumber(longLong: propValue), forKey: propName!) } else if let propValue: UInt8 = propValue as? UInt8 { setValue(propertiesDictionary, value: NSNumber(unsignedChar: propValue), forKey: propName!) } else if let propValue: UInt16 = propValue as? UInt16 { setValue(propertiesDictionary, value: NSNumber(unsignedShort: propValue), forKey: propName!) } else if let propValue: UInt32 = propValue as? UInt32 { setValue(propertiesDictionary, value: NSNumber(unsignedInt: propValue), forKey: propName!) } else if let propValue: UInt64 = propValue as? UInt64 { setValue(propertiesDictionary, value: NSNumber(unsignedLongLong: propValue), forKey: propName!) } else if isEnum(propValue) { setValue(propertiesDictionary, value: "\(propValue)", forKey: propName!) } } return propertiesDictionary } /** Converts the class to JSON. - returns: The class as JSON, wrapped in NSData. */ public func toJson(prettyPrinted: Bool = false) -> NSData? { let dictionary = self.toDictionary() if NSJSONSerialization.isValidJSONObject(dictionary) { do { let json = try NSJSONSerialization.dataWithJSONObject(dictionary, options: (prettyPrinted ? .PrettyPrinted: NSJSONWritingOptions())) return json } catch let error as NSError { print("ERROR: Unable to serialize json, error: \(error)") } } return nil } /** Converts the class to a JSON string. - returns: The class as a JSON string. */ public func toJsonString(prettyPrinted: Bool = false) -> String? { if let jsonData = self.toJson(prettyPrinted) { return NSString(data: jsonData, encoding: NSUTF8StringEncoding) as String? } return nil } /** Unwraps 'any' object. See http://stackoverflow.com/questions/27989094/how-to-unwrap-an-optional-value-from-any-type - returns: The unwrapped object. */ func unwrap(any: Any) -> Any? { let mi = Mirror(reflecting: any) if mi.displayStyle != .Optional { return any } if mi.children.count == 0 { return nil } let (_, some) = mi.children.first! return some } func isEnum(any: Any) -> Bool { return Mirror(reflecting: any).displayStyle == .Enum } func dateToSringJSON(date: NSDate) -> String { let format = "MMM d, yyyy hh:mm:ss a" let formatter:NSDateFormatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.timeZone = NSTimeZone() formatter.dateFormat = format return formatter.stringFromDate(date) } }
mit
f660a58caa7ded67638a8535073e389d
38.071856
148
0.613946
4.988532
false
false
false
false
apple/swift
test/SILGen/private_import_other.swift
22
2543
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -module-name Mod -emit-module -enable-private-imports -swift-version 5 -o %t %S/Inputs/private_import_module.swift // RUN: %target-swift-emit-silgen -I %t -primary-file %s %S/private_import.swift -module-name main -swift-version 5 | %FileCheck %s // RUN: %target-swift-emit-silgen -I %t %s %S/private_import.swift -module-name main -swift-version 5 | %FileCheck %s // RUN: %target-swift-emit-silgen -I %t %S/private_import.swift %s -module-name main -swift-version 5 | %FileCheck %s // RUN: %target-swift-emit-ir -I %t -primary-file %s %S/private_import.swift -module-name main -o /dev/null // RUN: %target-swift-emit-ir -I %t -O -primary-file %s %S/private_import.swift -module-name main -o /dev/null @_private(sourceFile: "private_import_module.swift") import Mod func use<F: Fooable>(_ f: F) { f.foo() } func test(internalFoo: FooImpl, publicFoo: PublicFooImpl) { use(internalFoo) use(publicFoo) internalFoo.foo() publicFoo.foo() } // CHECK-LABEL: sil hidden [ossa] @$s4main4test11internalFoo06publicD0yAA0D4ImplV_AA06PublicdF0VtF // CHECK: [[USE_1:%.+]] = function_ref @$s4main3useyyxAA7FooableRzlF // CHECK: = apply [[USE_1]]<FooImpl>({{%.+}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Fooable> (@in_guaranteed τ_0_0) -> () // CHECK: [[USE_2:%.+]] = function_ref @$s4main3useyyxAA7FooableRzlF // CHECK: = apply [[USE_2]]<PublicFooImpl>({{%.+}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Fooable> (@in_guaranteed τ_0_0) -> () // CHECK: [[IMPL_1:%.+]] = function_ref @$s3Mod13HasDefaultFoo33_{{.*}}PAAE3fooyyF // CHECK: = apply [[IMPL_1]]<FooImpl>({{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaultFoo> (@in_guaranteed τ_0_0) -> () // CHECK: [[IMPL_2:%.+]] = function_ref @$s3Mod13HasDefaultFoo33_{{.*}}PAAE3fooyyF // CHECK: = apply [[IMPL_2]]<PublicFooImpl>({{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaultFoo> (@in_guaranteed τ_0_0) -> () // CHECK: } // end sil function '$s4main4test11internalFoo06publicD0yAA0D4ImplV_AA06PublicdF0VtF' func test(internalSub: Sub, publicSub: PublicSub) { internalSub.foo() publicSub.foo() } // CHECK-LABEL: sil hidden [ossa] @$s4main4test11internalSub06publicD0yAA0D0C_AA06PublicD0CtF // CHECK: bb0([[ARG0:%.*]] : @guaranteed $Sub, [[ARG1:%.*]] : @guaranteed $PublicSub): // CHECK: = class_method [[ARG0]] : $Sub, #Sub.foo : // CHECK: = class_method [[ARG1]] : $PublicSub, #PublicSub.foo : // CHECK: } // end sil function '$s4main4test11internalSub06publicD0yAA0D0C_AA06PublicD0CtF'
apache-2.0
86fbb28453d8b628420ee06ec2f64e8a
57.860465
145
0.678388
2.859887
false
true
false
false
makhiye/flagMatching
Pods/LTMorphingLabel/LTMorphingLabel/LTStringDiffResult.swift
6
3926
// // LTStringDiffResult.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2016 Lex Tang, http://lexrus.com // // 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 public typealias LTStringDiffResult = ([LTCharacterDiffResult], skipDrawingResults: [Bool]) public extension String { public func diffWith(_ anotherString: String?) -> LTStringDiffResult { guard let anotherString = anotherString else { let diffResults: [LTCharacterDiffResult] = Array(repeating: .delete, count: characters.count) let skipDrawingResults: [Bool] = Array(repeating: false, count: characters.count) return (diffResults, skipDrawingResults) } let newChars = anotherString.characters.enumerated() let lhsLength = characters.count let rhsLength = anotherString.characters.count var skipIndexes = [Int]() let leftChars = Array(characters) let maxLength = max(lhsLength, rhsLength) var diffResults: [LTCharacterDiffResult] = Array(repeating: .add, count: maxLength) var skipDrawingResults: [Bool] = Array(repeating: false, count: maxLength) for i in 0..<maxLength { // If new string is longer than the original one if i > lhsLength - 1 { continue } let leftChar = leftChars[i] // Search left character in the new string var foundCharacterInRhs = false for (j, newChar) in newChars { if skipIndexes.contains(j) || leftChar != newChar { continue } skipIndexes.append(j) foundCharacterInRhs = true if i == j { // Character not changed diffResults[i] = .same } else { // foundCharacterInRhs and move let offset = j - i if i <= rhsLength - 1 { // Move to a new index and add a new character to new original place diffResults[i] = .moveAndAdd(offset: offset) } else { diffResults[i] = .move(offset: offset) } skipDrawingResults[j] = true } break } if !foundCharacterInRhs { if i < rhsLength - 1 { diffResults[i] = .replace } else { diffResults[i] = .delete } } } return (diffResults, skipDrawingResults) } }
mit
69eb1ae32d9ea8d4085476a73bdf3146
37.411765
93
0.570955
4.891386
false
false
false
false
ContinuousLearning/PokemonKit
Carthage/Checkouts/PromiseKit/Sources/State.swift
1
3733
import Foundation.NSError enum Resolution { case Fulfilled(Any) //TODO make type T when Swift can handle it case Rejected(NSError) } enum Seal { case Pending(Handlers) case Resolved(Resolution) } protocol State { func get() -> Resolution? func get(body: (Seal) -> Void) } class UnsealedState: State { private let barrier = dispatch_queue_create("org.promisekit.barrier", DISPATCH_QUEUE_CONCURRENT) private var seal: Seal /** Quick return, but will not provide the handlers array because it could be modified while you are using it by another thread. If you need the handlers, use the second `get` variant. */ func get() -> Resolution? { var result: Resolution? dispatch_sync(barrier) { switch self.seal { case .Resolved(let resolution): result = resolution case .Pending: break } } return result } func get(body: (Seal) -> Void) { var sealed = false dispatch_sync(barrier) { switch self.seal { case .Resolved: sealed = true case .Pending: sealed = false } } if !sealed { dispatch_barrier_sync(barrier) { switch (self.seal) { case .Pending: body(self.seal) case .Resolved: sealed = true // welcome to race conditions } } } if sealed { body(seal) } } init(inout resolver: ((Resolution) -> Void)!) { seal = .Pending(Handlers()) resolver = { resolution in var handlers: Handlers? dispatch_barrier_sync(self.barrier) { switch self.seal { case .Pending(let hh): self.seal = .Resolved(resolution) handlers = hh case .Resolved: break } } if let handlers = handlers { for handler in handlers { handler(resolution) } } } } } class SealedState: State { private let resolution: Resolution init(resolution: Resolution) { self.resolution = resolution } func get() -> Resolution? { return resolution } func get(body: (Seal) -> Void) { body(.Resolved(resolution)) } } class Handlers: SequenceType { var bodies: [(Resolution)->()] = [] func append(body: (Resolution)->()) { bodies.append(body) } func generate() -> IndexingGenerator<[(Resolution)->()]> { return bodies.generate() } var count: Int { return bodies.count } } extension Resolution: CustomDebugStringConvertible { var debugDescription: String { switch self { case Fulfilled(let value): return "Fulfilled with value: \(value)" case Rejected(let error): return "Rejected with error: \(error)" } } } extension UnsealedState: CustomDebugStringConvertible { var debugDescription: String { var rv: String? get { seal in switch seal { case .Pending(let handlers): rv = "Pending with \(handlers.count) handlers" case .Resolved(let resolution): rv = "\(resolution)" } } return "UnsealedState: \(rv!)" } } extension SealedState: CustomDebugStringConvertible { var debugDescription: String { return "SealedState: \(resolution)" } }
mit
416aa5c54124742256b105cdd38e4a13
23.721854
100
0.5221
4.816774
false
false
false
false
brentdax/swift
test/IRGen/sil_generic_witness_methods.swift
2
4868
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // FIXME: These should be SIL tests, but we can't parse generic types in SIL // yet. protocol P { func concrete_method() static func concrete_static_method() func generic_method<Z>(_ x: Z) } struct S {} // CHECK-LABEL: define hidden swiftcc void @"$s27sil_generic_witness_methods05call_D0{{[_0-9a-zA-Z]*}}F"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U, i8** %T.P) func call_methods<T: P, U>(_ x: T, y: S, z: U) { // CHECK: [[STATIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 2 // CHECK: [[STATIC_METHOD_PTR:%.*]] = load i8*, i8** [[STATIC_METHOD_ADDR]], align 8 // CHECK: [[STATIC_METHOD:%.*]] = bitcast i8* [[STATIC_METHOD_PTR]] to void (%swift.type*, %swift.type*, i8**)* // CHECK: call swiftcc void [[STATIC_METHOD]](%swift.type* swiftself %T, %swift.type* %T, i8** %T.P) T.concrete_static_method() // CHECK: [[CONCRETE_METHOD_PTR_GEP:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 1 // CHECK: [[CONCRETE_METHOD_PTR:%.*]] = load i8*, i8** [[CONCRETE_METHOD_PTR_GEP]] // CHECK: [[CONCRETE_METHOD:%.*]] = bitcast i8* [[CONCRETE_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[CONCRETE_METHOD]](%swift.opaque* noalias nocapture swiftself {{%.*}}, %swift.type* %T, i8** %T.P) x.concrete_method() // CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 3 // CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8 // CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* {{.*}} @"$s27sil_generic_witness_methods1SVMf", {{.*}} %swift.opaque* noalias nocapture swiftself {{.*}}, %swift.type* %T, i8** %T.P) x.generic_method(y) // CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 3 // CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8 // CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* %U, %swift.opaque* noalias nocapture swiftself {{.*}}, %swift.type* %T, i8** %T.P) x.generic_method(z) } // CHECK-LABEL: define hidden swiftcc void @"$s27sil_generic_witness_methods017call_existential_D0{{[_0-9a-zA-Z]*}}F"(%T27sil_generic_witness_methods1PP* noalias nocapture dereferenceable({{.*}})) func call_existential_methods(_ x: P, y: S) { // CHECK: [[METADATA_ADDR:%.*]] = getelementptr inbounds %T27sil_generic_witness_methods1PP, %T27sil_generic_witness_methods1PP* [[X:%0]], i32 0, i32 1 // CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]], align 8 // CHECK: [[WTABLE_ADDR:%.*]] = getelementptr inbounds %T27sil_generic_witness_methods1PP, %T27sil_generic_witness_methods1PP* [[X]], i32 0, i32 2 // CHECK: [[WTABLE:%.*]] = load i8**, i8*** [[WTABLE_ADDR]], align 8 // CHECK: [[CONCRETE_METHOD_PTR_GEP:%.*]] = getelementptr inbounds i8*, i8** [[WTABLE]], i32 1 // CHECK: [[CONCRETE_METHOD_PTR:%.*]] = load i8*, i8** [[CONCRETE_METHOD_PTR_GEP]], align 8 // CHECK: [[CONCRETE_METHOD:%.*]] = bitcast i8* [[CONCRETE_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[CONCRETE_METHOD]](%swift.opaque* noalias nocapture swiftself {{%.*}}, %swift.type* [[METADATA]], i8** [[WTABLE]]) x.concrete_method() // CHECK: [[METADATA_ADDR:%.*]] = getelementptr inbounds %T27sil_generic_witness_methods1PP, %T27sil_generic_witness_methods1PP* [[X]], i32 0, i32 1 // CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]], align 8 // CHECK: [[WTABLE_ADDR:%.*]] = getelementptr inbounds %T27sil_generic_witness_methods1PP, %T27sil_generic_witness_methods1PP* [[X:%.*]], i32 0, i32 2 // CHECK: [[WTABLE:%.*]] = load i8**, i8*** [[WTABLE_ADDR]], align 8 // CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[WTABLE]], i32 3 // CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8 // CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* {{.*}} @"$s27sil_generic_witness_methods1SVMf", {{.*}} %swift.opaque* noalias nocapture swiftself {{%.*}}, %swift.type* [[METADATA]], i8** [[WTABLE]]) x.generic_method(y) }
apache-2.0
6bb211a5840a6bf9208e6b2f5b384cdb
77.516129
253
0.637634
3.247498
false
false
false
false
brentdax/swift
test/ClangImporter/optional.swift
1
3903
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name optional -I %S/Inputs/custom-modules -enable-sil-ownership -emit-silgen -o - %s | %FileCheck %s // REQUIRES: objc_interop import ObjectiveC import Foundation import objc_ext import TestProtocols class A { @objc func foo() -> String? { return "" } // CHECK-LABEL: sil hidden [thunk] @$s8optional1AC3fooSSSgyFTo : $@convention(objc_method) (A) -> @autoreleased Optional<NSString> // CHECK: bb0([[SELF:%.*]] : @unowned $A): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[T0:%.*]] = function_ref @$s8optional1AC3fooSSSgyF // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: switch_enum [[T1]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // Something branch: project value, translate, inject into result. // CHECK: [[SOME_BB]]([[STR:%.*]] : @owned $String): // CHECK: [[T0:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK-NEXT: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BORROWED_STR]]) // CHECK-NEXT: enum $Optional<NSString>, #Optional.some!enumelt.1, [[T1]] // CHECK-NEXT: end_borrow [[BORROWED_STR:%.*]] // CHECK-NEXT: destroy_value [[STR]] // CHECK-NEXT: br // Nothing branch: inject nothing into result. // // CHECK: [[NONE_BB]]: // CHECK-NEXT: enum $Optional<NSString>, #Optional.none!enumelt // CHECK-NEXT: br // Continuation. // CHECK: bb3([[T0:%.*]] : @owned $Optional<NSString>): // CHECK-NEXT: return [[T0]] @objc func bar(x x : String?) {} // CHECK-LABEL: sil hidden [thunk] @$s8optional1AC3bar1xySSSg_tFTo : $@convention(objc_method) (Optional<NSString>, A) -> () // CHECK: bb0([[ARG:%.*]] : @unowned $Optional<NSString>, [[SELF:%.*]] : @unowned $A): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: switch_enum [[ARG_COPY]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // Something branch: project value, translate, inject into result. // CHECK: [[SOME_BB]]([[NSSTR:%.*]] : @owned $NSString): // CHECK: [[T0:%.*]] = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ // Make a temporary initialized string that we're going to clobber as part of the conversion process (?). // CHECK-NEXT: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR]] : $NSString // CHECK-NEXT: [[STRING_META:%.*]] = metatype $@thin String.Type // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[NSSTR_BOX]], [[STRING_META]]) // CHECK-NEXT: enum $Optional<String>, #Optional.some!enumelt.1, [[T1]] // CHECK-NEXT: destroy_value [[NSSTR_BOX]] // CHECK-NEXT: br // // Nothing branch: inject nothing into result. // CHECK: [[NONE_BB]]: // CHECK: enum $Optional<String>, #Optional.none!enumelt // CHECK-NEXT: br // Continuation. // CHECK: bb3([[T0:%.*]] : @owned $Optional<String>): // CHECK: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[T1:%.*]] = function_ref @$s8optional1AC3bar1xySSSg_tF // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[BORROWED_T0]], [[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[T2]] : $() } // rdar://15144951 class TestWeak : NSObject { weak var b : WeakObject? = nil } class WeakObject : NSObject {}
apache-2.0
9399ce0441882359b0f6b11dc115fa7a
46.024096
170
0.627978
3.222956
false
false
false
false
kikettas/Swarkn
Swarkn/Classes/NSDate.swift
1
3366
// // NSDate.swift // Worktoday // // Created by kikettas on 12/2/16. // Copyright © 2016. All rights reserved. // import Foundation extension Date{ public static let dayInMinutes:Double = 1440 public static let dayInSeconds:Double = 86400 public static let dayInMiliSeconds:Double = 86400000 public enum TimeUnit{ case milisecond,second,minute,hour,day,week,month,year } public var timeIntervalSince1970InMs : Double{ get{ return self.timeIntervalSince1970 * 1000 } } public enum DateSymbolsLongitude{ case short, veryShort, standalone, normal } public func monthName(_ dateSymbolsLongityde:DateSymbolsLongitude, monthNumber:Int)-> String{ let dateFormatter: DateFormatter = DateFormatter() let months:[String]? switch dateSymbolsLongityde{ case .short: months = dateFormatter.shortMonthSymbols break case .veryShort: months = dateFormatter.veryShortMonthSymbols break case .standalone: months = dateFormatter.standaloneMonthSymbols break case .normal: months = dateFormatter.monthSymbols break } return months![monthNumber] } public func weekDayName(_ dateSymbolsLongityde:DateSymbolsLongitude, dayNumber:Int)-> String{ let dateFormatter: DateFormatter = DateFormatter() let days:[String]? switch dateSymbolsLongityde{ case .short: days = dateFormatter.shortWeekdaySymbols break case .veryShort: days = dateFormatter.veryShortWeekdaySymbols break case .standalone: days = dateFormatter.standaloneWeekdaySymbols break case .normal: days = dateFormatter.weekdaySymbols break } return days![dayNumber] } public func getYearMonthDay() -> (Int, Int, Int){ let calendar = Calendar.current let components = (calendar as NSCalendar).components([NSCalendar.Unit.year,NSCalendar.Unit.month,NSCalendar.Unit.day], from: self) return (components.year!,components.month!,components.day!) } public static func from(unit:TimeUnit, value:Int, toUnit:TimeUnit) -> Double{ let toMsScale = [1,1000,60000,3600000,86400000] var fromIndexOnArray:Int = 0 var toIndexOnArray:Int = 0 switch unit{ case .milisecond: fromIndexOnArray = 0 break case .second: fromIndexOnArray = 1 break case .minute: fromIndexOnArray = 2 case .hour: fromIndexOnArray = 3 case .day: fromIndexOnArray = 4 default: break } switch toUnit{ case .milisecond: toIndexOnArray = 0 break case .second: toIndexOnArray = 1 break case .minute: toIndexOnArray = 2 case .hour: toIndexOnArray = 3 case .day: toIndexOnArray = 4 default: break } return Double(value * toMsScale[fromIndexOnArray] / toMsScale[toIndexOnArray]) } }
mit
56fa3079d182301d9781800380423df1
27.277311
138
0.583655
5.022388
false
false
false
false
carlospaelinck/pokebattle
PokéBattle/Type.swift
1
957
// // Type.swift // PokéBattle // // Created by Carlos Paelinck on 4/11/16. // Copyright © 2016 Carlos Paelinck. All rights reserved. // import Foundation enum PokémonType: String { case Bug = "Bug" case Dark = "Dark" case Dragon = "Dragon" case Electric = "Electric" case Fairy = "Fairy" case Fighting = "Fighting" case Fire = "Fire" case Flying = "Flying" case Ghost = "Ghost" case Grass = "Grass" case Ground = "Ground" case Ice = "Ice" case Normal = "Normal" case Poison = "Poison" case Psychic = "Psychic" case Rock = "Rock" case Steel = "Steel" case Water = "Water" case None = "None" } internal var AllPokémonTypes: [PokémonType] { get { return [ .Bug, .Dark, .Dragon, .Electric, .Fairy, .Fighting, .Fire, .Flying, .Ghost, .Grass, .Ground, .Ice, .Normal, .Poison, .Psychic, .Rock, .Steel, .Water ] } }
mit
53820b83d6796b1f4abda4e74bb5ea86
22.243902
63
0.57563
3.328671
false
false
false
false
hooman/swift
test/AutoDiff/Sema/differentiable_attr_type_checking.swift
1
24735
// RUN: %target-swift-frontend-typecheck -verify -disable-availability-checking %s // RUN: %target-swift-frontend-typecheck -enable-testing -verify -disable-availability-checking %s import _Differentiation // Dummy `Differentiable`-conforming type. public struct DummyTangentVector: Differentiable & AdditiveArithmetic { public static var zero: Self { Self() } public static func + (_: Self, _: Self) -> Self { Self() } public static func - (_: Self, _: Self) -> Self { Self() } public typealias TangentVector = Self } @differentiable(reverse) // expected-error {{'@differentiable' attribute cannot be applied to this declaration}} let globalConst: Float = 1 @differentiable(reverse) // expected-error {{'@differentiable' attribute cannot be applied to this declaration}} var globalVar: Float = 1 func testLocalVariables() { // expected-error @+1 {{'_' has no parameters to differentiate with respect to}} @differentiable(reverse) var getter: Float { return 1 } // expected-error @+1 {{'_' has no parameters to differentiate with respect to}} @differentiable(reverse) var getterSetter: Float { get { return 1 } set {} } } @differentiable(reverse) // expected-error {{'@differentiable' attribute cannot be applied to this declaration}} protocol P {} @differentiable(reverse) // ok! func no_jvp_or_vjp(_ x: Float) -> Float { return x * x } // Test duplicate `@differentiable` attributes. @differentiable(reverse) // expected-error {{duplicate '@differentiable' attribute with same parameters}} @differentiable(reverse) // expected-note {{other attribute declared here}} func dupe_attributes(arg: Float) -> Float { return arg } @differentiable(reverse, wrt: arg1) @differentiable(reverse, wrt: arg2) // expected-error {{duplicate '@differentiable' attribute with same parameters}} @differentiable(reverse, wrt: arg2) // expected-note {{other attribute declared here}} func dupe_attributes(arg1: Float, arg2: Float) -> Float { return arg1 } struct ComputedPropertyDupeAttributes<T: Differentiable>: Differentiable { typealias TangentVector = DummyTangentVector mutating func move(by _: TangentVector) {} var value: T @differentiable(reverse) // expected-note {{other attribute declared here}} var computed1: T { @differentiable(reverse) // expected-error {{duplicate '@differentiable' attribute with same parameters}} get { value } set { value = newValue } } // TODO(TF-482): Remove diagnostics when `@differentiable` attributes are // also uniqued based on generic requirements. @differentiable(reverse where T == Float) // expected-error {{duplicate '@differentiable' attribute with same parameters}} @differentiable(reverse where T == Double) // expected-note {{other attribute declared here}} var computed2: T { get { value } set { value = newValue } } } // Test TF-568. protocol WrtOnlySelfProtocol: Differentiable { @differentiable(reverse) var computedProperty: Float { get } @differentiable(reverse) func method() -> Float } class Class: Differentiable { typealias TangentVector = DummyTangentVector func move(by _: TangentVector) {} } @differentiable(reverse, wrt: x) func invalidDiffWrtClass(_ x: Class) -> Class { return x } protocol Proto {} // expected-error @+1 {{can only differentiate functions with results that conform to 'Differentiable', but 'Proto' does not conform to 'Differentiable'}} @differentiable(reverse, wrt: x) func invalidDiffWrtExistential(_ x: Proto) -> Proto { return x } // expected-error @+1 {{can only differentiate with respect to parameters that conform to 'Differentiable', but '@differentiable(reverse) (Float) -> Float' does not conform to 'Differentiable'}} @differentiable(reverse, wrt: fn) func invalidDiffWrtFunction(_ fn: @differentiable(reverse) (Float) -> Float) -> Float { return fn(.pi) } // expected-error @+1 {{'invalidDiffNoParams()' has no parameters to differentiate with respect to}} @differentiable(reverse) func invalidDiffNoParams() -> Float { return 1 } // expected-error @+1 {{cannot differentiate void function 'invalidDiffVoidResult(x:)'}} @differentiable(reverse) func invalidDiffVoidResult(x: Float) {} // Test static methods. struct StaticMethod { // expected-error @+1 {{'invalidDiffNoParams()' has no parameters to differentiate with respect to}} @differentiable(reverse) static func invalidDiffNoParams() -> Float { return 1 } // expected-error @+1 {{cannot differentiate void function 'invalidDiffVoidResult(x:)'}} @differentiable(reverse) static func invalidDiffVoidResult(x: Float) {} } // Test instance methods. struct InstanceMethod { // expected-error @+1 {{'invalidDiffNoParams()' has no parameters to differentiate with respect to}} @differentiable(reverse) func invalidDiffNoParams() -> Float { return 1 } // expected-error @+1 {{cannot differentiate void function 'invalidDiffVoidResult(x:)'}} @differentiable(reverse) func invalidDiffVoidResult(x: Float) {} } // Test instance methods for a `Differentiable` type. struct DifferentiableInstanceMethod: Differentiable { typealias TangentVector = DummyTangentVector mutating func move(by _: TangentVector) {} @differentiable(reverse) // ok func noParams() -> Float { return 1 } } // Test subscript methods. struct SubscriptMethod: Differentiable { typealias TangentVector = DummyTangentVector mutating func move(by _: TangentVector) {} @differentiable(reverse) // ok subscript(implicitGetter x: Float) -> Float { return x } @differentiable(reverse) // ok subscript(implicitGetterSetter x: Float) -> Float { get { return x } set {} } subscript(explicit x: Float) -> Float { @differentiable(reverse) // ok get { return x } @differentiable(reverse) set {} } subscript(x: Float, y: Float) -> Float { @differentiable(reverse) // ok get { return x + y } @differentiable(reverse) set {} } } // expected-error @+3 {{type 'Scalar' constrained to non-protocol, non-class type 'Float'}} // expected-error @+2 {{no differentiation parameters could be inferred; must differentiate with respect to at least one parameter conforming to 'Differentiable'}} // expected-note @+1 {{use 'Scalar == Float' to require 'Scalar' to be 'Float'}} @differentiable(reverse where Scalar: Float) func invalidRequirementConformance<Scalar>(x: Scalar) -> Scalar { return x } @differentiable(reverse where T: AnyObject) func invalidAnyObjectRequirement<T: Differentiable>(x: T) -> T { return x } // expected-error @+1 {{'@differentiable' attribute does not yet support layout requirements}} @differentiable(reverse where Scalar: _Trivial) func invalidRequirementLayout<Scalar>(x: Scalar) -> Scalar { return x } // expected-error @+1 {{no differentiation parameters could be inferred; must differentiate with respect to at least one parameter conforming to 'Differentiable'}} @differentiable(reverse) func missingConformance<T>(_ x: T) -> T { return x } protocol ProtocolRequirements: Differentiable { // expected-note @+2 {{protocol requires initializer 'init(x:y:)' with type '(x: Float, y: Float)'}} @differentiable(reverse) init(x: Float, y: Float) // expected-note @+2 {{protocol requires initializer 'init(x:y:)' with type '(x: Float, y: Int)'}} @differentiable(reverse, wrt: x) init(x: Float, y: Int) // expected-note @+2 {{protocol requires function 'amb(x:y:)' with type '(Float, Float) -> Float';}} @differentiable(reverse) func amb(x: Float, y: Float) -> Float // expected-note @+2 {{protocol requires function 'amb(x:y:)' with type '(Float, Int) -> Float';}} @differentiable(reverse, wrt: x) func amb(x: Float, y: Int) -> Float // expected-note @+3 {{protocol requires function 'f1'}} // expected-note @+2 {{overridden declaration is here}} @differentiable(reverse, wrt: (self, x)) func f1(_ x: Float) -> Float // expected-note @+2 {{protocol requires function 'f2'}} @differentiable(reverse, wrt: (self, x, y)) func f2(_ x: Float, _ y: Float) -> Float } protocol ProtocolRequirementsRefined: ProtocolRequirements { // expected-error @+1 {{overriding declaration is missing attribute '@differentiable(reverse)'}} func f1(_ x: Float) -> Float } // Test missing `@differentiable` attribute for internal protocol witnesses. // No errors expected; internal `@differentiable` attributes are created. struct InternalDiffAttrConformance: ProtocolRequirements { typealias TangentVector = DummyTangentVector mutating func move(by _: TangentVector) {} var x: Float var y: Float init(x: Float, y: Float) { self.x = x self.y = y } init(x: Float, y: Int) { self.x = x self.y = Float(y) } func amb(x: Float, y: Float) -> Float { return x } func amb(x: Float, y: Int) -> Float { return x } func f1(_ x: Float) -> Float { return x } @differentiable(reverse, wrt: (self, x)) func f2(_ x: Float, _ y: Float) -> Float { return x + y } } // Test missing `@differentiable` attribute for public protocol witnesses. Errors expected. // expected-error @+1 {{does not conform to protocol 'ProtocolRequirements'}} public struct PublicDiffAttrConformance: ProtocolRequirements { public typealias TangentVector = DummyTangentVector public mutating func move(by _: TangentVector) {} var x: Float var y: Float // FIXME(TF-284): Fix unexpected diagnostic. // expected-note @+2 {{candidate is missing explicit '@differentiable(reverse)' attribute to satisfy requirement}} {{10-10=@differentiable(reverse) }} // expected-note @+1 {{candidate has non-matching type '(x: Float, y: Float)'}} public init(x: Float, y: Float) { self.x = x self.y = y } // FIXME(TF-284): Fix unexpected diagnostic. // expected-note @+2 {{candidate is missing explicit '@differentiable(reverse)' attribute to satisfy requirement}} {{10-10=@differentiable(reverse) }} // expected-note @+1 {{candidate has non-matching type '(x: Float, y: Int)'}} public init(x: Float, y: Int) { self.x = x self.y = Float(y) } // expected-note @+2 {{candidate is missing explicit '@differentiable(reverse)' attribute to satisfy requirement}} {{10-10=@differentiable(reverse) }} // expected-note @+1 {{candidate has non-matching type '(Float, Float) -> Float'}} public func amb(x: Float, y: Float) -> Float { return x } // expected-note @+2 {{candidate is missing explicit '@differentiable(reverse, wrt: x)' attribute to satisfy requirement}} {{10-10=@differentiable(reverse, wrt: x) }} // expected-note @+1 {{candidate has non-matching type '(Float, Int) -> Float'}} public func amb(x: Float, y: Int) -> Float { return x } // expected-note @+1 {{candidate is missing explicit '@differentiable(reverse)' attribute to satisfy requirement}} public func f1(_ x: Float) -> Float { return x } // expected-note @+2 {{candidate is missing explicit '@differentiable(reverse)' attribute to satisfy requirement}} @differentiable(reverse, wrt: (self, x)) public func f2(_ x: Float, _ y: Float) -> Float { return x + y } } protocol ProtocolRequirementsWithDefault_NoConformingTypes { @differentiable(reverse) func f1(_ x: Float) -> Float } extension ProtocolRequirementsWithDefault_NoConformingTypes { // TODO(TF-650): It would be nice to diagnose protocol default implementation // with missing `@differentiable` attribute. func f1(_ x: Float) -> Float { x } } protocol ProtocolRequirementsWithDefault { @differentiable(reverse) func f1(_ x: Float) -> Float } extension ProtocolRequirementsWithDefault { func f1(_ x: Float) -> Float { x } } struct DiffAttrConformanceErrors2: ProtocolRequirementsWithDefault { func f1(_ x: Float) -> Float { x } } protocol NotRefiningDiffable { @differentiable(reverse, wrt: x) func a(_ x: Float) -> Float } struct CertainlyNotDiffableWrtSelf: NotRefiningDiffable { func a(_ x: Float) -> Float { return x * 5.0 } } protocol TF285: Differentiable { @differentiable(reverse, wrt: (x, y)) @differentiable(reverse, wrt: x) func foo(x: Float, y: Float) -> Float } struct TF285MissingOneDiffAttr: TF285 { typealias TangentVector = DummyTangentVector mutating func move(by _: TangentVector) {} // Requirement is missing the required `@differentiable(reverse, wrt: (x, y))` attribute. // Since `TF285MissingOneDiffAttr.foo` is internal, the attribute is implicitly created. @differentiable(reverse, wrt: x) func foo(x: Float, y: Float) -> Float { return x } } // TF-521: Test invalid `@differentiable` attribute due to invalid // `Differentiable` conformance (`TangentVector` does not conform to // `AdditiveArithmetic`). struct TF_521<T: FloatingPoint> { var real: T var imaginary: T // expected-error @+1 {{can only differentiate functions with results that conform to 'Differentiable', but 'TF_521<T>' does not conform to 'Differentiable'}} @differentiable(reverse where T: Differentiable, T == T.TangentVector) init(real: T = 0, imaginary: T = 0) { self.real = real self.imaginary = imaginary } } // expected-error @+1 {{type 'TF_521<T>' does not conform to protocol 'Differentiable'}} extension TF_521: Differentiable where T: Differentiable { // expected-note @+1 {{possibly intended match 'TF_521<T>.TangentVector' (aka 'TF_521<T>') does not conform to 'AdditiveArithmetic'}} typealias TangentVector = TF_521 } // expected-error @+1 {{result type 'TF_521<Float>' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}} let _: @differentiable(reverse) (Float, Float) -> TF_521<Float> = { r, i in TF_521(real: r, imaginary: i) } // expected-error @+1 {{result type 'TF_521<Float>' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}} let _: @differentiable(reverse) (_, _) -> TF_521<Float> = { (r: Float, i: Float) in TF_521(real: r, imaginary: i) } // expected-error @+1 {{result type 'TF_521<Float>' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}} let _: @differentiable(reverse) (Float, Float) -> _ = { r, i in TF_521(real: r, imaginary: i) } // TF-296: Infer `@differentiable` wrt parameters to be to all parameters that conform to `Differentiable`. @differentiable(reverse) func infer1(_ a: Float, _ b: Int) -> Float { return a + Float(b) } @differentiable(reverse) func infer2(_ fn: @differentiable(reverse) (Float) -> Float, x: Float) -> Float { return fn(x) } struct DiffableStruct: Differentiable { typealias TangentVector = DummyTangentVector mutating func move(by _: TangentVector) {} var a: Float @differentiable(reverse) func fn(_ b: Float, _ c: Int) -> Float { return a + b + Float(c) } } struct NonDiffableStruct { var a: Float @differentiable(reverse) func fn(_ b: Float) -> Float { return a + b } } // Index based 'wrt:' struct NumberWrtStruct: Differentiable { typealias TangentVector = DummyTangentVector mutating func move(by _: TangentVector) {} var a, b: Float @differentiable(reverse, wrt: 0) // ok @differentiable(reverse, wrt: 1) // ok func foo1(_ x: Float, _ y: Float) -> Float { return a*x + b*y } @differentiable(reverse, wrt: -1) // expected-error {{expected a parameter, which can be a function parameter name, parameter index, or 'self'}} @differentiable(reverse, wrt: (1, x)) // expected-error {{parameters must be specified in original order}} func foo2(_ x: Float, _ y: Float) -> Float { return a*x + b*y } @differentiable(reverse, wrt: (x, 1)) // ok @differentiable(reverse, wrt: (0)) // ok static func staticFoo1(_ x: Float, _ y: Float) -> Float { return x + y } @differentiable(reverse, wrt: (1, 1)) // expected-error {{parameters must be specified in original order}} @differentiable(reverse, wrt: (2)) // expected-error {{parameter index is larger than total number of parameters}} static func staticFoo2(_ x: Float, _ y: Float) -> Float { return x + y } } @differentiable(reverse, wrt: y) // ok func two1(x: Float, y: Float) -> Float { return x + y } @differentiable(reverse, wrt: (x, y)) // ok func two2(x: Float, y: Float) -> Float { return x + y } @differentiable(reverse, wrt: (0, y)) // ok func two3(x: Float, y: Float) -> Float { return x + y } @differentiable(reverse, wrt: (x, 1)) // ok func two4(x: Float, y: Float) -> Float { return x + y } @differentiable(reverse, wrt: (0, 1)) // ok func two5(x: Float, y: Float) -> Float { return x + y } @differentiable(reverse, wrt: 2) // expected-error {{parameter index is larger than total number of parameters}} func two6(x: Float, y: Float) -> Float { return x + y } @differentiable(reverse, wrt: (1, 0)) // expected-error {{parameters must be specified in original order}} func two7(x: Float, y: Float) -> Float { return x + y } @differentiable(reverse, wrt: (1, x)) // expected-error {{parameters must be specified in original order}} func two8(x: Float, y: Float) -> Float { return x + y } @differentiable(reverse, wrt: (y, 0)) // expected-error {{parameters must be specified in original order}} func two9(x: Float, y: Float) -> Float { return x + y } // Inout 'wrt:' arguments. @differentiable(reverse, wrt: y) func inout1(x: Float, y: inout Float) -> Void { let _ = x + y } // expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}} @differentiable(reverse, wrt: y) func inout2(x: Float, y: inout Float) -> Float { let _ = x + y } // Test refining protocol requirements with `@differentiable` attribute. public protocol Distribution { associatedtype Value func logProbability(of value: Value) -> Float } public protocol DifferentiableDistribution: Differentiable, Distribution { // expected-note @+2 {{overridden declaration is here}} @differentiable(reverse, wrt: self) func logProbability(of value: Value) -> Float } // Adding a more general `@differentiable` attribute. public protocol DoubleDifferentiableDistribution: DifferentiableDistribution where Value: Differentiable { // expected-error @+1 {{overriding declaration is missing attribute '@differentiable(reverse, wrt: self)'}} {{3-3=@differentiable(reverse, wrt: self) }} func logProbability(of value: Value) -> Float } // Test failure to satisfy protocol requirement's `@differentiable` attribute. public protocol HasRequirement { @differentiable(reverse) // expected-note @+1 {{protocol requires function 'requirement' with type '<T> (T, T) -> T'; do you want to add a stub?}} func requirement<T: Differentiable>(_ x: T, _ y: T) -> T } // expected-error @+1 {{type 'AttemptsToSatisfyRequirement' does not conform to protocol 'HasRequirement'}} public struct AttemptsToSatisfyRequirement: HasRequirement { // This `@differentiable` attribute does not satisfy the requirement because // it is mroe constrained than the requirement's `@differentiable` attribute. @differentiable(reverse where T: CustomStringConvertible) // expected-note @+1 {{candidate is missing explicit '@differentiable(reverse, wrt: (x, y))' attribute to satisfy requirement}} public func requirement<T: Differentiable>(_ x: T, _ y: T) -> T { x } } // Test protocol requirement `@differentiable` attribute unsupported features. protocol ProtocolRequirementUnsupported: Differentiable { associatedtype Scalar // expected-error @+1 {{'@differentiable' attribute on protocol requirement cannot specify 'where' clause}} @differentiable(reverse where Scalar: Differentiable) func unsupportedWhereClause(value: Scalar) -> Float } extension ProtocolRequirementUnsupported { func dfoo(_ x: Float) -> (Float, (Float) -> Float) { (x, { $0 }) } } // Classes. class Super: Differentiable { typealias TangentVector = DummyTangentVector func move(by _: TangentVector) {} var base: Float // expected-error @+1 {{'@differentiable' attribute cannot be declared on 'init' in a non-final class; consider making 'Super' final}} @differentiable(reverse) init(base: Float) { self.base = base } // NOTE(TF-1040): `@differentiable` attribute on class methods currently // does two orthogonal things: // - Requests derivative generation for the class method. // - Adds JVP/VJP vtable entries for the class method. // There's currently no way using `@differentiable` to do only one of the // above. @differentiable(reverse) func testClassMethod(_ x: Float) -> Float { x } @differentiable(reverse) final func testFinalMethod(_ x: Float) -> Float { x } @differentiable(reverse) static func testStaticMethod(_ x: Float) -> Float { x } @differentiable(reverse, wrt: (self, x)) @differentiable(reverse, wrt: x) // expected-note @+1 2 {{overridden declaration is here}} func testMissingAttributes(_ x: Float) -> Float { x } @differentiable(reverse, wrt: x) func testSuperclassDerivatives(_ x: Float) -> Float { x } // Test duplicate attributes with different derivative generic signatures. // expected-error @+1 {{duplicate '@differentiable' attribute with same parameters}} @differentiable(reverse, wrt: x where T: Differentiable) // expected-note @+1 {{other attribute declared here}} @differentiable(reverse, wrt: x) func instanceMethod<T>(_ x: Float, y: T) -> Float { x } // expected-error @+1 {{'@differentiable' attribute cannot be declared on class members returning 'Self'}} @differentiable(reverse) func dynamicSelfResult() -> Self { self } // expected-error @+1 {{'@differentiable' attribute cannot be declared on class members returning 'Self'}} @differentiable(reverse) var testDynamicSelfProperty: Self { self } // TODO(TF-632): Fix "'TangentVector' is not a member type of 'Self'" diagnostic. // The underlying error should appear instead: // "covariant 'Self' can only appear at the top level of method result type". // expected-error @+1 2 {{'TangentVector' is not a member type of type 'Self'}} func vjpDynamicSelfResult() -> (Self, (Self.TangentVector) -> Self.TangentVector) { return (self, { $0 }) } } class Sub: Super { // expected-error @+2 {{overriding declaration is missing attribute '@differentiable(reverse, wrt: x)'}} // expected-error @+1 {{overriding declaration is missing attribute '@differentiable(reverse)'}} override func testMissingAttributes(_ x: Float) -> Float { x } } final class FinalClass: Differentiable { typealias TangentVector = DummyTangentVector func move(by _: TangentVector) {} var base: Float @differentiable(reverse) init(base: Float) { self.base = base } } // Test `inout` parameters. @differentiable(reverse, wrt: y) func inoutVoid(x: Float, y: inout Float) {} // expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}} @differentiable(reverse) func multipleSemanticResults(_ x: inout Float) -> Float { x } // expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}} @differentiable(reverse, wrt: y) func swap(x: inout Float, y: inout Float) {} struct InoutParameters: Differentiable { typealias TangentVector = DummyTangentVector mutating func move(by _: TangentVector) {} } extension InoutParameters { @differentiable(reverse) static func staticMethod(_ lhs: inout Self, rhs: Self) {} // expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}} @differentiable(reverse) static func multipleSemanticResults(_ lhs: inout Self, rhs: Self) -> Self {} } extension InoutParameters { @differentiable(reverse) mutating func mutatingMethod(_ other: Self) {} // expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}} @differentiable(reverse) mutating func mutatingMethod(_ other: Self) -> Self {} } // Test accessors: `set`, `_read`, `_modify`. struct Accessors: Differentiable { typealias TangentVector = DummyTangentVector mutating func move(by _: TangentVector) {} var stored: Float var computed: Float { @differentiable(reverse) set { stored = newValue } // `_read` is a coroutine: `(Self) -> () -> ()`. // expected-error @+1 {{'@differentiable' attribute cannot be applied to this declaration}} @differentiable(reverse) _read { yield stored } // `_modify` is a coroutine: `(inout Self) -> () -> ()`. // expected-error @+1 {{'@differentiable' attribute cannot be applied to this declaration}} @differentiable(reverse) _modify { yield &stored } } } // expected-error @+1 {{cannot differentiate functions returning opaque result types}} @differentiable(reverse) func opaqueResult(_ x: Float) -> some Differentiable { x }
apache-2.0
9d2bb03fba3aec7617b1d1ed0140a263
32.976648
194
0.700788
4.017379
false
false
false
false
XLabKC/Badger
Badger/Badger/TeamCircle.swift
1
1036
import UIKit import Haneke class TeamCircle: UIImageView { private var team: Team? override init(frame: CGRect) { super.init(frame: frame) self.setUp() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setUp() } func setTeam(team: Team) { self.team = team let placeholder = UIImage(named: "DefaultTeamLogo") if team.logo != "" { let url = Helpers.getProfileImageUrl(team.logo) self.hnk_setImageFromURL(url, placeholder: placeholder, format: nil, failure: nil, success: nil) } else { self.image = placeholder } } override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = self.frame.height / 2.0 } private func setUp() { self.clipsToBounds = true self.layer.borderColor = Colors.UnknownStatus.CGColor self.layer.borderWidth = 1 self.layer.cornerRadius = self.frame.height / 2.0 } }
gpl-2.0
dcd4201057a4386f8e265d44f93fdd8a
24.925
108
0.605212
4.280992
false
false
false
false
MAARK/Charts
Source/Charts/Renderers/BubbleChartRenderer.swift
8
14487
// // BubbleChartRenderer.swift // Charts // // Bubble chart implementation: // Copyright 2015 Pierre-Marc Airoldi // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class BubbleChartRenderer: BarLineScatterCandleBubbleRenderer { /// A nested array of elements ordered logically (i.e not in visual/drawing order) for use with VoiceOver. private lazy var accessibilityOrderedElements: [[NSUIAccessibilityElement]] = accessibilityCreateEmptyOrderedElements() @objc open weak var dataProvider: BubbleChartDataProvider? @objc public init(dataProvider: BubbleChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } open override func drawData(context: CGContext) { guard let dataProvider = dataProvider, let bubbleData = dataProvider.bubbleData else { return } // If we redraw the data, remove and repopulate accessible elements to update label values and frames accessibleChartElements.removeAll() accessibilityOrderedElements = accessibilityCreateEmptyOrderedElements() // Make the chart header the first element in the accessible elements array if let chart = dataProvider as? BubbleChartView { let element = createAccessibleHeader(usingChart: chart, andData: bubbleData, withDefaultDescription: "Bubble Chart") accessibleChartElements.append(element) } for (i, set) in (bubbleData.dataSets as! [IBubbleChartDataSet]).enumerated() where set.isVisible { drawDataSet(context: context, dataSet: set, dataSetIndex: i) } // Merge nested ordered arrays into the single accessibleChartElements. accessibleChartElements.append(contentsOf: accessibilityOrderedElements.flatMap { $0 } ) accessibilityPostLayoutChangedNotification() } private func getShapeSize( entrySize: CGFloat, maxSize: CGFloat, reference: CGFloat, normalizeSize: Bool) -> CGFloat { let factor: CGFloat = normalizeSize ? ((maxSize == 0.0) ? 1.0 : sqrt(entrySize / maxSize)) : entrySize let shapeSize: CGFloat = reference * factor return shapeSize } private var _pointBuffer = CGPoint() private var _sizeBuffer = [CGPoint](repeating: CGPoint(), count: 2) @objc open func drawDataSet(context: CGContext, dataSet: IBubbleChartDataSet, dataSetIndex: Int) { guard let dataProvider = dataProvider else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let phaseY = animator.phaseY _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) let valueToPixelMatrix = trans.valueToPixelMatrix _sizeBuffer[0].x = 0.0 _sizeBuffer[0].y = 0.0 _sizeBuffer[1].x = 1.0 _sizeBuffer[1].y = 0.0 trans.pointValuesToPixel(&_sizeBuffer) context.saveGState() defer { context.restoreGState() } let normalizeSize = dataSet.isNormalizeSizeEnabled // calcualte the full width of 1 step on the x-axis let maxBubbleWidth: CGFloat = abs(_sizeBuffer[1].x - _sizeBuffer[0].x) let maxBubbleHeight: CGFloat = abs(viewPortHandler.contentBottom - viewPortHandler.contentTop) let referenceSize: CGFloat = min(maxBubbleHeight, maxBubbleWidth) for j in _xBounds { guard let entry = dataSet.entryForIndex(j) as? BubbleChartDataEntry else { continue } _pointBuffer.x = CGFloat(entry.x) _pointBuffer.y = CGFloat(entry.y * phaseY) _pointBuffer = _pointBuffer.applying(valueToPixelMatrix) let shapeSize = getShapeSize(entrySize: entry.size, maxSize: dataSet.maxSize, reference: referenceSize, normalizeSize: normalizeSize) let shapeHalf = shapeSize / 2.0 guard viewPortHandler.isInBoundsTop(_pointBuffer.y + shapeHalf), viewPortHandler.isInBoundsBottom(_pointBuffer.y - shapeHalf), viewPortHandler.isInBoundsLeft(_pointBuffer.x + shapeHalf) else { continue } guard viewPortHandler.isInBoundsRight(_pointBuffer.x - shapeHalf) else { break } let color = dataSet.color(atIndex: j) let rect = CGRect( x: _pointBuffer.x - shapeHalf, y: _pointBuffer.y - shapeHalf, width: shapeSize, height: shapeSize ) context.setFillColor(color.cgColor) context.fillEllipse(in: rect) // Create and append the corresponding accessibility element to accessibilityOrderedElements if let chart = dataProvider as? BubbleChartView { let element = createAccessibleElement(withIndex: j, container: chart, dataSet: dataSet, dataSetIndex: dataSetIndex, shapeSize: shapeSize) { (element) in element.accessibilityFrame = rect } accessibilityOrderedElements[dataSetIndex].append(element) } } } open override func drawValues(context: CGContext) { guard let dataProvider = dataProvider, let bubbleData = dataProvider.bubbleData, isDrawingValuesAllowed(dataProvider: dataProvider), let dataSets = bubbleData.dataSets as? [IBubbleChartDataSet] else { return } let phaseX = max(0.0, min(1.0, animator.phaseX)) let phaseY = animator.phaseY var pt = CGPoint() for i in 0..<dataSets.count { let dataSet = dataSets[i] guard shouldDrawValues(forDataSet: dataSet), let formatter = dataSet.valueFormatter else { continue } let alpha = phaseX == 1 ? phaseY : phaseX _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let iconsOffset = dataSet.iconsOffset for j in _xBounds { guard let e = dataSet.entryForIndex(j) as? BubbleChartDataEntry else { break } let valueTextColor = dataSet.valueTextColorAt(j).withAlphaComponent(CGFloat(alpha)) pt.x = CGFloat(e.x) pt.y = CGFloat(e.y * phaseY) pt = pt.applying(valueToPixelMatrix) guard viewPortHandler.isInBoundsRight(pt.x) else { break } guard viewPortHandler.isInBoundsLeft(pt.x), viewPortHandler.isInBoundsY(pt.y) else { continue } let text = formatter.stringForValue( Double(e.size), entry: e, dataSetIndex: i, viewPortHandler: viewPortHandler) // Larger font for larger bubbles? let valueFont = dataSet.valueFont let lineHeight = valueFont.lineHeight if dataSet.isDrawValuesEnabled { ChartUtils.drawText( context: context, text: text, point: CGPoint( x: pt.x, y: pt.y - (0.5 * lineHeight)), align: .center, attributes: [NSAttributedString.Key.font: valueFont, NSAttributedString.Key.foregroundColor: valueTextColor]) } if let icon = e.icon, dataSet.isDrawIconsEnabled { ChartUtils.drawImage(context: context, image: icon, x: pt.x + iconsOffset.x, y: pt.y + iconsOffset.y, size: icon.size) } } } } open override func drawExtras(context: CGContext) { } open override func drawHighlighted(context: CGContext, indices: [Highlight]) { guard let dataProvider = dataProvider, let bubbleData = dataProvider.bubbleData else { return } context.saveGState() defer { context.restoreGState() } let phaseY = animator.phaseY for high in indices { guard let dataSet = bubbleData.getDataSetByIndex(high.dataSetIndex) as? IBubbleChartDataSet, dataSet.isHighlightEnabled, let entry = dataSet.entryForXValue(high.x, closestToY: high.y) as? BubbleChartDataEntry, isInBoundsX(entry: entry, dataSet: dataSet) else { continue } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) _sizeBuffer[0].x = 0.0 _sizeBuffer[0].y = 0.0 _sizeBuffer[1].x = 1.0 _sizeBuffer[1].y = 0.0 trans.pointValuesToPixel(&_sizeBuffer) let normalizeSize = dataSet.isNormalizeSizeEnabled // calcualte the full width of 1 step on the x-axis let maxBubbleWidth: CGFloat = abs(_sizeBuffer[1].x - _sizeBuffer[0].x) let maxBubbleHeight: CGFloat = abs(viewPortHandler.contentBottom - viewPortHandler.contentTop) let referenceSize: CGFloat = min(maxBubbleHeight, maxBubbleWidth) _pointBuffer.x = CGFloat(entry.x) _pointBuffer.y = CGFloat(entry.y * phaseY) trans.pointValueToPixel(&_pointBuffer) let shapeSize = getShapeSize(entrySize: entry.size, maxSize: dataSet.maxSize, reference: referenceSize, normalizeSize: normalizeSize) let shapeHalf = shapeSize / 2.0 guard viewPortHandler.isInBoundsTop(_pointBuffer.y + shapeHalf), viewPortHandler.isInBoundsBottom(_pointBuffer.y - shapeHalf), viewPortHandler.isInBoundsLeft(_pointBuffer.x + shapeHalf) else { continue } guard viewPortHandler.isInBoundsRight(_pointBuffer.x - shapeHalf) else { break } let originalColor = dataSet.color(atIndex: Int(entry.x)) var h: CGFloat = 0.0 var s: CGFloat = 0.0 var b: CGFloat = 0.0 var a: CGFloat = 0.0 originalColor.getHue(&h, saturation: &s, brightness: &b, alpha: &a) let color = NSUIColor(hue: h, saturation: s, brightness: b * 0.5, alpha: a) let rect = CGRect( x: _pointBuffer.x - shapeHalf, y: _pointBuffer.y - shapeHalf, width: shapeSize, height: shapeSize) context.setLineWidth(dataSet.highlightCircleWidth) context.setStrokeColor(color.cgColor) context.strokeEllipse(in: rect) high.setDraw(x: _pointBuffer.x, y: _pointBuffer.y) } } /// Creates a nested array of empty subarrays each of which will be populated with NSUIAccessibilityElements. private func accessibilityCreateEmptyOrderedElements() -> [[NSUIAccessibilityElement]] { guard let chart = dataProvider as? BubbleChartView else { return [] } let dataSetCount = chart.bubbleData?.dataSetCount ?? 0 return Array(repeating: [NSUIAccessibilityElement](), count: dataSetCount) } /// Creates an NSUIAccessibleElement representing individual bubbles location and relative size. private func createAccessibleElement(withIndex idx: Int, container: BubbleChartView, dataSet: IBubbleChartDataSet, dataSetIndex: Int, shapeSize: CGFloat, modifier: (NSUIAccessibilityElement) -> ()) -> NSUIAccessibilityElement { let element = NSUIAccessibilityElement(accessibilityContainer: container) let xAxis = container.xAxis guard let e = dataSet.entryForIndex(idx) else { return element } guard let dataProvider = dataProvider else { return element } // NOTE: The formatter can cause issues when the x-axis labels are consecutive ints. // i.e. due to the Double conversion, if there are more than one data set that are grouped, // there is the possibility of some labels being rounded up. A floor() might fix this, but seems to be a brute force solution. let label = xAxis.valueFormatter?.stringForValue(e.x, axis: xAxis) ?? "\(e.x)" let elementValueText = dataSet.valueFormatter?.stringForValue(e.y, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler) ?? "\(e.y)" let dataSetCount = dataProvider.bubbleData?.dataSetCount ?? -1 let doesContainMultipleDataSets = dataSetCount > 1 element.accessibilityLabel = "\(doesContainMultipleDataSets ? (dataSet.label ?? "") + ", " : "") \(label): \(elementValueText), bubble size: \(String(format: "%.2f", (shapeSize/dataSet.maxSize) * 100)) %" modifier(element) return element } }
apache-2.0
1bacefaea97a87f48da15a3860b1b46e
39.35376
213
0.566508
5.626019
false
false
false
false
KrishMunot/swift
test/SILOptimizer/definite_init_failable_initializers.swift
6
66260
// RUN: %target-swift-frontend -emit-sil -disable-objc-attr-requires-foundation-module %s | FileCheck %s // High-level tests that DI handles early returns from failable and throwing // initializers properly. The main complication is conditional release of self // and stored properties. // FIXME: not all of the test cases have CHECKs. Hopefully the interesting cases // are fully covered, though. //// // Structs with failable initializers //// protocol Pachyderm { init() } class Canary : Pachyderm { required init() {} } // <rdar://problem/20941576> SILGen crash: Failable struct init cannot delegate to another failable initializer struct TrivialFailableStruct { init?(blah: ()) { } init?(wibble: ()) { self.init(blah: wibble) } } struct FailableStruct { let x, y: Canary init(noFail: ()) { x = Canary() y = Canary() } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers14FailableStructCfT24failBeforeInitializationT__GSqS0__ // CHECK: bb0(%0 : $@thin FailableStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: br bb1 // CHECK: bb1: // CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[SELF]] init?(failBeforeInitialization: ()) { return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers14FailableStructCfT30failAfterPartialInitializationT__GSqS0__ // CHECK: bb0(%0 : $@thin FailableStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[CANARY:%.*]] = apply // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: store [[CANARY]] to [[X_ADDR]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: strong_release [[CANARY]] // CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[SELF]] init?(failAfterPartialInitialization: ()) { x = Canary() return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers14FailableStructCfT27failAfterFullInitializationT__GSqS0__ // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[CANARY1:%.*]] = apply // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: store [[CANARY1]] to [[X_ADDR]] // CHECK: [[CANARY2:%.*]] = apply // CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: store [[CANARY2]] to [[Y_ADDR]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: [[SELF:%.*]] = struct $FailableStruct ([[CANARY1]] : $Canary, [[CANARY2]] : $Canary) // CHECK-NEXT: release_value [[SELF]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] init?(failAfterFullInitialization: ()) { x = Canary() y = Canary() return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers14FailableStructCfT46failAfterWholeObjectInitializationByAssignmentT__GSqS0__ // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[CANARY]] = apply // CHECK-NEXT: store [[CANARY]] to [[SELF_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: release_value [[CANARY]] // CHECK-NEXT: [[SELF_VALUE:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[SELF_VALUE]] init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableStruct(noFail: ()) return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers14FailableStructCfT46failAfterWholeObjectInitializationByDelegationT__GSqS0__ // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers14FailableStructCfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: release_value [[NEW_SELF]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers14FailableStructCfT20failDuringDelegationT__GSqS0__ // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers14FailableStructCfT24failBeforeInitializationT__GSqS0__ // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0) // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], bb1, bb2 // CHECK: bb1: // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableStruct>) // CHECK: bb2: // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableStruct>) // CHECK: bb3([[NEW_SELF:%.*]] : $Optional<FailableStruct>) // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // IUO to IUO init!(failDuringDelegation3: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation4: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation5: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableStruct { init?(failInExtension: ()) { self.init(failInExtension: failInExtension) } init?(assignInExtension: ()) { self = FailableStruct(noFail: ()) } } struct FailableAddrOnlyStruct<T : Pachyderm> { var x, y: T init(noFail: ()) { x = T() y = T() } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers22FailableAddrOnlyStructC{{.*}}24failBeforeInitialization // CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T> // CHECK: br bb1 // CHECK: bb1: // CHECK-NEXT: inject_enum_addr %0 // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return init?(failBeforeInitialization: ()) { return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers22FailableAddrOnlyStructC{{.*}}failAfterPartialInitialization // CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T> // CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1 // CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type // CHECK-NEXT: [[X_BOX:%.*]] = alloc_stack $T // CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]]) // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]] // CHECK-NEXT: dealloc_stack [[X_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[X_ADDR]] // CHECK-NEXT: inject_enum_addr %0 // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return init?(failAfterPartialInitialization: ()) { x = T() return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers22FailableAddrOnlyStructC{{.*}}failAfterFullInitialization // CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T> // CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1 // CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type // CHECK-NEXT: [[X_BOX:%.*]] = alloc_stack $T // CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]]) // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]] // CHECK-NEXT: dealloc_stack [[X_BOX]] // CHECK-NEXT: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1 // CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type // CHECK-NEXT: [[Y_BOX:%.*]] = alloc_stack $T // CHECK-NEXT: apply [[T_INIT_FN]]<T>([[Y_BOX]], [[T_TYPE]]) // CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: copy_addr [take] [[Y_BOX]] to [initialization] [[Y_ADDR]] // CHECK-NEXT: dealloc_stack [[Y_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: inject_enum_addr %0 // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return init?(failAfterFullInitialization: ()) { x = T() y = T() return nil } init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableAddrOnlyStruct(noFail: ()) return nil } init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation3: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation4: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableAddrOnlyStruct { init?(failInExtension: ()) { self.init(failBeforeInitialization: failInExtension) } init?(assignInExtension: ()) { self = FailableAddrOnlyStruct(noFail: ()) } } //// // Structs with throwing initializers //// func unwrap(_ x: Int) throws -> Int { return x } struct ThrowStruct { var x: Canary init(fail: ()) throws { x = Canary() } init(noFail: ()) { x = Canary() } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT20failBeforeDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT28failBeforeOrDuringDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfzT4failT__S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init(fail: ()) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT29failBeforeOrDuringDelegation2Si_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfzT20failBeforeDelegationSi_S0_ // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: try_apply [[INIT_FN]]([[RESULT]], %1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT20failDuringDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfzT4failT__S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failDuringDelegation: Int) throws { try self.init(fail: ()) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT19failAfterDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK: release_value [[NEW_SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT27failDuringOrAfterDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfzT4failT__S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:.*]] : $ThrowStruct): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failDuringOrAfterDelegation: Int) throws { try self.init(fail: ()) try unwrap(failDuringOrAfterDelegation) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT27failBeforeOrAfterDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfT16throwsToOptionalSi_GSqS0__ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfzT20failDuringDelegationSi_S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%0, %1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[NEW_SELF]] // CHECK-NEXT: br bb2([[SELF_OPTIONAL]] : $Optional<ThrowStruct>) // CHECK: bb2([[SELF_OPTIONAL:%.*]] : $Optional<ThrowStruct>): // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], bb3, bb4 // CHECK: bb3: // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: br bb5([[NEW_SELF]] : $Optional<ThrowStruct>) // CHECK: bb4: // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb5([[NEW_SELF]] : $Optional<ThrowStruct>) // CHECK: bb5([[NEW_SELF:%.*]] : $Optional<ThrowStruct>): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] : $Optional<ThrowStruct> // CHECK: bb6: // CHECK-NEXT: strong_release [[ERROR:%.*]] : $ErrorProtocol // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb2([[NEW_SELF]] : $Optional<ThrowStruct>) // CHECK: bb7([[ERROR]] : $ErrorProtocol): // CHECK-NEXT: br bb6 init?(throwsToOptional: Int) { try? self.init(failDuringDelegation: throwsToOptional) } init(throwsToIUO: Int) { try! self.init(failDuringDelegation: throwsToIUO) } init?(throwsToOptionalThrows: Int) throws { try? self.init(fail: ()) } init(throwsOptionalToThrows: Int) throws { self.init(throwsToOptional: throwsOptionalToThrows)! } init?(throwsOptionalToOptional: Int) { try! self.init(throwsToOptionalThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowStruct(noFail: ()) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT25failDuringSelfReplacementSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfzT4failT__S0_ // CHECK-NEXT: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type // CHECK-NEXT: try_apply [[INIT_FN]]([[SELF_TYPE]]) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failDuringSelfReplacement: Int) throws { try self = ThrowStruct(fail: ()) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT24failAfterSelfReplacementSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfT6noFailT__S0_ // CHECK-NEXT: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[SELF_TYPE]]) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: release_value [[NEW_SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterSelfReplacement: Int) throws { self = ThrowStruct(noFail: ()) try unwrap(failAfterSelfReplacement) } } extension ThrowStruct { init(failInExtension: ()) throws { try self.init(fail: failInExtension) } init(assignInExtension: ()) throws { try self = ThrowStruct(fail: ()) } } struct ThrowAddrOnlyStruct<T : Pachyderm> { var x : T init(fail: ()) throws { x = T() } init(noFail: ()) { x = T() } init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init(fail: ()) } init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } init(failDuringDelegation: Int) throws { try self.init(fail: ()) } init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } init(failDuringOrAfterDelegation: Int) throws { try self.init(fail: ()) try unwrap(failDuringOrAfterDelegation) } init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } init?(throwsToOptional: Int) { try? self.init(failDuringDelegation: throwsToOptional) } init(throwsToIUO: Int) { try! self.init(failDuringDelegation: throwsToIUO) } init?(throwsToOptionalThrows: Int) throws { try? self.init(fail: ()) } init(throwsOptionalToThrows: Int) throws { self.init(throwsToOptional: throwsOptionalToThrows)! } init?(throwsOptionalToOptional: Int) { try! self.init(throwsOptionalToThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowAddrOnlyStruct(noFail: ()) } init(failAfterSelfReplacement: Int) throws { self = ThrowAddrOnlyStruct(noFail: ()) try unwrap(failAfterSelfReplacement) } } extension ThrowAddrOnlyStruct { init(failInExtension: ()) throws { try self.init(fail: failInExtension) } init(assignInExtension: ()) throws { self = ThrowAddrOnlyStruct(noFail: ()) } } //// // Classes with failable initializers //// class FailableBaseClass { var member: Canary init(noFail: ()) { member = Canary() } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17FailableBaseClasscfT28failBeforeFullInitializationT__GSqS0__ // CHECK: bb0(%0 : $FailableBaseClass): // CHECK: [[METATYPE:%.*]] = metatype $@thick FailableBaseClass.Type // CHECK: dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]] // CHECK: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK: return [[RESULT]] init?(failBeforeFullInitialization: ()) { return nil } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17FailableBaseClasscfT27failAfterFullInitializationT__GSqS0__ // CHECK: bb0(%0 : $FailableBaseClass): // CHECK: [[CANARY:%.*]] = apply // CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0 // CHECK-NEXT: store [[CANARY]] to [[MEMBER_ADDR]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: strong_release %0 // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: return [[NEW_SELF]] init?(failAfterFullInitialization: ()) { member = Canary() return nil } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17FailableBaseClasscfT20failBeforeDelegationT__GSqS0__ // CHECK: bb0(%0 : $FailableBaseClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass // CHECK: store %0 to [[SELF_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick FailableBaseClass.Type, %0 : $FailableBaseClass // CHECK-NEXT: dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]] : $@thick FailableBaseClass.Type // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[RESULT]] convenience init?(failBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17FailableBaseClasscfT19failAfterDelegationT__GSqS0__ // CHECK: bb0(%0 : $FailableBaseClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass // CHECK: store %0 to [[SELF_BOX]] // CHECK: [[INIT_FN:%.*]] = class_method %0 // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: strong_release [[NEW_SELF]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[RESULT]] convenience init?(failAfterDelegation: ()) { self.init(noFail: ()) return nil } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17FailableBaseClasscfT20failDuringDelegationT__GSqS0__ // CHECK: bb0(%0 : $FailableBaseClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass // CHECK: store %0 to [[SELF_BOX]] // CHECK: [[INIT_FN:%.*]] = class_method %0 // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0) // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], bb1, bb2 // CHECK: bb1: // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableBaseClass>) // CHECK: bb2: // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableBaseClass>) // CHECK: bb3([[NEW_SELF:%.*]] : $Optional<FailableBaseClass>): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // Optional to optional convenience init?(failDuringDelegation: ()) { self.init(failBeforeFullInitialization: ()) } // IUO to optional convenience init!(failDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // unnecessary-but-correct '!' } // IUO to IUO convenience init!(noFailDuringDelegation: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional convenience init(noFailDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // necessary '!' } } extension FailableBaseClass { convenience init?(failInExtension: ()) throws { self.init(failBeforeFullInitialization: failInExtension) } } // Chaining to failable initializers in a superclass class FailableDerivedClass : FailableBaseClass { var otherMember: Canary // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers20FailableDerivedClasscfT27derivedFailBeforeDelegationT__GSqS0__ // CHECK: bb0(%0 : $FailableDerivedClass): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass // CHECK: store %0 to [[SELF_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick FailableDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref %0 : $FailableDerivedClass, [[METATYPE]] : $@thick FailableDerivedClass.Type // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[RESULT]] init?(derivedFailBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers20FailableDerivedClasscfT27derivedFailDuringDelegationT__GSqS0__ // CHECK: bb0(%0 : $FailableDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass // CHECK: store %0 to [[SELF_BOX]] // CHECK: [[CANARY:%.*]] = apply // CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0 // CHECK-NEXT: store [[CANARY]] to [[MEMBER_ADDR]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %0 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17FailableBaseClasscfT28failBeforeFullInitializationT__GSqS0__ // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], bb1, bb2 // CHECK: bb1: // CHECK-NEXT: [[BASE_SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_ref_cast [[BASE_SELF_VALUE]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableDerivedClass>) // CHECK: bb2: // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt // CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableDerivedClass>) // CHECK: bb3([[NEW_SELF:%.*]] : $Optional<FailableDerivedClass>): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] : $Optional<FailableDerivedClass> init?(derivedFailDuringDelegation: ()) { self.otherMember = Canary() super.init(failBeforeFullInitialization: ()) } init?(derivedFailAfterDelegation: ()) { self.otherMember = Canary() super.init(noFail: ()) return nil } // non-optional to IUO init(derivedNoFailDuringDelegation: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // necessary '!' } // IUO to IUO init!(derivedFailDuringDelegation2: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // unnecessary-but-correct '!' } } extension FailableDerivedClass { convenience init?(derivedFailInExtension: ()) throws { self.init(derivedFailDuringDelegation: derivedFailInExtension) } } //// // Classes with throwing initializers //// class ThrowBaseClass { required init() throws {} init(noFail: ()) {} } class ThrowDerivedClass : ThrowBaseClass { // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT_S0_ // CHECK: bb0(%0 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %0 to [[SELF_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %0 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfzT_S0_ // CHECK-NEXT: try_apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] required init() throws { try super.init() } override init(noFail: ()) { try! super.init() } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT28failBeforeFullInitializationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %1 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] : $ThrowDerivedClass // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) super.init(noFail: ()) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT28failBeforeFullInitializationSi28failDuringFullInitializationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %2 to [[SELF_BOX]] : $*ThrowDerivedClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int) // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %2 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfzT_S0_ // CHECK: try_apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref %2 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) try super.init() } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT27failAfterFullInitializationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %1 to [[SELF_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %1 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: strong_release [[DERIVED_SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterFullInitialization: Int) throws { super.init(noFail: ()) try unwrap(failAfterFullInitialization) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT27failAfterFullInitializationSi28failDuringFullInitializationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %2 to [[SELF_BOX]] // CHECK-NEXT: [[DERIVED_SELF:%.*]] = upcast %2 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfzT_S0_ // CHECK: try_apply [[INIT_FN]]([[DERIVED_SELF]]) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterFullInitialization: Int, failDuringFullInitialization: Int) throws { try super.init() try unwrap(failAfterFullInitialization) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT28failBeforeFullInitializationSi27failAfterFullInitializationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %2 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %2 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfT6noFailT__S0_ // CHECK: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%1) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND:%.*]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: [[BITMAP:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref [[BITMAP]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] : $ErrorProtocol init(failBeforeFullInitialization: Int, failAfterFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) super.init(noFail: ()) try unwrap(failAfterFullInitialization) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT28failBeforeFullInitializationSi28failDuringFullInitializationSi27failAfterFullInitializationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $Int, %3 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %3 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %3 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfzT_S0_ // CHECK: try_apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%2) // CHECK: bb3([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb7([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: br bb7([[ERROR]] : $ErrorProtocol) // CHECK: bb6([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb7([[ERROR]] : $ErrorProtocol) // CHECK: bb7([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb8, bb9 // CHECK: bb8: // CHECK-NEXT: br bb13 // CHECK: bb9: // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb10, bb11 // CHECK: bb10: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb12 // CHECK: bb11: // CHECK-NEXT: [[SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref [[SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb12 // CHECK: bb12: // CHECK-NEXT: br bb13 // CHECK: bb13: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int, failAfterFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) try super.init() try unwrap(failAfterFullInitialization) } convenience init(noFail2: ()) { try! self.init() } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT20failBeforeDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[ARG:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, %1 : $ThrowDerivedClass // CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT20failDuringDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT_S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] : $ErrorProtocol convenience init(failDuringDelegation: Int) throws { try self.init() } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT28failBeforeOrDuringDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] : $*Builtin.Int2 // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[ARG:%.*]] : $Int): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT_S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR1:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR1]] : $ErrorProtocol) // CHECK: bb4([[ERROR2:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: br bb5([[ERROR2]] : $ErrorProtocol) // CHECK: bb5([[ERROR3:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BITMAP_VALUE:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[BIT_NUM:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP_VALUE]] : $Builtin.Int2, [[BIT_NUM]] : $Builtin.Int2) // CHECK-NEXT: [[CONDITION:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[CONDITION]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, %1 : $ThrowDerivedClass // CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR3]] convenience init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init() } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT29failBeforeOrDuringDelegation2Si_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] : $*Builtin.Int2 // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[ARG:%.*]] : $Int): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT20failBeforeDelegationSi_S0_ // CHECK-NEXT: try_apply [[INIT_FN]]([[ARG]], %1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR1:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: br bb5([[ERROR1]] : $ErrorProtocol) // CHECK: bb5([[ERROR2:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BITMAP_VALUE:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[BIT_NUM:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP_VALUE]] : $Builtin.Int2, [[BIT_NUM]] : $Builtin.Int2) // CHECK-NEXT: [[CONDITION:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[CONDITION]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, %1 : $ThrowDerivedClass // CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR2]] convenience init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT19failAfterDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: strong_release [[NEW_SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT27failDuringOrAfterDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %1 to [[SELF_BOX]] // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT_S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR1:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: br bb5([[ERROR1]] : $ErrorProtocol) // CHECK: bb4([[ERROR2:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR2]] : $ErrorProtocol) // CHECK: bb5([[ERROR3:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR3]] convenience init(failDuringOrAfterDelegation: Int) throws { try self.init() try unwrap(failDuringOrAfterDelegation) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT27failBeforeOrAfterDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: [[OLD_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, [[OLD_SELF]] : $ThrowDerivedClass // CHECK-NEXT: dealloc_partial_ref [[OLD_SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } } //// // Enums with failable initializers //// enum FailableEnum { case A init?(a: Int64) { self = .A } init!(b: Int64) { self.init(a: b)! // unnecessary-but-correct '!' } init(c: Int64) { self.init(a: c)! // necessary '!' } init(d: Int64) { self.init(b: d)! // unnecessary-but-correct '!' } } //// // Protocols and protocol extensions //// // Delegating to failable initializers from a protocol extension to a // protocol. protocol P1 { init?(p1: Int64) } extension P1 { init!(p1a: Int64) { self.init(p1: p1a)! // unnecessary-but-correct '!' } init(p1b: Int64) { self.init(p1: p1b)! // necessary '!' } } protocol P2 : class { init?(p2: Int64) } extension P2 { init!(p2a: Int64) { self.init(p2: p2a)! // unnecessary-but-correct '!' } init(p2b: Int64) { self.init(p2: p2b)! // necessary '!' } } @objc protocol P3 { init?(p3: Int64) } extension P3 { init!(p3a: Int64) { self.init(p3: p3a)! // unnecessary-but-correct '!' } init(p3b: Int64) { self.init(p3: p3b)! // necessary '!' } } // Delegating to failable initializers from a protocol extension to a // protocol extension. extension P1 { init?(p1c: Int64) { self.init(p1: p1c) } init!(p1d: Int64) { self.init(p1c: p1d)! // unnecessary-but-correct '!' } init(p1e: Int64) { self.init(p1c: p1e)! // necessary '!' } } extension P2 { init?(p2c: Int64) { self.init(p2: p2c) } init!(p2d: Int64) { self.init(p2c: p2d)! // unnecessary-but-correct '!' } init(p2e: Int64) { self.init(p2c: p2e)! // necessary '!' } } //// // self.dynamicType with uninitialized self //// func use(_ a : Any) {} class DynamicTypeBase { var x: Int init() { use(self.dynamicType) x = 0 } convenience init(a : Int) { use(self.dynamicType) self.init() } } class DynamicTypeDerived : DynamicTypeBase { override init() { use(self.dynamicType) super.init() } convenience init(a : Int) { use(self.dynamicType) self.init() } } struct DynamicTypeStruct { var x: Int init() { use(self.dynamicType) x = 0 } init(a : Int) { use(self.dynamicType) self.init() } }
apache-2.0
4aa0416b47b83ee16a082baf763accef
41.748387
191
0.624811
3.297994
false
false
false
false
PiXeL16/BudgetShare
BudgetShare/Entities/Utils/BudgetDateUtils.swift
1
1970
// // Created by Chris Jimenez on 9/2/18. // Copyright (c) 2018 Chris Jimenez. All rights reserved. // import Foundation import DateToolsSwift internal struct BudgetDateUtils { func dayOfBudgetStartDay(budgetStartDay: StartDay) -> Int? { switch budgetStartDay { case .LastDayOfMonth: return Date().endOfMonth().day case .Unknown: return nil default: return budgetStartDay.rawValue } } //TODO change this to time left, to also return hours when on the last day of the month func daysLeft(fromReferenceDate: Date = Date(), budgetStartDay: StartDay) -> Int { var budgetEnds: Date? var daysLeft = 0 guard let budgetStartDay = self.dayOfBudgetStartDay(budgetStartDay: budgetStartDay) else { return 0 } // We are still in the current budget month if fromReferenceDate.day < budgetStartDay { budgetEnds = fromReferenceDate.dateWithinMonth(day: budgetStartDay) } else { // The budget end is one month in the future let oneMonthFromReference = fromReferenceDate.add(1.months) budgetEnds = oneMonthFromReference.dateWithinMonth(day: budgetStartDay) } if budgetEnds != nil { daysLeft = budgetEnds!.daysLater(than: fromReferenceDate) } return daysLeft } func totalDaysOfBudget(fromReferenceDate: Date = Date(), budgetStartDay: StartDay) -> Int? { let today = fromReferenceDate guard let startDay = self.dayOfBudgetStartDay(budgetStartDay: budgetStartDay) else { return nil } guard let budgetStartDay = today.dateWithinMonth(day: startDay) else { return nil } let budgetEndDay = budgetStartDay.add(1.months) let totalDaysOfBudget = budgetEndDay.daysLater(than: budgetStartDay) return totalDaysOfBudget } }
mit
bf07b641c7be5ec40561cc44e134f795
25.266667
98
0.639594
4.46712
false
false
false
false
xwu/swift
stdlib/public/core/ObjectIdentifier.swift
4
3822
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A unique identifier for a class instance or metatype. /// /// This unique identifier is only valid for comparisons during the lifetime /// of the instance. /// /// In Swift, only class instances and metatypes have unique identities. There /// is no notion of identity for structs, enums, functions, or tuples. @frozen // trivial-implementation public struct ObjectIdentifier: Sendable { @usableFromInline // trivial-implementation internal let _value: Builtin.RawPointer /// Creates an instance that uniquely identifies the given class instance. /// /// The following example creates an example class `IntegerRef` and compares /// instances of the class using their object identifiers and the identical-to /// operator (`===`): /// /// class IntegerRef { /// let value: Int /// init(_ value: Int) { /// self.value = value /// } /// } /// /// let x = IntegerRef(10) /// let y = x /// /// print(ObjectIdentifier(x) == ObjectIdentifier(y)) /// // Prints "true" /// print(x === y) /// // Prints "true" /// /// let z = IntegerRef(10) /// print(ObjectIdentifier(x) == ObjectIdentifier(z)) /// // Prints "false" /// print(x === z) /// // Prints "false" /// /// - Parameter x: An instance of a class. @inlinable // trivial-implementation public init(_ x: AnyObject) { self._value = Builtin.bridgeToRawPointer(x) } /// Creates an instance that uniquely identifies the given metatype. /// /// - Parameter: A metatype. @inlinable // trivial-implementation public init(_ x: Any.Type) { self._value = unsafeBitCast(x, to: Builtin.RawPointer.self) } } extension ObjectIdentifier: CustomDebugStringConvertible { /// A textual representation of the identifier, suitable for debugging. public var debugDescription: String { return "ObjectIdentifier(\(_rawPointerToString(_value)))" } } extension ObjectIdentifier: Equatable { @inlinable // trivial-implementation public static func == (x: ObjectIdentifier, y: ObjectIdentifier) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(x._value, y._value)) } } extension ObjectIdentifier: Comparable { @inlinable // trivial-implementation public static func < (lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool { return UInt(bitPattern: lhs) < UInt(bitPattern: rhs) } } extension ObjectIdentifier: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(Int(Builtin.ptrtoint_Word(_value))) } } extension UInt { /// Creates an integer that captures the full value of the given object /// identifier. @inlinable // trivial-implementation public init(bitPattern objectID: ObjectIdentifier) { self.init(Builtin.ptrtoint_Word(objectID._value)) } } extension Int { /// Creates an integer that captures the full value of the given object /// identifier. @inlinable // trivial-implementation public init(bitPattern objectID: ObjectIdentifier) { self.init(bitPattern: UInt(bitPattern: objectID)) } }
apache-2.0
7590f870d83210ab11a98d4182ced4c2
31.948276
80
0.648613
4.533808
false
false
false
false
bigfish24/ABFRealmTableViewController
RealmTableViewController/RealmTableViewController.swift
1
9651
// // RealmTableViewController.swift // RealmTableViewControllerExample // // Created by Adam Fish on 10/5/15. // Copyright © 2015 Adam Fish. All rights reserved. // import UIKit import RealmSwift import RBQFetchedResultsController public class RealmTableViewController: UITableViewController { // MARK: Properties /// The name of the Realm Object managed by the grid controller @IBInspectable public var entityName: String? { didSet { self.updateFetchedResultsController() } } /// The section name key path used to create the sections. Can be nil if no sections. @IBInspectable public var sectionNameKeyPath: String? { didSet { self.updateFetchedResultsController() } } /// The base predicet to to filter the Realm Objects on public var basePredicate: NSPredicate? { didSet { self.updateFetchedResultsController() } } /// Array of SortDescriptors /// /// http://realm.io/docs/cocoa/0.89.2/#ordering-results public var sortDescriptors: [SortDescriptor]? { didSet { if let descriptors = self.sortDescriptors { var rlmSortDescriptors = [RLMSortDescriptor]() for sortDesc in descriptors { let rlmSortDesc = RLMSortDescriptor(property: sortDesc.property, ascending: sortDesc.ascending) rlmSortDescriptors.append(rlmSortDesc) } self.rlmSortDescriptors = rlmSortDescriptors } self.updateFetchedResultsController() } } /// The configuration for the Realm in which the entity resides /// /// Default is [RLMRealmConfiguration defaultConfiguration] public var realmConfiguration: Realm.Configuration? { set { self.internalConfiguration = newValue self.updateFetchedResultsController() } get { if let configuration = self.internalConfiguration { return configuration } return Realm.Configuration.defaultConfiguration } } /// The Realm in which the given entity resides in public var realm: Realm? { if let configuration = self.realmConfiguration { return try! Realm(configuration: configuration) } return nil } /// The underlying RBQFetchedResultsController public var fetchedResultsController: RBQFetchedResultsController { return internalFetchedResultsController } // MARK: Object Retrieval /** Retrieve the RLMObject for a given index path :warning: Returned object is not thread-safe. :param: indexPath the index path of the object :returns: RLMObject */ public func objectAtIndexPath<T: Object>(type: T.Type, indexPath: NSIndexPath) -> T? { if let anObject: AnyObject = self.fetchedResultsController.objectAtIndexPath(indexPath) { return unsafeBitCast(anObject, T.self) } return nil } // MARK: Initializers // MARK: Initialization override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.baseInit() } override public init(style: UITableViewStyle) { super.init(style: style) self.baseInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.baseInit() } private func baseInit() { self.internalFetchedResultsController = RBQFetchedResultsController() self.internalFetchedResultsController.delegate = self } // MARK: Private Functions private var viewLoaded: Bool = false private var internalConfiguration: Realm.Configuration? private var internalFetchedResultsController: RBQFetchedResultsController! private var rlmSortDescriptors: [RLMSortDescriptor]? private var rlmRealm: RLMRealm? { if let realmConfiguration = self.realmConfiguration { let configuration = self.toRLMConfiguration(realmConfiguration) return try! RLMRealm(configuration: configuration) } return nil } private func updateFetchedResultsController() { objc_sync_enter(self) if let fetchRequest = self.tableFetchRequest(self.entityName, inRealm: self.rlmRealm, predicate:self.basePredicate) { self.fetchedResultsController.updateFetchRequest(fetchRequest, sectionNameKeyPath: self.sectionNameKeyPath, andPerformFetch: true) if self.viewLoaded { self.runOnMainThread({ [weak self] () -> Void in self?.tableView.reloadData() }) } } objc_sync_exit(self) } private func tableFetchRequest(entityName: String?, inRealm realm: RLMRealm?, predicate: NSPredicate?) -> RBQFetchRequest? { if entityName != nil && realm != nil { let fetchRequest = RBQFetchRequest(entityName: entityName!, inRealm: realm!, predicate: predicate) fetchRequest.sortDescriptors = self.rlmSortDescriptors return fetchRequest } return nil } private func toRLMConfiguration(configuration: Realm.Configuration) -> RLMRealmConfiguration { let rlmConfiguration = RLMRealmConfiguration() if (configuration.fileURL != nil) { rlmConfiguration.fileURL = configuration.fileURL } if (configuration.inMemoryIdentifier != nil) { rlmConfiguration.inMemoryIdentifier = configuration.inMemoryIdentifier } rlmConfiguration.encryptionKey = configuration.encryptionKey rlmConfiguration.readOnly = configuration.readOnly rlmConfiguration.schemaVersion = configuration.schemaVersion return rlmConfiguration } private func runOnMainThread(block: () -> Void) { if NSThread.isMainThread() { block() } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in block() }) } } } // MARK: - UIViewController extension RealmTableViewController { public override func viewDidLoad() { self.viewLoaded = true self.updateFetchedResultsController() } } // MARK: - UIViewControllerDataSource extension RealmTableViewController { override public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fetchedResultsController.numberOfSections() } override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.fetchedResultsController.numberOfRowsForSectionIndex(section) } override public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.fetchedResultsController.titleForHeaderInSection(section) } } // MARK: - RBQFetchedResultsControllerDelegate extension RealmTableViewController: RBQFetchedResultsControllerDelegate { public func controllerWillChangeContent(controller: RBQFetchedResultsController) { self.tableView.beginUpdates() } public func controller(controller: RBQFetchedResultsController, didChangeSection section: RBQFetchedResultsSectionInfo, atIndex sectionIndex: UInt, forChangeType type: NSFetchedResultsChangeType) { let tableView = self.tableView switch(type) { case .Insert: let insertedSection = NSIndexSet(index: Int(sectionIndex)) tableView.insertSections(insertedSection, withRowAnimation: UITableViewRowAnimation.Fade) case .Delete: let deletedSection = NSIndexSet(index: Int(sectionIndex)) tableView.deleteSections(deletedSection, withRowAnimation: UITableViewRowAnimation.Fade) default: break } } public func controller(controller: RBQFetchedResultsController, didChangeObject anObject: RBQSafeRealmObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { let tableView = self.tableView switch(type) { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade) case .Update: if tableView.indexPathsForVisibleRows?.contains(indexPath!) == true { tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade) } case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade) } } public func controllerDidChangeContent(controller: RBQFetchedResultsController) { self.tableView.endUpdates() } }
mit
8f3cf26bad2bcc0ebcac42b8f8d417fa
32.275862
228
0.639585
6.065368
false
true
false
false
mightydeveloper/swift
test/SILGen/objc_ownership_conventions.swift
9
10771
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen | FileCheck %s // REQUIRES: objc_interop import gizmo // CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions5test3FT_CSo8NSObject func test3() -> NSObject { // initializer returns at +1 return Gizmo() // CHECK: [[CTOR:%[0-9]+]] = function_ref @_TFCSo5GizmoC{{.*}} : $@convention(thin) (@thick Gizmo.Type) -> @owned ImplicitlyUnwrappedOptional<Gizmo> // CHECK-NEXT: [[GIZMO_META:%[0-9]+]] = metatype $@thick Gizmo.Type // CHECK-NEXT: [[GIZMO:%[0-9]+]] = apply [[CTOR]]([[GIZMO_META]]) : $@convention(thin) (@thick Gizmo.Type) -> @owned ImplicitlyUnwrappedOptional<Gizmo> // CHECK: [[GIZMO_NS:%[0-9]+]] = upcast [[GIZMO:%[0-9]+]] : $Gizmo to $NSObject // CHECK: return [[GIZMO_NS]] : $NSObject // CHECK-LABEL: sil shared @_TFCSo5GizmoC{{.*}} : $@convention(thin) (@thick Gizmo.Type) -> @owned ImplicitlyUnwrappedOptional<Gizmo> // alloc is implicitly ns_returns_retained // init is implicitly ns_consumes_self and ns_returns_retained // CHECK: bb0([[GIZMO_META:%[0-9]+]] : $@thick Gizmo.Type): // CHECK-NEXT: [[GIZMO_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[GIZMO_META]] : $@thick Gizmo.Type to $@objc_metatype Gizmo.Type // CHECK-NEXT: [[GIZMO:%[0-9]+]] = alloc_ref_dynamic [objc] [[GIZMO_META_OBJC]] : $@objc_metatype Gizmo.Type, $Gizmo // CHECK-NEXT: // function_ref // CHECK-NEXT: [[INIT_CTOR:%[0-9]+]] = function_ref @_TTOFCSo5Gizmoc{{.*}} // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[INIT_CTOR]]([[GIZMO]]) : $@convention(method) (@owned Gizmo) -> @owned ImplicitlyUnwrappedOptional<Gizmo> // CHECK-NEXT: return [[RESULT]] : $ImplicitlyUnwrappedOptional<Gizmo> } // Normal message send with argument, no transfers. // CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions5test5 func test5(g: Gizmo) { var g = g Gizmo.inspect(g) // CHECK: [[CLASS:%.*]] = metatype $@thick Gizmo.Type // CHECK-NEXT: [[METHOD:%.*]] = class_method [volatile] [[CLASS]] : {{.*}}, #Gizmo.inspect!1.foreign // CHECK-NEXT: [[OBJC_CLASS:%[0-9]+]] = thick_to_objc_metatype [[CLASS]] : $@thick Gizmo.Type to $@objc_metatype Gizmo.Type // CHECK: [[V:%.*]] = load %2#1 // CHECK: strong_retain [[V]] // CHECK: [[G:%.*]] = enum $ImplicitlyUnwrappedOptional<Gizmo>, #ImplicitlyUnwrappedOptional.Some!enumelt.1, [[V]] // CHECK-NEXT: apply [[METHOD]]([[G]], [[OBJC_CLASS]]) // CHECK-NEXT: release_value [[G]] } // The argument to consume is __attribute__((ns_consumed)). // CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions5test6 func test6(g: Gizmo) { var g = g Gizmo.consume(g) // CHECK: [[CLASS:%.*]] = metatype $@thick Gizmo.Type // CHECK-NEXT: [[METHOD:%.*]] = class_method [volatile] [[CLASS]] : {{.*}}, #Gizmo.consume!1.foreign // CHECK-NEXT: [[OBJC_CLASS:%.*]] = thick_to_objc_metatype [[CLASS]] : $@thick Gizmo.Type to $@objc_metatype Gizmo.Type // CHECK: [[V:%.*]] = load %2#1 // CHECK: strong_retain [[V]] // CHECK: [[G:%.*]] = enum $ImplicitlyUnwrappedOptional<Gizmo>, #ImplicitlyUnwrappedOptional.Some! // CHECK-NEXT: apply [[METHOD]]([[G]], [[OBJC_CLASS]]) // CHECK-NOT: release_value [[G]] } // fork is __attribute__((ns_consumes_self)). // CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions5test7 func test7(g: Gizmo) { var g = g g.fork() // CHECK: [[G:%.*]] = load // CHECK-NEXT: retain [[G]] // CHECK-NEXT: [[METHOD:%.*]] = class_method [volatile] [[G]] : {{.*}}, #Gizmo.fork!1.foreign // CHECK-NEXT: apply [[METHOD]]([[G]]) // CHECK-NOT: release [[G]] } // clone is __attribute__((ns_returns_retained)). // CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions5test8 func test8(g: Gizmo) -> Gizmo { return g.clone() // CHECK: bb0([[G:%.*]] : $Gizmo): // CHECK-NOT: retain // CHECK: alloc_stack $ImplicitlyUnwrappedOptional<Gizmo> // CHECK-NEXT: [[METHOD:%.*]] = class_method [volatile] [[G]] : {{.*}}, #Gizmo.clone!1.foreign // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[G]]) // CHECK-NEXT: store // CHECK-NEXT: function_ref // CHECK-NEXT: function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue // CHECK-NEXT: alloc_stack // CHECK-NEXT: apply // CHECK-NEXT: [[RESULT:%.*]] = load // CHECK-NEXT: dealloc_stack // CHECK-NOT: release [[G]] // CHECK-NEXT: dealloc_stack // CHECK-NEXT: release [[G]] // CHECK-NEXT: return [[RESULT]] } // duplicate returns an autoreleased object at +0. // CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions5test9 func test9(g: Gizmo) -> Gizmo { return g.duplicate() // CHECK: bb0([[G:%.*]] : $Gizmo): // CHECK-NOT: retain [[G:%0]] // CHECK: alloc_stack // CHECK-NEXT: [[METHOD:%.*]] = class_method [volatile] [[G]] : {{.*}}, #Gizmo.duplicate!1.foreign // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[G]]) // CHECK-NEXT: retain_autoreleased [[RESULT]] // CHECK-NEXT: store [[RESULT]] // CHECK-NEXT: function_ref // CHECK-NEXT: function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue // CHECK-NEXT: alloc_stack // CHECK-NEXT: apply // CHECK-NEXT: [[RESULT:%.*]] = load // CHECK-NEXT: dealloc_stack // CHECK-NOT: release [[G]] // CHECK-NEXT: dealloc_stack // CHECK-NEXT: release [[G]] // CHECK-NEXT: return [[RESULT]] } // CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions6test10 func test10(g: Gizmo) -> AnyClass { // CHECK: bb0([[G:%[0-9]+]] : $Gizmo): // CHECK: strong_retain [[G]] // CHECK-NEXT: [[NS_G:%[0-9]+]] = upcast [[G:%[0-9]+]] : $Gizmo to $NSObject // CHECK-NEXT: [[GETTER:%[0-9]+]] = class_method [volatile] [[NS_G]] : $NSObject, #NSObject.classProp!getter.1.foreign : NSObject -> () -> AnyObject.Type! , $@convention(objc_method) (NSObject) -> ImplicitlyUnwrappedOptional<@objc_metatype AnyObject.Type> // CHECK-NEXT: [[OPT_OBJC:%.*]] = apply [[GETTER]]([[NS_G]]) : $@convention(objc_method) (NSObject) -> ImplicitlyUnwrappedOptional<@objc_metatype AnyObject.Type> // CHECK: select_enum [[OPT_OBJC]] // CHECK: [[OBJC:%.*]] = unchecked_enum_data [[OPT_OBJC]] // CHECK-NEXT: [[THICK:%.*]] = objc_to_thick_metatype [[OBJC]] // CHECK: [[T0:%.*]] = enum $ImplicitlyUnwrappedOptional<AnyObject.Type>, #ImplicitlyUnwrappedOptional.Some!enumelt.1, [[THICK]] // CHECK: [[T0:%.*]] = function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue // CHECK: apply [[T0]]<AnyObject.Type>([[THICK_BUF:%.*]]#1, {{.*}}) // CHECK-NEXT: [[RES:%.*]] = load [[THICK_BUF]]#1 // CHECK: strong_release [[G]] : $Gizmo // CHECK: strong_release [[G]] : $Gizmo // CHECK-NEXT: return [[RES]] : $@thick AnyObject.Type return g.classProp } // CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions6test11 func test11(g: Gizmo) -> AnyClass { // CHECK: bb0([[G:%[0-9]+]] : $Gizmo): // CHECK: strong_retain [[G]] // CHECK: [[NS_G:%[0-9]+]] = upcast [[G:%[0-9]+]] : $Gizmo to $NSObject // CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[NS_G]] : $NSObject, #NSObject.qualifiedClassProp!getter.1.foreign : NSObject -> () -> AnyObject.Type! , $@convention(objc_method) (NSObject) -> ImplicitlyUnwrappedOptional<@objc_metatype AnyObject.Type> // CHECK-NEXT: [[OPT_OBJC:%.*]] = apply [[GETTER]]([[NS_G]]) : $@convention(objc_method) (NSObject) -> ImplicitlyUnwrappedOptional<@objc_metatype AnyObject.Type> // CHECK: select_enum [[OPT_OBJC]] // CHECK: [[OBJC:%.*]] = unchecked_enum_data [[OPT_OBJC]] // CHECK-NEXT: [[THICK:%.*]] = objc_to_thick_metatype [[OBJC]] // CHECK: [[T0:%.*]] = enum $ImplicitlyUnwrappedOptional<AnyObject.Type>, #ImplicitlyUnwrappedOptional.Some!enumelt.1, [[THICK]] // CHECK: [[T0:%.*]] = function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue // CHECK: apply [[T0]]<AnyObject.Type>([[THICK_BUF:%.*]]#1, {{.*}}) // CHECK-NEXT: [[RES:%.*]] = load [[THICK_BUF]]#1 // CHECK: strong_release [[G]] : $Gizmo // CHECK: strong_release [[G]] : $Gizmo // CHECK-NEXT: return [[RES]] : $@thick AnyObject.Type return g.qualifiedClassProp } // ObjC blocks should have cdecl calling convention and follow C/ObjC // ownership conventions, where the callee, arguments, and return are all +0. // CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions10applyBlock func applyBlock(f: @convention(block) Gizmo -> Gizmo, x: Gizmo) -> Gizmo { // CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (Gizmo) -> @autoreleased Gizmo, [[ARG:%.*]] : $Gizmo): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: strong_retain [[BLOCK_COPY]] // CHECK: [[RESULT:%.*]] = apply [[BLOCK_COPY]]([[ARG]]) // CHECK: strong_retain_autoreleased [[RESULT]] // CHECK: strong_release [[BLOCK_COPY]] // CHECK: strong_release [[ARG]] // CHECK: strong_release [[BLOCK_COPY]] // CHECK: strong_release [[BLOCK]] // CHECK: return [[RESULT]] return f(x) } // CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions15maybeApplyBlock func maybeApplyBlock(f: (@convention(block) Gizmo -> Gizmo)?, x: Gizmo) -> Gizmo? { // CHECK: bb0([[BLOCK:%.*]] : $Optional<@convention(block) Gizmo -> Gizmo>, [[ARG:%.*]] : $Gizmo): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] return f?(x) } func useInnerPointer(p: UnsafeMutablePointer<Void>) {} // Handle inner-pointer methods by autoreleasing self after the call. // CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions18innerPointerMethod // CHECK: [[USE:%.*]] = function_ref @_TF26objc_ownership_conventions15useInnerPointer // CHECK: [[METHOD:%.*]] = class_method [volatile] %0 : $Gizmo, #Gizmo.getBytes!1.foreign : Gizmo -> () -> UnsafeMutablePointer<()> , $@convention(objc_method) (Gizmo) -> @unowned_inner_pointer UnsafeMutablePointer<()> // CHECK: strong_retain %0 // CHECK: [[PTR:%.*]] = apply [[METHOD]](%0) // CHECK: autorelease_value %0 // CHECK: apply [[USE]]([[PTR]]) // CHECK: strong_release %0 func innerPointerMethod(g: Gizmo) { useInnerPointer(g.getBytes()) } // CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions20innerPointerProperty // CHECK: [[USE:%.*]] = function_ref @_TF26objc_ownership_conventions15useInnerPointer // CHECK: [[METHOD:%.*]] = class_method [volatile] %0 : $Gizmo, #Gizmo.innerProperty!getter.1.foreign : Gizmo -> () -> UnsafeMutablePointer<()> , $@convention(objc_method) (Gizmo) -> @unowned_inner_pointer UnsafeMutablePointer<()> // CHECK: strong_retain %0 // CHECK: [[PTR:%.*]] = apply [[METHOD]](%0) // CHECK: autorelease_value %0 // CHECK: apply [[USE]]([[PTR]]) // CHECK: strong_release %0 func innerPointerProperty(g: Gizmo) { useInnerPointer(g.innerProperty) }
apache-2.0
10a3d502e300c0e57a14edb89cb2caee
52.059113
261
0.622876
3.514192
false
true
false
false
DingSoung/CCExtension
Sources/Foundation/URL+Cookie.swift
2
1051
// Created by Songwen Ding on 2017/11/23. // Copyright © 2017年 DingSoung. All rights reserved. #if canImport(Foundation) import Foundation.NSURL import Foundation.NSHTTPCookie extension URL { public func cookiePreperties(value: String, forName name: String) -> [HTTPCookiePropertyKey: Any] { var properties: [HTTPCookiePropertyKey: Any] = [ .name: name, .value: value, .path: "/", //self.path, .expires: Date(timeIntervalSinceNow: 24 * 60 * 60), .originURL: self, //.maximumAge //.discard .version: "0" //.comment ] as [HTTPCookiePropertyKey: Any] if let host = host { properties[.domain] = host } if let port = port { properties[.port] = port } return properties } public func cookie(value: String, forName name: String) -> HTTPCookie? { let properties = self.cookiePreperties(value: value, forName: name) return HTTPCookie(properties: properties) } } #endif
mit
6a945a77a0e019bda575f22bc613a75b
33.933333
103
0.604962
4.421941
false
false
false
false
qq456cvb/DeepLearningKitForiOS
tvOSDeepLearningKitApp/tvOSDeepLearningKitApp/tvOSDeepLearningKitApp/DeepNetwork+SetupNetworkFromDict.swift
2
4391
// // DeepNetwork+SetupNetworkFromDict.swift // MemkiteMetal // // Created by Amund Tveit on 10/12/15. // Copyright © 2015 memkite. All rights reserved. // import Foundation import Metal public extension DeepNetwork { func setupNetworkFromDict(deepNetworkAsDict: NSDictionary, inputimage: MTLBuffer, inputshape: [Float], caching_mode:Bool) { let start = NSDate() print(" ==> setupNetworkFromDict()") // Add input image var layer_number = 0 layer_data_caches.append(Dictionary<String, MTLBuffer>()) // for input pool_type_caches.append(Dictionary<String,String>()) blob_cache.append(Dictionary<String,([Float],[Float])>()) namedDataLayers.append(("input", inputimage)) ++layer_number // Add remaining network var previousBuffer:MTLBuffer = inputimage var previousShape:[Float] = inputshape self.deepNetworkAsDict = deepNetworkAsDict // create new command buffer for next layer var currentCommandBuffer: MTLCommandBuffer = metalCommandQueue.commandBufferWithUnretainedReferences() var t = NSDate() for layer in deepNetworkAsDict["layer"] as! [NSDictionary] { if let type = layer["type"] as? String { let layer_string = layer["name"] as! String layer_data_caches.append(Dictionary<String, MTLBuffer>()) pool_type_caches.append(Dictionary<String,String>()) blob_cache.append(Dictionary<String,([Float],[Float])>()) if type == "ReLU" { self.gpuCommandLayers.append(currentCommandBuffer) //(previousBuffer, currentCommandBuffer) = createRectifierLayer(previousBuffer) (previousBuffer, currentCommandBuffer) = createRectifierLayer(previousBuffer, metalCommandQueue:metalCommandQueue, metalDefaultLibrary:metalDefaultLibrary, metalDevice:metalDevice) self.namedDataLayers.append((layer["name"]! as! String, previousBuffer)) } else if type == "Pooling" { self.gpuCommandLayers.append(currentCommandBuffer) // (previousBuffer, currentCommandBuffer, previousShape) = createPoolingLayer(layer, inputBuffer: previousBuffer, inputShape: previousShape) (previousBuffer, currentCommandBuffer, previousShape) = createPoolingLayerCached(layer, inputBuffer: previousBuffer, inputShape: previousShape, metalCommandQueue: metalCommandQueue, metalDefaultLibrary: metalDefaultLibrary, metalDevice: metalDevice, pool_type_caches: &pool_type_caches, layer_data_caches: &layer_data_caches, layer_number: layer_number, layer_string: layer_string, caching_mode: caching_mode) self.namedDataLayers.append((layer["name"]! as! String, previousBuffer)) } else if type == "Convolution" { self.gpuCommandLayers.append(currentCommandBuffer) // (previousBuffer, currentCommandBuffer, previousShape) = createConvolutionLayer(layer, inputBuffer: previousBuffer, inputShape: previousShape) (previousBuffer, currentCommandBuffer, previousShape) = createConvolutionLayerCached(layer, inputBuffer: previousBuffer, inputShape: previousShape, metalCommandQueue: metalCommandQueue, metalDefaultLibrary:metalDefaultLibrary, metalDevice:metalDevice, layer_data_caches: &layer_data_caches, blob_cache: &blob_cache, layer_number: layer_number, layer_string: layer_string, caching_mode: caching_mode) self.namedDataLayers.append((layer["name"]! as! String, previousBuffer)) } let name = layer["name"] as! String print("\(name): \(NSDate().timeIntervalSinceDate(t))") t = NSDate() ++layer_number } } self.gpuCommandLayers.append(currentCommandBuffer) print("bar") print("AFTER LAYER DATA CHACES = \(layer_data_caches[0])") print("POOL TYPE CACHES = \(pool_type_caches)") print("Time to set up network: \(NSDate().timeIntervalSinceDate(start))") } }
apache-2.0
5c8c773f72e5ad84b47782047d6be90f
51.261905
429
0.632118
5.063437
false
false
false
false
linhaosunny/yeehaiyake
椰海雅客微博/椰海雅客微博/Classes/Home/LSXHomeViewController.swift
1
5538
// // LSXHomeViewController.swift // 椰海雅客微博 // // Created by 李莎鑫 on 2017/4/2. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit import QorumLogs import SVProgressHUD import LSXPropertyTool class LSXHomeViewController: LSXBaseTableViewController { let cellID = "homeCell" var homeTimelines:Array<LSXHomeViewModel>? { didSet{ //: 跟新数据 tableView.reloadData() } } fileprivate var selectButton:UIButton? //MARK: 懒加载 lazy var animationManager:LSXPresentationManager = { () -> LSXPresentationManager in let manager = LSXPresentationManager() manager.presentAreaSize = CGSize(width: 200, height: 300) return manager }() //MARK: 系统方法 convenience init() { self.init(style:.grouped) } override func viewDidLoad() { super.viewDidLoad() if !isLogin { visitorView?.setupVisitorInfo(imageName: nil, title: "关注一些人,回这里看看有什么惊喜") return } //: 设置导航条 navigationItem.leftBarButtonItem = UIBarButtonItem("navigationbar_friendattention", target: self, action: #selector(friendDattention)) navigationItem.rightBarButtonItem = UIBarButtonItem("navigationbar_pop", target: self, action: #selector(navigationScanQRCode)) let title = LSXUserAccountModel.loadAccount()?.screen_name navigationItem.titleView = LSXTitleButton(title, imageName:"navigationbar_arrow_up",selectImageName:"navigationbar_arrow_down", target: self, action: #selector(titleButtonClick(button:))) //: 获取主页网络数据 loadHomeWeiboData() //: 自动预估高度 tableView.estimatedRowHeight = 800 tableView.rowHeight = UITableViewAutomaticDimension } //MARK: 私有方法 private func loadHomeWeiboData() { LSXHttpTools.shareInstance.loadHomeWeiboStatus { (array, error) in if error != nil { SVProgressHUD.showError(withStatus: "更新数据失败") return } guard let data = array as Array<Any>? else { SVProgressHUD.showError(withStatus: "正在获取数据...") return } //: JOSN数据过大生产代码耗性能 // PropertyCodeMake.propertyCodeMake(withDictionaryArray: data, fileName: "Statuses", filePath: "/Users/lishaxin/Desktop/Models/yehaiyake") self.homeTimelines = LSXHomeViewModel.viewModel(withModelArray: ExchangeToModel.model(withClassName: "Statuses", withArray: data) as? Array<Statuses>) guard self.homeTimelines?.count != 0 else{ return } } } @objc private func titleButtonClick(button:UIButton){ button.isSelected = !button.isSelected selectButton = button let controller = UIViewController() controller.view = LSXPopoverView(.middle) controller.modalPresentationStyle = .custom controller.transitioningDelegate = animationManager; animationManager.delegate = self animationManager.sourceRect = button.frame animationManager.popoverArrowDirection = (controller.view as! LSXPopoverView).popoverArrowDirection present(controller, animated: true, completion: nil) } //MARK: 内部回调方法 @objc private func friendDattention(){ // present(LSXWelcomeViewController(), animated: true, completion: nil) present(LSXNewFeatureViewController(), animated: true, completion: nil) } @objc private func navigationScanQRCode(){ present(UINavigationController(rootViewController: LSXQRCodeViewController()), animated: true, completion: nil) } //MARK: 其他 override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: 数据源方法 override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 10 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 10 } override func numberOfSections(in tableView: UITableView) -> Int { return self.homeTimelines?.count ?? 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: cellID) as? LSXHomeViewCell if cell == nil { cell = LSXHomeViewCell(style: .default, reuseIdentifier: cellID) } cell?.viewModel = self.homeTimelines![indexPath.section] return cell! } } //MARK: 转场动画代理方法->LSXPresentationManagerDelegate extension LSXHomeViewController:LSXPresentationManagerDelegate{ func animationControllerPresented(manager: LSXPresentationManager) { } func animationControllerDismissed(manager: LSXPresentationManager) { selectButton?.isSelected = !selectButton!.isSelected } }
mit
fed0f57d04ef59546311db793907b476
31.260606
195
0.642495
5.157946
false
false
false
false
CPRTeam/CCIP-iOS
OPass/Tabs/CheckinTab/CheckinCardViewController.swift
1
2791
// // CheckinCardViewController.swift // OPass // // Created by 腹黒い茶 on 2019/6/14. // 2019 OPass. // import Foundation import UIKit class CheckinCardViewController: UIViewController { @IBOutlet public weak var checkinSmallCard: UIView! @IBOutlet public weak var checkinDate: UILabel! @IBOutlet public weak var checkinTitle: UILabel! @IBOutlet public weak var checkinText: UILabel! @IBOutlet public weak var checkinBtn: UIButton! @IBOutlet public weak var checkinIcon: UIImageView! public var delegate: CheckinViewController? public var scenario: Dictionary<String, NSObject>? public var id: String = "" public var used: Int? public var disabled: String? private var cardView: CheckinCardView? override func viewDidLoad() { super.viewDidLoad() self.cardView = self.view as? CheckinCardView if let csc = self.cardView?.checkinSmallCard { csc.layer.cornerRadius = 5 csc.layer.masksToBounds = false csc.layer.shadowOffset = CGSize(width: 0, height: 50) csc.layer.shadowRadius = 50 csc.layer.shadowOpacity = 0.1 } } override func viewDidLayoutSubviews() { guard let checkinBtn = self.cardView?.checkinBtn else { return } guard let layer = checkinBtn.layer.sublayers?.first else { return } layer.cornerRadius = checkinBtn.frame.size.height / 2 checkinBtn.layer.cornerRadius = checkinBtn.frame.size.height / 2 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setScenario(_ scenario: Scenario?) { self.cardView?.scenario = scenario guard let id = scenario?.Id else { return } if id == "vipkit" && scenario?.Disabled == nil { self.cardView?.layer.shadowColor = UIColor.colorFromHtmlColor("#cff1").cgColor self.cardView?.layer.shadowRadius = 20 let animation = CABasicAnimation.init(keyPath: "shadowOpacity") animation.fromValue = 0.3 animation.toValue = 0.5 animation.repeatCount = HUGE animation.duration = 1 animation.autoreverses = true animation.timingFunction = CAMediaTimingFunction.init(name: .easeInEaseOut) self.cardView?.layer.add(animation, forKey: "pulse") } } func setId(_ id: String) { self.cardView?.id = id } func setUsed(_ used: Int?) { self.cardView?.used = used } func setDisabled(_ disabled: String?) { self.cardView?.disabled = disabled } func setDelegate(_ delegate: CheckinViewController) { self.cardView?.delegate = delegate } }
gpl-3.0
e1837dcf47721ffebd0ac14e2b9c878e
31.360465
90
0.647503
4.584843
false
false
false
false
BridgeTheGap/KRMathInputView
KRMathInputView/Classes/Model/TerminalNode.swift
1
1056
// // TerminalNode.swift // TestScript // // Created by Joshua Park on 08/02/2017. // Copyright © 2017 Knowre. All rights reserved. // import UIKit @objc public protocol TerminalNodeType { var indexes: [Int] { get } var candidates: [String] { get } } public class InkNode: NSObject, TerminalNodeType { public let indexes: [Int] public let candidates: [String] override public var description: String { return "<InkNode: stroke indexes=\(indexes); candidates=\(candidates)>" } @objc public init(indexes: [Int], candidates: [String]) { (self.indexes, self.candidates) = (indexes, candidates) } } public class CharacterNode: NSObject, TerminalNodeType { public let indexes: [Int] public let candidates: [String] override public var description: String { return "<CharacterNode: index=\(indexes); character=\(candidates)>" } @objc public init(indexes: [Int], candidates: [String]) { (self.indexes, self.candidates) = (indexes, candidates) } }
mit
0512264e333e27c3e4e09c040c666000
25.375
79
0.652133
4.073359
false
false
false
false
raychrd/tada
tada/NewEventViewController.swift
1
3207
// // NewEventViewController.swift // tada // // Created by Ray on 15/1/27. // Copyright (c) 2015年 Ray. All rights reserved. // import UIKit class NewEventViewController: UIViewController { var returnPressed:Bool = false @IBOutlet var textField: MKTextField! @IBOutlet weak var newButton: UIButton! @IBOutlet weak var time: UILabel! @IBOutlet weak var reminderTitle: UILabel! @IBAction func textFieldReturn(sender: AnyObject) { analyseString(textField.text) reminderTitle.text = reminderText let currentDate = NSCalendar.currentCalendar().dateFromComponents(reminderTimeComponent!) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM-dd HH:mm" let timeString = dateFormatter.stringFromDate(currentDate!) if setAlarm { time.text = "提醒时间 "+timeString } else { time.text = "未指定具体时间" } returnPressed = true sender.resignFirstResponder() } override func viewDidLoad() { super.viewDidLoad() textField.layer.borderColor = UIColor.clearColor().CGColor textField.floatingPlaceholderEnabled = true textField.placeholder = "New Reminder" textField.tintColor = UIColor.MKColor.moreGreen textField.rippleLocation = .Right textField.cornerRadius = 0 textField.bottomBorderEnabled = true newButton.layer.cornerRadius = 20 // Do any additional setup after loading the view. self.navigationController?.interactivePopGestureRecognizer.delegate = nil textField.becomeFirstResponder(); } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { textField.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func add(sender: AnyObject) { if returnPressed { createReminder() } else { analyseString(textField.text) reminderTitle.text = reminderText let currentDate = NSCalendar.currentCalendar().dateFromComponents(reminderTimeComponent!) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM-dd HH:mm" let timeString = dateFormatter.stringFromDate(currentDate!) if setAlarm { time.text = "提醒时间 "+timeString } else { time.text = "未指定具体时间" } createReminder() returnPressed = false } let bbb = refreshEvents() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
be6922cab971c7f3ceb00d6ef8d92440
30.61
106
0.622588
5.394198
false
false
false
false
qingtianbuyu/Mono
Moon/Classes/Other/Extension/UIImage+Extension.swift
1
1088
// // UIImage+Extension.swift // Moon // // Created by YKing on 16/5/29. // Copyright © 2016年 YKing. All rights reserved. // import UIKit extension UIImage { class func imageWithColor( _ color: UIColor, size: CGSize) -> UIImage { //开启上下文 UIGraphicsBeginImageContextWithOptions(size, false, 0.0) //获取上下文 let ctx = UIGraphicsGetCurrentContext(); let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height); ctx!.setFillColor(color.cgColor) //在画布上面绘制出来 ctx!.fill(rect) //从上下文读取Image信息 let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image!; } class func imageName(_ name: String) -> (normalImage: UIImage, highLightedImage: UIImage) { let image = UIImage(named: name)!.withRenderingMode(UIImageRenderingMode.alwaysOriginal) let imageName = "\(name)-act" let highLightImage = UIImage(named: imageName)!.withRenderingMode(UIImageRenderingMode.alwaysOriginal) return (image, highLightImage) } }
mit
2bfe4e85b36dfa6bbbc40fb900cd2048
27.638889
106
0.700291
4.22541
false
false
false
false
urbn/URBNSwiftAlert
URBNSwiftAlert/Classes/AlertAction.swift
1
3322
// // AlertAction.swift // Pods // // Created by Kevin Taniguchi on 5/23/17. // // import Foundation public class AlertAction: NSObject { /** * ActionType sets predefined title / highlight / background colors for buttons * normal, destructive, and cancel are convenience types when you have a lot of alerts throughout an app that * have similar functions (for example, you want all cancel buttons in the app to look the same, so you set the colors once) */ public enum ActionType { case normal // applies title color and background for normal buttons case destructive // applies title color and background for destructive buttons case cancel // applies title color and background for cancel buttons case passive // no button added, action will be applied on tapping alert case custom // applies title color and background for custom buttons } let type: ActionType let shouldDismiss: Bool let isEnabled: Bool let completion: ((AlertAction) -> Void)? public var button: UIButton? var title: String? /** * Init an action with custom button, action type, dismissable and enabled bool, and completion handler * Used for creating connecting a custom button to an action * @param type Required. Type of action. * @param shouldDismiss Default true. On completion, the action will dismiss the alert. * @param isEnabled Default true. Action is enabled * @param completion Optional. Closure that takes in the action as a param and completes when the selector of the target fires. */ public convenience init(customButton: UIButton, shouldDismiss: Bool = true, isEnabled: Bool = true, completion: ((AlertAction) -> Void)? = nil) { self.init(type: .custom, shouldDismiss: shouldDismiss, isEnabled: isEnabled, completion: completion) add(button: customButton) } /** * Init an action with a title, action type, dismissable and enabled bool, and completion handler * Used for creating a standard URBNSwiftAlert button or passive action * @param title Optional. The button title * @param type Required. Type of action. * @param shouldDismiss Default true. On completion, the action will dismiss the alert. * @param isEnabled Default true. Action is enabled * @param completion Optional. Closure that takes in the action as a param and completes when the selector of the target fires. */ public init(type: AlertAction.ActionType, shouldDismiss: Bool = true, isEnabled: Bool = true, title: String? = nil, completion: ((AlertAction) -> Void)? = nil) { self.type = type self.shouldDismiss = shouldDismiss self.isEnabled = isEnabled self.completion = completion super.init() self.title = title } func add(button: UIButton) { button.addTarget(self, action: #selector(completeAction), for: .touchUpInside) self.button = button } /** * Enables / Disables the Button in the alert (non custom only) */ public func set(isEnabled: Bool) { button?.isEnabled = isEnabled } @objc func completeAction() { completion?(self) } }
mit
88444c717b6fdc7cb6c8e5ca5c395192
39.512195
165
0.667369
4.82148
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
Playground Collection/Part 2 - Robot Maze 2/Boolean Expressions/Boolean Expressions.playground/Pages/Introduction.xcplaygroundpage/Contents.swift
1
166
//: Boolean Expressions import UIKit // Introduction to Boolean Expressions var age = 5 var timeForKindergarten = age == 5 var canVote = age >= 18 //: [Next](@next)
mit
13b0d4fd6e29f311619a22053c5c512d
17.555556
38
0.704819
3.688889
false
false
false
false
shaps80/Peek
Pod/Classes/Peekable/UIColor+Peekable.swift
1
3362
/* Copyright © 23/04/2016 Shaps 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 extension UIColor { @objc var peek_alpha: CGFloat { return CGFloat(Color(system: self)?.rgba.alpha ?? 0) } @objc var peek_HEX: String { if let hex = Color(system: self)?.toHex(withAlpha: false) { return "#\(hex)" } else { return "Unknown" } } @objc var peek_HSL: String { return "\(Int(hslComponents.hue * 360)), \(Int(hslComponents.saturation * 100)), \(Int(hslComponents.brightness * 100))" } @objc var peek_RGB: String { return "\(Int(rgbComponents.red * 255)), \(Int(rgbComponents.green * 255)), \(Int(rgbComponents.blue * 255))" } @available(iOS 10.0, *) @objc var colorSpace: String { let colorSpace = cgColor.colorSpace ?? CGColorSpaceCreateDeviceRGB() return colorSpace.name as String? ?? "Unknown" } open override func preparePeek(with coordinator: Coordinator) { if cgColor.pattern != nil || (self != .clear && rgbComponents.alpha != 0) { let width = UIScreen.main.nativeBounds.width / UIScreen.main.nativeScale let image = ImageRenderer(size: CGSize(width: width, height: 88)).image { context in let rect = context.format.bounds setFill() UIRectFill(rect) } coordinator.appendPreview(image: image, forModel: self) } if #available(iOS 10.0, *) { coordinator.appendDynamic(keyPaths: ["colorSpace"], forModel: self, in: .general) } guard cgColor.pattern == nil else { coordinator.appendStatic(keyPath: "cgColor.pattern", title: "Color", detail: nil, value: "Pattern", in: .general) return } guard self != .clear else { coordinator.appendStatic(keyPath: "self", title: "Color", detail: nil, value: "Clear", in: .general) return } coordinator.appendDynamic(keyPathToName: [ ["peek_HEX": "HEX"], ["peek_RGB": "RGB"], ["peek_HSL": "HSL"], ["peek_alpha": "Alpha"], ], forModel: self, in: .general) super.preparePeek(with: coordinator) } }
mit
cf3b6f23c2536d59354f7f999701080e
36.764045
128
0.623624
4.523553
false
false
false
false
wilfreddekok/Antidote
Antidote/PinAuthorizationCoordinator.swift
1
6903
// 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 AudioToolbox import LocalAuthentication class PinAuthorizationCoordinator: NSObject { private enum State { case Unlocked case Locked(lockTime: CFTimeInterval) case ValidatingPin } private let theme: Theme private let window: UIWindow private weak var submanagerObjects: OCTSubmanagerObjects! private var state: State var preventFromLocking: Bool = false { didSet { if !preventFromLocking && UIApplication.sharedApplication().applicationState != .Active { // In case if locking option change in background we want to lock app when user comes back. lockIfNeeded(CACurrentMediaTime()) } } } init(theme: Theme, submanagerObjects: OCTSubmanagerObjects, lockOnStartup: Bool) { self.theme = theme self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.submanagerObjects = submanagerObjects self.state = .Unlocked super.init() // Showing window on top of all other windows. window.windowLevel = UIWindowLevelStatusBar + 1000 if lockOnStartup { lockIfNeeded(0) } NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PinAuthorizationCoordinator.appWillResignActiveNotification), name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PinAuthorizationCoordinator.appDidBecomeActiveNotification), name: UIApplicationDidBecomeActiveNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func appWillResignActiveNotification() { lockIfNeeded(CACurrentMediaTime()) } func appDidBecomeActiveNotification() { switch state { case .Unlocked: // unlocked, nothing to do here break case .Locked(let lockTime): isPinDateExpired(lockTime) ? challengeUserToAuthorize(lockTime) : unlock() case .ValidatingPin: // checking pin, no action required break } } } extension PinAuthorizationCoordinator: CoordinatorProtocol { func startWithOptions(options: CoordinatorOptions?) { switch state { case .Locked(let lockTime): challengeUserToAuthorize(lockTime) case .Unlocked: // ignore break case .ValidatingPin: // ignore break } } } extension PinAuthorizationCoordinator: EnterPinControllerDelegate { func enterPinController(controller: EnterPinController, successWithPin pin: String) { unlock() } func enterPinControllerFailure(controller: EnterPinController) { controller.resetEnteredPin() controller.topText = String(localized: "pin_incorrect") AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } } private extension PinAuthorizationCoordinator { func lockIfNeeded(lockTime: CFTimeInterval) { guard submanagerObjects.getProfileSettings().unlockPinCode != nil else { return } if preventFromLocking { return } for window in UIApplication.sharedApplication().windows { window.endEditing(true) } let storyboard = UIStoryboard(name: "LaunchPlaceholderBoard", bundle: NSBundle.mainBundle()) window.rootViewController = storyboard.instantiateViewControllerWithIdentifier("LaunchPlaceholderController") window.hidden = false switch state { case .Unlocked: state = .Locked(lockTime: lockTime) case .Locked: // In case of Locked state don't want to update lockTime. break case .ValidatingPin: // In case of ValidatingPin state we also don't want to do anything. break } } func unlock() { state = .Unlocked window.hidden = true } func challengeUserToAuthorize(lockTime: CFTimeInterval) { if window.rootViewController is EnterPinController { // already showing pin controller return } if shouldUseTouchID() { state = .ValidatingPin LAContext().evaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, localizedReason: String(localized: "pin_touch_id_description"), reply: { [weak self] success, error in dispatch_async(dispatch_get_main_queue()) { self?.state = .Locked(lockTime: lockTime) success ? self?.unlock() : self?.showValidatePinController() } }) } else { showValidatePinController() } } func showValidatePinController() { let settings = submanagerObjects.getProfileSettings() guard let pin = settings.unlockPinCode else { fatalError("pin shouldn't be nil") } let controller = EnterPinController(theme: theme, state: .ValidatePin(validPin: pin)) controller.topText = String(localized: "pin_enter_to_unlock") controller.delegate = self window.rootViewController = controller } func isPinDateExpired(lockTime: CFTimeInterval) -> Bool { let settings = submanagerObjects.getProfileSettings() let delta = CACurrentMediaTime() - lockTime switch settings.lockTimeout { case .Immediately: return true case .Seconds30: return delta > 30 case .Minute1: return delta > 60 case .Minute2: return delta > (60 * 2) case .Minute5: return delta > (60 * 5) } } func shouldUseTouchID() -> Bool { guard submanagerObjects.getProfileSettings().useTouchID else { return false } guard LAContext().canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: nil) else { return false } return true } }
mpl-2.0
3ad6d244119ea585f4f62b1890294115
32.347826
138
0.586846
5.805719
false
false
false
false
wilfreddekok/Antidote
Antidote/AppCoordinator.swift
1
6437
// 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 UIKit class AppCoordinator { private let window: UIWindow private var activeCoordinator: TopCoordinatorProtocol! private var theme: Theme init(window: UIWindow) { self.window = window let filepath = NSBundle.mainBundle().pathForResource("default-theme", ofType: "yaml")! let yamlString = try! NSString(contentsOfFile:filepath, encoding:NSUTF8StringEncoding) as String theme = try! Theme(yamlString: yamlString) applyTheme(theme) } } // MARK: CoordinatorProtocol extension AppCoordinator: TopCoordinatorProtocol { func startWithOptions(options: CoordinatorOptions?) { let storyboard = UIStoryboard(name: "LaunchPlaceholderBoard", bundle: NSBundle.mainBundle()) window.rootViewController = storyboard.instantiateViewControllerWithIdentifier("LaunchPlaceholderController") recreateActiveCoordinator(options: options) } func handleLocalNotification(notification: UILocalNotification) { activeCoordinator.handleLocalNotification(notification) } func handleInboxURL(url: NSURL) { activeCoordinator.handleInboxURL(url) } } extension AppCoordinator: RunningCoordinatorDelegate { func runningCoordinatorDidLogout(coordinator: RunningCoordinator, importToxProfileFromURL: NSURL?) { KeychainManager().deleteActiveAccountData() recreateActiveCoordinator() if let url = importToxProfileFromURL, let coordinator = activeCoordinator as? LoginCoordinator { coordinator.handleInboxURL(url) } } func runningCoordinatorDeleteProfile(coordinator: RunningCoordinator) { let userDefaults = UserDefaultsManager() let profileManager = ProfileManager() let name = userDefaults.lastActiveProfile! do { try profileManager.deleteProfileWithName(name) KeychainManager().deleteActiveAccountData() userDefaults.lastActiveProfile = nil recreateActiveCoordinator() } catch let error as NSError { handleErrorWithType(.DeleteProfile, error: error) } } func runningCoordinatorRecreateCoordinatorsStack(coordinator: RunningCoordinator, options: CoordinatorOptions) { recreateActiveCoordinator(options: options, skipAuthorizationChallenge: true) } } extension AppCoordinator: LoginCoordinatorDelegate { func loginCoordinatorDidLogin(coordinator: LoginCoordinator, manager: OCTManager, password: String) { KeychainManager().toxPasswordForActiveAccount = password recreateActiveCoordinator(manager: manager, skipAuthorizationChallenge: true) } } // MARK: Private private extension AppCoordinator { func applyTheme(theme: Theme) { let linkTextColor = theme.colorForType(.LinkText) UIButton.appearance().tintColor = linkTextColor UISwitch.appearance().onTintColor = linkTextColor UINavigationBar.appearance().tintColor = linkTextColor } func recreateActiveCoordinator(options options: CoordinatorOptions? = nil, manager: OCTManager? = nil, skipAuthorizationChallenge: Bool = false) { if let password = KeychainManager().toxPasswordForActiveAccount { let successBlock: OCTManager -> Void = { [unowned self] manager -> Void in self.activeCoordinator = self.createRunningCoordinatorWithManager(manager, options: options, skipAuthorizationChallenge: skipAuthorizationChallenge) } if let manager = manager { successBlock(manager) } else { let deleteActiveAccountAndRetry: Void -> Void = { [unowned self] in KeychainManager().deleteActiveAccountData() self.recreateActiveCoordinator(options: options, manager: manager, skipAuthorizationChallenge: skipAuthorizationChallenge) } guard let profileName = UserDefaultsManager().lastActiveProfile else { deleteActiveAccountAndRetry() return } let path = ProfileManager().pathForProfileWithName(profileName) guard let configuration = OCTManagerConfiguration.configurationWithBaseDirectory(path) else { deleteActiveAccountAndRetry() return } ToxFactory.createToxWithConfiguration(configuration, encryptPassword: password, successBlock: successBlock, failureBlock: { _ in log("Cannot create tox with configuration \(configuration)") deleteActiveAccountAndRetry() }) } } else { activeCoordinator = createLoginCoordinator(options) } } func createRunningCoordinatorWithManager(manager: OCTManager, options: CoordinatorOptions?, skipAuthorizationChallenge: Bool) -> RunningCoordinator { let coordinator = RunningCoordinator(theme: theme, window: window, toxManager: manager, skipAuthorizationChallenge: skipAuthorizationChallenge) coordinator.delegate = self coordinator.startWithOptions(options) return coordinator } func createLoginCoordinator(options: CoordinatorOptions?) -> LoginCoordinator { let coordinator = LoginCoordinator(theme: theme, window: window) coordinator.delegate = self coordinator.startWithOptions(options) return coordinator } }
mpl-2.0
c1cb64ad9afd3e99f9ab539c41c3ad4f
38.490798
137
0.612552
6.65667
false
false
false
false
roadfire/SwiftFonts
SwiftFonts/MasterViewController.swift
1
1729
// // MasterViewController.swift // SwiftFonts // // Created by Josh Brown on 6/3/14. // Copyright (c) 2014 Roadfire Software. All rights reserved. // import UIKit class MasterViewController: UITableViewController { let viewModel = MasterViewModel() override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.viewModel.numberOfSections() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.viewModel.numberOfRowsInSection(section) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) self.configureCell(cell, atIndexPath: indexPath); return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let label = UILabel(frame: CGRectMake(0, 0, 280, 200)) label.text = viewModel.titleAtIndexPath(indexPath) label.font = self.fontAtIndexPath(indexPath) label.sizeToFit() return max(label.font.lineHeight + label.font.ascender + -label.font.descender, 44) } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { cell.textLabel?.text = viewModel.titleAtIndexPath(indexPath) cell.textLabel?.font = self.fontAtIndexPath(indexPath) } func fontAtIndexPath(indexPath: NSIndexPath) -> UIFont { let fontName = viewModel.titleAtIndexPath(indexPath) return UIFont(name:fontName, size: UIFont.systemFontSize())! } }
mit
419f979f3072627dc1f95c9b51239301
32.25
116
0.70561
4.982709
false
false
false
false
elsucai/Hummingbird
Hummingbird/UserListTableViewController.swift
1
4951
// // ListsTableViewController.swift // Hummingbird // // Created by Xiang Cai on 12/15/16. // Copyright © 2016 Xiang Cai. All rights reserved. // import UIKit import TwitterKit class UserListTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() let userList = UserList() let session = Twitter.sharedInstance().sessionStore.session() as! TWTRSession self.userName = session.userName let attrs = [ NSForegroundColorAttributeName: self.view.tintColor//, // NSFontAttributeName: UIFont(name: "Georgia-Bold", size: 24) ] as [String : Any] self.navigationController?.navigationBar.titleTextAttributes = attrs userList.getUserLists("abc", { (returnedLists: [ListItem]) -> Void in self.userLists = returnedLists self.userLists.insert(ListItem(slug: "All Tweets", name: "All Tweets", listOwnerName: self.userName), at: 0) self.tableView.reloadData() }) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source var userLists = [ListItem]() var selectedListName = "" var selectedListSlug = "" var allTweetsSelected = false var userName = "" var selectedListOwnerName = "" override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return userLists.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) // Configure the cell... cell.textLabel?.text = userLists[indexPath.row].name return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) self.selectedListName = userLists[indexPath.row].name self.selectedListSlug = userLists[indexPath.row].slug self.selectedListOwnerName = userLists[indexPath.row].listOwnerName self.allTweetsSelected = indexPath.row == 0 performSegue(withIdentifier: "unwindToTimelineController", sender: nil) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "unwindToTimelineController" { let timelineViewController = segue.destination as! TimelineViewController timelineViewController.listSlug = self.allTweetsSelected ? "" : self.selectedListSlug timelineViewController.listOwnerName = self.allTweetsSelected ? self.userName : self.selectedListOwnerName timelineViewController.titleButton.setTitle(self.selectedListName, for: .normal) } } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ }
gpl-3.0
cb5a66fc4f7d311d12f2a9820f71b537
38.6
136
0.676566
5.140187
false
false
false
false
Kawoou/FlexibleImage
Sources/Filter/GammaFilter.swift
1
2552
// // GammaFilter.swift // FlexibleImage // // Created by Kawoou on 2017. 5. 12.. // Copyright © 2017년 test. All rights reserved. // #if !os(watchOS) import Metal #endif internal class GammaFilter: ImageFilter { // MARK: - Property internal override var metalName: String { get { return "GammaFilter" } } internal var gamma: Float = 1.0 // MARK: - Internal #if !os(watchOS) @available(OSX 10.11, iOS 8, tvOS 9, *) internal override func processMetal(_ device: ImageMetalDevice, _ commandBuffer: MTLCommandBuffer, _ commandEncoder: MTLComputeCommandEncoder) -> Bool { let factors: [Float] = [self.gamma] for i in 0..<factors.count { var factor = factors[i] let size = max(MemoryLayout<Float>.size, 16) let options: MTLResourceOptions if #available(iOS 9.0, *) { options = [.storageModeShared] } else { options = [.cpuCacheModeWriteCombined] } let buffer = device.device.makeBuffer( bytes: &factor, length: size, options: options ) #if swift(>=4.0) commandEncoder.setBuffer(buffer, offset: 0, index: i) #else commandEncoder.setBuffer(buffer, offset: 0, at: i) #endif } return super.processMetal(device, commandBuffer, commandEncoder) } #endif override func processNone(_ device: ImageNoneDevice) -> Bool { let memoryPool = device.memoryPool! let width = Int(device.drawRect!.width) let height = Int(device.drawRect!.height) var index = 0 for _ in 0..<height { for _ in 0..<width { let r = Float(memoryPool[index + 0]) / 255.0 let g = Float(memoryPool[index + 1]) / 255.0 let b = Float(memoryPool[index + 2]) / 255.0 memoryPool[index + 0] = UInt8(powf(r, self.gamma) * 255.0) memoryPool[index + 1] = UInt8(powf(g, self.gamma) * 255.0) memoryPool[index + 2] = UInt8(powf(b, self.gamma) * 255.0) index += 4 } } return super.processNone(device) } }
mit
54b36369cbf6ad559aa64a8e63388485
29.710843
160
0.488035
4.535587
false
false
false
false
EugeneVegner/sws-copyleaks-sdk-test
PlagiarismChecker/Classes/CopyleaksSessionDelegate.swift
1
6461
/* * The MIT License(MIT) * * Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com) * * 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 public class CopyleaksSessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate { private var subdelegates: [Int: CopyleaksRequest.TaskDelegate] = [:] private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) /* Access the task delegate for the specified task in a thread-safe manner.*/ public subscript(task: NSURLSessionTask) -> CopyleaksRequest.TaskDelegate? { get { var subdelegate: CopyleaksRequest.TaskDelegate? dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } return subdelegate } set { dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } } } /** Initializes the CopyleaksSessionDelegate instance. - returns: The new CopyleaksSessionDelegate instance. */ public override init() { super.init() } // MARK: - NSURLSessionDelegate /* Overrides default behavior for NSURLSessionDelegate method URLSession:didBecomeInvalidWithError: */ public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)? /* Overrides default behavior for NSURLSessionDelegate method URLSession:didReceiveChallenge:completionHandler:.*/ public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? /* Overrides all behavior for NSURLSessionDelegate method URLSession:didReceiveChallenge:completionHandler: and requires the caller to call the completionHandler.*/ public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? /* Overrides default behavior for NSURLSessionDelegate method URLSessionDidFinishEventsForBackgroundURLSession:.*/ public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? /** Tells the delegate that all messages enqueued for a session have been delivered. - parameter session: The session that no longer has any outstanding requests. */ public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { sessionDidFinishEventsForBackgroundURLSession?(session) } // MARK: - NSURLSessionTaskDelegate /* Overrides default behavior for NSURLSessionTaskDelegate method URLSession:task:didCompleteWithError:.*/ public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? /** Tells the delegate that the task finished transferring data. - parameter session: The session containing the task whose request finished transferring data. - parameter task: The task whose request finished transferring data. - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. */ public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let taskDidComplete = taskDidComplete { taskDidComplete(session, task, error) } else if let delegate = self[task] { delegate.URLSession(session, task: task, didCompleteWithError: error) } self[task] = nil } // MARK: - NSURLSessionDataDelegate /* Overrides default behavior for NSURLSessionDataDelegate method URLSession:dataTask:didReceiveData:.*/ public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? /** Tells the delegate that the data task has received some of the expected data. - parameter session: The session containing the data task that provided data. - parameter dataTask: The data task that provided data. - parameter data: A data object containing the transferred data. */ public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { print(#function) if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else if let delegate = self[dataTask] as? CopyleaksRequest.DataTaskDelegate { delegate.URLSession(session, dataTask: dataTask, didReceiveData: data) } } // MARK: - NSObject public override func respondsToSelector(selector: Selector) -> Bool { switch selector { case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)): return sessionDidBecomeInvalidWithError != nil case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)): return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) case #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)): return sessionDidFinishEventsForBackgroundURLSession != nil default: return self.dynamicType.instancesRespondToSelector(selector) } } }
mit
ecb756c12595c45f460002c385e7eb41
46.859259
178
0.72543
5.960332
false
false
false
false
czechboy0/BuildaUtils
Source/TimeUtils.swift
2
1928
// // TimeUtils.swift // Buildasaur // // Created by Honza Dvorsky on 15/05/15. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation public extension Date { public func nicelyFormattedRelativeTimeToNow() -> String { let relative = -1 * self.timeIntervalSinceNow let seconds = Int(relative) let formatted = TimeUtils.secondsToNaturalTime(seconds) return "\(formatted) ago" } static public func dateFromXCSString(_ date: String) -> Date? { // XCS date formatter let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ" return formatter.date(from: date) } static public func XCSStringFromDate(_ date: Date) -> String? { // XCS date formatter let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ" return formatter.string(from: date) } } open class TimeUtils { //formats up to hours open class func secondsToNaturalTime(_ seconds: Int) -> String { let intSeconds = Int(seconds) let minutes = intSeconds / 60 let remainderSeconds = intSeconds % 60 let hours = minutes / 60 let remainderMinutes = minutes % 60 let formattedSeconds = "second".pluralizeStringIfNecessary(remainderSeconds) var result = "\(remainderSeconds) \(formattedSeconds)" if remainderMinutes > 0 { let formattedMinutes = "minute".pluralizeStringIfNecessary(remainderMinutes) result = "\(remainderMinutes) \(formattedMinutes) and " + result } if hours > 0 { let formattedHours = "hour".pluralizeStringIfNecessary(hours) result = "\(hours) \(formattedHours), " + result } return result } }
mit
aca5f34b42f17372c3a397af48b59267
28.661538
88
0.603734
4.784119
false
false
false
false
joalbright/Relax
Example/Relax/LoginViewController.swift
1
2480
// // WebViewController.swift // InPassing // // Created by Jo Albright on 7/21/15. // Copyright (c) 2015 Jo Albright. All rights reserved. // import UIKit extension UIViewController { } class LoginViewController: UIViewController, UIWebViewDelegate, Loginable { var loginWebView = UIWebView() var session: API! convenience init(session: API) { self.init(); self.session = session } override func viewWillAppear(_ animated: Bool) { guard let urlString = try? session.url(loginDetails.auth) else { return } guard let url = URL(string: urlString) else { return } view.addSubview(loginWebView) loginWebView.delegate = self loginWebView.frame = view.frame loginWebView.loadRequest(URLRequest(url: url)) } var loaded = false func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { guard let loadedURL = request.url?.absoluteString else { return true } if loadedURL.contains("client_id") { return true } requestToken(loadedURL, endpoint: loginDetails.authCode, api: session) { [weak self] (success) -> Void in self?.dismiss(animated: true, completion: nil) } return true } } class ViewController: UIViewController { override func viewWillAppear(_ animated: Bool) { UIView.animate(withDuration: 0.4, animations: { self.navigationController?.navigationBar.barTintColor = UIColor(hue: 0, saturation: 0, brightness: 0.5, alpha: 1.0) }) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let button = sender as? UIButton else { return } navigationItem.backBarButtonItem?.tintColor = UIColor.white UIView.animate(withDuration: 0.4, animations: { self.navigationController?.navigationBar.barTintColor = button.backgroundColor }) } } @IBDesignable class RoundButton: UIButton { @IBInspectable var cornerRadius: CGFloat = 0 override func draw(_ rect: CGRect) { layer.cornerRadius = cornerRadius layer.masksToBounds = true } }
mit
f0bdedcf6682c55ae7d0d38e632a0453
25.105263
130
0.593952
5.210084
false
false
false
false
tiagobsbraga/TBPagarME
Pod/Classes/TBPagarME.swift
1
10131
// // TBPagarME.swift // // Created by Tiago Braga on 4/14/16. // Copyright © 2016 Tiago Braga. All rights reserved. // import Foundation import SwiftyRSA public typealias SuccessCardHash = (_ card_hash: String) -> Void public typealias FailureCardHash = (_ message: String) -> Void public typealias SuccessTransaction = (_ data: [String: Any]) -> Void public typealias FailureTransaction = (_ message: String) -> Void public struct Card { public var cardNumber: String? public var cardHolderName: String? public var cardExpirationMonth: String? public var cardExpirationYear: String? public var cardCVV: String? internal func cardHash() -> String { return String(format: "card_number=%@&card_holder_name=%@&card_expiration_date=%@%@&card_cvv=%@", cardNumber!, cardHolderName!, cardExpirationMonth!, cardExpirationYear!, cardCVV!) } internal func check() -> String? { if let cn = self.cardNumber { if cn.isValidCardNumber() == false { return "invalid cardNumber" } } else { return "check the card number" } if self.cardHolderName == nil || self.cardHolderName?.characters.count <= 0 { return "check the card holder name" } if self.cardExpirationMonth == nil || self.cardExpirationMonth?.characters.count < 2 || (Int(self.cardExpirationMonth!)! <= 0 || Int(self.cardExpirationMonth!)! > 12) { return "check the card expiration month" } if self.cardExpirationYear == nil || self.cardExpirationYear?.characters.count < 2 || (Int(self.cardExpirationYear!)! <= 0 || Int(self.cardExpirationYear!)! > 99) { return "check the card expiration year" } if self.cardCVV == nil || self.cardCVV?.characters.count != 3 { return "check the card security code (CVV)" } return nil } func luhnAlgorithm(cardNumber: String) -> Bool{ var luhn_sum = 0 var digit_count = 0 //reverse the card for c in cardNumber.characters.reversed() { //count digits //print(c.self) let this_digit = Int(String(c as Character))! //print(this_digit) digit_count += 1 //double every even digit if digit_count % 2 == 0{ if this_digit * 2 > 9 { luhn_sum = luhn_sum + this_digit * 2 - 9 }else{ luhn_sum = luhn_sum + this_digit * 2 } }else{ luhn_sum = luhn_sum + this_digit } } if luhn_sum % 10 == 0{ return true } return false } } public struct Customer { public var name: String? = nil public var document_number: String? = nil public var email: String? = nil public var street: String? = nil public var neighborhood: String? = nil public var zipcode: String? = nil public var street_number: String? = nil public var complementary: String? = nil public var ddd: String? = nil public var number: String? = nil public init () { } public func data() -> [String: Any] { var customer = [String: Any]() customer["name"] = name customer["document_number"] = document_number customer["email"] = email var address = [String: Any]() address["street"] = street address["neighborhood"] = neighborhood address["zipcode"] = zipcode address["street_number"] = street_number address["complementary"] = complementary customer["address"] = address var phone = [String: Any]() phone["ddd"] = ddd phone["number"] = number customer["phone"] = phone return customer } } public class TBPagarME: NSObject { // API pagar.me static private let baseURL: String = "https://api.pagar.me/1" static private let transactions = "/transactions" // endPoint transaction static private let card_hash = transactions + "/card_hash_key?encryption_key=%@" // generate card_hash static private let API_KEY: String = "apiKey" static private let ENCRYPTION_KEY: String = "encryptionKey" public var card = Card() public var customer = Customer() // MARK: Singleton public class var sharedInstance: TBPagarME { struct Static { static let instance: TBPagarME = TBPagarME() } return Static.instance } // MARK: Public static public func storeKeys(apiKey: String, encryptionKey key: String) { let userDefaults = UserDefaults.standard userDefaults.setValue(apiKey, forKeyPath: API_KEY) userDefaults.setValue(key, forKeyPath: ENCRYPTION_KEY) } public func generateCardHash(success: @escaping SuccessCardHash, failure: @escaping FailureCardHash) { if let message = self.card.check() { failure(message) return } self.generateNewPublicKey(success: { (card_hash) in success(card_hash) }) { (message) in failure(message) } return } public func transaction(amount: String, success: @escaping SuccessTransaction, failure: @escaping FailureTransaction) { if let message = self.card.check() { failure(message) return } self.generateNewPublicKey(success: { (card_hash) in var params: [String: Any] = [String: Any]() params["api_key"] = self.apiKey() params["amount"] = amount params["card_hash"] = card_hash params["customer"] = self.customer.data() do { let url = NSURL(string: String(format: "%@%@", TBPagarME.baseURL, TBPagarME.transactions)) let request = NSMutableURLRequest(url: url! as URL, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 20.0) request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions()) let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) in do { let json = try JSONSerialization.jsonObject(with: data!, options: []) if let jsonDict = json as? [String : Any] { ////print("json: \(jsonDict)") ////print("err \(jsonDict["error"])") let _id = jsonDict["id"] as! Int let publicKeyPEM = jsonDict["public_key"] as! String let swiftRSA = try SwiftyRSA.encryptString(self.card.cardHash(), publicKeyPEM: publicKeyPEM) ////print(String(format: "Sucess: %@_%@", String(_id), swiftRSA)) success(["transition": String(format: "%@_%@", String(_id), swiftRSA)]) } } catch let err as NSError { print(err.localizedDescription) } } dataTask.resume() } catch let err as NSError { print(err.localizedDescription) } }) { (message) in failure(message) } } // MARK: Private private func generateNewPublicKey(success: @escaping SuccessCardHash, failure: @escaping FailureCardHash) { let url = NSURL(string: String(format: "%@%@", TBPagarME.baseURL, String(format: TBPagarME.card_hash, self.encryptionKey()))) let request = NSMutableURLRequest(url: url! as URL, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 10.0) request.httpMethod = "GET" let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) in if let _ = error { //print("error \(error)") return; } do { let json = try JSONSerialization.jsonObject(with: data!, options: []) if let jsonDict = json as? [String : Any] { //print("json: \(jsonDict)") //print("err: \(jsonDict["error"])") let _id = jsonDict["id"] as! Int let publicKeyPEM = jsonDict["public_key"] as! String let swiftRSA = try SwiftyRSA.encryptString(self.card.cardHash(), publicKeyPEM: publicKeyPEM) success(String(format: "%@_%@", String(_id), swiftRSA)) } if let jsonErr = json as? [String : Any] { let err = jsonErr["error"] if let _ = err { print("err \(err)") } } } catch let err as NSError { print("Error: \(err.localizedDescription)") } } dataTask.resume() } // MARK: Helper private func apiKey() -> String { let userDefaults = UserDefaults.standard return userDefaults.value(forKey: TBPagarME.API_KEY) as! String } private func encryptionKey() -> String { let userDefaults = UserDefaults.standard return userDefaults.value(forKey: TBPagarME.ENCRYPTION_KEY) as! String } }
mit
59dea370e53b7774872de8c9c4f16950
36.106227
176
0.539684
4.917476
false
false
false
false
SwiftStudies/OysterKit
Sources/OysterKit/Parser/Intermediate Representations/NodeStack.swift
1
4429
// Copyright (c) 2016, RED When Excited // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation /// An extension to arrays of `Equatable` `Element`s that adds a set like append behaviour extension Array where Element : Equatable{ /** Adds an element to the `Array` if and only if the new `element` is not already in the array - Parameter unique: A candidate element to add to the array */ mutating func append(unique element:Element){ for existingError in self{ if existingError == element { return } } append(element) } } /** `NodeStackEntry`'s are used to capture parsing context (for example child-nodes and errors) ASTs are constructed. */ public final class NodeStackEntry<NodeType:Node> : CustomStringConvertible{ /// The child nodes of this node public var nodes = [NodeType]() /** Should be called when a child node is created - Parameter node: The new child node */ public func append(_ node: NodeType){ nodes.append(node) } /** Adds all of the supplied nodes as this nodes children - Parameter nodes: The new child nodes */ public func adopt(_ nodes: [NodeType]){ self.nodes.append(contentsOf: nodes) } /// A human readable description of the context public var description: String{ return "\(nodes.count) nodes" } } /** A `NodeStack` can be used to manage AST construction state, as new rule evaluations begin new contexts can be pushed onto the node stack and then popped and discarded on failure, or popped and acted on for success. */ public final class NodeStack<NodeType:Node> : CustomStringConvertible{ /// The stack itself private var stack = [NodeStackEntry<NodeType>]() /// Creates a new instance of the stack with an active context public init() { reset() } /// Removes all current stack entries and adds a new initial context public func reset(){ stack.removeAll() push() } /// Adds a new context to the top of the stack public func push(){ stack.append(NodeStackEntry()) } /// Removes the stack entry from the top of the stack /// - Returns: The popped entry public func pop()->NodeStackEntry<NodeType>{ return stack.removeLast() } /// The entry currently on the top of the stack, if any public var top : NodeStackEntry<NodeType>?{ return stack.last } /// The depth of the stack public var depth : Int { return stack.count } /// An inverted (from deepest to shallowest) representation of the stack public var all : [NodeStackEntry<NodeType>] { return stack.reversed() } /// A human readable description of the stack public var description: String{ var result = "NodeStack: \n" for node in stack.reversed(){ result += "\(node)\n" } return result } }
bsd-2-clause
0e04885b0565bf9a4218c7903d8f3b8e
32.80916
215
0.658162
4.731838
false
false
false
false
SomeSimpleSolutions/MemorizeItForever
MemorizeItForever/MemorizeItForever/AppDelegate.swift
1
9488
// // AppDelegate.swift // MemorizeItForever // // Created by Hadi Zamani on 10/16/16. // Copyright © 2016 SomeSimpleSolutions. All rights reserved. // import UIKit import CoreData import MemorizeItForeverCore import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. setContext() setUserDefaults() FirebaseApp.configure() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } private func setUserDefaults(){ let defaults = UserDefaults.standard if defaults.object(forKey: Settings.wordSwitching.rawValue) == nil{ defaults.setValue(true, forKey: Settings.wordSwitching.rawValue) } if defaults.object(forKey: Settings.newWordsCount.rawValue) == nil{ defaults.setValue(10, forKey: Settings.newWordsCount.rawValue) } if defaults.object(forKey: Settings.judgeMyself.rawValue) == nil{ defaults.setValue(true, forKey: Settings.judgeMyself.rawValue) } if defaults.colorForKey(Settings.phraseColor.rawValue) == nil { defaults.setColor(UIColor.black, forKey: Settings.phraseColor.rawValue) } if defaults.colorForKey(Settings.meaningColor.rawValue) == nil { defaults.setColor(UIColor.red, forKey: Settings.meaningColor.rawValue) } if defaults.object(forKey: Settings.capitalization.rawValue) == nil{ defaults.setValue(true, forKey: Settings.capitalization.rawValue) } } // MARK: - Core Data stack @available(iOS 10.0, *) lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "MemorizeItForever", managedObjectModel: self.managedObjectModel) container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "org.somesimplesolution.MemorizeItForever" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let memorizeItForeverCoreBundle = Bundle(identifier: "org.somesimplesolutions.MemorizeItForeverCore") let modelURL = memorizeItForeverCoreBundle!.url(forResource: "MemorizeItForever", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { var context: NSManagedObjectContext context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } private func setContext(){ var context: NSManagedObjectContext context = self.persistentContainer.viewContext ContextHelper.shared.setContext(context: context) } }
mit
2773913103f68d41a768e20abbcb0be9
52.903409
291
0.692843
5.767173
false
false
false
false
eeschimosu/Swift-Prompts
Swift-Prompts/UIImageEffects.swift
3
13724
/* File: UIImage+ImageEffects.m Abstract: This is a category of UIImage that adds methods to apply blur and tint effects to an image. This is the code you’ll want to look out to find out how to use vImage to efficiently calculate a blur. Version: 1.0 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2013 Apple Inc. All Rights Reserved. Copyright © 2013 Apple Inc. All rights reserved. WWDC 2013 License NOTE: This Apple Software was supplied by Apple as part of a WWDC 2013 Session. Please refer to the applicable WWDC 2013 Session for further information. IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. EA1002 5/3/2013 */ // // UIImage.swift // Today // // Created by Alexey Globchastyy on 15/09/14. // Copyright (c) 2014 Alexey Globchastyy. All rights reserved. // import UIKit import Accelerate public extension UIImage { public func applyLightEffect() -> UIImage? { return applyBlurWithRadius(30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.8) } public func applyExtraLightEffect() -> UIImage? { return applyBlurWithRadius(20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8) } public func applyDarkEffect() -> UIImage? { return applyBlurWithRadius(20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8) } public func applyTintEffectWithColor(tintColor: UIColor) -> UIImage? { let effectColorAlpha: CGFloat = 0.6 var effectColor = tintColor let componentCount = CGColorGetNumberOfComponents(tintColor.CGColor) if componentCount == 2 { var b: CGFloat = 0 if tintColor.getWhite(&b, alpha: nil) { effectColor = UIColor(white: b, alpha: effectColorAlpha) } } else { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) { effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha) } } return applyBlurWithRadius(10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil) } public func applyBlurWithRadius(blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? { // Check pre-conditions. if (size.width < 1 || size.height < 1) { println("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)") return nil } if self.CGImage == nil { println("*** error: image must be backed by a CGImage: \(self)") return nil } if maskImage != nil && maskImage!.CGImage == nil { println("*** error: maskImage must be backed by a CGImage: \(maskImage)") return nil } let __FLT_EPSILON__ = CGFloat(FLT_EPSILON) let screenScale = UIScreen.mainScreen().scale let imageRect = CGRect(origin: CGPointZero, size: size) var effectImage = self let hasBlur = blurRadius > __FLT_EPSILON__ let hasSaturationChange = fabs(saturationDeltaFactor - 1.0) > __FLT_EPSILON__ if hasBlur || hasSaturationChange { func createEffectBuffer(context: CGContext) -> vImage_Buffer { let data = CGBitmapContextGetData(context) let width = UInt(CGBitmapContextGetWidth(context)) let height = UInt(CGBitmapContextGetHeight(context)) let rowBytes = CGBitmapContextGetBytesPerRow(context) return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes) } UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let effectInContext = UIGraphicsGetCurrentContext() CGContextScaleCTM(effectInContext, 1.0, -1.0) CGContextTranslateCTM(effectInContext, 0, -size.height) CGContextDrawImage(effectInContext, imageRect, self.CGImage) var effectInBuffer = createEffectBuffer(effectInContext) UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let effectOutContext = UIGraphicsGetCurrentContext() var effectOutBuffer = createEffectBuffer(effectOutContext) if hasBlur { // A description of how to compute the box kernel width from the Gaussian // radius (aka standard deviation) appears in the SVG spec: // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // // For larger values of 's' (s >= 2.0), an approximation can be used: Three // successive box-blurs build a piece-wise quadratic convolution kernel, which // approximates the Gaussian kernel to within roughly 3%. // // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. // let inputRadius = blurRadius * screenScale var radius = UInt32(floor(inputRadius * 3.0 * CGFloat(sqrt(2 * M_PI)) / 4 + 0.5)) if radius % 2 != 1 { radius += 1 // force radius to be odd so that the three box-blur methodology works. } let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) } var effectImageBuffersAreSwapped = false if hasSaturationChange { let s: CGFloat = saturationDeltaFactor let floatingPointSaturationMatrix: [CGFloat] = [ 0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0, 0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0, 0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0, 0, 0, 0, 1 ] let divisor: CGFloat = 256 let matrixSize = floatingPointSaturationMatrix.count var saturationMatrix = [Int16](count: matrixSize, repeatedValue: 0) for var i: Int = 0; i < matrixSize; ++i { saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor)) } if hasBlur { vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) effectImageBuffersAreSwapped = true } else { vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) } } if !effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() if effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() } // Set up output context. UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let outputContext = UIGraphicsGetCurrentContext() CGContextScaleCTM(outputContext, 1.0, -1.0) CGContextTranslateCTM(outputContext, 0, -size.height) // Draw base image. CGContextDrawImage(outputContext, imageRect, self.CGImage) // Draw effect image. if hasBlur { CGContextSaveGState(outputContext) if let image = maskImage { CGContextClipToMask(outputContext, imageRect, image.CGImage); } CGContextDrawImage(outputContext, imageRect, effectImage.CGImage) CGContextRestoreGState(outputContext) } // Add in color tint. if let color = tintColor { CGContextSaveGState(outputContext) CGContextSetFillColorWithColor(outputContext, color.CGColor) CGContextFillRect(outputContext, imageRect) CGContextRestoreGState(outputContext) } // Output image is ready. let outputImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return outputImage } }
mit
45ae5e9c48904440f073ce043a761ce0
45.832765
205
0.662488
5.106438
false
false
false
false
nagyistoce/xrecord
xrecord/main.swift
2
4169
// // main.swift // xrecord // // Created by Patrick Meenan on 12/10/15. // Copyright (c) 2015 WPO Foundation. All rights reserved. // import Foundation import AVFoundation let cli = CommandLine() let list = BoolOption(shortFlag: "l", longFlag: "list", helpMessage: "List available capture devices.") let name = StringOption(shortFlag: "n", longFlag: "name", required: false, helpMessage: "Device Name.") let id = StringOption(shortFlag: "i", longFlag: "id", required: false, helpMessage: "Device ID.") let outFile = StringOption(shortFlag: "o", longFlag: "out", required: false, helpMessage: "Output File.") let force = BoolOption(shortFlag: "f", longFlag: "force", helpMessage: "Overwrite existing files.") let qt = BoolOption(shortFlag: "q", longFlag: "quicktime", helpMessage: "Start QuickTime in the background (necessary for iOS recording).") let time = IntOption(shortFlag: "t", longFlag: "time", required: false, helpMessage: "Recording time in seconds (records until stopped if not specified).") let debug = BoolOption(shortFlag: "d", longFlag: "debug", helpMessage: "Display debugging info to stderr.") let help = BoolOption(shortFlag: "h", longFlag: "help", helpMessage: "Prints a help message.") cli.addOptions(list, name, id, outFile, force, qt, time, debug, help) let (success, error) = cli.parse() if !success { println(error!) cli.printUsage() exit(EX_USAGE) } // Check to make sure a sane combination of options were specified var ok = true if !list.value { if name.value == nil && id.value == nil { ok = false } if outFile.value == nil { ok = false } } if !ok { cli.printUsage() exit(EX_USAGE) } // See if we need to launch quicktime in the background if qt.value { XRecord_Bridge.startQuickTime() } let capture = Capture() if list.value { println("Available capture devices:") capture.listDevices() exit(0) } // Set up the input device if id.value != nil { if !capture.setDeviceById(id.value) { println("Device not found") exit(1) } } if name.value != nil { if !capture.setDeviceByName(name.value) { println("Device not found") exit(1) } } // See if a video file already exists in the given location if outFile.value != nil && NSFileManager.defaultManager().fileExistsAtPath(outFile.value!) { if force.value { var error:NSError? NSFileManager.defaultManager().removeItemAtPath(outFile.value!, error: &error) if (error != nil) { println("Error overwriting existing file (\(error)).") exit(2) } } else { println("The output file already exists, please use a different file: \(outFile.value!)") exit(2) } } // If we were not launched with the debug flag, re-spawn and suppress stderr if !debug.value { let proc = NSTask() var args = Process.arguments proc.launchPath = args[0] args.append("--debug") proc.arguments = args proc.standardError = NSPipe() proc.launch() XRecord_Bridge.installSignalHandler(proc.processIdentifier) proc.waitUntilExit() exit(proc.terminationStatus) } // Start a real capture XRecord_Bridge.installSignalHandler(0) NSLog("Starting capture....") capture.start(outFile.value) let start = NSDate() if time.value != nil && time.value > 0 { println("Recording for \(time.value!) seconds. Hit ctrl-C to stop.") NSLog("Recording for \(time.value!) seconds. Hit ctrl-C to stop.") sleep(UInt32(time.value!)) } else { println("Recording started. Hit ctrl-C to stop.") NSLog("Recording started. Hit ctrl-C to stop.") } // Loop until we get a ctrl-C or the time limit expires var done = false do { usleep(100) if XRecord_Bridge.didSignal() { done = true } else if time.value != nil && time.value > 0 { let now = NSDate() let elapsed: Double = now.timeIntervalSinceDate(start) if elapsed >= Double(time.value!) { done = true } } } while !done println("Stopping recording...") NSLog("Stopping recording...") capture.stop() println("Done") NSLog("Done")
bsd-3-clause
f57e9be0fa30194400a34c71d2774936
27.360544
97
0.654833
3.755856
false
false
false
false
crazypoo/PTools
PooToolsSource/Attributed/YBAttributedStringTools.swift
1
8284
// // YBAttributedStringTools.swift // MinaTicket // // Created by 林勇彬 on 2022/6/8. // Copyright © 2022 Hola. All rights reserved. // import Foundation import UIKit fileprivate var ChangeStrKey = "getChangeStr" public extension NSMutableAttributedString { private func changeStr() -> String { return (objc_getAssociatedObject(self, &ChangeStrKey) as? String) ?? "" } private func changeStr(changeStr:String) { objc_setAssociatedObject(self, &ChangeStrKey, changeStr, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } /// 设置段落属性 /// - Parameters: /// - lineSpacing: 行距 /// - paragraphSpacing: 段落距 /// - alignment: 对其方式 /// - lineBreakMode: 内容显示不完全时的省略方式 /// - Returns: 本身 @discardableResult func yb_paragraphStyle(lineSpacing: CGFloat = 0,paragraphSpacing:CGFloat = 0,alignment:NSTextAlignment = .left,lineBreakMode: NSLineBreakMode = .byTruncatingTail) -> Self { self.getParagraphStyle(range: NSMakeRange(0, self.string.count)) { paragraphStyle,range in paragraphStyle.lineSpacing = lineSpacing paragraphStyle.paragraphSpacing = paragraphSpacing paragraphStyle.alignment = alignment paragraphStyle.lineBreakMode = lineBreakMode self.addAttributes([NSAttributedString.Key.paragraphStyle:paragraphStyle], range: range) } return self } @discardableResult func yb_lineSpacing(spacing: CGFloat) -> Self { self.getParagraphStyle(range: NSMakeRange(0, self.string.count)) { paragraphStyle,range in paragraphStyle.lineSpacing = spacing self.addAttributes([NSAttributedString.Key.paragraphStyle:paragraphStyle], range: range) } return self } /// 设置对齐方式 /// - Parameter alignment: 对齐方式 /// - Returns: 本身 @discardableResult func yb_alignment(alignment:NSTextAlignment) -> Self { self.getParagraphStyle(range: NSMakeRange(0, self.string.count)) { paragraphStyle,range in paragraphStyle.alignment = alignment self.addAttributes([NSAttributedString.Key.paragraphStyle:paragraphStyle], range: range) } return self } /// 设置字符间距 /// - Parameter spacing: 间距 /// - Returns: 本身 @discardableResult func yb_kern(spacing: CGFloat) -> Self { self.addAttributes([NSAttributedString.Key.kern:spacing], range: NSMakeRange(0, self.string.count)) return self } /// 设置删除线 /// - Parameters: /// - changeStr: 需要修改的文字 /// - style: 删除线的样式 /// - Returns: 本身 @discardableResult func yb_strikethrough(changeStr: String? = nil,style: NSUnderlineStyle = .single) -> Self { let changeString = changeStr ?? self.changeStr() self.changeStr(changeStr: changeString) self.addAttribute(NSAttributedString.Key.strikethroughStyle, value: style.rawValue, range: (self.string as NSString).range(of: changeString)) return self } /// 设置下划线 /// - Parameters: /// - changeStr: 需要修改的文字 /// - style: 删除线的样式 /// - Returns: 本身 @discardableResult func yb_underline(changeStr: String? = nil,style: NSUnderlineStyle = .single) -> Self { let changeString = changeStr ?? self.changeStr() self.changeStr(changeStr: changeString) self.addAttribute(NSAttributedString.Key.underlineStyle, value: style.rawValue, range: (self.string as NSString).range(of: changeString)) return self } /// 设置字体描边 /// - Parameters: /// - changeStr: 需要修改的文字 /// - color: 描边颜色 /// - value: 描边大小 /// - Returns: 本身 @discardableResult func yb_stroke(changeStr: String? = nil,color: UIColor, value: CGFloat = 0) -> Self { let changeString = changeStr ?? self.changeStr() self.changeStr(changeStr: changeString) self.addAttributes([NSAttributedString.Key.strokeColor: color, NSAttributedString.Key.strokeWidth: value], range: (self.string as NSString).range(of: changeString)) return self } @discardableResult func yb_font(font:UIFont,changeStr:String? = nil) -> Self { let changeString = changeStr ?? self.changeStr() self.changeStr(changeStr: changeString) self.addAttribute(NSAttributedString.Key.font, value: font, range: (self.string as NSString).range(of: changeString)) return self } @discardableResult func yb_color(color:UIColor,changeStr:String? = nil) -> Self { let changeString = changeStr ?? self.changeStr() self.changeStr(changeStr: changeString) self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: (self.string as NSString).range(of: changeString)) return self } @discardableResult func yb_mutableColor(color:UIColor,changeStr:String? = nil) -> Self { let changeString = changeStr ?? self.changeStr() self.changeStr(changeStr: changeString) var replaceString = "" for _ in changeString { replaceString.append(" ") } var copyTotalString = self.string while copyTotalString.contains(changeString) { guard let range = copyTotalString.range(of: changeString, options: .caseInsensitive) else { return self} self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSRange(range,in:changeString)) copyTotalString = copyTotalString.replacingCharacters(in: range, with: replaceString) } return self } @discardableResult func yb_mutableFont(font:UIFont,changeStr:String? = nil) -> Self { let changeString = changeStr ?? self.changeStr() self.changeStr(changeStr: changeString) var replaceString = "" for _ in changeString { replaceString.append(" ") } var copyTotalString = self.string while copyTotalString.contains(changeString) { guard let range = copyTotalString.range(of: changeString, options: .caseInsensitive) else { return self} self.addAttribute(NSAttributedString.Key.font, value: font, range: NSRange(range,in:changeString)) copyTotalString = copyTotalString.replacingCharacters(in: range, with: replaceString) } return self } func getParagraphStyle(range:NSRange, reslut:((NSMutableParagraphStyle,NSRange)->())) { self.enumerateAttribute(NSAttributedString.Key.paragraphStyle, in: range, options: NSAttributedString.EnumerationOptions.init(rawValue: 0)) { value, subRange, stop in var style:NSMutableParagraphStyle? if (value != nil) { if value is NSMutableParagraphStyle { style = value as? NSMutableParagraphStyle }else { style = NSMutableParagraphStyle() } }else { style = NSMutableParagraphStyle() } reslut(style ?? NSMutableParagraphStyle(),range) } } } public extension UILabel { @discardableResult func yb_text(text:String?) -> Self { self.text = text return self } @discardableResult func yb_color(color:UIColor) -> Self { self.textColor = color return self } @discardableResult func yb_font(font:CGFloat) -> Self { self.font = UIFont.systemFont(ofSize: font) return self } @discardableResult func yb_blodFont(blodFont:CGFloat) -> Self { self.font = UIFont.boldSystemFont(ofSize: blodFont) return self } @discardableResult func yb_alignment(alignment:NSTextAlignment) -> Self { self.textAlignment = alignment return self } @discardableResult func yb_attribute(text:String? = nil) -> NSMutableAttributedString { let subText = text ?? (self.text ?? "") let attriString = NSMutableAttributedString(string: subText) return attriString } }
mit
6a3240c92d477aeed0783417df2df1ca
38.446078
195
0.645582
4.528419
false
false
false
false
crazypoo/PTools
Pods/InAppViewDebugger/InAppViewDebugger/TreeTableViewDataSource.swift
1
2566
// // TreeTableViewDataSource.swift // InAppViewDebugger // // Created by Indragie Karunaratne on 4/6/19. // Copyright © 2019 Indragie Karunaratne. All rights reserved. // import UIKit protocol Tree { var children: [Self] { get } } final class TreeTableViewDataSource<TreeType: Tree>: NSObject, UITableViewDataSource { typealias CellFactory = (UITableView /* tableView */, TreeType /* value */, Int /* depth */, IndexPath /* indexPath */, Bool /* isCollapsed */) -> UITableViewCell private let tree: TreeType private let cellFactory: CellFactory private let flattenedTree: [FlattenedTree<TreeType>] init(tree: TreeType, maxDepth: Int?, cellFactory: @escaping CellFactory) { self.tree = tree self.cellFactory = cellFactory self.flattenedTree = flatten(tree: tree, depth: 0, maxDepth: maxDepth) } public func value(atIndexPath indexPath: IndexPath) -> TreeType { return flattenedTree[indexPath.row].value } // MARK: UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return flattenedTree.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let tree = flattenedTree[indexPath.row] return cellFactory(tableView, tree.value, tree.depth, indexPath, tree.isCollapsed) } } extension TreeTableViewDataSource where TreeType: AnyObject { func indexPath(forValue value: TreeType) -> IndexPath? { return flattenedTree .firstIndex { $0.value === value } .flatMap { IndexPath(row: $0, section: 0) } } } private struct FlattenedTree<TreeType: Tree> { let value: TreeType let depth: Int var isCollapsed = false init(value: TreeType, depth: Int) { self.value = value self.depth = depth } } private func flatten<TreeType: Tree>(tree: TreeType, depth: Int = 0, maxDepth: Int?) -> [FlattenedTree<TreeType>] { let initial = [FlattenedTree<TreeType>(value: tree, depth: depth)] let childDepth = depth + 1 if let maxDepth = maxDepth, childDepth > maxDepth { return initial } else { return tree.children.reduce(initial) { (result, child) in var newResult = result newResult.append(contentsOf: flatten(tree: child, depth: childDepth, maxDepth: maxDepth)) return newResult } } }
mit
11d8331d22319bf51dfb99c380b0ec30
31.468354
166
0.659649
4.492119
false
false
false
false
crazypoo/PTools
PooToolsSource/NetWork/Network.swift
1
16473
// // Network.swift // MiniChatSwift // // Created by 林勇彬 on 2022/5/21. // Copyright © 2022 九州所想. All rights reserved. // import UIKit import Alamofire import MBProgressHUD import KakaJSON import SwiftyJSON public enum NetWorkStatus: String { case unknown = "未知网络" case notReachable = "网络无连接" case wwan = "2,3,4G网络" case wifi = "wifi网络" } public enum NetWorkEnvironment: String { case Development = "开发环境" case Test = "测试环境" case Distribution = "生产环境" } public typealias ReslutClosure = (_ result: ResponseModel?,_ error: AFError?) -> Void public typealias NetWorkStatusBlock = (_ NetWorkStatus: String, _ NetWorkEnvironment: String,_ NetworkStatusType:NetworkReachabilityManager.NetworkReachabilityStatus) -> Void public typealias NetWorkErrorBlock = () -> Void public typealias NetWorkServerStatusBlock = (_ result: ResponseModel) -> Void public typealias UploadProgress = (_ progress: Progress) -> Void public var PTBaseURLMode:NetWorkEnvironment { guard let sliderValue = UserDefaults.standard.value(forKey: "AppServiceIdentifier") as? String else { return .Distribution } if sliderValue == "1" { return .Distribution }else if sliderValue == "2" { return .Test }else if sliderValue == "3" { return .Development } return .Distribution } // MARK: - 网络运行状态监听 public class XMNetWorkStatus { static let shared = XMNetWorkStatus() /// 当前网络环境状态 private var currentNetWorkStatus: NetWorkStatus = .wifi /// 当前运行环境状态 private var currentEnvironment: NetWorkEnvironment = .Test let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.baidu.com") private func detectNetWork(netWork: @escaping NetWorkStatusBlock) { reachabilityManager?.startListening(onUpdatePerforming: { [weak self] (status) in guard let weakSelf = self else { return } if self?.reachabilityManager?.isReachable ?? false { switch status { case .notReachable: weakSelf.currentNetWorkStatus = .notReachable case .unknown: weakSelf.currentNetWorkStatus = .unknown case .reachable(.cellular): weakSelf.currentNetWorkStatus = .wwan case .reachable(.ethernetOrWiFi): weakSelf.currentNetWorkStatus = .wifi } } else { weakSelf.currentNetWorkStatus = .notReachable } netWork(weakSelf.currentNetWorkStatus.rawValue, weakSelf.currentEnvironment.rawValue,status) }) } ///监听网络运行状态 public func obtainDataFromLocalWhenNetworkUnconnected(handle:((NetworkReachabilityManager.NetworkReachabilityStatus)->Void)?) { detectNetWork { (status, environment,statusType) in PTNSLog("当前网络环境为-> \(status) 当前运行环境为-> \(environment)") if handle != nil { handle!(statusType) } } } } @objcMembers public class Network: NSObject { static public let share = Network() static var header:HTTPHeaders? public var netRequsetTime:TimeInterval = 20 public var serverAddress:String = "" public var serverAddress_dev:String = "" public var userToken:String = "" /// manager private static var manager: Session = { let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = Network.share.netRequsetTime return Session(configuration: configuration) }() /// manager public static var hud: MBProgressHUD = { let hud = MBProgressHUD.init(view: AppWindows!) AppWindows!.addSubview(hud) hud.show(animated: true) return hud }() //MARK: 服务器URL public class func gobalUrl() -> String { if UIApplication.applicationEnvironment() != .appStore { PTLocalConsoleFunction.share.pNSLog("PTBaseURLMode:\(PTBaseURLMode)") switch PTBaseURLMode { case .Development: let userDefaults_url = UserDefaults.standard.value(forKey: "UI_test_url") let url_debug:String = userDefaults_url == nil ? "" : (userDefaults_url as! String) if url_debug.isEmpty { return Network.share.serverAddress_dev } else { return url_debug } case .Test: return Network.share.serverAddress_dev case .Distribution: return Network.share.serverAddress } } else { return Network.share.serverAddress } } //JSONEncoding JSON参数 //URLEncoding URL参数 /// 项目总接口 /// - Parameters: /// - urlStr: url地址 /// - method: 方法类型,默认post /// - parameters: 请求参数,默认nil /// - modelType: 是否需要传入接口的数据模型,默认nil /// - encoder: 编码方式,默认url编码 /// - showHud: 是否需要loading,默认true /// - resultBlock: 方法回调 class public func requestApi(urlStr:String, method: HTTPMethod = .post, parameters: Parameters? = nil, modelType: Convertible.Type? = nil, encoder:ParameterEncoding = URLEncoding.default, showHud:Bool? = true, jsonRequest:Bool? = false, netWorkErrorBlock:NetWorkErrorBlock? = nil, netWorkServerStatusBlock:NetWorkServerStatusBlock? = nil, resultBlock: @escaping ReslutClosure){ let urlStr = Network.gobalUrl() + urlStr // 判断网络是否可用 if let reachabilityManager = XMNetWorkStatus.shared.reachabilityManager { if !reachabilityManager.isReachable { if netWorkErrorBlock != nil { netWorkErrorBlock!() } return } } let token = Network.share.userToken if !token.stringIsEmpty() { header = HTTPHeaders.init(["token":token,"device":"iOS"]) if jsonRequest! { header!["Content-Type"] = "application/json;charset=UTF-8" header!["Accept"] = "application/json" } } if showHud!{ Network.hud.show(animated: true) } PTLocalConsoleFunction.share.pNSLog("😂😂😂😂😂😂😂😂😂😂😂😂\n❤️1.请求地址 = \(urlStr)\n💛2.参数 = \(parameters?.jsonString() ?? "没有参数")\n💙3.请求头 = \(header?.dictionary.jsonString() ?? "没有请求头")\n😂😂😂😂😂😂😂😂😂😂😂😂") PTUtils.showNetworkActivityIndicator(true) Network.manager.request(urlStr, method: method, parameters: parameters, encoding: encoder, headers: header).responseData { data in if showHud! { Network.hud.hide(animated: true) } PTUtils.showNetworkActivityIndicator(false) switch data.result { case .success(_): let json = JSON(data.value ?? "") guard let jsonStr = json.rawString(String.Encoding.utf8, options: JSONSerialization.WritingOptions.prettyPrinted) else { return } PTLocalConsoleFunction.share.pNSLog("😂😂😂😂😂😂😂😂😂😂😂😂\n❤️1.请求地址 = \(urlStr)\n💛2.result:\(jsonStr)\n😂😂😂😂😂😂😂😂😂😂😂😂") guard let responseModel = jsonStr.kj.model(ResponseModel.self) else { return } responseModel.originalString = jsonStr if netWorkServerStatusBlock != nil { netWorkServerStatusBlock!(responseModel) } guard let modelType = modelType else { resultBlock(responseModel,nil); return } if responseModel.data is [String : Any] { guard let reslut = responseModel.data as? [String : Any] else {resultBlock(responseModel,nil); return } responseModel.data = reslut.kj.model(type: modelType) }else if responseModel.data is Array<Any> { responseModel.datas = (responseModel.data as! Array<Any>).kj.modelArray(type: modelType) } resultBlock(responseModel,nil) case .failure(let error): PTLocalConsoleFunction.share.pNSLog("------------------------------------>\n接口:\(urlStr)\n----------------------出现错误----------------------\n\(String(describing: error.errorDescription))",error: true) resultBlock(nil,error) } } } /// 图片上传接口 /// - Parameters: /// - images: 图片集合 /// - progressBlock: 进度回调 /// - success: 成功回调 /// - failure: 失败回调 class public func imageUpload(images:[UIImage]?, path:String? = "/api/project/ossImg", fileKey:String? = "images", parmas:[String:String]? = nil, netWorkErrorBlock:NetWorkErrorBlock? = nil, progressBlock:UploadProgress? = nil, resultBlock: @escaping ReslutClosure) { let pathUrl = Network.gobalUrl() + path! // 判断网络是否可用 if let reachabilityManager = XMNetWorkStatus.shared.reachabilityManager { if !reachabilityManager.isReachable { if netWorkErrorBlock != nil { netWorkErrorBlock!() } return } } let hud:MBProgressHUD = MBProgressHUD.showAdded(to: AppWindows!, animated: true) hud.show(animated: true) var headerDic = [String:String]() headerDic["device"] = "iOS" let token = Network.share.userToken if !token.stringIsEmpty() { headerDic["token"] = token } let requestHeaders = HTTPHeaders.init(headerDic) Network.manager.upload(multipartFormData: { (multipartFormData) in images?.enumerated().forEach { index,image in if let imgData = image.jpegData(compressionQuality: 0.2) { multipartFormData.append(imgData, withName: fileKey!,fileName: "image_\(index).png", mimeType: "image/png") } } if parmas != nil { parmas?.keys.enumerated().forEach({ index,value in multipartFormData.append(Data(parmas![value]!.utf8), withName: value) }) } }, to: pathUrl,method: .post, headers: requestHeaders) { (result) in } .uploadProgress(closure: { (progress) in if progressBlock != nil { progressBlock!(progress) } }) .response { response in hud.hide(animated: true) switch response.result { case .success(let result): guard let responseModel = result?.toDict()?.kj.model(ResponseModel.self) else { return } PTLocalConsoleFunction.share.pNSLog("😂😂😂😂😂😂😂😂😂😂😂😂\n❤️1.请求地址 = \(pathUrl)\n💛2.result:\(result!.toDict()!)\n😂😂😂😂😂😂😂😂😂😂😂😂") resultBlock(responseModel,nil) case .failure(let error): PTLocalConsoleFunction.share.pNSLog("😂😂😂😂😂😂😂😂😂😂😂😂\n❤️1.请求地址 =\(pathUrl)\n💛2.error:\(error)",error: true) resultBlock(nil,error) } } } } @objcMembers public class PTFileDownloadApi: NSObject { public typealias FileDownloadProgress = (_ bytesRead:Int64,_ totalBytesRead:Int64,_ progrss:Double)->() public typealias FileDownloadSuccess = (_ reponse:Any)->() public typealias FileDownloadFail = (_ error:Error?)->() @objc public var fileUrl:String = "" @objc public var saveFilePath:String = "" // 文件下载保存的路径 public var cancelledData : Data?//用于停止下载时,保存已下载的部分 public var downloadRequest:DownloadRequest? //下载请求对象 public var destination:DownloadRequest.Destination!//下载文件的保存路径 public var progress:FileDownloadProgress? public var success:FileDownloadSuccess? public var fail:FileDownloadFail? private var queue:DispatchQueue = DispatchQueue.main // 默认主线程 public convenience init(fileUrl:String,saveFilePath:String,queue:DispatchQueue? = DispatchQueue.main,progress:FileDownloadProgress?,success:FileDownloadSuccess?, fail:FileDownloadFail?) { self.init() self.fileUrl = fileUrl self.saveFilePath = saveFilePath self.success = success self.progress = progress self.fail = fail if queue != nil { self.queue = queue! } // 配置下载存储路径 self.destination = {_,response in let saveUrl = URL(fileURLWithPath: saveFilePath) return (saveUrl,[.removePreviousFile, .createIntermediateDirectories] ) } // 这里直接就开始下载了 self.startDownloadFile() } // 暂停下载 public func suspendDownload() { self.downloadRequest?.task?.suspend() } // 取消下载 public func cancelDownload() { self.downloadRequest?.cancel() self.downloadRequest = nil; self.progress = nil } // 开始下载 public func startDownloadFile() { if self.cancelledData != nil { self.downloadRequest = AF.download(resumingWith: self.cancelledData!, to: self.destination) self.downloadRequest?.downloadProgress { [weak self] (pro) in guard let `self` = self else {return} DispatchQueue.main.async { self.progress?(pro.completedUnitCount,pro.totalUnitCount,pro.fractionCompleted) } } self.downloadRequest?.responseData(queue: queue, completionHandler: downloadResponse) }else if self.downloadRequest != nil { self.downloadRequest?.task?.resume() }else { self.downloadRequest = AF.download(fileUrl, to: self.destination) self.downloadRequest?.downloadProgress { [weak self] (pro) in guard let `self` = self else {return} DispatchQueue.main.async { self.progress?(pro.completedUnitCount,pro.totalUnitCount,pro.fractionCompleted) } } self.downloadRequest?.responseData(queue: queue, completionHandler: downloadResponse) } } //根据下载状态处理 private func downloadResponse(response:AFDownloadResponse<Data>){ switch response.result { case .success: if let data = response.value, data.count > 1000 { if self.success != nil{ DispatchQueue.main.async { self.success?(response) } } }else { DispatchQueue.main.async { self.fail?(NSError(domain: "文件下载失败", code: 12345, userInfo: nil) as Error) } } case .failure: self.cancelledData = response.resumeData//意外停止的话,把已下载的数据存储起来 DispatchQueue.main.async { self.fail?(response.error) } } } }
mit
23adcf5efe3f799674802d54582a35da
36.362981
215
0.564048
4.813565
false
false
false
false
Quick/Spry
Source/Spry/Matchers/equal.swift
1
6174
// // EqualTests.swift // Spry // // Created by Shaps Benkau on 22/02/2017. // // import Foundation /// A Nimble matcher that succeeds when the actual value is equal to the expected value. /// Values can support equal by supporting the Equatable protocol. /// /// @see beCloseTo if you want to match imprecise types (eg - floats, doubles). public func equal<T: Equatable>(_ expectedValue: T) -> Matcher<T> { return Matcher { expression in let actualValue = try expression.evaluate() return actualValue == expectedValue } } /// A Nimble matcher that succeeds when the actual value is equal to the expected value. /// Values can support equal by supporting the Equatable protocol. /// /// @see beCloseTo if you want to match imprecise types (eg - floats, doubles). public func equal<T: Equatable, C: Equatable>(_ expectedValue: [T: C]) -> Matcher<[T: C]> { return Matcher { expression in guard let actualValue = try expression.evaluate() else { return false } return expectedValue == actualValue } } /// A Nimble matcher that succeeds when the actual collection is equal to the expected collection. /// Items must implement the Equatable protocol. public func equal<T: Equatable>(_ expectedValue: [T]) -> Matcher<[T]> { return Matcher { expression in let _actualValue = try expression.evaluate() guard let actualValue = _actualValue else { return false } return expectedValue == actualValue } } /// A Nimble matcher allowing comparison of collection with optional type public func equal<T: Equatable>(_ expectedValue: [T?]) -> Matcher<[T?]> { return Matcher { expression in if let actualValue = try expression.evaluate() { if expectedValue.count != actualValue.count { return false } for (index, item) in actualValue.enumerated() { let otherItem = expectedValue[index] if item == nil && otherItem == nil { continue } else if item == nil && otherItem != nil { return false } else if item != nil && otherItem == nil { return false } else if item! != otherItem! { return false } } return true } return false } } /// A Nimble matcher that succeeds when the actual set is equal to the expected set. public func equal<T>(_ expectedValue: Set<T>) -> Matcher<Set<T>> { return equalSet(expectedValue) } /// A Nimble matcher that succeeds when the actual set is equal to the expected set. public func equal<T: Comparable>(_ expectedValue: Set<T>) -> Matcher<Set<T>> { return equalSet(expectedValue) } private func equalSet<T>(_ expectedValue: Set<T>) -> Matcher<Set<T>> { return Matcher { actualExpression in if let actualValue = try actualExpression.evaluate(), expectedValue == actualValue { return true } return false } } // Operator Overloads /// A Nimble matcher that succeeds when the actual value is equal to the expected value. /// Values can support equal by supporting the Equatable protocol. /// /// @see beCloseTo if you want to match imprecise types (eg - floats, doubles). @discardableResult public func ==<T: Equatable>(lhs: Expectation<T>, rhs: T) -> ExpectationResult { return lhs.to(equal(rhs)) } /// A Nimble matcher that succeeds when the actual value is not equal to the expected value. /// Values can support equal by supporting the Equatable protocol. /// /// @see beCloseTo if you want to match imprecise types (eg - floats, doubles). @discardableResult public func !=<T: Equatable>(lhs: Expectation<T>, rhs: T) -> ExpectationResult { return lhs.toNot(equal(rhs)) } /// A Nimble matcher that succeeds when the actual collection is equal to the expected collection. /// Items must implement the Equatable protocol. @discardableResult public func ==<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) -> ExpectationResult { return lhs.to(equal(rhs!)) } /// A Nimble matcher that succeeds when the actual collection is not equal to the expected collection. /// Items must implement the Equatable protocol. @discardableResult public func !=<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) -> ExpectationResult { return lhs.toNot(equal(rhs!)) } /// A Nimble matcher that succeeds when the actual set is equal to the expected set. @discardableResult public func == <T>(lhs: Expectation<Set<T>>, rhs: Set<T>?) -> ExpectationResult { return lhs.to(equal(rhs!)) } /// A Nimble matcher that succeeds when the actual set is not equal to the expected set. @discardableResult public func != <T>(lhs: Expectation<Set<T>>, rhs: Set<T>?) -> ExpectationResult { return lhs.toNot(equal(rhs!)) } /// A Nimble matcher that succeeds when the actual set is equal to the expected set. @discardableResult public func ==<T: Comparable>(lhs: Expectation<Set<T>>, rhs: Set<T>?) -> ExpectationResult { return lhs.to(equal(rhs!)) } /// A Nimble matcher that succeeds when the actual set is not equal to the expected set. @discardableResult public func !=<T: Comparable>(lhs: Expectation<Set<T>>, rhs: Set<T>?) -> ExpectationResult { return lhs.toNot(equal(rhs!)) } /// A Nimble matcher that succeeds when the actual value is equal to the expected value. /// Values can support equal by supporting the Equatable protocol. /// /// @see beCloseTo if you want to match imprecise types (eg - floats, doubles). @discardableResult public func ==<T: Equatable, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) -> ExpectationResult { return lhs.to(equal(rhs!)) } /// A Nimble matcher that succeeds when the actual value is not equal to the expected value. /// Values can support equal by supporting the Equatable protocol. /// /// @see beCloseTo if you want to match imprecise types (eg - floats, doubles). @discardableResult public func !=<T: Equatable, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) -> ExpectationResult { return lhs.toNot(equal(rhs!)) }
apache-2.0
22320e67c13f82529ea4a38147ac7294
36.192771
105
0.667153
4.381831
false
false
false
false
zevwings/ZVRefreshing
ZVRefreshing/Header/ZVRefreshFlatHeader.swift
1
3072
// // ZRefreshNormalHeader.swift // ZVRefreshing // // Created by zevwings on 16/3/30. // Copyright © 2016年 zevwings. All rights reserved. // import UIKit import ZVActivityIndicatorView public class ZVRefreshFlatHeader: ZVRefreshStateHeader { // MARK: - Property public private(set) var activityIndicator: ActivityIndicatorView? // MARK: didSet override public var pullingPercent: CGFloat { didSet { activityIndicator?.progress = pullingPercent } } // MARK: - Subviews override public func prepare() { super.prepare() if activityIndicator == nil { activityIndicator = ActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 24, height: 24)) activityIndicator?.tintColor = .lightGray activityIndicator?.hidesWhenStopped = false addSubview(activityIndicator!) } } override public func placeSubViews() { super.placeSubViews() if let activityIndicator = activityIndicator, activityIndicator.constraints.isEmpty { var activityIndicatorCenterX = frame.width * 0.5 if let stateLabel = stateLabel, !stateLabel.isHidden { var maxLabelWidth: CGFloat = 0.0 if let lastUpdatedTimeLabel = lastUpdatedTimeLabel, !lastUpdatedTimeLabel.isHidden { maxLabelWidth = max(lastUpdatedTimeLabel.textWidth, stateLabel.textWidth) } else { maxLabelWidth = stateLabel.textWidth } activityIndicatorCenterX -= (maxLabelWidth * 0.5 + labelInsetLeft + activityIndicator.frame.width * 0.5) } let activityIndicatorCenterY = frame.height * 0.5 let activityIndicatorCenter = CGPoint(x: activityIndicatorCenterX, y: activityIndicatorCenterY) activityIndicator.center = activityIndicatorCenter } } // MARK: - State Update public override func refreshStateUpdate( _ state: ZVRefreshControl.RefreshState, oldState: ZVRefreshControl.RefreshState ) { super.refreshStateUpdate(state, oldState: oldState) switch state { case .idle: if refreshState == .refreshing { UIView.animate(withDuration: AnimationDuration.slow, animations: { self.activityIndicator?.alpha = 0.0 }, completion: { _ in guard self.refreshState == .idle else { return } self.activityIndicator?.stopAnimating() }) } else { activityIndicator?.stopAnimating() } case .refreshing: activityIndicator?.startAnimating() default: break } } } // MARK: - System Override extension ZVRefreshFlatHeader { override open var tintColor: UIColor! { didSet { activityIndicator?.tintColor = tintColor } } }
mit
69b3be8c3b84af98966abd02ec1527f2
30.316327
120
0.594982
5.620879
false
false
false
false
allen-zeng/PromiseKit
Tests/A+ Specs/2.3.2.swift
2
3319
import PromiseKit import XCTest // describe: 2.3.2: If `x` is a promise, adopt its state class Test2321: XCTestCase { // describe: 2.3.2.1: If `x` is pending, `promise` must remain pending until `x` is fulfilled or rejected. func test1() { testPromiseResolution({ return Promise.pendingPromise().promise }, test: { promise in let ex = self.expectationWithDescription("") var wasFulfilled = false var wasRejected = false promise.then { _ in wasFulfilled = true } promise.error { _ in wasRejected = true } later(4) { XCTAssertFalse(wasFulfilled) XCTAssertFalse(wasRejected) ex.fulfill() } }) } } class Test2322: XCTestCase { // 2.3.2.2: If/when `x` is fulfilled, fulfill `promise` with the same value. func test1() { let sentinel = Int(arc4random()) // describe: `x` is already-fulfilled testPromiseResolution({ return Promise(sentinel) }, test: { promise in let ex = self.expectationWithDescription("") promise.then { value -> Void in XCTAssertEqual(value, sentinel) ex.fulfill() } }) } func test2() { let sentinel = Int(arc4random()) // `x` is eventually-fulfilled testPromiseResolution({ after(0.1).then { sentinel } }, test: { promise in let ex = self.expectationWithDescription("") promise.then{ value -> Void in XCTAssertEqual(value, sentinel) ex.fulfill() } }) } } class Test2323: XCTestCase { // describe: 2.3.2.3: If/when `x` is rejected, reject `promise` with the same reason func test1() { let sentinel = Error.Dummy // specify: `x` is already-rejected testPromiseResolution({ return Promise(error: sentinel) }, test: { promise in let ex = self.expectationWithDescription("") promise.error { error -> Void in XCTAssertEqual(error, sentinel) ex.fulfill() } }) } func test2() { let sentinel = Error.Dummy // specify: `x` is eventually-rejected testPromiseResolution({ after(0.1).then { throw sentinel } }, test: { promise in let ex = self.expectationWithDescription("") promise.error { error -> Void in XCTAssertEqual(error, sentinel) ex.fulfill() } }) } } ///////////////////////////////////////////////////////////////////////// extension XCTestCase { private func testPromiseResolution(factory: () -> Promise<Int>, test: (Promise<Int>) -> Void) { // specify: via return from a fulfilled promise test(Promise(Int(arc4random())).then { _ in factory() }) waitForExpectationsWithTimeout(1, handler: nil) // specify: via return from a rejected promise test(Promise<Int>(error: Error.Dummy).recover { _ in factory() }) waitForExpectationsWithTimeout(1, handler: nil) } }
mit
eeea1dbbc66002d9365e8017fbf17889
25.133858
110
0.526062
4.782421
false
true
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/01224-swift-parser-skipsingle.swift
11
977
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse func e<l { enum e { func p() { p class A { class func a() -> Self { } } func b<T>(t: AnyObject.Type) -> T! { } func b<d-> d { class d:b class b protocol A { } func f() { } func ^(d: e, Bool) -> Bool {g !(d) } protocol d { f k } } protocol n { } class o: n{ cla) u p).v.c() k e.w == l> { } func p(c: Any, m: Any) -> (((Any, Any) -> Any) { func f<o>() -> (o, o -> o) -> o { o m o.j = { o) { return { -> T class func a() -> String { struct c { static let d: String = { b {A { u) { func g<T where T.E == F>(f: B<T>) { func e( class A { class func a() -> String { struct c { static let d
apache-2.0
eb23cb05475966bc77e7a3c642902ca4
19.354167
78
0.601842
2.676712
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Main/View/STCollectionView.swift
1
5932
// // STCollectionView.swift // DYZB // // Created by xiudou on 2017/7/13. // Copyright © 2017年 xiudo. All rights reserved. // import UIKit fileprivate let STCollectionViewCellIdentifier = "STCollectionViewCellIdentifier" fileprivate let STLocationReusableViewIdentifier = "STLocationReusableViewIdentifier" @objc protocol STCollectionViewDataSource : class { /*********必须实现***********/ // func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int /// 多少行 @objc func collectionView(_ stCollectionView: STCollectionView, numberOfItemsInSection section: Int) -> Int /// 每行的标题 @objc func collectionViewTitleInRow(_ stCollectionView : STCollectionView, _ indexPath : IndexPath)->String /*********选择实现***********/ /// 普通图片 // @objc optional func imageName(_ collectionView : STCollectionView, _ indexPath : IndexPath)->String /// 高亮图片 // @objc optional func highImageName(_ collectionView : STCollectionView, _ indexPath : IndexPath)->String /// 多少区间 @objc optional func numberOfSections(in stCollectionView: STCollectionView) -> Int /// 是否有箭头 @objc optional func isHiddenArrowImageView(_ stCollectionView : STCollectionView, _ indexPath : IndexPath)->Bool } @objc protocol STCollectionViewDelegate : class{ /// 点击事件 @objc optional func stCollection(_ stCollectionView : STCollectionView, didSelectItemAt indexPath: IndexPath) // 区间头部head的文字 @objc optional func stCollectionHeadInSection(_ stCollectionView: STCollectionView, at indexPath: IndexPath) -> String } class STCollectionView: UIView { weak var dataSource : STCollectionViewDataSource? weak var delegate : STCollectionViewDelegate? // MARK:- 懒加载 lazy var collectionView : UICollectionView = { // 设置layout属性 let layout = XDPlanFlowLayout() layout.naviHeight = 64 let width = sScreenW // 默认值(如果改动可以添加代理方法) layout.itemSize = CGSize(width: width, height: 44) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 layout.headerReferenceSize = CGSize(width: sScreenW, height: 20) // 创建UICollectionView let collectionView = UICollectionView(frame: CGRect(x: 0, y:0 , width: 0 , height: 0), collectionViewLayout: layout) collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.backgroundColor = UIColor(r: 239, g: 239, b: 239) // 注册cell collectionView.register(STCollectionViewCell.self, forCellWithReuseIdentifier: STCollectionViewCellIdentifier) collectionView.register(LocationReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: STLocationReusableViewIdentifier) return collectionView; }() override func layoutSubviews() { super.layoutSubviews() collectionView.frame = bounds } override init(frame: CGRect) { super.init(frame: frame) addSubview(collectionView) // 设置数据源 collectionView.dataSource = self collectionView.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension STCollectionView : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int{ let sectionCount = dataSource?.numberOfSections?(in: self) if sectionCount == nil || sectionCount == 0 { return 1 }else{ return sectionCount! } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ guard let itemsCount = dataSource?.collectionView(self, numberOfItemsInSection: section) else { return 0 } return itemsCount } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: STCollectionViewCellIdentifier, for: indexPath) as! STCollectionViewCell cell.contentView.backgroundColor = UIColor.randomColor() // title let text = dataSource?.collectionViewTitleInRow(self, indexPath) ?? "" cell.titleLabel.text = text // 是否右箭头 if let isHidden = dataSource?.isHiddenArrowImageView?(self, indexPath){ cell.arrowImageView.isHidden = isHidden }else{ cell.arrowImageView.isHidden = true } // 必须添加下面这句话,不然系统不知道什么时候刷新cell(参考:http://www.jianshu.com/writer#/notebooks/8510661/notes/14529933/preview) cell.setNeedsLayout() return cell } } extension STCollectionView : UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.stCollection?(self, didSelectItemAt: indexPath) } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: STLocationReusableViewIdentifier, for: indexPath) as! LocationReusableView view.titleString = delegate?.stCollectionHeadInSection?(self, at: indexPath) return view } }
mit
17ec28e7d585181778ebd64dfd1b782d
34.981132
208
0.683447
5.581463
false
false
false
false
GrouponChina/groupon-up
Groupon UP/Groupon UP/UpListConstants.swift
1
548
// // UpListConstants.swift // Groupon UP // // Created by Ping Zhang on 12/5/15. // Copyright © 2015 Chang Liu. All rights reserved. // import Foundation import UIKit struct UpListCell { static let span = 8 static let titleFont = UIFont(name: UPFontBold, size: 14) static let otherFont = UIFont(name: UPFont, size: 13) static let otherFontColor = UPDarkGray static let segmentFont = UIFont(name: UPFontBold, size: 16) static let segmentTintColor = UIColor(red: 120/255, green: 181/255, blue: 72/255, alpha: 1) }
apache-2.0
d263aaedd4df13a746226671dae9f37d
26.4
95
0.69287
3.529032
false
false
false
false
accepton/accepton-apple
Pod/Vendor/Alamofire/Stream.swift
1
6501
// Stream.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation #if !os(watchOS) @available(iOS 9.0, OSX 10.11, *) extension Manager { private enum Streamable { case Stream(String, Int) case NetService(NSNetService) } private func stream(streamable: Streamable) -> Request { var streamTask: NSURLSessionStreamTask! switch streamable { case .Stream(let hostName, let port): dispatch_sync(queue) { streamTask = self.session.streamTaskWithHostName(hostName, port: port) } case .NetService(let netService): dispatch_sync(queue) { streamTask = self.session.streamTaskWithNetService(netService) } } let request = Request(session: session, task: streamTask) delegate[request.delegate.task] = request.delegate if startRequestsImmediately { request.resume() } return request } /** Creates a request for bidirectional streaming with the given hostname and port. - parameter hostName: The hostname of the server to connect to. - parameter port: The port of the server to connect to. :returns: The created stream request. */ func stream(hostName hostName: String, port: Int) -> Request { return stream(.Stream(hostName, port)) } /** Creates a request for bidirectional streaming with the given `NSNetService`. - parameter netService: The net service used to identify the endpoint. - returns: The created stream request. */ func stream(netService netService: NSNetService) -> Request { return stream(.NetService(netService)) } } // MARK: - @available(iOS 9.0, OSX 10.11, *) extension Manager.SessionDelegate: NSURLSessionStreamDelegate { // MARK: Override Closures /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:readClosedForStreamTask:`. var streamTaskReadClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { get { return _streamTaskReadClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void } set { _streamTaskReadClosed = newValue } } /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:writeClosedForStreamTask:`. var streamTaskWriteClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { get { return _streamTaskWriteClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void } set { _streamTaskWriteClosed = newValue } } /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:betterRouteDiscoveredForStreamTask:`. var streamTaskBetterRouteDiscovered: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { get { return _streamTaskBetterRouteDiscovered as? (NSURLSession, NSURLSessionStreamTask) -> Void } set { _streamTaskBetterRouteDiscovered = newValue } } /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:streamTask:didBecomeInputStream:outputStream:`. var streamTaskDidBecomeInputStream: ((NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void)? { get { return _streamTaskDidBecomeInputStream as? (NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void } set { _streamTaskDidBecomeInputStream = newValue } } // MARK: Delegate Methods /** Tells the delegate that the read side of the connection has been closed. - parameter session: The session. - parameter streamTask: The stream task. */ func URLSession(session: NSURLSession, readClosedForStreamTask streamTask: NSURLSessionStreamTask) { streamTaskReadClosed?(session, streamTask) } /** Tells the delegate that the write side of the connection has been closed. - parameter session: The session. - parameter streamTask: The stream task. */ func URLSession(session: NSURLSession, writeClosedForStreamTask streamTask: NSURLSessionStreamTask) { streamTaskWriteClosed?(session, streamTask) } /** Tells the delegate that the system has determined that a better route to the host is available. - parameter session: The session. - parameter streamTask: The stream task. */ func URLSession(session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask) { streamTaskBetterRouteDiscovered?(session, streamTask) } /** Tells the delegate that the stream task has been completed and provides the unopened stream objects. - parameter session: The session. - parameter streamTask: The stream task. - parameter inputStream: The new input stream. - parameter outputStream: The new output stream. */ func URLSession( session: NSURLSession, streamTask: NSURLSessionStreamTask, didBecomeInputStream inputStream: NSInputStream, outputStream: NSOutputStream) { streamTaskDidBecomeInputStream?(session, streamTask, inputStream, outputStream) } } #endif
mit
faabe622461616c989621a0023e14911
35.105556
132
0.683798
5.470539
false
false
false
false
gregomni/swift
test/SILGen/function_conversion_objc.swift
5
6364
// RUN: %target-swift-emit-silgen -module-name function_conversion_objc -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -enable-objc-interop -verify | %FileCheck %s import Foundation // ==== Metatype to object conversions // CHECK-LABEL: sil hidden [ossa] @$s24function_conversion_objc20convMetatypeToObjectyySo8NSObjectCmADcF func convMetatypeToObject(_ f: @escaping (NSObject) -> NSObject.Type) { // CHECK: function_ref @$sSo8NSObjectCABXMTIeggd_AByXlIeggo_TR // CHECK: partial_apply let _: (NSObject) -> AnyObject = f } // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sSo8NSObjectCABXMTIeggd_AByXlIeggo_TR : $@convention(thin) (@guaranteed NSObject, @guaranteed @callee_guaranteed (@guaranteed NSObject) -> @thick NSObject.Type) -> @owned AnyObject { // CHECK: apply %1(%0) // CHECK: thick_to_objc_metatype {{.*}} : $@thick NSObject.Type to $@objc_metatype NSObject.Type // CHECK: objc_metatype_to_object {{.*}} : $@objc_metatype NSObject.Type to $AnyObject // CHECK: return @objc protocol NSBurrito {} // CHECK-LABEL: sil hidden [ossa] @$s24function_conversion_objc31convExistentialMetatypeToObjectyyAA9NSBurrito_pXpAaC_pcF func convExistentialMetatypeToObject(_ f: @escaping (NSBurrito) -> NSBurrito.Type) { // CHECK: function_ref @$s24function_conversion_objc9NSBurrito_pAaB_pXmTIeggd_AaB_pyXlIeggo_TR // CHECK: partial_apply let _: (NSBurrito) -> AnyObject = f } // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s24function_conversion_objc9NSBurrito_pAaB_pXmTIeggd_AaB_pyXlIeggo_TR : $@convention(thin) (@guaranteed NSBurrito, @guaranteed @callee_guaranteed (@guaranteed NSBurrito) -> @thick NSBurrito.Type) -> @owned AnyObject // CHECK: apply %1(%0) // CHECK: thick_to_objc_metatype {{.*}} : $@thick NSBurrito.Type to $@objc_metatype NSBurrito.Type // CHECK: objc_existential_metatype_to_object {{.*}} : $@objc_metatype NSBurrito.Type to $AnyObject // CHECK: return // CHECK-LABEL: sil hidden [ossa] @$s24function_conversion_objc28convProtocolMetatypeToObjectyyAA9NSBurrito_pmycF func convProtocolMetatypeToObject(_ f: @escaping () -> NSBurrito.Protocol) { // CHECK: function_ref @$s24function_conversion_objc9NSBurrito_pXMtIegd_So8ProtocolCIego_TR // CHECK: partial_apply let _: () -> Protocol = f } // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s24function_conversion_objc9NSBurrito_pXMtIegd_So8ProtocolCIego_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> @thin NSBurrito.Protocol) -> @owned Protocol // CHECK: apply %0() : $@callee_guaranteed () -> @thin NSBurrito.Protocol // CHECK: objc_protocol #NSBurrito : $Protocol // CHECK: copy_value // CHECK: return // ==== Representation conversions // CHECK-LABEL: sil hidden [ossa] @$s24function_conversion_objc11funcToBlockyyyXByycF : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @owned @convention(block) () -> () // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] // CHECK: [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) () -> () // CHECK: return [[COPY]] func funcToBlock(_ x: @escaping () -> ()) -> @convention(block) () -> () { return x } // CHECK-LABEL: sil hidden [ossa] @$s24function_conversion_objc11blockToFuncyyycyyXBF : $@convention(thin) (@guaranteed @convention(block) () -> ()) -> @owned @callee_guaranteed () -> () // CHECK: bb0([[ARG:%.*]] : @guaranteed $@convention(block) () -> ()): // CHECK: [[COPIED:%.*]] = copy_block [[ARG]] // CHECK: [[BORROWED_COPIED:%.*]] = begin_borrow [lexical] [[COPIED]] // CHECK: [[COPIED_2:%.*]] = copy_value [[BORROWED_COPIED]] // CHECK: [[THUNK:%.*]] = function_ref @$sIeyB_Ieg_TR // CHECK: [[FUNC:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[COPIED_2]]) // CHECK: end_borrow [[BORROWED_COPIED]] // CHECK: destroy_value [[COPIED]] // CHECK-NOT: destroy_value [[ARG]] // CHECK: return [[FUNC]] func blockToFunc(_ x: @escaping @convention(block) () -> ()) -> () -> () { return x } // ==== Representation change + function type conversion // CHECK-LABEL: sil hidden [ossa] @$s24function_conversion_objc22blockToFuncExistentialyypycSiyXBF : $@convention(thin) (@guaranteed @convention(block) () -> Int) -> @owned @callee_guaranteed () -> @out Any // CHECK: function_ref @$sSiIeyBd_SiIegd_TR // CHECK: partial_apply // CHECK: function_ref @$sSiIegd_ypIegr_TR // CHECK: partial_apply // CHECK: return func blockToFuncExistential(_ x: @escaping @convention(block) () -> Int) -> () -> Any { return x } // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sSiIeyBd_SiIegd_TR : $@convention(thin) (@guaranteed @convention(block) () -> Int) -> Int // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sSiIegd_ypIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> Int) -> @out Any // C function pointer conversions class A : NSObject {} class B : A {} // CHECK-LABEL: sil hidden [ossa] @$s24function_conversion_objc18cFuncPtrConversionyyAA1BCXCyAA1ACXCF func cFuncPtrConversion(_ x: @escaping @convention(c) (A) -> ()) -> @convention(c) (B) -> () { // CHECK: convert_function %0 : $@convention(c) (A) -> () to $@convention(c) (B) -> () // CHECK: return return x } func cFuncPtr(_ a: A) {} // CHECK-LABEL: sil hidden [ossa] @$s24function_conversion_objc19cFuncDeclConversionyAA1BCXCyF func cFuncDeclConversion() -> @convention(c) (B) -> () { // CHECK: function_ref @$s24function_conversion_objc8cFuncPtryyAA1ACFTo : $@convention(c) (A) -> () // CHECK: convert_function %0 : $@convention(c) (A) -> () to $@convention(c) (B) -> () // CHECK: return return cFuncPtr } func cFuncPtrConversionUnsupported(_ x: @escaping @convention(c) (@convention(block) () -> ()) -> ()) -> @convention(c) (@convention(c) () -> ()) -> () { return x // expected-error{{C function pointer signature '@convention(c) (@convention(block) () -> ()) -> ()' is not compatible with expected type '@convention(c) (@convention(c) () -> ()) -> ()'}} }
apache-2.0
8f62858eadc42a08025ae248c0c19fcf
54.33913
300
0.659648
3.54738
false
false
false
false
DavidSteuber/QRKoan
QRKoan/main.swift
1
3945
// // main.swift // QRKoan // // Created by David Steuber on 4/28/15. // Copyright (c) 2015 David Steuber. // // Create a Quick Response code that contains a representation of itself // by looking for a "zero point". What would be really cool is to create // a QR code that represents a PNG file representing that QR code. import Foundation import QuartzCore let fileName = "/Users/david/Desktop/test.png" let maxCapacity = 2953 // Quick Response code generator func qrCodeWithMessage(data: NSData) -> CIImage? { if data.length > maxCapacity { println("Data length \(data.length) exceeds maxCapacity of \(maxCapacity)") return nil } let qrEncoder = CIFilter(name: "CIQRCodeGenerator", withInputParameters: ["inputMessage":data, "inputCorrectionLevel":"L"]) let ciImage = qrEncoder.outputImage return ciImage } func colorSpaceIndexed() -> CGColorSpace! { let colorTable = [0, 255] let graySpace = CGColorSpaceCreateDeviceGray() return CGColorSpaceCreateIndexed(graySpace!, 1, UnsafePointer<UInt8>(colorTable)) } func createBitmapContext (size: CGRect) -> CGContext! { let context = CGBitmapContextCreate(nil, Int(size.width), Int(size.height), 8, 0, CGColorSpaceCreateDeviceRGB(), CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)) CGContextSetInterpolationQuality(context, kCGInterpolationNone) CGContextSetShouldAntialias(context, false) return context } func createCGImage(ci: CIImage) -> CGImage? { let cgContext = createBitmapContext(ci.extent()) let context = CIContext(CGContext: cgContext, options: nil) CGContextDrawImage(cgContext, ci.extent(), context.createCGImage(ci, fromRect: ci.extent())) return CGBitmapContextCreateImage(cgContext) } func saveImage(path: String, image: NSData) { image.writeToFile(path, atomically: true) } func toCFDictionary<K: NSObject, V: NSObject where K: Hashable>(d: Dictionary<K,V>) -> CFDictionary { return d as NSDictionary as CFDictionary } func getImageFileData(image: CGImage) -> NSData? { var pngDataRef = CFDataCreateMutable(nil, 0) var depth = 1 var isIndexed = kCFBooleanTrue var options = toCFDictionary([kCGImagePropertyDepth:CFNumberCreate(nil, CFNumberType.IntType, &depth), kCGImagePropertyIsIndexed:isIndexed, kCGImagePropertyHasAlpha:kCFBooleanFalse]) var pngDest = CGImageDestinationCreateWithData(pngDataRef, kUTTypePNG, 1, nil) CGImageDestinationSetProperties(pngDest, options) CGImageDestinationAddImage(pngDest, image, options) CGImageDestinationFinalize(pngDest) return pngDataRef } func compare(d1: NSData, d2: NSData) -> Bool { if d1.length == d2.length { let m = d1.bytes let n = d2.bytes for i in 0 ..< d1.length { if m != n { println("different byte at index \(i) of \(d1.length)") return false } } } else { println("different lengths: \(d1.length), \(d2.length)") return false } return true } func main() { var qrcode = qrCodeWithMessage(NSData()) // initial image with null data var image = createCGImage(qrcode!) var data = getImageFileData(image!) var round = 1 do { print("Round \(round): ") if let qrcode2 = qrCodeWithMessage(data!), let image2 = createCGImage(qrcode2), let data2 = getImageFileData(image2) { if compare(data!, data2) { break } else { qrcode = qrcode2 image = image2 data = data2 round++ } } else { break } if data!.length > maxCapacity { println("Non convergence!") break } } while true saveImage(fileName, data!) } main()
unlicense
1c9b4e4e41d64711f7289b94543f2b2d
28.447761
127
0.64512
4.427609
false
false
false
false
hsusmita/Functional-Reactive-Example
Action.playground/Contents.swift
1
583
//: Playground - noun: a place where people can play import UIKit import ReactiveSwift import Result var str = "Hello, playground" let action = Action<Int, String, NoError> { number -> SignalProducer<String, NoError> in return SignalProducer<String, NoError> { (innerObserver, disposable) in innerObserver.send(value: "\(number * 3)") innerObserver.sendCompleted() } } let numberSignalProducer = action.apply(1) let observer: Observer<String, ActionError<NoError>> = Observer(value: { (value) in print("value received = \(value)") }) numberSignalProducer.start(observer)
mit
1edf5d8bc4cece7b94f813271ce42f77
26.761905
88
0.744425
3.886667
false
false
false
false
wangjianxue/CKWaveCollectionViewTransition
Classes/Extensions/UICollectionViewExtension.swift
21
970
// // UICollectionViewExtension.swift // CKWaveCollectionViewTransition // // Created by Salvation on 7/21/15. // Copyright (c) 2015 CezaryKopacz. All rights reserved. // import UIKit extension UICollectionView { func numberOfVisibleRowsAndColumn() -> (rows: Int, columns: Int) { var rows = 1 var columns = 0 var currentWidth: CGFloat = 0.0 let visibleCells = self.visibleCells() as? Array<UICollectionViewCell> for cell in visibleCells! { if (currentWidth + cell.frame.size.width) < self.frame.size.width { currentWidth += cell.frame.size.width if rows == 1 { //we only care about first row columns++ } } else { rows++ currentWidth = cell.frame.size.width } } return (rows, columns) } }
mit
6379e01a004302df5ede005ef3890bda
24.526316
79
0.52268
4.754902
false
false
false
false
LoopKit/LoopKit
LoopKitUI/Views/GuidePage.swift
1
1759
// // GuidePage.swift // LoopKitUI // // Created by Pete Schwamb on 2020-03-04. // Copyright © 2020 LoopKit Authors. All rights reserved. // import SwiftUI public struct GuidePage<Content, ActionAreaContent>: View where Content: View, ActionAreaContent: View { let content: Content let actionAreaContent: ActionAreaContent @Environment(\.horizontalSizeClass) var horizontalSizeClass public init(@ViewBuilder content: @escaping () -> Content, @ViewBuilder actionAreaContent: @escaping () -> ActionAreaContent) { self.content = content() self.actionAreaContent = actionAreaContent() } public var body: some View { VStack(spacing: 0) { List { if self.horizontalSizeClass == .compact { Section(header: EmptyView(), footer: EmptyView()) { self.content } } else { self.content } } .insetGroupedListStyle() VStack { self.actionAreaContent } .padding(self.horizontalSizeClass == .regular ? .bottom : []) .background(Color(UIColor.secondarySystemGroupedBackground).shadow(radius: 5)) } .edgesIgnoringSafeArea(.bottom) } } struct GuidePage_Previews: PreviewProvider { static var previews: some View { GuidePage(content: { Text("content") Text("more content") Image(systemName: "circle") }) { Button(action: { print("Button tapped") }) { Text("Action Button") .actionButtonStyle() } } } }
mit
1a9a0abad71d9d2ada9b672da7a2b66e
27.354839
104
0.546644
5.125364
false
false
false
false
kiwitechnologies/SocialManageriOS
SocialSharing/SocialSharing/InstagramManager/TSGInstagramManager.swift
1
4782
// // TSGInstagramManager.swift // SocialSharing // // Created by Yogesh Bhatt on 21/06/16. // Copyright © 2016 kiwitech. All rights reserved. // import UIKit import TSGServiceClient class TSGInstagramManager:NSObject { var success:(status:Bool)->()? = {_ in return} internal class var sharedInstance:TSGInstagramManager{ struct Static{ static var onceToken: dispatch_once_t = 0 static var instance: TSGInstagramManager? = nil } dispatch_once(&Static.onceToken) { Static.instance = TSGInstagramManager() } return Static.instance! } /* * @functionName : instagramPostImage * description: This method is used to post image in Instagram app. * */ func instagramPostImage(view:UIView,image:UIImage, success:(status:Bool)->()){ let url = NSURL(string: "instagram://") self.success = success if UIApplication.sharedApplication().canOpenURL(url!) { NSDataWritingOptions.AtomicWrite let image = image let imageData = UIImageJPEGRepresentation(image, 1.0) let temporaryDirectory = NSTemporaryDirectory() as NSString let temporaryImagePath = temporaryDirectory.stringByAppendingPathComponent("instag.igo") let boolValue = imageData!.writeToFile(temporaryImagePath, atomically: true) print(boolValue) docFile = UIDocumentInteractionController() docFile!.delegate = self docFile!.URL = NSURL.fileURLWithPath(temporaryImagePath) print(docFile!.URL) // docFile?.annotation = NSDictionary docFile!.UTI = "com.instagram.exclusivegram" docFile!.presentOpenInMenuFromRect( view.bounds, inView: view, animated: true ) } } /* * @functionName : instagramUserProfile * description: This method is used to get UserProfile * */ func instagramUserProfile(successBlock:(AnyObject)->(), failureBlock:(AnyObject)->()){ if let token = NSUserDefaults().valueForKey("Instagram_Token") { let queryParam = ["access_token":token as! String] ServiceManager.setBaseURL("https://api.instagram.com/v1/") ServiceManager.hitRequestForAPI("users/self/", withQueryParam: queryParam, typeOfRequest: .GET, typeOFResponse: .JSON, success: { (object) in print(object) }) { (error) in print(error) } }else{ failureBlock("Token Not found") } } /* * @functionName : instagramUserProfile * description: This method is used to get friendProfile based on ID * */ func instagramFriendProfile(userID:String, successBlock:(AnyObject)->(),failureBlock:(AnyObject)->()){ if let token = NSUserDefaults().valueForKey("Instagram_Token") { let queryParam = ["access_token":token as! String] ServiceManager.setBaseURL("https://api.instagram.com/v1/") ServiceManager.hitRequestForAPI("users/\(userID)", withQueryParam: queryParam, typeOfRequest: .GET, typeOFResponse: .JSON, success: { (object) in print(object) }) { (error) in print(error) } } else { failureBlock("Token Not found") } } /* * @functionName : instagramLogOut * description: This method is used to logOut from Instagram * */ func instagramLogOut(success:(status:Bool)->()){ let cookieJar : NSHTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage() for cookie in cookieJar.cookies! as [NSHTTPCookie]{ NSLog("cookie.domain = %@", cookie.domain) if cookie.domain == "www.instagram.com" || cookie.domain == "api.instagram.com"{ cookieJar.deleteCookie(cookie) } } NSUserDefaults().removeObjectForKey("Instagram_Token") NSUserDefaults.standardUserDefaults().synchronize() success(status: true) } } extension TSGInstagramManager: UIDocumentInteractionControllerDelegate{ func documentInteractionController(controller: UIDocumentInteractionController, didEndSendingToApplication application: String?) { success(status: true) } func documentInteractionControllerDidDismissOpenInMenu(controller: UIDocumentInteractionController) { success(status: false) } }
mit
1d583783e7f02c0113ee35203dc6199b
32.914894
157
0.596528
5.312222
false
false
false
false
aliceatlas/daybreak
Additions/Array-SBAdditions.swift
1
3844
/* Array-SBAdditions.swift Copyright (c) 2014, Alice Atlas Copyright (c) 2010, Atsushi Jike All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation extension Array { func containsIndexes(indexes: NSIndexSet) -> Bool { for var i = indexes.lastIndex; i != NSNotFound; i = indexes.indexLessThanIndex(i) { if i >= count { return false } } return true } mutating func insertItems(items: [Element], atIndexes indexes: NSIndexSet) { var currentIndex = indexes.firstIndex if items.count != indexes.count { fatalError("inconsistent number of items") } for item in items { insert(item, atIndex: currentIndex) currentIndex = indexes.indexGreaterThanIndex(currentIndex) } } func objectsAtIndexes(indexes: NSIndexSet) -> [Element] { var objs: [Element] = [] indexes.enumerateIndexesUsingBlock { (Int i, _) in objs.append(self[i]) } return objs } mutating func removeObjectsAtIndexes(indexes: NSIndexSet) { indexes.enumerateIndexesWithOptions(.Reverse) { (index: Int, _) in self.removeAtIndex(index) return } } func first(@noescape condition: (Element) -> Bool) -> Element? { for item in self { if condition(item) { return item } } return nil } func firstIndex(@noescape condition: (Element) -> Bool) -> Int? { for (index, item) in enumerate(self) { if condition(item) { return index } } return nil } func any(@noescape condition: (Element) -> Bool) -> Bool { if let x = first(condition) { return true } return false } func get(index: Int) -> Element? { return (index >= 0 && index < count) &? self[index] } var ifNotEmpty: Array? { return isEmpty ? nil : self } func optionalMap<U>(transform: (T) -> U?) -> [U] { return map(transform).filter{$0 != nil}.map{$0!} } } func removeItem<T: Equatable>(inout array: [T], toRemove: T) { if let index = array.firstIndex({ $0 == toRemove }) { array.removeAtIndex(index) } } func removeItems<T: Equatable>(inout array: [T], toRemove: [T]) { for item in array { removeItem(&array, item) } } func indexOfItem<T: Equatable>(array: [T], value: T) -> Int? { return array.firstIndex { $0 == value } }
bsd-2-clause
cf87e382cb0577d9928417555a343619
30.77686
91
0.632674
4.549112
false
false
false
false
NghiaTranUIT/Unofficial-Uber-macOS
UberGoCore/UberGoCore/UberPersonalPlaceObj.swift
1
866
// // UberPersonalPlaceObj.swift // UberGoCore // // Created by Nghia Tran on 6/8/17. // Copyright © 2017 Nghia Tran. All rights reserved. // import Foundation import Unbox public final class UberPersonalPlaceObj: Unboxable { // MARK: - Variable public var placeType: PlaceType = .work public var address: String public fileprivate(set) var invalid = false // MARK: - Map public init(address: String, invalid: Bool = false) { self.address = address self.invalid = invalid } public required init(unboxer: Unboxer) throws { address = try unboxer.unbox(key: Constants.Object.UberPersonalPlace.Address) } } // MARK: - Public extension UberPersonalPlaceObj { public static var invalidPlace: UberPersonalPlaceObj { return UberPersonalPlaceObj(address: "Add place", invalid: true) } }
mit
af8ed125f69258c9580162d2612dd944
23.027778
84
0.684393
4.119048
false
false
false
false
danmurrelljr/BotGallery
BotGallery/BotViewController.swift
1
13610
// // BotViewController.swift // BotGallery // // Created by Dan Murrell on 10/24/16. // Copyright © 2016 Mutant Soup. All rights reserved. // import Foundation import UIKit typealias ImageCompletion = (UIImage?) -> () class BotViewController: UIViewController, KeyboardObservation { let bot: PullStringBot let scrollView = UIScrollView() let stackView = UIStackView() let separator = UIView() let textInputView = UIView() let textField = TextField() let sendButton = UIButton() let botColor = UIColor(red:0.90, green:0.90, blue:0.92, alpha:1.00) let botTextColor = UIColor.black let humanColor = UIColor(red:0.08, green:0.49, blue:0.98, alpha:1.00) let humanTextColor = UIColor.white var delayedResponseTimer: Timer? = nil var lastChatBubble: ChatBubble? = nil var textInputViewBottomConstraint: NSLayoutConstraint? = nil init(withBot bot: PullStringBot) { self.bot = bot super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupView() setupViewHierarchy() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let textInputViewBottomConstraint = textInputViewBottomConstraint { addKeyboardFrameWillChangeObserver(forView: textInputView, withBottomConstraint: textInputViewBottomConstraint) } resumeIfNecessary(bot: bot) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) removeKeyboardFrameWillChangeObserver() } private func resumeIfNecessary(bot: PullStringBot) { if bot.active { let title = NSLocalizedString("Resume bot?", comment: "") let message = String(format: NSLocalizedString("There is a currently active conversation with %@.\n\nDo you want to resume it, or start new?", comment: ""), bot.name) let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) let resumeAction = UIAlertAction(title: NSLocalizedString("Resume", comment: ""), style: UIAlertActionStyle.default) { [weak self] action in self?.continueConversation(withBot: bot) } alert.addAction(resumeAction) let newAction = UIAlertAction(title: NSLocalizedString("New Converation", comment: ""), style: UIAlertActionStyle.default) { [weak self] action in self?.startConversation(withBot: bot) } alert.addAction(newAction) self.present(alert, animated: true, completion: nil) } else { startConversation(withBot: bot) } } private func startConversation(withBot bot: PullStringBot) { bot.startConversation { [weak self](json, error) in print("json: \(json)") if let json = json { self?.process(json: json) } } } private func continueConversation(withBot bot: PullStringBot) { guard let uuid = bot.conversation else { print("Unable to resume the conversation") startConversation(withBot: bot) return } addBubble(withText: NSLocalizedString("Resuming conversation..", comment: ""), orImage: nil, asBot: true) bot.say(text: nil, uuid: uuid) { [weak self](json, error) in print("json: \(json)\n-----------------------------\n\n") if let json = json { self?.process(json: json) } } } } extension BotViewController { func process(json: JSONDictionary) { bot.conversation = json["conversation"] as? String if let outputs = json["outputs"] as? [JSONDictionary] { processOutputs(outputs: outputs) } if let timedResponseInterval = json["timed_response_interval"] as? Double, delayedResponseTimer == nil { delayedResponseTimer = Timer(timeInterval: timedResponseInterval, repeats: false) { [weak self](timer) in self?.stopDelayedResponseTimer() self?.send(text: nil) } if let delayedResponseTimer = delayedResponseTimer { RunLoop.main.add(delayedResponseTimer, forMode: RunLoopMode.defaultRunLoopMode) } } } func processOutputs(outputs: [JSONDictionary]) { for line in outputs { // let type = line["type"] as? String // let character = line["character"] as? String // let id = line["id"] as? String let behavior = line["behavior"] as? String let parameters = line["parameters"] as? JSONDictionary let text = line["text"] as? String if let behavior = behavior, let parameters = parameters { processBehavior(behavior: behavior, parameters: parameters) } if let text = text { addBubble(withText: text, orImage: nil, asBot: true) } } } func processBehavior(behavior: String, parameters: JSONDictionary) { if behavior == "show_image" { if let image = parameters["image"] as? String, let url = URL(string: image) { loadImage(url: url) { [weak self](image) in self?.addBubble(withText: nil, orImage: image, asBot: true) } } } } func addBubble(withText text: String?, orImage: UIImage?, asBot: Bool) { DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } let color = asBot ? strongSelf.botColor : strongSelf.humanColor let textColor = asBot ? strongSelf.botTextColor : strongSelf.humanTextColor let direction: ChatBubbleDirection = asBot ? .left : .right if let text = text, let lastChatBubble = strongSelf.lastChatBubble, lastChatBubble.direction == direction, lastChatBubble.image == nil { print("Last chat bubble is in our direction, and does not have an image. We can concatenate!") lastChatBubble.append(text: text) } else { let chatBubble = ChatBubble(direction: direction, color: color, image: orImage, text: text, textColor: textColor) strongSelf.stackView.addArrangedSubview(chatBubble) strongSelf.lastChatBubble = chatBubble } strongSelf.scrollView.layoutIfNeeded() let contentHeight = strongSelf.scrollView.contentSize.height let scrollHeight = strongSelf.scrollView.bounds.size.height if contentHeight >= scrollHeight { let bottomOffset = CGPoint(x: 0, y: contentHeight - scrollHeight) strongSelf.scrollView.setContentOffset(bottomOffset, animated: true) } } } private func loadImage(url: URL, completion: ImageCompletion?) { let task = URLSession.shared.dataTask(with: url) { (data, response, error) in if let data = data, let image = UIImage(data: data) { if let completion = completion { completion(image) } } } task.resume() } } extension BotViewController { func setupView() { view.backgroundColor = UIColor.white title = bot.name } func setupViewHierarchy() { setupScrollView() setupStackView() setupSeparator() setupInputView() setupTextField() setupSendButton() setupTapGestureRecognizer() } func setupScrollView() { view.addSubview(scrollView) scrollView.alignTop(toView: view) scrollView.alignLeading(toView: view) scrollView.alignTrailing(toView: view) } func setupStackView() { scrollView.addSubview(stackView) stackView.alignTop(toView: scrollView) stackView.alignBottom(toView: scrollView) stackView.alignLeading(toView: view) stackView.alignTrailing(toView: view) stackView.backgroundColor = UIColor.red stackView.axis = .vertical stackView.alignment = .fill stackView.distribution = .fill stackView.spacing = 20 stackView.isLayoutMarginsRelativeArrangement = true } func setupTapGestureRecognizer() { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) stackView.addGestureRecognizer(tapGestureRecognizer) } func setupSeparator() { view.addSubview(separator) separator.backgroundColor = UIColor(white: 0.9, alpha: 1) separator.layout(belowView: scrollView) separator.alignLeading(toView: view) separator.alignTrailing(toView: view) separator.addConstraint(withHeight: 1) separator.setContentHuggingPriority(UILayoutPriorityRequired, for: .vertical) } func setupInputView() { view.addSubview(textInputView) textInputView.layout(belowView: separator, withPadding: 8) textInputView.alignLeading(toView: view, withOffset: 8) textInputView.alignTrailing(toView: view, withOffset: 8) textInputViewBottomConstraint = textInputView.alignBottom(toView: view, withOffset: 8) } func setupTextField() { textInputView.addSubview(textField) textField.alignTop(toView: textInputView) textField.alignBottom(toView: textInputView) textField.alignLeading(toView: textInputView) textField.setContentHuggingPriority(UILayoutPriorityDefaultLow, for: .horizontal) textField.setContentHuggingPriority(UILayoutPriorityRequired, for: .vertical) let format = NSLocalizedString("Message to %@", comment: "") textField.placeholder = String(format: format, bot.name) textField.layer.borderColor = UIColor.lightGray.cgColor textField.layer.borderWidth = 1 textField.layer.cornerRadius = 8 textField.delegate = self } func setupSendButton() { textInputView.addSubview(sendButton) sendButton.alignTop(toView: textInputView) sendButton.alignBottom(toView: textInputView) sendButton.alignTrailing(toView: textInputView) sendButton.layout(rightOfView: textField, withPadding: 8) sendButton.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .horizontal) sendButton.setTitle(NSLocalizedString("Send", comment: ""), for: .normal) sendButton.setTitleColor(UIColor.white, for: .normal) sendButton.setTitleColor(UIColor.white.withAlphaComponent(0.5), for: .disabled) sendButton.backgroundColor = humanColor sendButton.isEnabled = false sendButton.layer.cornerRadius = 8 sendButton.contentEdgeInsets = UIEdgeInsets(top: 4, left: 12, bottom: 4, right: 12) sendButton.addTarget(self, action: #selector(sendInput), for: .touchUpInside) } func sendInput() { guard let text = textField.text, text.characters.count > 0 else { return } stopDelayedResponseTimer() print("\n\n=====================\nSending... \(textField.text)") addBubble(withText: text, orImage: nil, asBot: false) send(text: text) textField.text = nil } func send(text: String?) { if let conversation = bot.conversation { bot.say(text: text, uuid: conversation) { [weak self](json, error) in print("json: \(json)\n-----------------------------\n\n") if let json = json { self?.process(json: json) } } } else { bot.startConversation() { [weak self](json, error) in print("json: \(json)\n-----------------------------\n\n") if let json = json { self?.process(json: json) } } } } func stopDelayedResponseTimer() { delayedResponseTimer?.invalidate() delayedResponseTimer = nil } func dismissKeyboard() { self.textField.resignFirstResponder() } } extension BotViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let currentString = textField.text ?? "" let finalString = (currentString as NSString).replacingCharacters(in: range, with: string) sendButton.isEnabled = (finalString.characters.count > 0) return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { sendInput() return true } }
mit
3f75a3e909cea819e71f20bd12e1c3e5
32.111922
178
0.593872
5.151022
false
false
false
false
RMizin/PigeonMessenger-project
FalconMessenger/Supporting Files/UIComponents/INSPhotosGallery/OverlayDefaultBottomView.swift
1
1522
// // OverlayDefaultBottomView.swift // FalconMessenger // // Created by Roman Mizin on 1/31/19. // Copyright © 2019 Roman Mizin. All rights reserved. // import UIKit public class OverlayDefaultBottomView: UIView { let insPhotoBottomView: OverlayPhotoBottomView = { let insPhotoBottomView = OverlayPhotoBottomView() insPhotoBottomView.isHidden = true insPhotoBottomView.translatesAutoresizingMaskIntoConstraints = false return insPhotoBottomView }() let insVideoBottomView: OverlayVideoBottomView = { let insVideoBottomView = OverlayVideoBottomView() insVideoBottomView.isHidden = true insVideoBottomView.translatesAutoresizingMaskIntoConstraints = false return insVideoBottomView }() override init(frame: CGRect) { super.init(frame: frame) addSubview(insVideoBottomView) addSubview(insPhotoBottomView) NSLayoutConstraint.activate([ insPhotoBottomView.topAnchor.constraint(equalTo: topAnchor), insPhotoBottomView.bottomAnchor.constraint(equalTo: bottomAnchor), insPhotoBottomView.leftAnchor.constraint(equalTo: leftAnchor), insPhotoBottomView.rightAnchor.constraint(equalTo: rightAnchor), insVideoBottomView.topAnchor.constraint(equalTo: topAnchor), insVideoBottomView.bottomAnchor.constraint(equalTo: bottomAnchor), insVideoBottomView.leftAnchor.constraint(equalTo: leftAnchor), insVideoBottomView.rightAnchor.constraint(equalTo: rightAnchor) ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-3.0
693f7c74a3754fb9016b5b2c0f0d2cc5
29.42
70
0.798159
4.358166
false
false
false
false
10Duke/DukeSwiftLibs
DukeSwiftLibs/Classes/singletons/ApiTokenImpl.swift
1
3064
import Foundation import Locksmith /** * Class for handling OAuth2 API token and it's secure persistence. */ public class ApiTokenImpl: ApiToken { /** * Singleton instance of the ApiToken class. */ public static let shared = ApiTokenImpl() /** * Static string for idpToken, used for keychain storage data key. */ let IDP_TOKEN = "idpToken" /** * Static string for userId, used for defaults storage key. */ let IDP_USERID = "userId" /** * Defaults that is used for storing user UUID. */ let m_defaults = UserDefaults() /** * OAuth2 token. * * In case memory stored token exists, returns it, otherwise tries to look it up from keychain based * on earlier login related UUID. * - returns: OAuth2 Bearer token as a string and nil in case no token is fond. */ public func getToken() -> String? { // if let id = m_defaults.string(forKey: IDP_USERID) { if let dictionary = Locksmith.loadDataForUserAccount(userAccount: id) { // if let token = dictionary["\(IDP_TOKEN)"] as? String { // if token == "" { return nil } return token } } } // return nil } /** * Stores token to specific UUID. * * - parameter id: The UUID of the logged in user. * - parameter token: The token string to be stored. * - returns: Boolean true if token storing is successful, false if it fails. */ public func storeToken(id: String, token: String) -> Bool { // do { // m_defaults.setValue(id, forKey: IDP_USERID) try Locksmith.updateData(data: [IDP_TOKEN: token], forUserAccount: id) return true } catch let error { // print("ERROR: Storing token failed with error: \(error)") return false } } /** * Resets and clears the token and user information from defaults and keychain. * * This function resets the memory stored token and alcso clears the keychain of the user. */ public func resetToken() { // if let id = m_defaults.string(forKey: IDP_USERID) { // do { // //try Locksmith.updateData(data: [IDP_TOKEN: ""], forUserAccount: id) try Locksmith.deleteDataForUserAccount(userAccount: id) m_defaults.removeObject(forKey: IDP_USERID) } catch let error { // print("ERROR: Resetting token failed with error: \(error)") } } } /** * Getter for user id stored in defaults. */ public func getUserId() -> String? { // if let userId = m_defaults.string(forKey: IDP_USERID) { // return userId } // return nil } }
mit
bcecaa83fba70dcf940064f6f6e271f8
25.643478
104
0.526762
4.635401
false
false
false
false
carabina/SAWaveToast
SAWaveToast/SAWaveToast.swift
1
9585
// // SAWaveToast.swift // SAWaveToast // // Created by Taiki Suzuki on 2015/08/24. // // import UIKit public class SAWaveToast: UIViewController { static let Spaces = UIEdgeInsets(top: 10, left: 10, bottom: 5, right: 10) static let ExtraSpace: CGFloat = 5 private let containerView: UIView = UIView() private let waveView: SAWaveView = SAWaveView() private let contentView: UIView = UIView() private let textView: UITextView = UITextView() private var waveColor: UIColor = .cyanColor() private var attributedText: NSMutableAttributedString = NSMutableAttributedString() private var stopAnimation: Bool = false private var duration: NSTimeInterval = 5 //Constrants private var containerViewBottomConstraint: NSLayoutConstraint? private var textViewCenterXConstraint: NSLayoutConstraint? public convenience init(text: String, font: UIFont? = nil, fontColor: UIColor? = nil, waveColor: UIColor? = nil, duration: NSTimeInterval? = nil) { var attributes: [NSObject : AnyObject] = [NSObject : AnyObject]() if let font = font { attributes[NSFontAttributeName] = font } if let fontColor = fontColor { attributes[NSForegroundColorAttributeName] = fontColor } self.init(attributedText: NSAttributedString(string: text, attributes: attributes), waveColor: waveColor, duration: duration) } public init(attributedText: NSAttributedString, waveColor: UIColor? = nil, duration: NSTimeInterval? = nil) { super.init(nibName: nil, bundle: nil) if let waveColor = waveColor { self.waveColor = waveColor } if let duration = duration { self.duration = duration } self.attributedText.appendAttributedString(attributedText) waveView.color = self.waveColor switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) { case .OrderedSame, .OrderedDescending: providesPresentationContextTransitionStyle = true definesPresentationContext = true modalPresentationStyle = .OverCurrentContext case .OrderedAscending: modalPresentationStyle = .CurrentContext } } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit {} public override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.backgroundColor = .clearColor() let width = UIScreen.mainScreen().bounds.size.width - SAWaveToast.Spaces.left + SAWaveToast.Spaces.right let textHeight = attributedText.boundingRectWithSize(CGSize(width: width, height: CGFloat.max), options: .UsesLineFragmentOrigin | .UsesFontLeading, context: nil).size.height setContainerView(textHeight) setWaveView(textHeight) setContentView(textHeight) setTextView(textHeight) } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) waveView.startAnimation() floatingAnimation() containerViewBottomConstraint?.constant = 0 UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseOut, animations: { self.containerView.layoutIfNeeded() }, completion: nil) let delay = duration * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue()) { self.stopAnimation = true } } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //MARK: - Private Methods extension SAWaveToast { private func setContainerView(textHeight: CGFloat) { view.addSubview(containerView) containerView.backgroundColor = .clearColor() containerView.setTranslatesAutoresizingMaskIntoConstraints(false) let height = textHeight + SAWaveView.Height + SAWaveToast.Spaces.top + SAWaveToast.Spaces.bottom + SAWaveToast.ExtraSpace let bottomConstraint = NSLayoutConstraint(item: containerView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant:height) view.addConstraints([ NSLayoutConstraint(item: containerView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0), bottomConstraint, NSLayoutConstraint(item: containerView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 0), NSLayoutConstraint(item: containerView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: height) ]) containerViewBottomConstraint = bottomConstraint } private func setWaveView(textHeight: CGFloat) { containerView.addSubview(waveView) waveView.setTranslatesAutoresizingMaskIntoConstraints(false) view.addConstraints([ NSLayoutConstraint(item: waveView, attribute: .Left, relatedBy: .Equal, toItem: containerView, attribute: .Left, multiplier: 1, constant: 0), NSLayoutConstraint(item: waveView, attribute: .Top, relatedBy: .Equal, toItem: containerView, attribute: .Top, multiplier: 1, constant: 0), NSLayoutConstraint(item: waveView, attribute: .Right, relatedBy: .Equal, toItem: containerView, attribute: .Right, multiplier: 1, constant: 0), NSLayoutConstraint(item: waveView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: SAWaveView.Height) ]) } private func setContentView(textHeight: CGFloat) { containerView.addSubview(contentView) contentView.backgroundColor = waveColor contentView.setTranslatesAutoresizingMaskIntoConstraints(false) view.addConstraints([ NSLayoutConstraint(item: contentView, attribute: .Left, relatedBy: .Equal, toItem: containerView, attribute: .Left, multiplier: 1, constant: 0), NSLayoutConstraint(item: contentView, attribute: .Bottom, relatedBy: .Equal, toItem: containerView, attribute: .Bottom, multiplier: 1, constant: 0), NSLayoutConstraint(item: contentView, attribute: .Right, relatedBy: .Equal, toItem: containerView, attribute: .Right, multiplier: 1, constant: 0), NSLayoutConstraint(item: contentView, attribute: .Top, relatedBy: .Equal, toItem: waveView, attribute: .Bottom, multiplier: 1, constant: 0) ]) } private func setTextView(textHeight: CGFloat) { contentView.addSubview(textView) textView.backgroundColor = .clearColor() textView.setTranslatesAutoresizingMaskIntoConstraints(false) textView.userInteractionEnabled = false textView.contentInset = UIEdgeInsets(top: -10, left: -4, bottom: 0, right: 0) let width = UIScreen.mainScreen().bounds.size.width - (SAWaveToast.Spaces.right + SAWaveToast.Spaces.left) let centerXConstraint = NSLayoutConstraint(item: textView, attribute: .CenterX, relatedBy: .Equal, toItem: contentView, attribute: .CenterX, multiplier: 1, constant: 0) contentView.addConstraints([ centerXConstraint, NSLayoutConstraint(item: textView, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: -(SAWaveToast.Spaces.bottom + SAWaveToast.ExtraSpace)), NSLayoutConstraint(item: textView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: width), NSLayoutConstraint(item: textView, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: SAWaveToast.Spaces.top) ]) textViewCenterXConstraint = centerXConstraint textView.attributedText = attributedText } private func willDisappearToast() { containerViewBottomConstraint?.constant = containerView.frame.size.height UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseIn, animations: { self.containerView.layoutIfNeeded() }) { finished in self.dismissViewControllerAnimated(false, completion: nil) } } private func floatingAnimation() { stopAnimation = false let totalValue = (SAWaveToast.Spaces.left + SAWaveToast.Spaces.right) / 4 let delta = (CGFloat(arc4random_uniform(UINT32_MAX)) / CGFloat(UINT32_MAX) ) * totalValue textViewCenterXConstraint?.constant = (arc4random_uniform(UINT32_MAX) % 2 == 0) ? delta : -delta if containerViewBottomConstraint?.constant == 0 { containerViewBottomConstraint?.constant = SAWaveToast.ExtraSpace } else { containerViewBottomConstraint?.constant = 0 } UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseInOut, animations: { self.containerView.layoutIfNeeded() }) { finished in if self.stopAnimation { self.willDisappearToast() } else { self.floatingAnimation() } } } }
mit
3ec6cbb8c08258681bcdfdea7b2e0ce0
47.414141
207
0.677204
5.08758
false
false
false
false
me-abhinav/NumberMorphView
Example/NumberMorphView/ViewController.swift
1
2859
// // ViewController.swift // NumberMorphView // // Created by Abhinav Chauhan on 03/14/2016. // Copyright (c) 2016 Abhinav Chauhan. All rights reserved. // import UIKit import NumberMorphView class ViewController: UIViewController { @IBOutlet weak var h0: NumberMorphView! @IBOutlet weak var h1: NumberMorphView! @IBOutlet weak var m0: NumberMorphView! @IBOutlet weak var m1: NumberMorphView! @IBOutlet weak var s0: NumberMorphView! @IBOutlet weak var s1: NumberMorphView! @IBOutlet weak var n1: NumberMorphView! @IBOutlet weak var n2: NumberMorphView! @IBOutlet weak var n3: NumberMorphView! @IBOutlet weak var n4: NumberMorphView! @IBOutlet weak var n5: NumberMorphView! @IBOutlet weak var n6: NumberMorphView! var digit = 0; override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated); Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.updateTime), userInfo: nil, repeats: true); n1.interpolator = NumberMorphView.LinearInterpolator(); n2.interpolator = NumberMorphView.OvershootInterpolator(); n3.interpolator = NumberMorphView.SpringInterpolator(); n4.interpolator = NumberMorphView.BounceInterpolator(); n5.interpolator = NumberMorphView.AnticipateOvershootInterpolator(); n6.interpolator = NumberMorphView.CubicHermiteInterpolator(); } @objc func updateTime() { let date = Date(); let components = Calendar(identifier: .gregorian).dateComponents([.hour, .minute, .second], from: date); var hour = components.hour ?? 0; let minute = components.minute ?? 0; let second = components.second ?? 0; if hour > 12 { hour -= 12; } if hour / 10 != h1.currentDigit || h1.currentDigit == 0 { h1.nextDigit = hour / 10; } if hour % 10 != h0.currentDigit || h0.currentDigit == 0 { h0.nextDigit = hour % 10; } if minute / 10 != m1.currentDigit || m1.currentDigit == 0 { m1.nextDigit = minute / 10; } if minute % 10 != m0.currentDigit || m0.currentDigit == 0 { m0.nextDigit = minute % 10; } if second / 10 != s1.currentDigit || s1.currentDigit == 0 { s1.nextDigit = second / 10; } if second % 10 != s0.currentDigit || s0.currentDigit == 0 { s0.nextDigit = second % 10; } n1.nextDigit = digit; n2.nextDigit = digit; n3.nextDigit = digit; n4.nextDigit = digit; n5.nextDigit = digit; n6.nextDigit = digit; digit = (digit + 1) % 10; } }
mit
1c2b38bddd327979b90d792163ee43f9
31.488636
138
0.603708
3.954357
false
false
false
false
josve05a/wikipedia-ios
Wikipedia/Code/InsertMediaViewController.swift
1
16281
protocol InsertMediaViewControllerDelegate: AnyObject { func insertMediaViewController(_ insertMediaViewController: InsertMediaViewController, didTapCloseButton button: UIBarButtonItem) func insertMediaViewController(_ insertMediaViewController: InsertMediaViewController, didPrepareWikitextToInsert wikitext: String) } final class InsertMediaViewController: ViewController { private let selectedImageViewController = InsertMediaSelectedImageViewController() private let searchViewController: InsertMediaSearchViewController private let searchResultsCollectionViewController = InsertMediaSearchResultsCollectionViewController() weak var delegate: InsertMediaViewControllerDelegate? init(articleTitle: String?, siteURL: URL?) { searchViewController = InsertMediaSearchViewController(articleTitle: articleTitle, siteURL: siteURL) searchResultsCollectionViewController.delegate = selectedImageViewController super.init() selectedImageViewController.delegate = self searchViewController.progressController = FakeProgressController(progress: navigationBar, delegate: navigationBar) searchViewController.delegate = self searchViewController.searchBarDelegate = self searchResultsCollectionViewController.scrollDelegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var closeButton: UIBarButtonItem = { let closeButton = UIBarButtonItem.wmf_buttonType(.X, target: self, action: #selector(delegateCloseButtonTap(_:))) closeButton.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel return closeButton }() private lazy var nextButton: UIBarButtonItem = { let nextButton = UIBarButtonItem(title: CommonStrings.nextTitle, style: .done, target: self, action: #selector(goToMediaSettings(_:))) nextButton.isEnabled = false return nextButton }() override func viewDidLoad() { super.viewDidLoad() navigationController?.isNavigationBarHidden = true title = CommonStrings.insertMediaTitle navigationItem.leftBarButtonItem = closeButton navigationItem.rightBarButtonItem = nextButton navigationItem.backBarButtonItem = UIBarButtonItem(title: CommonStrings.accessibilityBackTitle, style: .plain, target: nil, action: nil) navigationBar.displayType = .modal navigationBar.isBarHidingEnabled = false navigationBar.isUnderBarViewHidingEnabled = true navigationBar.isExtendedViewHidingEnabled = true navigationBar.isTopSpacingHidingEnabled = false addChild(selectedImageViewController) navigationBar.addUnderNavigationBarView(selectedImageViewController.view) selectedImageViewController.didMove(toParent: self) addChild(searchViewController) navigationBar.addExtendedNavigationBarView(searchViewController.view) searchViewController.didMove(toParent: self) wmf_add(childController: searchResultsCollectionViewController, andConstrainToEdgesOfContainerView: view) additionalSafeAreaInsets = searchResultsCollectionViewController.additionalSafeAreaInsets scrollView = searchResultsCollectionViewController.collectionView } private var selectedImageViewHeightConstraint: NSLayoutConstraint? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if selectedImageViewHeightConstraint == nil { selectedImageViewHeightConstraint = selectedImageViewController.view.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3) selectedImageViewHeightConstraint?.isActive = true } } private var isDisappearing = false override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) isDisappearing = true } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) isDisappearing = false } private var isTransitioningToNewCollection = false override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { isTransitioningToNewCollection = true super.willTransition(to: newCollection, with: coordinator) coordinator.animate(alongsideTransition: { _ in // }) { _ in self.isTransitioningToNewCollection = false } } @objc private func goToMediaSettings(_ sender: UIBarButtonItem) { guard let navigationController = navigationController, let selectedSearchResult = selectedImageViewController.searchResult, let image = selectedImageViewController.image ?? searchResultsCollectionViewController.selectedImage else { assertionFailure("Selected image and search result should be set by now") return } let settingsViewController = InsertMediaSettingsViewController(image: image, searchResult: selectedSearchResult) settingsViewController.title = WMFLocalizedString("insert-media-media-settings-title", value: "Media settings", comment: "Title for media settings view") let insertButton = UIBarButtonItem(title: WMFLocalizedString("insert-action-title", value: "Insert", comment: "Title for insert action"), style: .done, target: self, action: #selector(insertMedia(_:))) insertButton.tintColor = theme.colors.link settingsViewController.navigationItem.rightBarButtonItem = insertButton settingsViewController.apply(theme: theme) navigationController.pushViewController(settingsViewController, animated: true) } @objc private func insertMedia(_ sender: UIBarButtonItem) { guard let mediaSettingsTableViewController = navigationController?.topViewController as? InsertMediaSettingsViewController else { assertionFailure() return } let searchResult = mediaSettingsTableViewController.searchResult let wikitext: String switch mediaSettingsTableViewController.settings { case nil: wikitext = "[[\(searchResult.fileTitle)]]" case let mediaSettings?: switch (mediaSettings.caption, mediaSettings.alternativeText) { case (let caption?, let alternativeText?): wikitext = """ [[\(searchResult.fileTitle) | \(mediaSettings.advanced.imageType.rawValue) | \(mediaSettings.advanced.imageSize.rawValue) | \(mediaSettings.advanced.imagePosition.rawValue) | alt= \(alternativeText) | \(caption)]] """ case (let caption?, nil): wikitext = """ [[\(searchResult.fileTitle) | \(mediaSettings.advanced.imageType.rawValue) | \(mediaSettings.advanced.imageSize.rawValue) | \(mediaSettings.advanced.imagePosition.rawValue) | \(caption)]] """ case (nil, let alternativeText?): wikitext = """ [[\(searchResult.fileTitle) | \(mediaSettings.advanced.imageType.rawValue) | \(mediaSettings.advanced.imageSize.rawValue) | \(mediaSettings.advanced.imagePosition.rawValue) | alt= \(alternativeText)]] """ default: wikitext = """ [[\(searchResult.fileTitle) | \(mediaSettings.advanced.imageType.rawValue) | \(mediaSettings.advanced.imageSize.rawValue) | \(mediaSettings.advanced.imagePosition.rawValue)]] """ } } delegate?.insertMediaViewController(self, didPrepareWikitextToInsert: wikitext) } @objc private func delegateCloseButtonTap(_ sender: UIBarButtonItem) { delegate?.insertMediaViewController(self, didTapCloseButton: sender) } override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } selectedImageViewController.apply(theme: theme) searchViewController.apply(theme: theme) searchResultsCollectionViewController.apply(theme: theme) closeButton.tintColor = theme.colors.primaryText nextButton.tintColor = theme.colors.link } override func scrollViewInsetsDidChange() { super.scrollViewInsetsDidChange() searchResultsCollectionViewController.scrollViewInsetsDidChange() } override func keyboardDidChangeFrame(from oldKeyboardFrame: CGRect?, newKeyboardFrame: CGRect?) { guard !isAnimatingSearchBarState else { return } super.keyboardDidChangeFrame(from: oldKeyboardFrame, newKeyboardFrame: newKeyboardFrame) } override func accessibilityPerformEscape() -> Bool { delegate?.insertMediaViewController(self, didTapCloseButton: closeButton) return true } var isAnimatingSearchBarState: Bool = false func focusSearch(_ focus: Bool, animated: Bool = true, additionalAnimations: (() -> Void)? = nil) { useNavigationBarVisibleHeightForScrollViewInsets = focus navigationBar.isAdjustingHidingFromContentInsetChangesEnabled = true let completion = { (finished: Bool) in self.isAnimatingSearchBarState = false self.useNavigationBarVisibleHeightForScrollViewInsets = focus } let animations = { let underBarViewPercentHidden: CGFloat let extendedViewPercentHidden: CGFloat if let scrollView = self.scrollView, scrollView.isAtTop, !focus { underBarViewPercentHidden = 0 extendedViewPercentHidden = 0 } else { underBarViewPercentHidden = 1 extendedViewPercentHidden = focus ? 0 : 1 } self.navigationBar.setNavigationBarPercentHidden(0, underBarViewPercentHidden: underBarViewPercentHidden, extendedViewPercentHidden: extendedViewPercentHidden, topSpacingPercentHidden: 0, animated: false) self.searchViewController.searchBar.setShowsCancelButton(focus, animated: animated) additionalAnimations?() self.view.layoutIfNeeded() self.updateScrollViewInsets(preserveAnimation: true) } guard animated else { animations() completion(true) return } isAnimatingSearchBarState = true self.view.layoutIfNeeded() UIView.animate(withDuration: 0.3, animations: animations, completion: completion) } } extension InsertMediaViewController: InsertMediaSearchViewControllerDelegate { func insertMediaSearchViewController(_ insertMediaSearchViewController: InsertMediaSearchViewController, didFind searchResults: [InsertMediaSearchResult]) { searchResultsCollectionViewController.emptyViewType = .noSearchResults searchResultsCollectionViewController.searchResults = searchResults } func insertMediaSearchViewController(_ insertMediaSearchViewController: InsertMediaSearchViewController, didFind imageInfo: MWKImageInfo, for searchResult: InsertMediaSearchResult, at index: Int) { searchResultsCollectionViewController.setImageInfo(imageInfo, for: searchResult, at: index) } func insertMediaSearchViewController(_ insertMediaSearchViewController: InsertMediaSearchViewController, didFailWithError error: Error) { let emptyViewType: WMFEmptyViewType let nserror = error as NSError if nserror.wmf_isNetworkConnectionError() { emptyViewType = .noInternetConnection } else if nserror.domain == NSURLErrorDomain, nserror.code == NSURLErrorCancelled { emptyViewType = .none } else { emptyViewType = .noSearchResults } searchResultsCollectionViewController.emptyViewType = emptyViewType searchResultsCollectionViewController.searchResults = [] } } extension InsertMediaViewController: InsertMediaSelectedImageViewControllerDelegate { func insertMediaSelectedImageViewController(_ insertMediaSelectedImageViewController: InsertMediaSelectedImageViewController, willSetSelectedImageFrom searchResult: InsertMediaSearchResult) { nextButton.isEnabled = false } func insertMediaSelectedImageViewController(_ insertMediaSelectedImageViewController: InsertMediaSelectedImageViewController, didSetSelectedImage selectedImage: UIImage?, from searchResult: InsertMediaSearchResult) { nextButton.isEnabled = true } } extension InsertMediaViewController: InsertMediaSearchResultsCollectionViewControllerScrollDelegate { func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewDidScroll scrollView: UIScrollView) { guard !isAnimatingSearchBarState else { return } scrollViewDidScroll(scrollView) } func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewWillBeginDragging scrollView: UIScrollView) { scrollViewWillBeginDragging(scrollView) } func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewWillEndDragging scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { scrollViewWillEndDragging(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset) } func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewDidEndDecelerating scrollView: UIScrollView) { scrollViewDidEndDecelerating(scrollView) } func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewDidEndScrollingAnimation scrollView: UIScrollView) { scrollViewDidEndScrollingAnimation(scrollView) } func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewShouldScrollToTop scrollView: UIScrollView) -> Bool { return scrollViewShouldScrollToTop(scrollView) } func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewDidScrollToTop scrollView: UIScrollView) { scrollViewDidScrollToTop(scrollView) } } extension InsertMediaViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { searchViewController.search(for: searchText) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { unfocusSearch { searchBar.endEditing(true) } } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { navigationBar.isUnderBarViewHidingEnabled = false navigationBar.isExtendedViewHidingEnabled = false } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { guard !isAnimatingSearchBarState else { return } unfocusSearch { searchBar.endEditing(true) searchBar.text = nil } } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { navigationBar.isUnderBarViewHidingEnabled = true navigationBar.isExtendedViewHidingEnabled = true } func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { guard !isAnimatingSearchBarState else { return false } focusSearch(true) return true } private func unfocusSearch(additionalAnimations: (() -> Void)? = nil) { navigationBar.isUnderBarViewHidingEnabled = true navigationBar.isExtendedViewHidingEnabled = true focusSearch(false, additionalAnimations: additionalAnimations) } }
mit
d0553f61a86d94149fac90e151ebb1a7
47.6
297
0.735274
6.522837
false
false
false
false
marinehero/SwiftGraphics
SwiftGraphics/Quartz/CGPath.swift
2
11269
// // CGPath.swift // SwiftGraphics // // Created by Jonathan Wight on 8/27/14. // Copyright (c) 2014 schwa.io. All rights reserved. // import CoreGraphics public extension CGPathDrawingMode { public init(hasStroke:Bool, hasFill:Bool, evenOdd:Bool = false) { switch (Int(hasStroke), Int(hasFill), Int(evenOdd)) { case (1, 1, 0): self = .FillStroke case (0, 1, 0): self = .Fill case (1, 0, 0): self = .Stroke case (1, 1, 1): self = .EOFillStroke case (0, 1, 1): self = .EOFill default: preconditionFailure("Invalid combination (stroke:\(hasStroke), fill:\(hasFill), evenOdd:\(evenOdd))") } } public init(strokeColor:CGColorRef?, fillColor:CGColorRef?, evenOdd:Bool = false) { let hasStrokeColor = strokeColor != nil && strokeColor!.alpha > 0.0 let hasFillColor = fillColor != nil && fillColor!.alpha > 0.0 self.init(hasStroke: hasStrokeColor, hasFill: hasFillColor, evenOdd: evenOdd) } } public extension CGMutablePath { var currentPoint: CGPoint { return CGPathGetCurrentPoint(self) } func move(point:CGPoint, relative:Bool = false) -> CGMutablePath { if relative { return move(point + currentPoint) } else { CGPathMoveToPoint(self, nil, point.x, point.y) return self } } func close() -> CGMutablePath { CGPathCloseSubpath(self) return self } func addLine(point:CGPoint, relative:Bool = false) -> CGMutablePath { if relative { return addLine(point + currentPoint) } else { CGPathAddLineToPoint(self, nil, point.x, point.y) return self } } func addLines(points:[CGPoint], relative:Bool = false) -> CGMutablePath { for point in points { addLine(point, relative:relative) } return self } func addQuadCurveToPoint(end:CGPoint, control1:CGPoint, relative:Bool = false) -> CGMutablePath { if relative { return addQuadCurveToPoint(end + currentPoint, control1:control1 + currentPoint) } else { CGPathAddQuadCurveToPoint(self, nil, control1.x, control1.y, end.x, end.y) return self } } func addCubicCurveToPoint(end:CGPoint, control1:CGPoint, control2:CGPoint, relative:Bool = false) -> CGMutablePath { if relative { return addCubicCurveToPoint(end + currentPoint, control1:control1 + currentPoint, control2:control2 + currentPoint) } else { CGPathAddCurveToPoint(self, nil, control1.x, control1.y, control2.x, control2.y, end.x, end.y) return self } } func addCurve(curve:BezierCurve, relative:Bool = false) -> CGMutablePath { switch curve.order { case .Quadratic: if let start = curve.start { move(start) } return addQuadCurveToPoint(curve.end, control1:curve.controls[0], relative:relative) case .Cubic: if let start = curve.start { move(start) } return addCubicCurveToPoint(curve.end, control1:curve.controls[0], control2:curve.controls[1], relative:relative) default: assert(false) } return self } } // MARK: Add smooth curve segment whose start tangent is the end tangent of the previous segment public extension CGMutablePath { func addSmoothQuadCurveToPoint(end:CGPoint) -> CGMutablePath { return addQuadCurveToPoint(end, control1: outControlPoint()) } func addSmoothQuadCurveToPoint(end:CGPoint, relative:Bool) -> CGMutablePath { return addQuadCurveToPoint(end, control1: outControlPoint(), relative:relative) } func addSmoothCubicCurveToPoint(end:CGPoint, control2:CGPoint) -> CGMutablePath { return addCubicCurveToPoint(end, control1:outControlPoint(), control2:control2) } func addSmoothCubicCurveToPoint(end:CGPoint, control2:CGPoint, relative:Bool) -> CGMutablePath { return addCubicCurveToPoint(end, control1:outControlPoint(), control2:control2, relative:relative) } private func outControlPoint() -> CGPoint { let n = pointCount return n > 1 ? 2 * currentPoint - getPoint(n - 2)! : currentPoint } } // MARK: Enumerate path elements public extension CGPath { // typealias ElementPtr = UnsafePointer<CGPathElement> // typealias ApplyClosure = ElementPtr -> Void // func apply(var closure:ApplyClosure) { // var info = UnsafeMutablePointer<ApplyClosure> (&closure) // CGPathApply(self, info) { // (info:UnsafeMutablePointer<Void>, elementPtr:ElementPtr) -> Void in // let closure:ApplyClosure = info.memory // closure(elementPtr.memory) // } // } func enumerate(/*@noescape*/ block:(type:CGPathElementType, points:[CGPoint]) -> Void) { var curpt = CGPoint() var start = curpt // TODO: This is limiting noescape CGPathApplyWithBlock(self) { (elementPtr:UnsafePointer<CGPathElement>) -> Void in let element: CGPathElement = elementPtr.memory switch element.type.rawValue { case CGPathElementType.MoveToPoint.rawValue: curpt = element.points.memory start = curpt block(type:CGPathElementType.MoveToPoint, points:[curpt]) case CGPathElementType.AddLineToPoint.rawValue: let points = [curpt, element.points.memory] curpt = points[1] block(type:CGPathElementType.AddLineToPoint, points:points) case CGPathElementType.AddQuadCurveToPoint.rawValue: let cp = element.points.memory let end = element.points.advancedBy(1).memory let points = [curpt, (curpt + 2 * cp) / 3, (end + 2 * cp) / 3, end] block(type:CGPathElementType.AddCurveToPoint, points:points) curpt = end case CGPathElementType.AddCurveToPoint.rawValue: let points = [curpt, element.points.memory, element.points.advancedBy(1).memory, element.points.advancedBy(2).memory] block(type:CGPathElementType.AddCurveToPoint, points:points) curpt = points[3] case CGPathElementType.CloseSubpath.rawValue: block(type:CGPathElementType.CloseSubpath, points:[curpt, start]) default: () } } } func getPoint(index:Int) -> CGPoint? { var pt:CGPoint? var i = 0 enumerate() { (type, points) -> Void in switch type.rawValue { case CGPathElementType.MoveToPoint.rawValue: if index == i++ { pt = points[0] } case CGPathElementType.AddLineToPoint.rawValue: if index == i++ { pt = points[1] } case CGPathElementType.AddCurveToPoint.rawValue: if index >= i && index - i < 3 { pt = points[index - i + 1] } i = i + 3 default: () } } return pt } func dump() { enumerate() { (type:CGPathElementType, points:[CGPoint]) -> Void in switch type.rawValue { case CGPathElementType.MoveToPoint.rawValue: print("kCGPathElementMoveToPoint (\(points[0].x),\(points[0].y))", appendNewline: false) case CGPathElementType.AddLineToPoint.rawValue: print("kCGPathElementAddLineToPoint (\(points[0].x),\(points[0].y))-(\(points[1].x),\(points[1].y))", appendNewline: false) case CGPathElementType.AddCurveToPoint.rawValue: print("kCGPathElementAddCurveToPoint (\(points[0].x),\(points[0].y))-(\(points[1].x),\(points[1].y))" + ", (\(points[2].x),\(points[2].y))-(\(points[3].x),\(points[3].y))", appendNewline: false) case CGPathElementType.CloseSubpath.rawValue: print("kCGPathElementCloseSubpath (\(points[0].x),\(points[0].y))-(\(points[1].x),\(points[1].y))", appendNewline: false) default: assert(false) } } } } // MARK: Bounding box and length public extension CGPath { public var boundingBox: CGRect { return CGPathGetPathBoundingBox(self) } public var length: CGFloat { var ret:CGFloat = 0.0 enumerate() { (type:CGPathElementType, points:[CGPoint]) -> Void in switch type.rawValue { case CGPathElementType.AddLineToPoint.rawValue, CGPathElementType.CloseSubpath.rawValue: ret += points[0].distanceTo(points[1]) case CGPathElementType.AddCurveToPoint.rawValue: ret += BezierCurve(points:points).length default: () } } return ret } } // MARK: Get control points and endpoints of path segments public extension CGPath { var points: [CGPoint] { var ret:[CGPoint] = [] enumerate() { (type, points) -> Void in switch type.rawValue { case CGPathElementType.MoveToPoint.rawValue: ret.append(points[0]) case CGPathElementType.AddLineToPoint.rawValue: ret.append(points[1]) case CGPathElementType.AddCurveToPoint.rawValue: [1, 2, 3].map { ret.append(points[$0]) } default: () } } return ret } var pointCount: Int { var ret = 0 enumerate() { (type, points) -> Void in switch type.rawValue { case CGPathElementType.MoveToPoint.rawValue: ret = ret + 1 case CGPathElementType.AddLineToPoint.rawValue: ret = ret + 1 case CGPathElementType.AddCurveToPoint.rawValue: ret = ret + 3 default: () } } return ret } var isClosed: Bool { var ret = false CGPathApplyWithBlock(self) { (elementPtr) -> Void in if elementPtr.memory.type.rawValue == CGPathElementType.CloseSubpath.rawValue { ret = true } } return ret } } // MARK: End points and tangent vectors public extension CGPath { public var startPoint: CGPoint { return getPoint(0)! } public var endPoint: CGPoint { return getPoint(pointCount - 1)! } public var startTangent: CGPoint { return getPoint(1)! - getPoint(0)! } public var endTangent: CGPoint { let n = pointCount return getPoint(n - 1)! - getPoint(n - 2)! } }
bsd-2-clause
86a57451a64c65b40e176506471201ce
32.739521
139
0.5658
4.679817
false
false
false
false