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
CraigZheng/KomicaViewer
KomicaViewer/KomicaViewer/ViewController/SettingsTableViewController.swift
1
11206
// // SettingsTableViewController.swift // KomicaViewer // // Created by Craig Zheng on 15/12/16. // Copyright © 2016 Craig. All rights reserved. // import UIKit import StoreKit import SwiftMessages import MBProgressHUD class SettingsTableViewController: UITableViewController { fileprivate let cellIdentifier = "cellIdentifier" fileprivate let remoteActionCellIdentifier = "remoteActionCellIdentifier" fileprivate let selectedIndexPathKey = "selectedIndexPathKey" fileprivate let iapRemoveAd = "com.craig.KomicaViewer.removeAdvertisement" fileprivate var lastSectionIndex: Int { return numberOfSections(in: tableView) - 1 } fileprivate var iapProducts: [SKProduct] = [] fileprivate var isDownloading = false fileprivate var overrideLoadingIndicator = true fileprivate enum Section: Int { case settings, remoteActions } override func viewDidLoad() { super.viewDidLoad() let productIdentifiers: Set<ProductIdentifier> = [iapRemoveAd] overrideLoadingIndicator = false showLoading() IAPHelper.sharedInstance.requestProducts(productIdentifiers) { [weak self] (response, error) in DispatchQueue.main.async { self?.hideLoading() self?.overrideLoadingIndicator = true if let response = response, !response.products.isEmpty { // Reload tableView with the newly downloaded product. self?.iapProducts.append(contentsOf: response.products) if let product = self?.iapProducts.first { self?.removeAdCell.textLabel?.text = product.localizedTitle self?.removeAdCell.detailTextLabel?.text = product.localizedPrice() } self?.tableView.reloadData() } } } NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: Configuration.updatedNotification), object: nil, queue: OperationQueue.main) { [weak self] _ in self?.tableView.reloadData() } } override func showLoading() { isDownloading = true if overrideLoadingIndicator { // Show on the highest level, block all user interactions. MBProgressHUD.showAdded(to: self.navigationController?.view ?? self.view, animated: true) } else { super.showLoading() } } override func hideLoading() { isDownloading = false MBProgressHUD.hideAllHUDs(for: self.navigationController?.view ?? self.view, animated: true) super.hideLoading() } // MARK: - UI elements. @IBOutlet weak var showImageSwitch: UISwitch! { didSet { showImageSwitch.setOn(Configuration.singleton.showImage, animated: false) } } @IBOutlet weak var removeAdCell: UITableViewCell! @IBOutlet weak var restorePurchaseCell: UITableViewCell! @IBOutlet weak var noAdvertisementCell: UITableViewCell! // MARK: - UI actions. @IBAction func showImageSwitchAction(_ sender: AnyObject) { Configuration.singleton.showImage = showImageSwitch.isOn } // MARK: - Table view data source override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch Section(rawValue: indexPath.section)! { case .settings: // When IAP product is empty or the product is already purchased, don't show the removeAdCell and restorePurchaseCell. let cell = super.tableView(tableView, cellForRowAt: indexPath) switch cell { case restorePurchaseCell, removeAdCell: return iapProducts.isEmpty || AdConfiguration.singleton.isAdRemovePurchased ? 0 : UITableViewAutomaticDimension case noAdvertisementCell: return AdConfiguration.singleton.isAdRemovePurchased ? UITableViewAutomaticDimension : 0 default: return UITableViewAutomaticDimension } case .remoteActions: return CGFloat(Configuration.singleton.remoteActions.count * 44) + 20 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch Section(rawValue: indexPath.section)! { case .settings: // TODO: settings. return super.tableView(tableView, cellForRowAt: indexPath) case .remoteActions: let cell = super.tableView(tableView, cellForRowAt: indexPath) cell.textLabel?.text = "App Version: " + Configuration.bundleVersion return cell } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // When the app is performing network task, don't interrupt. if isDownloading { return } // Remote action section. if indexPath.section == lastSectionIndex, let urlString = Configuration.singleton.remoteActions[indexPath.row].values.first, let url = URL(string: urlString) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } } else { if let cell = tableView.cellForRow(at: indexPath) { switch cell { case removeAdCell: // Initiate purchasing. if let product = self.iapProducts.first { showLoading() IAPHelper.sharedInstance.purchaseProduct(product.productIdentifier) { [weak self] (purchasedIdentifier, error) in if let purchasedIdentifier = purchasedIdentifier, !purchasedIdentifier.isEmpty { // Inform success. AdConfiguration.singleton.isAdRemovePurchased = true self?.tableView.reloadData() MessagePopup.showMessage(title: "Payment Made", message: "You've acquired this item: \(product.localizedTitle)", layout: .cardView, theme: .success, position: .bottom, buttonTitle: "OK", buttonActionHandler: { _ in SwiftMessages.hide() }) } else { self?.handle(error) } self?.hideLoading() } } break case restorePurchaseCell: // Restore purchase. if let product = self.iapProducts.first { showLoading() IAPHelper.sharedInstance.restorePurchases({ [weak self] (productIdentifiers, error) in self?.hideLoading() if productIdentifiers.contains(product.productIdentifier) { // Restoration successful. AdConfiguration.singleton.isAdRemovePurchased = true self?.tableView.reloadData() MessagePopup.showMessage(title: "Restoration Successful", message: "You've acquired this item: \(product.localizedTitle)", layout: .cardView, theme: .success, position: .bottom, buttonTitle: "OK", buttonActionHandler: { _ in SwiftMessages.hide() }) } else if let error = error { self?.handle(error) } else { // Network transaction was successful, but no purchase is recorded. MessagePopup.showMessage(title: "Failed To Restore", message: "There is no previous payment made by this account, please verify your account and try again.", layout: .cardView, theme: .error, position: .bottom, buttonTitle: "OK", buttonActionHandler: { _ in SwiftMessages.hide() }) } }) } break default: break } } } } private func handle(_ error: Error?) { if let error = error as? NSError, let errorCode = SKError.Code(rawValue: error.code) { // If user cancels the transaction, no need to display any error. var message: String? switch errorCode { case .paymentCancelled: message = nil default: message = error.localizedFailureReason ?? error.localizedDescription } if let message = message, !message.isEmpty { MessagePopup.showMessage(title: "Failed To Purchase", message: "Cannot make a payment due to the following reason: \n\(message)", layout: .cardView, theme: .error, position: .bottom, buttonTitle: "OK", buttonActionHandler: { _ in SwiftMessages.hide() }) } } else { // Generic error. MessagePopup.showMessage(title: "Failed To Connect", message: "The connection to the server seems to be broken, please try again later.", layout: .cardView, theme: .error, position: .bottom, buttonTitle: "OK", buttonActionHandler: { _ in SwiftMessages.hide() }) } } }
mit
132a06b618f9fb0a2e4bae654433d3d1
44.922131
161
0.498081
6.552632
false
false
false
false
erprashantrastogi/iPadCustomKeyboard
Keyboard/Helper/CircularArray.swift
2
1275
// // CircularArray.swift // ELDeveloperKeyboard // // Created by Eric Lin on 2014-07-02. // Copyright (c) 2016 Kari Kraam. All rights reserved. // /** A circular array that can be cycled through. */ class CircularArray<T> { // MARK: Properties private let items: [T] private lazy var index = 0 var currentItem: T? { if items.count == 0 { return nil } return items[index] } var nextItem: T? { if items.count == 0 { return nil } return index + 1 == items.count ? items[0] : items[index + 1] } var previousItem: T? { if items.count == 0 { return nil } return index == 0 ? items[items.count - 1] : items[index - 1] } // MARK: Constructors init(items: [T]) { self.items = items } // MARK: Methods func increment() { if items.count > 0 { index += 1 if index == items.count { index = 0 } } } func decrement() { if items.count > 0 { index -= 1 if index < 0 { index = items.count - 1 } } } }
apache-2.0
6d934627403629d958e9189620bb92e8
18.333333
69
0.449412
4.13961
false
false
false
false
KevinYangGit/DYTV
DYZB/DYZB/Classes/Main/Controller/CustomNavigationController.swift
1
1134
// // CustomNavigationController.swift // DYZB // // Created by boxfishedu on 2016/10/22. // Copyright © 2016年 杨琦. All rights reserved. // import UIKit class CustomNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() guard let systemGes = interactivePopGestureRecognizer else { return } guard let v = systemGes.view else { return } let targets = systemGes.value(forKey: "_targets") as? [NSObject] guard let targetObjc = targets?.first else { return } guard let target = targetObjc.value(forKey: "target") else { return } let action = Selector(("handleNavigationTransition:")) let panGes = UIPanGestureRecognizer() v.addGestureRecognizer(panGes) panGes.addTarget(target, action: action) } override func pushViewController(_ viewController: UIViewController, animated: Bool) { viewController.hidesBottomBarWhenPushed = true super.pushViewController(viewController, animated: animated) } }
mit
b826d1d2dc38b647adc156b7febb974a
28.657895
90
0.64685
5.29108
false
false
false
false
ALiOSDev/ALTableView
ALTableViewSwift/ALTableView/ALTableView/ALTableViewClasses/Elements/Row/ALRowElement.swift
1
4028
// // RowElement.swift // ALTableView // // Created by lorenzo villarroel perez on 7/3/18. // Copyright © 2018 lorenzo villarroel perez. All rights reserved. // import UIKit public typealias ALCellPressedHandler = (UIViewController?, UITableViewCell) -> Void public typealias ALCellCreatedHandler = (Any?, UITableViewCell) -> Void public typealias ALCellDeselectedHandler = (UITableViewCell) -> Void //Implemented by ALRowElement public protocol ALRowElementProtocol { func rowElementPressed(viewController: UIViewController?, cell: UITableViewCell) func rowElementDeselected(cell: UITableViewCell) } //Implemented by UITableViewCell public protocol ALCellProtocol { func cellPressed (viewController: UIViewController?) -> Void func cellDeselected () -> Void func cellCreated(dataObject: Any?) -> Void } extension ALCellProtocol { public func cellPressed (viewController: UIViewController?) -> Void { } public func cellDeselected () -> Void { } public func cellCreated(dataObject: Any?) -> Void { print("ALCellProtocol") } } public class ALRowElement: ALElement, ALRowElementProtocol { //MARK: - Properties private var className: AnyClass //TODO es posible que el className no sea necesario private let cellStyle: UITableViewCell.CellStyle internal var editingAllowed: Bool private var pressedHandler: ALCellPressedHandler? private var createdHandler: ALCellCreatedHandler? private var deselectedHandler: ALCellDeselectedHandler? //MARK: - Initializers public init(className: AnyClass, identifier: String, dataObject: Any?, cellStyle: UITableViewCell.CellStyle = .default, estimateHeightMode: Bool = false, height: CGFloat = 44.0, editingAllowed: Bool = false, pressedHandler: ALCellPressedHandler? = nil, createdHandler: ALCellCreatedHandler? = nil, deselectedHandler: ALCellDeselectedHandler? = nil) { self.className = className self.cellStyle = cellStyle self.editingAllowed = editingAllowed self.pressedHandler = pressedHandler self.createdHandler = createdHandler self.deselectedHandler = deselectedHandler super.init(identifier: identifier, dataObject: dataObject, estimateHeightMode: estimateHeightMode, height: height) } //MARK: - Getters internal func getViewFrom(tableView: UITableView) -> UITableViewCell { guard let dequeuedElement: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: self.identifier) else { return UITableViewCell() } if let alCell = dequeuedElement as? ALCellProtocol { object_setClass(alCell, self.className) alCell.cellCreated(dataObject: self.dataObject) } if let handler:ALCellCreatedHandler = self.createdHandler { handler(self.dataObject, dequeuedElement) } return dequeuedElement } //MARK: - Setters internal func setCellHeight(height: CGFloat) -> Void { self.height = height } //MARK: - ALRowElementProtocol public func rowElementPressed(viewController: UIViewController?, cell: UITableViewCell) { if let cell: ALCellProtocol = cell as? ALCellProtocol { cell.cellPressed(viewController: viewController) } if let handler:ALCellPressedHandler = self.pressedHandler { handler(viewController, cell) } } public func rowElementDeselected(cell: UITableViewCell) { if let cell: ALCellProtocol = cell as? ALCellProtocol { cell.cellDeselected() } if let handler: ALCellDeselectedHandler = self.deselectedHandler { handler(cell) } } }
mit
0f69720423c0313f5173509f903ac7b3
24.649682
122
0.654582
5.1169
false
false
false
false
abbeycode/Carthage
Source/carthage/Build.swift
1
8740
// // Build.swift // Carthage // // Created by Justin Spahr-Summers on 2014-10-11. // Copyright (c) 2014 Carthage. All rights reserved. // import Box import CarthageKit import Commandant import Foundation import Result import ReactiveCocoa import ReactiveTask public struct BuildCommand: CommandType { public let verb = "build" public let function = "Build the project's dependencies" public func run(mode: CommandMode) -> Result<(), CommandantError<CarthageError>> { return producerWithOptions(BuildOptions.evaluate(mode)) |> flatMap(.Merge) { options in return self.buildWithOptions(options) |> promoteErrors } |> waitOnCommand } /// Builds a project with the given options. public func buildWithOptions(options: BuildOptions) -> SignalProducer<(), CarthageError> { return self.openLoggingHandle(options) |> flatMap(.Merge) { (stdoutHandle, temporaryURL) -> SignalProducer<(), CarthageError> in let directoryURL = NSURL.fileURLWithPath(options.directoryPath, isDirectory: true)! var buildProgress = self.buildProjectInDirectoryURL(directoryURL, options: options) |> flatten(.Concat) let stderrHandle = NSFileHandle.fileHandleWithStandardError() // Redirect any error-looking messages from stdout, because // Xcode doesn't always forward them. if !options.verbose { let (stdoutProducer, stdoutSink) = SignalProducer<NSData, NoError>.buffer(0) let grepTask: BuildSchemeProducer = launchTask(TaskDescription(launchPath: "/usr/bin/grep", arguments: [ "--extended-regexp", "(warning|error|failed):" ], standardInput: stdoutProducer)) |> on(next: { taskEvent in switch taskEvent { case let .StandardOutput(data): stderrHandle.writeData(data) default: break } }) |> catch { _ in .empty } |> then(.empty) |> promoteErrors(CarthageError.self) buildProgress = buildProgress |> on(next: { taskEvent in switch taskEvent { case let .StandardOutput(data): sendNext(stdoutSink, data) default: break } }, terminated: { sendCompleted(stdoutSink) }, interrupted: { sendInterrupted(stdoutSink) }) buildProgress = SignalProducer(values: [ grepTask, buildProgress ]) |> flatten(.Merge) } let formatting = options.colorOptions.formatting return buildProgress |> on(started: { if let temporaryURL = temporaryURL { carthage.println(formatting.bullets + "xcodebuild output can be found in " + formatting.path(string: temporaryURL.path!)) } }, next: { taskEvent in switch taskEvent { case let .StandardOutput(data): stdoutHandle.writeData(data) case let .StandardError(data): stderrHandle.writeData(data) case let .Success(box): let (project, scheme) = box.value carthage.println(formatting.bullets + "Building scheme " + formatting.quote(scheme) + " in " + formatting.projectName(string: project.description)) } }) |> then(.empty) } } /// Builds the project in the given directory, using the given options. /// /// Returns a producer of producers, representing each scheme being built. private func buildProjectInDirectoryURL(directoryURL: NSURL, options: BuildOptions) -> SignalProducer<BuildSchemeProducer, CarthageError> { let project = Project(directoryURL: directoryURL) let buildProducer = project.loadCombinedCartfile() |> map { _ in project } |> catch { error in if options.skipCurrent { return SignalProducer(error: error) } else { // Ignore Cartfile loading failures. Assume the user just // wants to build the enclosing project. return .empty } } |> flatMap(.Merge) { project in return project.migrateIfNecessary(options.colorOptions) |> on(next: carthage.println) |> then(SignalProducer(value: project)) } |> flatMap(.Merge) { project in return project.buildCheckedOutDependenciesWithConfiguration(options.configuration, forPlatform: options.buildPlatform.platform) } if options.skipCurrent { return buildProducer } else { let currentProducers = buildInDirectory(directoryURL, withConfiguration: options.configuration, platform: options.buildPlatform.platform) return buildProducer |> concat(currentProducers) } } /// Opens a temporary file on disk, returning a handle and the URL to the /// file. private func openTemporaryFile() -> SignalProducer<(NSFileHandle, NSURL), NSError> { return SignalProducer.try { var temporaryDirectoryTemplate: ContiguousArray<CChar> = NSTemporaryDirectory().stringByAppendingPathComponent("carthage-xcodebuild.XXXXXX.log").nulTerminatedUTF8.map { CChar($0) } let logFD = temporaryDirectoryTemplate.withUnsafeMutableBufferPointer { (inout template: UnsafeMutableBufferPointer<CChar>) -> Int32 in return mkstemps(template.baseAddress, 4) } if logFD < 0 { return .failure(NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil)) } let temporaryPath = temporaryDirectoryTemplate.withUnsafeBufferPointer { (ptr: UnsafeBufferPointer<CChar>) -> String in return String.fromCString(ptr.baseAddress)! } let handle = NSFileHandle(fileDescriptor: logFD, closeOnDealloc: true) let fileURL = NSURL.fileURLWithPath(temporaryPath, isDirectory: false)! return .success((handle, fileURL)) } } /// Opens a file handle for logging, returning the handle and the URL to any /// temporary file on disk. private func openLoggingHandle(options: BuildOptions) -> SignalProducer<(NSFileHandle, NSURL?), CarthageError> { if options.verbose { let out: (NSFileHandle, NSURL?) = (NSFileHandle.fileHandleWithStandardOutput(), nil) return SignalProducer(value: out) } else { return openTemporaryFile() |> map { handle, URL in (handle, .Some(URL)) } |> mapError { error in let temporaryDirectoryURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)! return .WriteFailed(temporaryDirectoryURL, error) } } } } public struct BuildOptions: OptionsType { public let configuration: String public let buildPlatform: BuildPlatform public let skipCurrent: Bool public let colorOptions: ColorOptions public let verbose: Bool public let directoryPath: String public static func create(configuration: String)(buildPlatform: BuildPlatform)(skipCurrent: Bool)(colorOptions: ColorOptions)(verbose: Bool)(directoryPath: String) -> BuildOptions { return self(configuration: configuration, buildPlatform: buildPlatform, skipCurrent: skipCurrent, colorOptions: colorOptions, verbose: verbose, directoryPath: directoryPath) } public static func evaluate(m: CommandMode) -> Result<BuildOptions, CommandantError<CarthageError>> { return create <*> m <| Option(key: "configuration", defaultValue: "Release", usage: "the Xcode configuration to build") <*> m <| Option(key: "platform", defaultValue: .All, usage: "the platform to build for (one of ‘all’, ‘Mac’, or ‘iOS’)") <*> m <| Option(key: "skip-current", defaultValue: true, usage: "don't skip building the Carthage project (in addition to its dependencies)") <*> ColorOptions.evaluate(m) <*> m <| Option(key: "verbose", defaultValue: false, usage: "print xcodebuild output inline") <*> m <| Option(defaultValue: NSFileManager.defaultManager().currentDirectoryPath, usage: "the directory containing the Carthage project") } } /// Represents the user’s chosen platform to build for. public enum BuildPlatform { /// Build for all available platforms. case All /// Build only for iOS. case iOS /// Build only for OS X. case Mac /// Build only for watchOS. case watchOS /// The `Platform` corresponding to this setting. public var platform: Platform? { switch self { case .All: return nil case .iOS: return .iOS case .Mac: return .Mac case .watchOS: return .watchOS } } } extension BuildPlatform: Printable { public var description: String { switch self { case .All: return "all" case .iOS: return "iOS" case .Mac: return "Mac" case .watchOS: return "watchOS" } } } extension BuildPlatform: ArgumentType { public static let name = "platform" private static let acceptedStrings: [String: BuildPlatform] = [ "Mac": .Mac, "macosx": .Mac, "iOS": .iOS, "iphoneos": .iOS, "iphonesimulator": .iOS, "watchOS": .watchOS, "watchsimulator": .watchOS, "all": .All ] public static func fromString(string: String) -> BuildPlatform? { for (key, platform) in acceptedStrings { if string.caseInsensitiveCompare(key) == NSComparisonResult.OrderedSame { return platform } } return nil } }
mit
0ccdc2dfae6130904511d4400fb9fa9b
31.681648
191
0.707541
4.068065
false
false
false
false
AnRanScheme/magiGlobe
magi/magiGlobe/Pods/SQLite.swift/Sources/SQLite/Typed/Query.swift
25
36369
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // public protocol QueryType : Expressible { var clauses: QueryClauses { get set } init(_ name: String, database: String?) } public protocol SchemaType : QueryType { static var identifier: String { get } } extension SchemaType { /// Builds a copy of the query with the `SELECT` clause applied. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let email = Expression<String>("email") /// /// users.select(id, email) /// // SELECT "id", "email" FROM "users" /// /// - Parameter all: A list of expressions to select. /// /// - Returns: A query with the given `SELECT` clause applied. public func select(_ column1: Expressible, _ more: Expressible...) -> Self { return select(false, [column1] + more) } /// Builds a copy of the query with the `SELECT DISTINCT` clause applied. /// /// let users = Table("users") /// let email = Expression<String>("email") /// /// users.select(distinct: email) /// // SELECT DISTINCT "email" FROM "users" /// /// - Parameter columns: A list of expressions to select. /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select(distinct column1: Expressible, _ more: Expressible...) -> Self { return select(true, [column1] + more) } /// Builds a copy of the query with the `SELECT` clause applied. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let email = Expression<String>("email") /// /// users.select([id, email]) /// // SELECT "id", "email" FROM "users" /// /// - Parameter all: A list of expressions to select. /// /// - Returns: A query with the given `SELECT` clause applied. public func select(_ all: [Expressible]) -> Self { return select(false, all) } /// Builds a copy of the query with the `SELECT DISTINCT` clause applied. /// /// let users = Table("users") /// let email = Expression<String>("email") /// /// users.select(distinct: [email]) /// // SELECT DISTINCT "email" FROM "users" /// /// - Parameter columns: A list of expressions to select. /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select(distinct columns: [Expressible]) -> Self { return select(true, columns) } /// Builds a copy of the query with the `SELECT *` clause applied. /// /// let users = Table("users") /// /// users.select(*) /// // SELECT * FROM "users" /// /// - Parameter star: A star literal. /// /// - Returns: A query with the given `SELECT *` clause applied. public func select(_ star: Star) -> Self { return select([star(nil, nil)]) } /// Builds a copy of the query with the `SELECT DISTINCT *` clause applied. /// /// let users = Table("users") /// /// users.select(distinct: *) /// // SELECT DISTINCT * FROM "users" /// /// - Parameter star: A star literal. /// /// - Returns: A query with the given `SELECT DISTINCT *` clause applied. public func select(distinct star: Star) -> Self { return select(distinct: [star(nil, nil)]) } /// Builds a scalar copy of the query with the `SELECT` clause applied. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// /// users.select(id) /// // SELECT "id" FROM "users" /// /// - Parameter all: A list of expressions to select. /// /// - Returns: A query with the given `SELECT` clause applied. public func select<V : Value>(_ column: Expression<V>) -> ScalarQuery<V> { return select(false, [column]) } public func select<V : Value>(_ column: Expression<V?>) -> ScalarQuery<V?> { return select(false, [column]) } /// Builds a scalar copy of the query with the `SELECT DISTINCT` clause /// applied. /// /// let users = Table("users") /// let email = Expression<String>("email") /// /// users.select(distinct: email) /// // SELECT DISTINCT "email" FROM "users" /// /// - Parameter column: A list of expressions to select. /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select<V : Value>(distinct column: Expression<V>) -> ScalarQuery<V> { return select(true, [column]) } public func select<V : Value>(distinct column: Expression<V?>) -> ScalarQuery<V?> { return select(true, [column]) } public var count: ScalarQuery<Int> { return select(Expression.count(*)) } } extension QueryType { fileprivate func select<Q : QueryType>(_ distinct: Bool, _ columns: [Expressible]) -> Q { var query = Q.init(clauses.from.name, database: clauses.from.database) query.clauses = clauses query.clauses.select = (distinct, columns) return query } // MARK: JOIN /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64>("user_id") /// /// users.join(posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ table: QueryType, on condition: Expression<Bool>) -> Self { return join(table, on: Expression<Bool?>(condition)) } /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64?>("user_id") /// /// users.join(posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ table: QueryType, on condition: Expression<Bool?>) -> Self { return join(.inner, table, on: condition) } /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64>("user_id") /// /// users.join(.LeftOuter, posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - type: The `JOIN` operator. /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ type: JoinType, _ table: QueryType, on condition: Expression<Bool>) -> Self { return join(type, table, on: Expression<Bool?>(condition)) } /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64?>("user_id") /// /// users.join(.LeftOuter, posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - type: The `JOIN` operator. /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ type: JoinType, _ table: QueryType, on condition: Expression<Bool?>) -> Self { var query = self query.clauses.join.append((type: type, query: table, condition: table.clauses.filters.map { condition && $0 } ?? condition as Expressible)) return query } // MARK: WHERE /// Adds a condition to the query’s `WHERE` clause. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// /// users.filter(id == 1) /// // SELECT * FROM "users" WHERE ("id" = 1) /// /// - Parameter condition: A boolean expression to filter on. /// /// - Returns: A query with the given `WHERE` clause applied. public func filter(_ predicate: Expression<Bool>) -> Self { return filter(Expression<Bool?>(predicate)) } /// Adds a condition to the query’s `WHERE` clause. /// /// let users = Table("users") /// let age = Expression<Int?>("age") /// /// users.filter(age >= 35) /// // SELECT * FROM "users" WHERE ("age" >= 35) /// /// - Parameter condition: A boolean expression to filter on. /// /// - Returns: A query with the given `WHERE` clause applied. public func filter(_ predicate: Expression<Bool?>) -> Self { var query = self query.clauses.filters = query.clauses.filters.map { $0 && predicate } ?? predicate return query } /// Adds a condition to the query’s `WHERE` clause. /// This is an alias for `filter(predicate)` public func `where`(_ predicate: Expression<Bool>) -> Self { return `where`(Expression<Bool?>(predicate)) } /// Adds a condition to the query’s `WHERE` clause. /// This is an alias for `filter(predicate)` public func `where`(_ predicate: Expression<Bool?>) -> Self { return filter(predicate) } // MARK: GROUP BY /// Sets a `GROUP BY` clause on the query. /// /// - Parameter by: A list of columns to group by. /// /// - Returns: A query with the given `GROUP BY` clause applied. public func group(_ by: Expressible...) -> Self { return group(by) } /// Sets a `GROUP BY` clause on the query. /// /// - Parameter by: A list of columns to group by. /// /// - Returns: A query with the given `GROUP BY` clause applied. public func group(_ by: [Expressible]) -> Self { return group(by, nil) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A column to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: Expressible, having: Expression<Bool>) -> Self { return group([by], having: having) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A column to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: Expressible, having: Expression<Bool?>) -> Self { return group([by], having: having) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A list of columns to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: [Expressible], having: Expression<Bool>) -> Self { return group(by, Expression<Bool?>(having)) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A list of columns to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: [Expressible], having: Expression<Bool?>) -> Self { return group(by, having) } fileprivate func group(_ by: [Expressible], _ having: Expression<Bool?>?) -> Self { var query = self query.clauses.group = (by, having) return query } // MARK: ORDER BY /// Sets an `ORDER BY` clause on the query. /// /// let users = Table("users") /// let email = Expression<String>("email") /// let name = Expression<String?>("name") /// /// users.order(email.desc, name.asc) /// // SELECT * FROM "users" ORDER BY "email" DESC, "name" ASC /// /// - Parameter by: An ordered list of columns and directions to sort by. /// /// - Returns: A query with the given `ORDER BY` clause applied. public func order(_ by: Expressible...) -> Self { return order(by) } /// Sets an `ORDER BY` clause on the query. /// /// let users = Table("users") /// let email = Expression<String>("email") /// let name = Expression<String?>("name") /// /// users.order([email.desc, name.asc]) /// // SELECT * FROM "users" ORDER BY "email" DESC, "name" ASC /// /// - Parameter by: An ordered list of columns and directions to sort by. /// /// - Returns: A query with the given `ORDER BY` clause applied. public func order(_ by: [Expressible]) -> Self { var query = self query.clauses.order = by return query } // MARK: LIMIT/OFFSET /// Sets the LIMIT clause (and resets any OFFSET clause) on the query. /// /// let users = Table("users") /// /// users.limit(20) /// // SELECT * FROM "users" LIMIT 20 /// /// - Parameter length: The maximum number of rows to return (or `nil` to /// return unlimited rows). /// /// - Returns: A query with the given LIMIT clause applied. public func limit(_ length: Int?) -> Self { return limit(length, nil) } /// Sets LIMIT and OFFSET clauses on the query. /// /// let users = Table("users") /// /// users.limit(20, offset: 20) /// // SELECT * FROM "users" LIMIT 20 OFFSET 20 /// /// - Parameters: /// /// - length: The maximum number of rows to return. /// /// - offset: The number of rows to skip. /// /// - Returns: A query with the given LIMIT and OFFSET clauses applied. public func limit(_ length: Int, offset: Int) -> Self { return limit(length, offset) } // prevents limit(nil, offset: 5) fileprivate func limit(_ length: Int?, _ offset: Int?) -> Self { var query = self query.clauses.limit = length.map { ($0, offset) } return query } // MARK: - Clauses // // MARK: SELECT // MARK: - fileprivate var selectClause: Expressible { return " ".join([ Expression<Void>(literal: clauses.select.distinct ? "SELECT DISTINCT" : "SELECT"), ", ".join(clauses.select.columns), Expression<Void>(literal: "FROM"), tableName(alias: true) ]) } fileprivate var joinClause: Expressible? { guard !clauses.join.isEmpty else { return nil } return " ".join(clauses.join.map { type, query, condition in " ".join([ Expression<Void>(literal: "\(type.rawValue) JOIN"), query.tableName(alias: true), Expression<Void>(literal: "ON"), condition ]) }) } fileprivate var whereClause: Expressible? { guard let filters = clauses.filters else { return nil } return " ".join([ Expression<Void>(literal: "WHERE"), filters ]) } fileprivate var groupByClause: Expressible? { guard let group = clauses.group else { return nil } let groupByClause = " ".join([ Expression<Void>(literal: "GROUP BY"), ", ".join(group.by) ]) guard let having = group.having else { return groupByClause } return " ".join([ groupByClause, " ".join([ Expression<Void>(literal: "HAVING"), having ]) ]) } fileprivate var orderClause: Expressible? { guard !clauses.order.isEmpty else { return nil } return " ".join([ Expression<Void>(literal: "ORDER BY"), ", ".join(clauses.order) ]) } fileprivate var limitOffsetClause: Expressible? { guard let limit = clauses.limit else { return nil } let limitClause = Expression<Void>(literal: "LIMIT \(limit.length)") guard let offset = limit.offset else { return limitClause } return " ".join([ limitClause, Expression<Void>(literal: "OFFSET \(offset)") ]) } // MARK: - public func alias(_ aliasName: String) -> Self { var query = self query.clauses.from = (clauses.from.name, aliasName, clauses.from.database) return query } // MARK: - Operations // // MARK: INSERT public func insert(_ value: Setter, _ more: Setter...) -> Insert { return insert([value] + more) } public func insert(_ values: [Setter]) -> Insert { return insert(nil, values) } public func insert(or onConflict: OnConflict, _ values: Setter...) -> Insert { return insert(or: onConflict, values) } public func insert(or onConflict: OnConflict, _ values: [Setter]) -> Insert { return insert(onConflict, values) } fileprivate func insert(_ or: OnConflict?, _ values: [Setter]) -> Insert { let insert = values.reduce((columns: [Expressible](), values: [Expressible]())) { insert, setter in (insert.columns + [setter.column], insert.values + [setter.value]) } let clauses: [Expressible?] = [ Expression<Void>(literal: "INSERT"), or.map { Expression<Void>(literal: "OR \($0.rawValue)") }, Expression<Void>(literal: "INTO"), tableName(), "".wrap(insert.columns) as Expression<Void>, Expression<Void>(literal: "VALUES"), "".wrap(insert.values) as Expression<Void>, whereClause ] return Insert(" ".join(clauses.flatMap { $0 }).expression) } /// Runs an `INSERT` statement against the query with `DEFAULT VALUES`. public func insert() -> Insert { return Insert(" ".join([ Expression<Void>(literal: "INSERT INTO"), tableName(), Expression<Void>(literal: "DEFAULT VALUES") ]).expression) } /// Runs an `INSERT` statement against the query with the results of another /// query. /// /// - Parameter query: A query to `SELECT` results from. /// /// - Returns: The number of updated rows and statement. public func insert(_ query: QueryType) -> Update { return Update(" ".join([ Expression<Void>(literal: "INSERT INTO"), tableName(), query.expression ]).expression) } // MARK: UPDATE public func update(_ values: Setter...) -> Update { return update(values) } public func update(_ values: [Setter]) -> Update { let clauses: [Expressible?] = [ Expression<Void>(literal: "UPDATE"), tableName(), Expression<Void>(literal: "SET"), ", ".join(values.map { " = ".join([$0.column, $0.value]) }), whereClause ] return Update(" ".join(clauses.flatMap { $0 }).expression) } // MARK: DELETE public func delete() -> Delete { let clauses: [Expressible?] = [ Expression<Void>(literal: "DELETE FROM"), tableName(), whereClause ] return Delete(" ".join(clauses.flatMap { $0 }).expression) } // MARK: EXISTS public var exists: Select<Bool> { return Select(" ".join([ Expression<Void>(literal: "SELECT EXISTS"), "".wrap(expression) as Expression<Void> ]).expression) } // MARK: - /// Prefixes a column expression with the query’s table name or alias. /// /// - Parameter column: A column expression. /// /// - Returns: A column expression namespaced with the query’s table name or /// alias. public func namespace<V>(_ column: Expression<V>) -> Expression<V> { return Expression(".".join([tableName(), column]).expression) } // FIXME: rdar://problem/18673897 // subscript<T>… public subscript(column: Expression<Blob>) -> Expression<Blob> { return namespace(column) } public subscript(column: Expression<Blob?>) -> Expression<Blob?> { return namespace(column) } public subscript(column: Expression<Bool>) -> Expression<Bool> { return namespace(column) } public subscript(column: Expression<Bool?>) -> Expression<Bool?> { return namespace(column) } public subscript(column: Expression<Double>) -> Expression<Double> { return namespace(column) } public subscript(column: Expression<Double?>) -> Expression<Double?> { return namespace(column) } public subscript(column: Expression<Int>) -> Expression<Int> { return namespace(column) } public subscript(column: Expression<Int?>) -> Expression<Int?> { return namespace(column) } public subscript(column: Expression<Int64>) -> Expression<Int64> { return namespace(column) } public subscript(column: Expression<Int64?>) -> Expression<Int64?> { return namespace(column) } public subscript(column: Expression<String>) -> Expression<String> { return namespace(column) } public subscript(column: Expression<String?>) -> Expression<String?> { return namespace(column) } /// Prefixes a star with the query’s table name or alias. /// /// - Parameter star: A literal `*`. /// /// - Returns: A `*` expression namespaced with the query’s table name or /// alias. public subscript(star: Star) -> Expression<Void> { return namespace(star(nil, nil)) } // MARK: - // TODO: alias support func tableName(alias aliased: Bool = false) -> Expressible { guard let alias = clauses.from.alias , aliased else { return database(namespace: clauses.from.alias ?? clauses.from.name) } return " ".join([ database(namespace: clauses.from.name), Expression<Void>(literal: "AS"), Expression<Void>(alias) ]) } func tableName(qualified: Bool) -> Expressible { if qualified { return tableName() } return Expression<Void>(clauses.from.alias ?? clauses.from.name) } func database(namespace name: String) -> Expressible { let name = Expression<Void>(name) guard let database = clauses.from.database else { return name } return ".".join([Expression<Void>(database), name]) } public var expression: Expression<Void> { let clauses: [Expressible?] = [ selectClause, joinClause, whereClause, groupByClause, orderClause, limitOffsetClause ] return " ".join(clauses.flatMap { $0 }).expression } } // TODO: decide: simplify the below with a boxed type instead /// Queries a collection of chainable helper functions and expressions to build /// executable SQL statements. public struct Table : SchemaType { public static let identifier = "TABLE" public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } public struct View : SchemaType { public static let identifier = "VIEW" public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } public struct VirtualTable : SchemaType { public static let identifier = "VIRTUAL TABLE" public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } // TODO: make `ScalarQuery` work in `QueryType.select()`, `.filter()`, etc. public struct ScalarQuery<V> : QueryType { public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } // TODO: decide: simplify the below with a boxed type instead public struct Select<T> : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } public struct Insert : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } public struct Update : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } public struct Delete : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } extension Connection { public func prepare(_ query: QueryType) throws -> AnySequence<Row> { let expression = query.expression let statement = try prepare(expression.template, expression.bindings) let columnNames: [String: Int] = try { var (columnNames, idx) = ([String: Int](), 0) column: for each in query.clauses.select.columns { var names = each.expression.template.characters.split { $0 == "." }.map(String.init) let column = names.removeLast() let namespace = names.joined(separator: ".") func expandGlob(_ namespace: Bool) -> ((QueryType) throws -> Void) { return { (query: QueryType) throws -> (Void) in var q = type(of: query).init(query.clauses.from.name, database: query.clauses.from.database) q.clauses.select = query.clauses.select let e = q.expression var names = try self.prepare(e.template, e.bindings).columnNames.map { $0.quote() } if namespace { names = names.map { "\(query.tableName().expression.template).\($0)" } } for name in names { columnNames[name] = idx; idx += 1 } } } if column == "*" { var select = query select.clauses.select = (false, [Expression<Void>(literal: "*") as Expressible]) let queries = [select] + query.clauses.join.map { $0.query } if !namespace.isEmpty { for q in queries { if q.tableName().expression.template == namespace { try expandGlob(true)(q) continue column } } fatalError("no such table: \(namespace)") } for q in queries { try expandGlob(query.clauses.join.count > 0)(q) } continue } columnNames[each.expression.template] = idx idx += 1 } return columnNames }() return AnySequence { AnyIterator { statement.next().map { Row(columnNames, $0) } } } } public func scalar<V : Value>(_ query: ScalarQuery<V>) throws -> V { let expression = query.expression return value(try scalar(expression.template, expression.bindings)) } public func scalar<V : Value>(_ query: ScalarQuery<V?>) throws -> V.ValueType? { let expression = query.expression guard let value = try scalar(expression.template, expression.bindings) as? V.Datatype else { return nil } return V.fromDatatypeValue(value) } public func scalar<V : Value>(_ query: Select<V>) throws -> V { let expression = query.expression return value(try scalar(expression.template, expression.bindings)) } public func scalar<V : Value>(_ query: Select<V?>) throws -> V.ValueType? { let expression = query.expression guard let value = try scalar(expression.template, expression.bindings) as? V.Datatype else { return nil } return V.fromDatatypeValue(value) } public func pluck(_ query: QueryType) throws -> Row? { return try prepare(query.limit(1, query.clauses.limit?.offset)).makeIterator().next() } /// Runs an `Insert` query. /// /// - SeeAlso: `QueryType.insert(value:_:)` /// - SeeAlso: `QueryType.insert(values:)` /// - SeeAlso: `QueryType.insert(or:_:)` /// - SeeAlso: `QueryType.insert()` /// /// - Parameter query: An insert query. /// /// - Returns: The insert’s rowid. @discardableResult public func run(_ query: Insert) throws -> Int64 { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) return self.lastInsertRowid } } /// Runs an `Update` query. /// /// - SeeAlso: `QueryType.insert(query:)` /// - SeeAlso: `QueryType.update(values:)` /// /// - Parameter query: An update query. /// /// - Returns: The number of updated rows. @discardableResult public func run(_ query: Update) throws -> Int { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) return self.changes } } /// Runs a `Delete` query. /// /// - SeeAlso: `QueryType.delete()` /// /// - Parameter query: A delete query. /// /// - Returns: The number of deleted rows. @discardableResult public func run(_ query: Delete) throws -> Int { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) return self.changes } } } public struct Row { fileprivate let columnNames: [String: Int] fileprivate let values: [Binding?] fileprivate init(_ columnNames: [String: Int], _ values: [Binding?]) { self.columnNames = columnNames self.values = values } /// Returns a row’s value for the given column. /// /// - Parameter column: An expression representing a column selected in a Query. /// /// - Returns: The value for the given column. public func get<V: Value>(_ column: Expression<V>) -> V { return get(Expression<V?>(column))! } public func get<V: Value>(_ column: Expression<V?>) -> V? { func valueAtIndex(_ idx: Int) -> V? { guard let value = values[idx] as? V.Datatype else { return nil } return (V.fromDatatypeValue(value) as? V)! } guard let idx = columnNames[column.template] else { let similar = Array(columnNames.keys).filter { $0.hasSuffix(".\(column.template)") } switch similar.count { case 0: fatalError("no such column '\(column.template)' in columns: \(columnNames.keys.sorted())") case 1: return valueAtIndex(columnNames[similar[0]]!) default: fatalError("ambiguous column '\(column.template)' (please disambiguate: \(similar))") } } return valueAtIndex(idx) } // FIXME: rdar://problem/18673897 // subscript<T>… public subscript(column: Expression<Blob>) -> Blob { return get(column) } public subscript(column: Expression<Blob?>) -> Blob? { return get(column) } public subscript(column: Expression<Bool>) -> Bool { return get(column) } public subscript(column: Expression<Bool?>) -> Bool? { return get(column) } public subscript(column: Expression<Double>) -> Double { return get(column) } public subscript(column: Expression<Double?>) -> Double? { return get(column) } public subscript(column: Expression<Int>) -> Int { return get(column) } public subscript(column: Expression<Int?>) -> Int? { return get(column) } public subscript(column: Expression<Int64>) -> Int64 { return get(column) } public subscript(column: Expression<Int64?>) -> Int64? { return get(column) } public subscript(column: Expression<String>) -> String { return get(column) } public subscript(column: Expression<String?>) -> String? { return get(column) } } /// Determines the join operator for a query’s `JOIN` clause. public enum JoinType : String { /// A `CROSS` join. case cross = "CROSS" /// An `INNER` join. case inner = "INNER" /// A `LEFT OUTER` join. case leftOuter = "LEFT OUTER" } /// ON CONFLICT resolutions. public enum OnConflict: String { case replace = "REPLACE" case rollback = "ROLLBACK" case abort = "ABORT" case fail = "FAIL" case ignore = "IGNORE" } // MARK: - Private public struct QueryClauses { var select = (distinct: false, columns: [Expression<Void>(literal: "*") as Expressible]) var from: (name: String, alias: String?, database: String?) var join = [(type: JoinType, query: QueryType, condition: Expressible)]() var filters: Expression<Bool?>? var group: (by: [Expressible], having: Expression<Bool?>?)? var order = [Expressible]() var limit: (length: Int, offset: Int?)? fileprivate init(_ name: String, alias: String?, database: String?) { self.from = (name, alias, database) } }
mit
b6f124b7794958d0f0419da37dbc30b8
30.268503
147
0.571861
4.341498
false
false
false
false
krzyzanowskim/Natalie
Sources/natalie/Natalie.swift
1
14239
// // Natalie.swift // Natalie // // Created by Marcin Krzyzanowski on 07/08/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // import Foundation struct Natalie { struct Header: CustomStringConvertible { var description: String { var output = String() output += "//\n" output += "// Autogenerated by Natalie - Storyboard Generator\n" output += "// by Marcin Krzyzanowski http://krzyzanowskim.com\n" output += "//\n" return output } } let storyboards: [StoryboardFile] let header = Header() var storyboardCustomModules: Set<String> { return Set(storyboards.lazy.flatMap { $0.storyboard.customModules }) } init(storyboards: [StoryboardFile]) { self.storyboards = storyboards assert(Set(storyboards.map { $0.storyboard.os }).count < 2) } static func process(storyboards: [StoryboardFile]) -> String { var output = String() for os in OS.allValues { let storyboardsForOS = storyboards.filter { $0.storyboard.os == os } if !storyboardsForOS.isEmpty { if storyboardsForOS.count != storyboards.count { output += "#if os(\(os.rawValue))\n" } output += Natalie(storyboards: storyboardsForOS).process(os: os) if storyboardsForOS.count != storyboards.count { output += "#endif\n" } } } return output } func process(os: OS) -> String { var output = "" output += header.description output += "import \(os.framework)\n" for module in storyboardCustomModules { output += "import \(module)\n" } output += "\n" output += "// MARK: - Storyboards\n" output += "\n" output += "extension \(os.storyboardType) {\n" for (signatureType, returnType) in os.storyboardInstantiationInfo { output += " func instantiateViewController<T: \(returnType)>(ofType type: T.Type) -> T? where T: IdentifiableProtocol {\n" output += " let instance = type.init()\n" output += " if let identifier = instance.storyboardIdentifier {\n" output += " return self.instantiate\(signatureType)(withIdentifier: identifier) as? T\n" output += " }\n" output += " return nil\n" output += " }\n" output += "\n" } output += "}\n" output += "\n" output += "protocol Storyboard {\n" output += " static var storyboard: \(os.storyboardType) { get }\n" output += " static var identifier: \(os.storyboardIdentifierType) { get }\n" output += "}\n" output += "\n" output += "struct Storyboards {\n" for file in storyboards { output += file.storyboard.processStoryboard(storyboardName: file.storyboardName, os: os) } output += "}\n" output += "\n" let colors = storyboards .flatMap { $0.storyboard.colors } .filter { $0.catalog != .system } .compactMap { $0.assetName } if !colors.isEmpty { output += "// MARK: - Colors\n" output += "@available(\(os.colorOS), *)\n" output += "extension \(os.colorType) {\n" for colorName in Set(colors) { output += " static let \(swiftRepresentation(for: colorName, firstLetter: .none)) = \(os.colorType)(named: \(initIdentifier(for: os.colorNameType, value: colorName)))\n" } output += "}\n" output += "\n" } output += "// MARK: - ReusableKind\n" output += "enum ReusableKind: String, CustomStringConvertible {\n" output += " case tableViewCell = \"tableViewCell\"\n" output += " case collectionViewCell = \"collectionViewCell\"\n" output += "\n" output += " var description: String { return self.rawValue }\n" output += "}\n" output += "\n" output += "// MARK: - SegueKind\n" output += "enum SegueKind: String, CustomStringConvertible {\n" output += " case relationship = \"relationship\"\n" output += " case show = \"show\"\n" output += " case presentation = \"presentation\"\n" output += " case embed = \"embed\"\n" output += " case unwind = \"unwind\"\n" output += " case push = \"push\"\n" output += " case modal = \"modal\"\n" output += " case popover = \"popover\"\n" output += " case replace = \"replace\"\n" output += " case custom = \"custom\"\n" output += "\n" output += " var description: String { return self.rawValue }\n" output += "}\n" output += "\n" output += "// MARK: - IdentifiableProtocol\n" output += "\n" output += "public protocol IdentifiableProtocol: Equatable {\n" output += " var storyboardIdentifier: \(os.storyboardSceneIdentifierType)? { get }\n" output += "}\n" output += "\n" output += "// MARK: - SegueProtocol\n" output += "\n" output += "public protocol SegueProtocol {\n" output += " var identifier: \(os.storyboardSegueIdentifierType)? { get }\n" output += "}\n" output += "\n" output += "public func ==<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {\n" output += " return lhs.identifier == rhs.identifier\n" output += "}\n" output += "\n" output += "public func ~=<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {\n" output += " return lhs.identifier == rhs.identifier\n" output += "}\n" output += "\n" output += "public func ==<T: SegueProtocol>(lhs: T, rhs: \(os.storyboardSegueIdentifierType)) -> Bool {\n" output += " return lhs.identifier == rhs\n" output += "}\n" output += "\n" output += "public func ~=<T: SegueProtocol>(lhs: T, rhs: \(os.storyboardSegueIdentifierType)) -> Bool {\n" output += " return lhs.identifier == rhs\n" output += "}\n" output += "\n" output += "public func ==<T: SegueProtocol>(lhs: \(os.storyboardSegueIdentifierType), rhs: T) -> Bool {\n" output += " return lhs == rhs.identifier\n" output += "}\n" output += "\n" output += "public func ~=<T: SegueProtocol>(lhs: \(os.storyboardSegueIdentifierType), rhs: T) -> Bool {\n" output += " return lhs == rhs.identifier\n" output += "}\n" output += "\n" if os.storyboardSegueIdentifierType != "String" { output += "extension \(os.storyboardSegueIdentifierType): ExpressibleByStringLiteral {\n" output += " public typealias StringLiteralType = String\n" output += " public init(stringLiteral value: StringLiteralType) {\n" output += " self.init(rawValue: value)\n" output += " }\n" output += "}\n" output += "\n" output += "public func ==<T: SegueProtocol>(lhs: T, rhs: String) -> Bool {\n" output += " return lhs.identifier?.rawValue == rhs\n" output += "}\n" output += "\n" output += "public func ~=<T: SegueProtocol>(lhs: T, rhs: String) -> Bool {\n" output += " return lhs.identifier?.rawValue == rhs\n" output += "}\n" output += "\n" output += "public func ==<T: SegueProtocol>(lhs: String, rhs: T) -> Bool {\n" output += " return lhs == rhs.identifier?.rawValue\n" output += "}\n" output += "\n" output += "public func ~=<T: SegueProtocol>(lhs: String, rhs: T) -> Bool {\n" output += " return lhs == rhs.identifier?.rawValue\n" output += "}\n" output += "\n" } output += "// MARK: - ReusableViewProtocol\n" output += "public protocol ReusableViewProtocol: IdentifiableProtocol {\n" output += " var viewType: \(os.viewType).Type? { get }\n" output += "}\n" output += "\n" output += "public func ==<T: ReusableViewProtocol, U: ReusableViewProtocol>(lhs: T, rhs: U) -> Bool {\n" output += " return lhs.storyboardIdentifier == rhs.storyboardIdentifier\n" output += "}\n" output += "\n" output += "// MARK: - Protocol Implementation\n" output += "extension \(os.storyboardSegueType): SegueProtocol {\n" output += "}\n" output += "\n" if let reusableViews = os.resuableViews { for reusableView in reusableViews { output += "extension \(reusableView): ReusableViewProtocol {\n" output += " public var viewType: UIView.Type? { return type(of: self) }\n" output += " public var storyboardIdentifier: String? { return self.reuseIdentifier }\n" output += "}\n" output += "\n" } } for controllerType in os.storyboardControllerTypes { output += "// MARK: - \(controllerType) extension\n" output += "extension \(controllerType) {\n" output += " func perform<T: SegueProtocol>(segue: T, sender: Any?) {\n" output += " if let identifier = segue.identifier {\n" output += " performSegue(withIdentifier: identifier, sender: sender)\n" output += " }\n" output += " }\n" output += "\n" output += " func perform<T: SegueProtocol>(segue: T) {\n" output += " perform(segue: segue, sender: nil)\n" output += " }\n" output += "}\n" } if os == OS.iOS { output += "// MARK: - UICollectionView\n" output += "\n" output += "extension UICollectionView {\n" output += "\n" output += " func dequeue<T: ReusableViewProtocol>(reusable: T, for: IndexPath) -> UICollectionViewCell? {\n" output += " if let identifier = reusable.storyboardIdentifier {\n" output += " return dequeueReusableCell(withReuseIdentifier: identifier, for: `for`)\n" output += " }\n" output += " return nil\n" output += " }\n" output += "\n" output += " func register<T: ReusableViewProtocol>(reusable: T) {\n" output += " if let type = reusable.viewType, let identifier = reusable.storyboardIdentifier {\n" output += " register(type, forCellWithReuseIdentifier: identifier)\n" output += " }\n" output += " }\n" output += "\n" output += " func dequeueReusableSupplementaryViewOfKind<T: ReusableViewProtocol>(elementKind: String, withReusable reusable: T, for: IndexPath) -> UICollectionReusableView? {\n" output += " if let identifier = reusable.storyboardIdentifier {\n" output += " return dequeueReusableSupplementaryView(ofKind: elementKind, withReuseIdentifier: identifier, for: `for`)\n" output += " }\n" output += " return nil\n" output += " }\n" output += "\n" output += " func register<T: ReusableViewProtocol>(reusable: T, forSupplementaryViewOfKind elementKind: String) {\n" output += " if let type = reusable.viewType, let identifier = reusable.storyboardIdentifier {\n" output += " register(type, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: identifier)\n" output += " }\n" output += " }\n" output += "}\n" output += "// MARK: - UITableView\n" output += "\n" output += "extension UITableView {\n" output += "\n" output += " func dequeue<T: ReusableViewProtocol>(reusable: T, for: IndexPath) -> UITableViewCell? {\n" output += " if let identifier = reusable.storyboardIdentifier {\n" output += " return dequeueReusableCell(withIdentifier: identifier, for: `for`)\n" output += " }\n" output += " return nil\n" output += " }\n" output += "\n" output += " func register<T: ReusableViewProtocol>(reusable: T) {\n" output += " if let type = reusable.viewType, let identifier = reusable.storyboardIdentifier {\n" output += " register(type, forCellReuseIdentifier: identifier)\n" output += " }\n" output += " }\n" output += "\n" output += " func dequeueReusableHeaderFooter<T: ReusableViewProtocol>(_ reusable: T) -> UITableViewHeaderFooterView? {\n" output += " if let identifier = reusable.storyboardIdentifier {\n" output += " return dequeueReusableHeaderFooterView(withIdentifier: identifier)\n" output += " }\n" output += " return nil\n" output += " }\n" output += "\n" output += " func registerReusableHeaderFooter<T: ReusableViewProtocol>(_ reusable: T) {\n" output += " if let type = reusable.viewType, let identifier = reusable.storyboardIdentifier {\n" output += " register(type, forHeaderFooterViewReuseIdentifier: identifier)\n" output += " }\n" output += " }\n" output += "}\n" } let storyboardModules = storyboardCustomModules for file in storyboards { output += file.storyboard.processViewControllers(storyboardCustomModules: storyboardModules) } return output } }
mit
1bacf9f2280d06386deea00fd2c54f1a
44.78135
192
0.524652
4.633257
false
false
false
false
BenEmdon/swift-algorithm-club
Ternary Search Tree/TST.playground/Sources/TernarySearchTree.swift
1
2719
// // TernarySearchTree.swift // // // Created by Siddharth Atre on 3/15/16. // // import Foundation public class TernarySearchTree<Element> { var root: TSTNode<Element>? public init() {} //MARK: - Insertion public func insert(data: Element, withKey key: String) -> Bool { return insertNode(&root, withData: data, andKey: key, atIndex: 0) } private func insertNode(inout aNode: TSTNode<Element>?, withData data: Element, andKey key: String, atIndex charIndex: Int) -> Bool { //sanity check. if key.characters.count == 0 { return false } //create a new node if necessary. if aNode == nil { let index = key.startIndex.advancedBy(charIndex) aNode = TSTNode<Element>(key: key[index]) } //if current char is less than the current node's char, go left let index = key.startIndex.advancedBy(charIndex) if key[index] < aNode!.key { return insertNode(&aNode!.left, withData: data, andKey: key, atIndex: charIndex) } //if it's greater, go right. else if key[index] > aNode!.key { return insertNode(&aNode!.right, withData: data, andKey: key, atIndex: charIndex) } //current char is equal to the current nodes, go middle else { //continue down the middle. if charIndex + 1 < key.characters.count { return insertNode(&aNode!.middle, withData: data, andKey: key, atIndex: charIndex + 1) } //otherwise, all done. else { aNode!.data = data aNode?.hasData = true return true } } } //MARK: - Finding public func find(key: String) -> Element? { return findNode(root, withKey: key, atIndex: 0) } private func findNode(aNode: TSTNode<Element>?, withKey key: String, atIndex charIndex: Int) -> Element? { //Given key does not exist in tree. if aNode == nil { return nil } let index = key.startIndex.advancedBy(charIndex) //go left if key[index] < aNode!.key { return findNode(aNode!.left, withKey: key, atIndex: charIndex) } //go right else if key[index] > aNode!.key { return findNode(aNode!.right, withKey: key, atIndex: charIndex) } //go middle else { if charIndex + 1 < key.characters.count { return findNode(aNode!.middle, withKey: key, atIndex: charIndex + 1) } else { return aNode!.data } } } }
mit
f893a55babb364891603d9d152b5eb58
27.322917
137
0.549099
4.202473
false
false
false
false
AnirudhDas/AniruddhaDas.github.io
RedBus/RedBus/Model/BusesList.swift
1
3607
// // BusesList.swift // RedBus // // Created by Anirudh Das on 8/22/18. // Copyright © 2018 Aniruddha Das. All rights reserved. // import Foundation enum SortBusesBy { case ratingAscending case ratingDescending case departureTimeAscending case departureTimeDescending case fareAscending case fareDescending case none } struct BusesList { var sortBy: SortBusesBy = .none var busType: BusType? var allBuses: [BusDetail]? = [] var filteredBuses: [BusDetail] { if let allBuses = allBuses { guard let busType = busType else { return sortBusList(busList: Array(allBuses)) } //No filter added if busType.isAc == false && busType.isNonAc == false && busType.isSeater == false && busType.isSleeper == false { return sortBusList(busList: Array(allBuses)) } //Set Filters let acBuses = allBuses.filter({ busType.isAc && (busType.isAc == $0.busType.isAc) }) let nonAcBuses = allBuses.filter({ busType.isNonAc && (busType.isNonAc == $0.busType.isNonAc) }) let seaterBuses = allBuses.filter({ busType.isSeater && (busType.isSeater == $0.busType.isSeater) }) let sleeperBuses = allBuses.filter({ busType.isSleeper && (busType.isSleeper == $0.busType.isSleeper) }) let setAcBuses: Set<BusDetail> = Set(acBuses) let setNonAcBuses: Set<BusDetail> = Set(nonAcBuses) let setSeaterBuses: Set<BusDetail> = Set(seaterBuses) let setSleeperBuses: Set<BusDetail> = Set(sleeperBuses) var filteredSet = setAcBuses.union(setNonAcBuses).union(setSeaterBuses).union(setSleeperBuses) if busType.isAc { filteredSet = filteredSet.intersection(setAcBuses) } if busType.isNonAc { filteredSet = filteredSet.intersection(setNonAcBuses) } if busType.isSeater { filteredSet = filteredSet.intersection(setSeaterBuses) } if busType.isSleeper { filteredSet = filteredSet.intersection(setSleeperBuses) } return sortBusList(busList: Array(filteredSet)) } return [] } func sortBusList(busList: [BusDetail]) -> [BusDetail] { var sortedList: [BusDetail] = [] switch sortBy { case .ratingAscending: sortedList = busList.sorted(by: { return ($0.rating != -1 && $1.rating != -1) ? $0.rating < $1.rating : true }) case .ratingDescending: sortedList = busList.sorted(by: { return ($0.rating != -1 && $1.rating != -1) ? $0.rating > $1.rating : true }) case .departureTimeAscending: sortedList = busList.sorted(by: { return $0.departureTime < $1.departureTime }) case .departureTimeDescending: sortedList = busList.sorted(by: { return $0.departureTime > $1.departureTime }) case .fareAscending: sortedList = busList.sorted(by: { return $0.fare < $1.fare }) case .fareDescending: sortedList = busList.sorted(by: { return $0.fare > $1.fare }) case .none: sortedList = busList } return sortedList } }
apache-2.0
44d0036a9b5fac98297ebaf4a9fb39a7
34.009709
127
0.546866
4.088435
false
false
false
false
dreamsxin/swift
validation-test/stdlib/CoreAudio.swift
3
10091
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos import StdlibUnittest import StdlibCollectionUnittest import CoreAudio // Used in tests below. extension AudioBuffer : Equatable {} public func == (lhs: AudioBuffer, rhs: AudioBuffer) -> Bool { return lhs.mNumberChannels == rhs.mNumberChannels && lhs.mDataByteSize == rhs.mDataByteSize && lhs.mData == rhs.mData } var CoreAudioTestSuite = TestSuite("CoreAudio") // The size of the non-flexible part of an AudioBufferList. #if arch(i386) || arch(arm) let ablHeaderSize = 4 #elseif arch(x86_64) || arch(arm64) let ablHeaderSize = 8 #endif CoreAudioTestSuite.test("UnsafeBufferPointer.init(_: AudioBuffer)") { do { let audioBuffer = AudioBuffer( mNumberChannels: 0, mDataByteSize: 0, mData: nil) let result: UnsafeBufferPointer<Float> = UnsafeBufferPointer(audioBuffer) expectEqual(nil, result.baseAddress) expectEqual(0, result.count) } do { let audioBuffer = AudioBuffer( mNumberChannels: 2, mDataByteSize: 1024, mData: UnsafeMutablePointer<Void>(bitPattern: 0x1234_5678)) let result: UnsafeBufferPointer<Float> = UnsafeBufferPointer(audioBuffer) expectEqual( UnsafePointer<Float>(audioBuffer.mData!), result.baseAddress) expectEqual(256, result.count) } } CoreAudioTestSuite.test("UnsafeMutableBufferPointer.init(_: AudioBuffer)") { do { let audioBuffer = AudioBuffer( mNumberChannels: 0, mDataByteSize: 0, mData: nil) let result: UnsafeMutableBufferPointer<Float> = UnsafeMutableBufferPointer(audioBuffer) expectEqual(nil, result.baseAddress) expectEqual(0, result.count) } do { let audioBuffer = AudioBuffer( mNumberChannels: 2, mDataByteSize: 1024, mData: UnsafeMutablePointer<Void>(bitPattern: 0x1234_5678)) let result: UnsafeMutableBufferPointer<Float> = UnsafeMutableBufferPointer(audioBuffer) expectEqual( UnsafeMutablePointer<Float>(audioBuffer.mData!), result.baseAddress) expectEqual(256, result.count) } } CoreAudioTestSuite.test( "AudioBuffer.init(_: UnsafeMutableBufferPointer, numberOfChannels: Int)") { do { // NULL pointer. let buffer = UnsafeMutableBufferPointer<Float>(start: nil, count: 0) let result = AudioBuffer(buffer, numberOfChannels: 2) expectEqual(2, result.mNumberChannels) expectEqual(0, result.mDataByteSize) expectEqual(nil, result.mData) } do { // Non-NULL pointer. let buffer = UnsafeMutableBufferPointer<Float>( start: UnsafeMutablePointer<Float>(bitPattern: 0x1234_5678), count: 0) let result = AudioBuffer(buffer, numberOfChannels: 2) expectEqual(2, result.mNumberChannels) expectEqual(0, result.mDataByteSize) expectEqual(buffer.baseAddress, result.mData) } } CoreAudioTestSuite.test( "AudioBuffer.init(_: UnsafeMutableBufferPointer, numberOfChannels: Int)/trap") { #if arch(i386) || arch(arm) let overflowingCount = Int.max #elseif arch(x86_64) || arch(arm64) let overflowingCount = Int(UInt32.max) #endif let buffer = UnsafeMutableBufferPointer<Float>( start: UnsafeMutablePointer<Float>(bitPattern: 0x1234_5678), count: overflowingCount) expectCrashLater() // An overflow happens when we try to compute the value for mDataByteSize. _ = AudioBuffer(buffer, numberOfChannels: 2) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)") { expectEqual(ablHeaderSize + strideof(AudioBuffer), AudioBufferList.sizeInBytes(maximumBuffers: 1)) expectEqual(ablHeaderSize + 16 * strideof(AudioBuffer), AudioBufferList.sizeInBytes(maximumBuffers: 16)) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/count<0") { expectCrashLater() AudioBufferList.sizeInBytes(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/count==0") { expectCrashLater() AudioBufferList.sizeInBytes(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/overflow") { expectCrashLater() AudioBufferList.sizeInBytes(maximumBuffers: Int.max) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)") { do { let ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 1) expectEqual(1, ablPtrWrapper.count) free(ablPtrWrapper.unsafeMutablePointer) } do { let ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 16) expectEqual(16, ablPtrWrapper.count) free(ablPtrWrapper.unsafeMutablePointer) } } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/count==0") { expectCrashLater() AudioBufferList.allocate(maximumBuffers: 0) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/count<0") { expectCrashLater() AudioBufferList.allocate(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/overflow") { expectCrashLater() AudioBufferList.allocate(maximumBuffers: Int.max) } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer/AssociatedTypes") { typealias Subject = UnsafeMutableAudioBufferListPointer expectRandomAccessCollectionAssociatedTypes( collectionType: Subject.self, iteratorType: IndexingIterator<Subject>.self, subSequenceType: MutableRandomAccessSlice<Subject>.self, indexType: Int.self, indexDistanceType: Int.self, indicesType: CountableRange<Int>.self) } CoreAudioTestSuite.test( "UnsafeMutableAudioBufferListPointer.init(_: UnsafeMutablePointer<AudioBufferList>)," + "UnsafeMutableAudioBufferListPointer.unsafePointer," + "UnsafeMutableAudioBufferListPointer.unsafeMutablePointer") { do { let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(nil) expectEmpty(ablPtrWrapper) } do { let ablPtrWrapper = UnsafeMutableAudioBufferListPointer( UnsafeMutablePointer<AudioBufferList>(bitPattern: 0x1234_5678)!) expectEqual( UnsafePointer<AudioBufferList>(bitPattern: 0x1234_5678), ablPtrWrapper.unsafePointer) expectEqual( UnsafePointer<AudioBufferList>(bitPattern: 0x1234_5678), ablPtrWrapper.unsafeMutablePointer) } do { let ablPtrWrapper = UnsafeMutableAudioBufferListPointer( UnsafeMutablePointer<AudioBufferList>(bitPattern: 0x1234_5678)) expectNotEmpty(ablPtrWrapper) expectEqual( UnsafePointer<AudioBufferList>(bitPattern: 0x1234_5678), ablPtrWrapper!.unsafePointer) expectEqual( UnsafePointer<AudioBufferList>(bitPattern: 0x1234_5678), ablPtrWrapper!.unsafeMutablePointer) } } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.count") { let sizeInBytes = AudioBufferList.sizeInBytes(maximumBuffers: 16) let ablPtr = UnsafeMutablePointer<AudioBufferList>( UnsafeMutablePointer<UInt8>(allocatingCapacity: sizeInBytes)) // It is important that 'ablPtrWrapper' is a 'let'. We are verifying that // the 'count' property has a nonmutating setter. let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(ablPtr) // Test getter. UnsafeMutablePointer<UInt32>(ablPtr).pointee = 0x1234_5678 expectEqual(0x1234_5678, ablPtrWrapper.count) // Test setter. ablPtrWrapper.count = 0x7765_4321 expectEqual(0x7765_4321, UnsafeMutablePointer<UInt32>(ablPtr).pointee) ablPtr.deallocateCapacity(sizeInBytes) } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)") { let sizeInBytes = AudioBufferList.sizeInBytes(maximumBuffers: 16) let ablPtr = UnsafeMutablePointer<AudioBufferList>( UnsafeMutablePointer<UInt8>(allocatingCapacity: sizeInBytes)) // It is important that 'ablPtrWrapper' is a 'let'. We are verifying that // the subscript has a nonmutating setter. let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(ablPtr) do { // Test getter. let audioBuffer = AudioBuffer( mNumberChannels: 2, mDataByteSize: 1024, mData: UnsafeMutablePointer<Void>(bitPattern: 0x1234_5678)) UnsafeMutablePointer<AudioBuffer>( UnsafeMutablePointer<UInt8>(ablPtr) + ablHeaderSize ).pointee = audioBuffer ablPtrWrapper.count = 1 expectEqual(2, ablPtrWrapper[0].mNumberChannels) expectEqual(1024, ablPtrWrapper[0].mDataByteSize) expectEqual(audioBuffer.mData, ablPtrWrapper[0].mData) } do { // Test setter. let audioBuffer = AudioBuffer( mNumberChannels: 5, mDataByteSize: 256, mData: UnsafeMutablePointer<Void>(bitPattern: 0x8765_4321 as UInt)) ablPtrWrapper.count = 2 ablPtrWrapper[1] = audioBuffer let audioBufferPtr = UnsafeMutablePointer<AudioBuffer>( UnsafeMutablePointer<UInt8>(ablPtr) + ablHeaderSize) + 1 expectEqual(5, audioBufferPtr.pointee.mNumberChannels) expectEqual(256, audioBufferPtr.pointee.mDataByteSize) expectEqual(audioBuffer.mData, audioBufferPtr.pointee.mData) } ablPtr.deallocateCapacity(sizeInBytes) } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)/trap") { let ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 4) ablPtrWrapper[0].mNumberChannels = 42 ablPtrWrapper[1].mNumberChannels = 42 ablPtrWrapper[2].mNumberChannels = 42 ablPtrWrapper[3].mNumberChannels = 42 expectCrashLater() ablPtrWrapper[4].mNumberChannels = 42 } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer/Collection") { var ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 16) expectType(UnsafeMutableAudioBufferListPointer.self, &ablPtrWrapper) var expected: [AudioBuffer] = [] for i in 0..<16 { let audioBuffer = AudioBuffer( mNumberChannels: UInt32(2 + i), mDataByteSize: UInt32(1024 * i), mData: UnsafeMutablePointer<Void>(bitPattern: 0x1234_5678 + i * 10)) ablPtrWrapper[i] = audioBuffer expected.append(audioBuffer) } // FIXME: use checkMutableRandomAccessCollection, when we have that function. checkRandomAccessCollection(expected, ablPtrWrapper) free(ablPtrWrapper.unsafeMutablePointer) } runAllTests()
apache-2.0
1600bda809e77fb3fd7668a52ce77ac3
32.413907
91
0.758101
4.900923
false
true
false
false
codeforgreenville/trolley-tracker-ios-client
TrolleyTracker/Controllers/UI/Schedule/ScheduleController.swift
1
2865
// // ScheduleController.swift // TrolleyTracker // // Created by Austin Younts on 7/30/17. // Copyright © 2017 Code For Greenville. All rights reserved. // import UIKit class ScheduleController: FunctionController { enum DisplayType: Int { case route, day static var all: [DisplayType] { return [.route, .day] } static var `default`: DisplayType { return .route } } typealias Dependencies = HasModelController private let dependencies: Dependencies private let viewController: ScheduleViewController private let dataSource: ScheduleDataSource private var routeController: RouteController? private var lastFetchRequestDate: Date? init(dependencies: Dependencies) { self.dependencies = dependencies self.dataSource = ScheduleDataSource() self.viewController = ScheduleViewController() } func prepare() -> UIViewController { let type = DisplayType.default dataSource.displayType = type viewController.displayTypeControl.selectedSegmentIndex = type.rawValue dataSource.displayRouteAction = displayRoute(_:) viewController.tabBarItem.image = #imageLiteral(resourceName: "Schedule") viewController.tabBarItem.title = LS.scheduleTitle viewController.delegate = self let nav = UINavigationController(rootViewController: viewController) viewController.tableView.dataSource = dataSource viewController.tableView.delegate = dataSource loadSchedules() return nav } private func loadSchedulesIfNeeded() { guard let lastDate = lastFetchRequestDate else { loadSchedules() return } guard lastDate.isAcrossQuarterHourBoundryFromNow else { return } loadSchedules() } private func loadSchedules() { lastFetchRequestDate = Date() dependencies.modelController.loadTrolleySchedules(handleNewSchedules(_:)) } private func handleNewSchedules(_ schedules: [RouteSchedule]) { dataSource.set(schedules: schedules) viewController.tableView.reloadData() } private func displayRoute(_ routeID: Int) { routeController = RouteController(routeID: routeID, presentationContext: viewController, dependencies: dependencies) routeController?.present() } } extension ScheduleController: ScheduleVCDelegate { func viewDidAppear() { loadSchedulesIfNeeded() } func didSelectScheduleTypeIndex(_ index: Int) { let displayType = ScheduleController.DisplayType(rawValue: index)! dataSource.displayType = displayType viewController.tableView.reloadData() } }
mit
aedf37fe42c89009130f810d512d89db
26.538462
81
0.660615
5.648915
false
false
false
false
incetro/NIO
Example/NioExample-iOS/Models/Plain/AdditivePlainObject.swift
1
825
// // AdditivePlainObject.swift // Nio // // Created by incetro on 16/07/2017. // // import NIO import Transformer // MARK: - AdditivePlainObject class AdditivePlainObject: TransformablePlain { var nioID: NioID { return NioID(value: id) } let id: Int64 let name: String let price: Double init(with name: String, price: Double, id: Int64) { self.name = name self.id = id self.price = price } var position: PositionPlainObject? = nil required init(with resolver: Resolver) throws { self.id = try resolver.value("id") self.name = try resolver.value("name") self.price = try resolver.value("price") self.position = try? resolver.value("position") } }
mit
831f7ca5a32859d08ef1e2300e369a31
19.121951
55
0.570909
3.784404
false
false
false
false
mapsme/omim
iphone/Maps/Bookmarks/Catalog/Dialogs/SubscriptionExpiredViewController.swift
6
814
class SubscriptionExpiredViewController: UIViewController { private let transitioning = FadeTransitioning<AlertPresentationController>(cancellable: false) private let onSubscribe: MWMVoidBlock private let onDelete: MWMVoidBlock init(onSubscribe: @escaping MWMVoidBlock, onDelete: @escaping MWMVoidBlock) { self.onSubscribe = onSubscribe self.onDelete = onDelete super.init(nibName: nil, bundle: nil) transitioningDelegate = transitioning modalPresentationStyle = .custom } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() } @IBAction func onSubscribe(_ sender: UIButton) { onSubscribe() } @IBAction func onDelete(_ sender: UIButton) { onDelete() } }
apache-2.0
88655fdef9d1ed1224a8f20ca4befd47
27.068966
96
0.737101
4.903614
false
false
false
false
CoderXiaoming/Ronaldo
SaleManager/SaleManager/Stock/Controller/SAMStockDetailController.swift
1
5147
// // SAMStockDetailController.swift // SaleManager // // Created by apple on 17/1/9. // Copyright © 2017年 YZH. All rights reserved. // import UIKit //库存明细重用标识符 private let SAMStockProductDetailCellReuseIdentifier = "SAMStockProductDetailCellReuseIdentifier" class SAMStockDetailController: UIViewController { //MARK: - 类工厂方法 class func instance(stockModel: SAMStockProductModel) -> SAMStockDetailController { let vc = SAMStockDetailController() vc.stockProductModel = stockModel //加载数据 vc.loadProductDeatilList() return vc } //MARK: - viewDidLoad override func viewDidLoad() { super.viewDidLoad() //设置圆角 view.layer.cornerRadius = 8 //设置标题 titleLabel.text = stockProductModel?.productIDName //设置collectionView setupCollectionView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) collectionView.reloadData() } ///设置collectionView fileprivate func setupCollectionView() { //设置数据源、代理 collectionView.dataSource = self collectionView.delegate = self collectionView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5) //注册cell collectionView.register(UINib(nibName: "SAMStockProductDetailCell", bundle: nil), forCellWithReuseIdentifier: SAMStockProductDetailCellReuseIdentifier) } //MARK: - 加载库存明细数据 fileprivate func loadProductDeatilList() { let parameters = ["productID": stockProductModel!.id, "storehouseID": "-1", "parentID": "-1"] //发送请求 SAMNetWorker.sharedNetWorker().get("getStockDetailList.ashx", parameters: parameters, progress: nil, success: {[weak self] (Task, json) in //获取模型数组 let Json = json as! [String: AnyObject] let dictArr = Json["body"] as? [[String: AnyObject]] let count = dictArr?.count ?? 0 //判断是否有模型数据 if count == 0 { //没有模型数据 }else {//有数据模型 self!.productDeatilList = SAMStockProductDeatil.mj_objectArray(withKeyValuesArray: dictArr)! } }) { (Task, Error) in } } //MARK: - 用户点击事件 @IBAction func dismissBtnClick(_ sender: UIButton) { dismiss(animated: true) { //发出通知 NotificationCenter.default.post(name: NSNotification.Name.init(SAMStockDetailControllerDismissSuccessNotification), object: nil) } } //MARK: - 属性 ///接收的库存模型 fileprivate var stockProductModel: SAMStockProductModel? ///模型数组 fileprivate var productDeatilList = NSMutableArray() //MARK: - XIB链接属性 @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var collectionView: UICollectionView! //MARK: - 其他方法 fileprivate init() { super.init(nibName: nil, bundle: nil) } fileprivate override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { //从xib加载view view = Bundle.main.loadNibNamed("SAMStockDetailController", owner: self, options: nil)![0] as! UIView } } //MARK: - UICollectionViewDataSource extension SAMStockDetailController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return productDeatilList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SAMStockProductDetailCellReuseIdentifier, for: indexPath) as! SAMStockProductDetailCell //赋值模型 let model = productDeatilList[indexPath.row] as! SAMStockProductDeatil cell.productDetailModel = model return cell } } //MARK: - collectionView布局代理 extension SAMStockDetailController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 90, height: 35) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 7 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } }
apache-2.0
ba345b7b3748456931d0d3a572c80863
33.055556
175
0.660481
5.09242
false
false
false
false
Bajocode/ExploringModerniOSArchitectures
Architectures/MVVM/ViewModel/ActorViewModel.swift
1
2811
// // ActorViewModel.swift // Architectures // // Created by Fabijan Bajo on 27/05/2017. // // import Foundation final class ActorViewModel: ViewModelInterface { // MARK: - Properties // Properties fileprivate var actors = [Actor]() { didSet { modelUpdate?() } } var count: Int { return actors.count } struct PresentableInstance: Transportable { let name: String let thumbnailURL: URL let fullSizeURL: URL let cornerRadius: Double } // MARK: - Binds typealias modelUpdateClosure = () -> Void typealias showDetailClosure = (URL, String) -> Void // Bind model updates and collectionview reload private var modelUpdate: modelUpdateClosure? func bindViewReload(with modelUpdate: @escaping modelUpdateClosure) { self.modelUpdate = modelUpdate } func fetchNewModelObjects() { DataManager.shared.fetchNewTmdbObjects(withType: .actor) { (result) in switch result { case let .success(transportables): self.actors = transportables as! [Actor] case let .failure(error): print(error) } } } // Bind collectionviewDidTap and detailVC presentation private var showDetail: showDetailClosure? func bindPresentation(with showDetail: @escaping showDetailClosure) { self.showDetail = showDetail } func showDetail(at indexPath: IndexPath) { let actor = actors[indexPath.row] let presentable = presentableInstance(from: actor) as! PresentableInstance showDetail?(presentable.fullSizeURL, presentable.name) } // MARK: - Helpers // Subscript: viewModel[i] -> PresentableInstance subscript (index: Int) -> Transportable { return presentableInstance(from: actors[index]) } func presentableInstance(from model: Transportable) -> Transportable { let actor = model as! Actor let thumbnailURL = TmdbAPI.tmdbImageURL(forSize: .thumb, path: actor.profilePath) let fullSizeURL = TmdbAPI.tmdbImageURL(forSize: .full, path: actor.profilePath) return PresentableInstance(name: actor.name, thumbnailURL: thumbnailURL, fullSizeURL: fullSizeURL, cornerRadius: 10.0) } } // MARK: - CollectionViewConfigurable extension ActorViewModel: CollectionViewConfigurable { // MARK: - Properties // Required var cellID: String { return "ActorCell" } var widthDivisor: Double { return 3.0 } var heightDivisor: Double { return 3.0 } // Optional var interItemSpacing: Double? { return 8 } var lineSpacing: Double? { return 8 } var topInset: Double? { return 8 } var horizontalInsets: Double? { return 8 } var bottomInset: Double? { return 49 } }
mit
618136e6ec1c0a0179f61510941dd01c
30.233333
126
0.657417
4.716443
false
false
false
false
KrishMunot/swift
test/IDE/print_ast_tc_decls.swift
2
51675
// RUN: rm -rf %t && mkdir %t // // Build swift modules this test depends on. // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/foo_swift_module.swift // // FIXME: BEGIN -enable-source-import hackaround // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift // FIXME: END -enable-source-import hackaround // // This file should not have any syntax or type checker errors. // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -parse -verify %s -F %S/Inputs/mock-sdk -disable-objc-attr-requires-foundation-module // // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=false -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_PRINT_AST -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_ONE_LINE_TYPE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PREFER_TYPE_PRINTING -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=true -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_PRINT_AST -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_ONE_LINE_TYPEREPR -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t -F %S/Inputs/mock-sdk -disable-objc-attr-requires-foundation-module %s // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -module-to-print=print_ast_tc_decls -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_RW_PROP_NO_GET_SET -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_2200_DESERIALIZED -strict-whitespace < %t.printed.txt // FIXME: rdar://15167697 // FIXME: FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt // // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -fully-qualified-types-if-ambiguous=true -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_QUAL_IF_AMBIGUOUS -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt // FIXME: FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt // FIXME: rdar://problem/19648117 Needs splitting objc parts out // XFAIL: linux import Bar import ObjectiveC import class Foo.FooClassBase import struct Foo.FooStruct1 import func Foo.fooFunc1 @_exported import FooHelper import foo_swift_module // FIXME: enum tests //import enum FooClangModule.FooEnum1 // PASS_COMMON: {{^}}import Bar{{$}} // PASS_COMMON: {{^}}import class Foo.FooClassBase{{$}} // PASS_COMMON: {{^}}import struct Foo.FooStruct1{{$}} // PASS_COMMON: {{^}}import func Foo.fooFunc1{{$}} // PASS_COMMON: {{^}}@_exported import FooHelper{{$}} // PASS_COMMON: {{^}}import foo_swift_module{{$}} //===--- //===--- Helper types. //===--- struct FooStruct {} class FooClass {} class BarClass {} protocol FooProtocol {} protocol BarProtocol {} protocol BazProtocol { func baz() } protocol QuxProtocol { associatedtype Qux } protocol SubFooProtocol : FooProtocol { } class FooProtocolImpl : FooProtocol {} class FooBarProtocolImpl : FooProtocol, BarProtocol {} class BazProtocolImpl : BazProtocol { func baz() {} } //===--- //===--- Basic smoketest. //===--- struct d0100_FooStruct { // PASS_COMMON-LABEL: {{^}}struct d0100_FooStruct {{{$}} var instanceVar1: Int = 0 // PASS_COMMON-NEXT: {{^}} var instanceVar1: Int{{$}} var computedProp1: Int { get { return 42 } } // PASS_COMMON-NEXT: {{^}} var computedProp1: Int { get }{{$}} func instanceFunc0() {} // PASS_COMMON-NEXT: {{^}} func instanceFunc0(){{$}} func instanceFunc1(a: Int) {} // PASS_COMMON-NEXT: {{^}} func instanceFunc1(a: Int){{$}} func instanceFunc2(a: Int, b: inout Double) {} // PASS_COMMON-NEXT: {{^}} func instanceFunc2(a: Int, b: inout Double){{$}} func instanceFunc3(a: Int, b: Double) { var a = a; a = 1; _ = a } // PASS_COMMON-NEXT: {{^}} func instanceFunc3(a: Int, b: Double){{$}} func instanceFuncWithDefaultArg1(a: Int = 0) {} // PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg1(a: Int = default){{$}} func instanceFuncWithDefaultArg2(a: Int = 0, b: Double = 0) {} // PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg2(a: Int = default, b: Double = default){{$}} func varargInstanceFunc0(v: Int...) {} // PASS_COMMON-NEXT: {{^}} func varargInstanceFunc0(v: Int...){{$}} func varargInstanceFunc1(a: Float, v: Int...) {} // PASS_COMMON-NEXT: {{^}} func varargInstanceFunc1(a: Float, v: Int...){{$}} func varargInstanceFunc2(a: Float, b: Double, v: Int...) {} // PASS_COMMON-NEXT: {{^}} func varargInstanceFunc2(a: Float, b: Double, v: Int...){{$}} func overloadedInstanceFunc1() -> Int { return 0; } // PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Int{{$}} func overloadedInstanceFunc1() -> Double { return 0.0; } // PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Double{{$}} func overloadedInstanceFunc2(x: Int) -> Int { return 0; } // PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Int) -> Int{{$}} func overloadedInstanceFunc2(x: Double) -> Int { return 0; } // PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Double) -> Int{{$}} func builderFunc1(a: Int) -> d0100_FooStruct { return d0100_FooStruct(); } // PASS_COMMON-NEXT: {{^}} func builderFunc1(a: Int) -> d0100_FooStruct{{$}} subscript(i: Int) -> Double { get { return Double(i) } } // PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Double { get }{{$}} subscript(i: Int, j: Int) -> Double { get { return Double(i + j) } } // PASS_COMMON-NEXT: {{^}} subscript(i: Int, j: Int) -> Double { get }{{$}} func bodyNameVoidFunc1(a: Int, b x: Float) {} // PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc1(a: Int, b x: Float){{$}} func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double) {} // PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double){{$}} func bodyNameStringFunc1(a: Int, b x: Float) -> String { return "" } // PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc1(a: Int, b x: Float) -> String{{$}} func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String { return "" } // PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String{{$}} struct NestedStruct {} // PASS_COMMON-NEXT: {{^}} struct NestedStruct {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} class NestedClass {} // PASS_COMMON-NEXT: {{^}} class NestedClass {{{$}} // PASS_COMMON-NEXT: {{^}} @objc deinit{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} enum NestedEnum {} // PASS_COMMON-NEXT: {{^}} enum NestedEnum {{{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} // Cannot declare a nested protocol. // protocol NestedProtocol {} typealias NestedTypealias = Int // PASS_COMMON-NEXT: {{^}} typealias NestedTypealias = Int{{$}} static var staticVar1: Int = 42 // PASS_COMMON-NEXT: {{^}} static var staticVar1: Int{{$}} static var computedStaticProp1: Int { get { return 42 } } // PASS_COMMON-NEXT: {{^}} static var computedStaticProp1: Int { get }{{$}} static func staticFunc0() {} // PASS_COMMON-NEXT: {{^}} static func staticFunc0(){{$}} static func staticFunc1(a: Int) {} // PASS_COMMON-NEXT: {{^}} static func staticFunc1(a: Int){{$}} static func overloadedStaticFunc1() -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Int{{$}} static func overloadedStaticFunc1() -> Double { return 0.0 } // PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Double{{$}} static func overloadedStaticFunc2(x: Int) -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Int) -> Int{{$}} static func overloadedStaticFunc2(x: Double) -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Double) -> Int{{$}} } // PASS_COMMON-NEXT: {{^}} init(instanceVar1: Int){{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} extension d0100_FooStruct { // PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct {{{$}} var extProp: Int { get { return 42 } } // PASS_COMMON-NEXT: {{^}} var extProp: Int { get }{{$}} func extFunc0() {} // PASS_COMMON-NEXT: {{^}} func extFunc0(){{$}} static var extStaticProp: Int { get { return 42 } } // PASS_COMMON-NEXT: {{^}} static var extStaticProp: Int { get }{{$}} static func extStaticFunc0() {} // PASS_COMMON-NEXT: {{^}} static func extStaticFunc0(){{$}} struct ExtNestedStruct {} // PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} class ExtNestedClass {} // PASS_COMMON-NEXT: {{^}} class ExtNestedClass {{{$}} // PASS_COMMON-NEXT: {{^}} @objc deinit{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} enum ExtNestedEnum { case ExtEnumX(Int) } // PASS_COMMON-NEXT: {{^}} enum ExtNestedEnum {{{$}} // PASS_COMMON-NEXT: {{^}} case ExtEnumX(Int){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} typealias ExtNestedTypealias = Int // PASS_COMMON-NEXT: {{^}} typealias ExtNestedTypealias = Int{{$}} } // PASS_COMMON-NEXT: {{^}}}{{$}} extension d0100_FooStruct.NestedStruct { // PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.NestedStruct {{{$}} struct ExtNestedStruct2 {} // PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct2 {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} } extension d0100_FooStruct.ExtNestedStruct { // PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.ExtNestedStruct {{{$}} struct ExtNestedStruct3 {} // PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct3 {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} } // PASS_COMMON-NEXT: {{^}}}{{$}} var fooObject: d0100_FooStruct = d0100_FooStruct() // PASS_ONE_LINE-DAG: {{^}}var fooObject: d0100_FooStruct{{$}} struct d0110_ReadWriteProperties { // PASS_RW_PROP_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}} // PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}} var computedProp1: Int { get { return 42 } set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp1: Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp1: Int{{$}} subscript(i: Int) -> Int { get { return 42 } set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int{{$}} static var computedStaticProp1: Int { get { return 42 } set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int{{$}} var computedProp2: Int { mutating get { return 42 } set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}} var computedProp3: Int { get { return 42 } nonmutating set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}} var computedProp4: Int { mutating get { return 42 } nonmutating set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}} subscript(i: Float) -> Int { get { return 42 } nonmutating set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} init(){{$}} // PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} init(){{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}} extension d0110_ReadWriteProperties { // PASS_RW_PROP_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}} // PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}} var extProp: Int { get { return 42 } set(v) {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var extProp: Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var extProp: Int{{$}} static var extStaticProp: Int { get { return 42 } set(v) {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} static var extStaticProp: Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var extStaticProp: Int{{$}} } // PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}} class d0120_TestClassBase { // PASS_COMMON-LABEL: {{^}}class d0120_TestClassBase {{{$}} required init() {} // PASS_COMMON-NEXT: {{^}} required init(){{$}} // FIXME: Add these once we can SILGen them reasonable. // init?(fail: String) { } // init!(iuoFail: String) { } final func baseFunc1() {} // PASS_COMMON-NEXT: {{^}} final func baseFunc1(){{$}} func baseFunc2() {} // PASS_COMMON-NEXT: {{^}} func baseFunc2(){{$}} subscript(i: Int) -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Int { get }{{$}} class var baseClassVar1: Int { return 0 } // PASS_COMMON-NEXT: {{^}} class var baseClassVar1: Int { get }{{$}} // FIXME: final class var not allowed to have storage, but static is? // final class var baseClassVar2: Int = 0 final class var baseClassVar3: Int { return 0 } // PASS_COMMON-NEXT: {{^}} final class var baseClassVar3: Int { get }{{$}} static var baseClassVar4: Int = 0 // PASS_COMMON-NEXT: {{^}} static var baseClassVar4: Int{{$}} static var baseClassVar5: Int { return 0 } // PASS_COMMON-NEXT: {{^}} static var baseClassVar5: Int { get }{{$}} class func baseClassFunc1() {} // PASS_COMMON-NEXT: {{^}} class func baseClassFunc1(){{$}} final class func baseClassFunc2() {} // PASS_COMMON-NEXT: {{^}} final class func baseClassFunc2(){{$}} static func baseClassFunc3() {} // PASS_COMMON-NEXT: {{^}} static func baseClassFunc3(){{$}} } class d0121_TestClassDerived : d0120_TestClassBase { // PASS_COMMON-LABEL: {{^}}class d0121_TestClassDerived : d0120_TestClassBase {{{$}} required init() { super.init() } // PASS_COMMON-NEXT: {{^}} required init(){{$}} final override func baseFunc2() {} // PASS_COMMON-NEXT: {{^}} {{(override |final )+}}func baseFunc2(){{$}} override final subscript(i: Int) -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} override final subscript(i: Int) -> Int { get }{{$}} } protocol d0130_TestProtocol { // PASS_COMMON-LABEL: {{^}}protocol d0130_TestProtocol {{{$}} associatedtype NestedTypealias // PASS_COMMON-NEXT: {{^}} associatedtype NestedTypealias{{$}} var property1: Int { get } // PASS_COMMON-NEXT: {{^}} var property1: Int { get }{{$}} var property2: Int { get set } // PASS_COMMON-NEXT: {{^}} var property2: Int { get set }{{$}} func protocolFunc1() // PASS_COMMON-NEXT: {{^}} func protocolFunc1(){{$}} } @objc protocol d0140_TestObjCProtocol { // PASS_COMMON-LABEL: {{^}}@objc protocol d0140_TestObjCProtocol {{{$}} optional var property1: Int { get } // PASS_COMMON-NEXT: {{^}} @objc optional var property1: Int { get }{{$}} optional func protocolFunc1() // PASS_COMMON-NEXT: {{^}} @objc optional func protocolFunc1(){{$}} } protocol d0150_TestClassProtocol : class {} // PASS_COMMON-LABEL: {{^}}protocol d0150_TestClassProtocol : class {{{$}} @objc protocol d0151_TestClassProtocol {} // PASS_COMMON-LABEL: {{^}}@objc protocol d0151_TestClassProtocol {{{$}} @noreturn @_silgen_name("exit") func d0160_testNoReturn() // PASS_COMMON-LABEL: {{^}}@_silgen_name("exit"){{$}} // PASS_COMMON-NEXT: {{^}}@noreturn func d0160_testNoReturn(){{$}} @noreturn func d0161_testNoReturn() { d0160_testNoReturn() } // PASS_COMMON-LABEL: {{^}}@noreturn func d0161_testNoReturn(){{$}} class d0162_TestNoReturn { // PASS_COMMON-LABEL: {{^}}class d0162_TestNoReturn {{{$}} @noreturn func instanceFunc() { d0160_testNoReturn() } // PASS_COMMON-NEXT: {{^}} @noreturn func instanceFunc(){{$}} @noreturn func classFunc() {d0160_testNoReturn() } // PASS_COMMON-NEXT: {{^}} @noreturn func classFunc(){{$}} } class d0170_TestAvailability { // PASS_COMMON-LABEL: {{^}}class d0170_TestAvailability {{{$}} @available(*, unavailable) func f1() {} // PASS_COMMON-NEXT: {{^}} @available(*, unavailable){{$}} // PASS_COMMON-NEXT: {{^}} func f1(){{$}} @available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee") func f2() {} // PASS_COMMON-NEXT: {{^}} @available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee"){{$}} // PASS_COMMON-NEXT: {{^}} func f2(){{$}} @available(iOS, unavailable) @available(OSX, unavailable) func f3() {} // PASS_COMMON-NEXT: {{^}} @available(iOS, unavailable){{$}} // PASS_COMMON-NEXT: {{^}} @available(OSX, unavailable){{$}} // PASS_COMMON-NEXT: {{^}} func f3(){{$}} @available(iOS 8.0, OSX 10.10, *) func f4() {} // PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, OSX 10.10, *){{$}} // PASS_COMMON-NEXT: {{^}} func f4(){{$}} // Convert long-form @available() to short form when possible. @available(iOS, introduced: 8.0) @available(OSX, introduced: 10.10) func f5() {} // PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, OSX 10.10, *){{$}} // PASS_COMMON-NEXT: {{^}} func f5(){{$}} } @objc class d0180_TestIBAttrs { // PASS_COMMON-LABEL: {{^}}@objc class d0180_TestIBAttrs {{{$}} @IBAction func anAction(_: AnyObject) {} // PASS_COMMON-NEXT: {{^}} @IBAction @objc func anAction(_: AnyObject){{$}} @IBDesignable class ADesignableClass {} // PASS_COMMON-NEXT: {{^}} @IBDesignable class ADesignableClass {{{$}} } @objc class d0181_TestIBAttrs { // PASS_EXPLODE_PATTERN-LABEL: {{^}}@objc class d0181_TestIBAttrs {{{$}} @IBOutlet weak var anOutlet: d0181_TestIBAttrs! // PASS_EXPLODE_PATTERN-NEXT: {{^}} @IBOutlet @objc weak var anOutlet: @sil_weak d0181_TestIBAttrs!{{$}} @IBInspectable var inspectableProp: Int = 0 // PASS_EXPLODE_PATTERN-NEXT: {{^}} @IBInspectable @objc var inspectableProp: Int{{$}} } struct d0190_LetVarDecls { // PASS_PRINT_AST-LABEL: {{^}}struct d0190_LetVarDecls {{{$}} // PASS_PRINT_MODULE_INTERFACE-LABEL: {{^}}struct d0190_LetVarDecls {{{$}} let instanceVar1: Int = 0 // PASS_PRINT_AST-NEXT: {{^}} let instanceVar1: Int{{$}} // PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} let instanceVar1: Int{{$}} let instanceVar2 = 0 // PASS_PRINT_AST-NEXT: {{^}} let instanceVar2: Int{{$}} // PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} let instanceVar2: Int{{$}} static let staticVar1: Int = 42 // PASS_PRINT_AST-NEXT: {{^}} static let staticVar1: Int{{$}} // PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} static let staticVar1: Int{{$}} static let staticVar2 = 42 // FIXME: PRINTED_WITHOUT_TYPE // PASS_PRINT_AST-NEXT: {{^}} static let staticVar2: Int{{$}} // PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} static let staticVar2: Int{{$}} } struct d0200_EscapedIdentifiers { // PASS_COMMON-LABEL: {{^}}struct d0200_EscapedIdentifiers {{{$}} struct `struct` {} // PASS_COMMON-NEXT: {{^}} struct `struct` {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} enum `enum` { case `case` } // PASS_COMMON-NEXT: {{^}} enum `enum` {{{$}} // PASS_COMMON-NEXT: {{^}} case `case`{{$}} // PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} class `class` {} // PASS_COMMON-NEXT: {{^}} class `class` {{{$}} // PASS_COMMON-NEXT: {{^}} @objc deinit{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} typealias `protocol` = `class` // PASS_ONE_LINE_TYPE-DAG: {{^}} typealias `protocol` = d0200_EscapedIdentifiers.`class`{{$}} // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} typealias `protocol` = `class`{{$}} class `extension` : `class` {} // PASS_ONE_LINE_TYPE-DAG: {{^}} class `extension` : d0200_EscapedIdentifiers.`class` {{{$}} // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} class `extension` : `class` {{{$}} // PASS_COMMON: {{^}} @objc deinit{{$}} // PASS_COMMON-NEXT: {{^}} {{(override )?}}init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} func `func`<`let`: `protocol`, `where` where `where` : `protocol`>( class: Int, struct: `protocol`, foo: `let`, bar: `where`) {} // PASS_COMMON-NEXT: {{^}} func `func`<`let` : `protocol`, `where` where `where` : `protocol`>(class: Int, struct: `protocol`, foo: `let`, bar: `where`){{$}} var `var`: `struct` = `struct`() // PASS_COMMON-NEXT: {{^}} var `var`: {{(d0200_EscapedIdentifiers.)?}}`struct`{{$}} var tupleType: (`var`: Int, `let`: `struct`) // PASS_COMMON-NEXT: {{^}} var tupleType: (`var`: Int, `let`: {{(d0200_EscapedIdentifiers.)?}}`struct`){{$}} var accessors1: Int { get { return 0 } set(`let`) {} } // PASS_COMMON-NEXT: {{^}} var accessors1: Int{{( { get set })?}}{{$}} static func `static`(protocol: Int) {} // PASS_COMMON-NEXT: {{^}} static func `static`(protocol: Int){{$}} // PASS_COMMON-NEXT: {{^}} init(`var`: {{(d0200_EscapedIdentifiers.)?}}`struct`, tupleType: (`var`: Int, `let`: {{(d0200_EscapedIdentifiers.)?}}`struct`)){{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} } struct d0210_Qualifications { // PASS_QUAL_UNQUAL: {{^}}struct d0210_Qualifications {{{$}} // PASS_QUAL_IF_AMBIGUOUS: {{^}}struct d0210_Qualifications {{{$}} var propFromStdlib1: Int = 0 // PASS_QUAL_UNQUAL-NEXT: {{^}} var propFromStdlib1: Int{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} var propFromStdlib1: Int{{$}} var propFromSwift1: FooSwiftStruct = FooSwiftStruct() // PASS_QUAL_UNQUAL-NEXT: {{^}} var propFromSwift1: FooSwiftStruct{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} var propFromSwift1: foo_swift_module.FooSwiftStruct{{$}} var propFromClang1: FooStruct1 = FooStruct1(x: 0, y: 0.0) // PASS_QUAL_UNQUAL-NEXT: {{^}} var propFromClang1: FooStruct1{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} var propFromClang1: FooStruct1{{$}} func instanceFuncFromStdlib1(a: Int) -> Float { return 0.0 } // PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}} func instanceFuncFromStdlib2(a: ObjCBool) {} // PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}} func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct { return FooSwiftStruct() } // PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromSwift1(a: foo_swift_module.FooSwiftStruct) -> foo_swift_module.FooSwiftStruct{{$}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1 { return FooStruct1(x: 0, y: 0.0) } // PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}} } // FIXME: this should be printed reasonably in case we use // -prefer-type-repr=true. Either we should print the types we inferred, or we // should print the initializers. class d0250_ExplodePattern { // PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0250_ExplodePattern {{{$}} var instanceVar1 = 0 var instanceVar2 = 0.0 var instanceVar3 = "" // PASS_EXPLODE_PATTERN: {{^}} var instanceVar1: Int{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar2: Double{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar3: String{{$}} var instanceVar4 = FooStruct() var (instanceVar5, instanceVar6) = (FooStruct(), FooStruct()) var (instanceVar7, instanceVar8) = (FooStruct(), FooStruct()) var (instanceVar9, instanceVar10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct()) final var (instanceVar11, instanceVar12) = (FooStruct(), FooStruct()) // PASS_EXPLODE_PATTERN: {{^}} var instanceVar4: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar5: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar6: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar7: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar8: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar9: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar10: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final var instanceVar11: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final var instanceVar12: FooStruct{{$}} let instanceLet1 = 0 let instanceLet2 = 0.0 let instanceLet3 = "" // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet1: Int{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet2: Double{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet3: String{{$}} let instanceLet4 = FooStruct() let (instanceLet5, instanceLet6) = (FooStruct(), FooStruct()) let (instanceLet7, instanceLet8) = (FooStruct(), FooStruct()) let (instanceLet9, instanceLet10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct()) // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet4: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet5: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet6: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet7: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet8: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet9: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet10: FooStruct{{$}} } class d0260_ExplodePattern_TestClassBase { // PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0260_ExplodePattern_TestClassBase {{{$}} init() { baseProp1 = 0 } // PASS_EXPLODE_PATTERN-NEXT: {{^}} init(){{$}} final var baseProp1: Int // PASS_EXPLODE_PATTERN-NEXT: {{^}} final var baseProp1: Int{{$}} var baseProp2: Int { get { return 0 } set {} } // PASS_EXPLODE_PATTERN-NEXT: {{^}} var baseProp2: Int{{$}} } class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase { // PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase {{{$}} override final var baseProp2: Int { get { return 0 } set {} } // PASS_EXPLODE_PATTERN-NEXT: {{^}} override final var baseProp2: Int{{$}} } //===--- //===--- Inheritance list in structs. //===--- struct StructWithoutInheritance1 {} // PASS_ONE_LINE-DAG: {{^}}struct StructWithoutInheritance1 {{{$}} struct StructWithInheritance1 : FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance1 : FooProtocol {{{$}} struct StructWithInheritance2 : FooProtocol, BarProtocol {} // PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance2 : FooProtocol, BarProtocol {{{$}} struct StructWithInheritance3 : QuxProtocol, SubFooProtocol { typealias Qux = Int } // PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}} //===--- //===--- Inheritance list in classes. //===--- class ClassWithoutInheritance1 {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithoutInheritance1 {{{$}} class ClassWithInheritance1 : FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance1 : FooProtocol {{{$}} class ClassWithInheritance2 : FooProtocol, BarProtocol {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance2 : FooProtocol, BarProtocol {{{$}} class ClassWithInheritance3 : FooClass {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance3 : FooClass {{{$}} class ClassWithInheritance4 : FooClass, FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance4 : FooClass, FooProtocol {{{$}} class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {{{$}} class ClassWithInheritance6 : QuxProtocol, SubFooProtocol { typealias Qux = Int } // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance6 : QuxProtocol, SubFooProtocol {{{$}} //===--- //===--- Inheritance list in enums. //===--- enum EnumWithoutInheritance1 {} // PASS_ONE_LINE-DAG: {{^}}enum EnumWithoutInheritance1 {{{$}} enum EnumWithInheritance1 : FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance1 : FooProtocol {{{$}} enum EnumWithInheritance2 : FooProtocol, BarProtocol {} // PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance2 : FooProtocol, BarProtocol {{{$}} enum EnumDeclWithUnderlyingType1 : Int { case X } // PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType1 : Int {{{$}} enum EnumDeclWithUnderlyingType2 : Int, FooProtocol { case X } // PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType2 : Int, FooProtocol {{{$}} enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol { typealias Qux = Int } // PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}} //===--- //===--- Inheritance list in protocols. //===--- protocol ProtocolWithoutInheritance1 {} // PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithoutInheritance1 {{{$}} protocol ProtocolWithInheritance1 : FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance1 : FooProtocol {{{$}} protocol ProtocolWithInheritance2 : FooProtocol, BarProtocol { } // PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance2 : FooProtocol, BarProtocol {{{$}} protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol { } // PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}} //===--- //===--- Inheritance list in extensions //===--- struct StructInherited { } // PASS_ONE_LINE-DAG: {{.*}}extension StructInherited : QuxProtocol, SubFooProtocol {{{$}} extension StructInherited : QuxProtocol, SubFooProtocol { typealias Qux = Int } //===--- //===--- Typealias printing. //===--- // Normal typealiases. typealias SimpleTypealias1 = FooProtocol // PASS_ONE_LINE-DAG: {{^}}typealias SimpleTypealias1 = FooProtocol{{$}} // Associated types. protocol AssociatedType1 { associatedtype AssociatedTypeDecl1 = Int // PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl1 = Int{{$}} associatedtype AssociatedTypeDecl2 : FooProtocol // PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl2 : FooProtocol{{$}} associatedtype AssociatedTypeDecl3 : FooProtocol, BarProtocol // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl3 : FooProtocol, BarProtocol{{$}} } //===--- //===--- Variable declaration printing. //===--- var d0300_topLevelVar1: Int = 42 // PASS_COMMON: {{^}}var d0300_topLevelVar1: Int{{$}} // PASS_COMMON-NOT: d0300_topLevelVar1 var d0400_topLevelVar2: Int = 42 // PASS_COMMON: {{^}}var d0400_topLevelVar2: Int{{$}} // PASS_COMMON-NOT: d0400_topLevelVar2 var d0500_topLevelVar2: Int { get { return 42 } } // PASS_COMMON: {{^}}var d0500_topLevelVar2: Int { get }{{$}} // PASS_COMMON-NOT: d0500_topLevelVar2 class d0600_InClassVar1 { // PASS_O600-LABEL: d0600_InClassVar1 var instanceVar1: Int // PASS_COMMON: {{^}} var instanceVar1: Int{{$}} // PASS_COMMON-NOT: instanceVar1 var instanceVar2: Int = 42 // PASS_COMMON: {{^}} var instanceVar2: Int{{$}} // PASS_COMMON-NOT: instanceVar2 // FIXME: this is sometimes printed without a type, see PASS_EXPLODE_PATTERN. // FIXME: PRINTED_WITHOUT_TYPE var instanceVar3 = 42 // PASS_COMMON: {{^}} var instanceVar3 // PASS_COMMON-NOT: instanceVar3 var instanceVar4: Int { get { return 42 } } // PASS_COMMON: {{^}} var instanceVar4: Int { get }{{$}} // PASS_COMMON-NOT: instanceVar4 // FIXME: uncomment when we have static vars. // static var staticVar1: Int init() { instanceVar1 = 10 } } //===--- //===--- Subscript declaration printing. //===--- class d0700_InClassSubscript1 { // PASS_COMMON-LABEL: d0700_InClassSubscript1 subscript(i: Int) -> Int { get { return 42 } } subscript(index i: Float) -> Int { return 42 } class `class` {} subscript(x: Float) -> `class` { return `class`() } // PASS_COMMON: {{^}} subscript(i: Int) -> Int { get }{{$}} // PASS_COMMON: {{^}} subscript(index i: Float) -> Int { get }{{$}} // PASS_COMMON: {{^}} subscript(x: Float) -> {{.*}} { get }{{$}} // PASS_COMMON-NOT: subscript // PASS_ONE_LINE_TYPE: {{^}} subscript(x: Float) -> d0700_InClassSubscript1.`class` { get }{{$}} // PASS_ONE_LINE_TYPEREPR: {{^}} subscript(x: Float) -> `class` { get }{{$}} } // PASS_COMMON: {{^}}}{{$}} //===--- //===--- Constructor declaration printing. //===--- struct d0800_ExplicitConstructors1 { // PASS_COMMON-LABEL: d0800_ExplicitConstructors1 init() {} // PASS_COMMON: {{^}} init(){{$}} init(a: Int) {} // PASS_COMMON: {{^}} init(a: Int){{$}} } struct d0900_ExplicitConstructorsSelector1 { // PASS_COMMON-LABEL: d0900_ExplicitConstructorsSelector1 init(int a: Int) {} // PASS_COMMON: {{^}} init(int a: Int){{$}} init(int a: Int, andFloat b: Float) {} // PASS_COMMON: {{^}} init(int a: Int, andFloat b: Float){{$}} } struct d1000_ExplicitConstructorsSelector2 { // PASS_COMMON-LABEL: d1000_ExplicitConstructorsSelector2 init(noArgs _: ()) {} // PASS_COMMON: {{^}} init(noArgs _: ()){{$}} init(_ a: Int) {} // PASS_COMMON: {{^}} init(_ a: Int){{$}} init(_ a: Int, withFloat b: Float) {} // PASS_COMMON: {{^}} init(_ a: Int, withFloat b: Float){{$}} init(int a: Int, _ b: Float) {} // PASS_COMMON: {{^}} init(int a: Int, _ b: Float){{$}} } //===--- //===--- Destructor declaration printing. //===--- class d1100_ExplicitDestructor1 { // PASS_COMMON-LABEL: d1100_ExplicitDestructor1 deinit {} // PASS_COMMON: {{^}} @objc deinit{{$}} } //===--- //===--- Enum declaration printing. //===--- enum d2000_EnumDecl1 { case ED1_First case ED1_Second } // PASS_COMMON: {{^}}enum d2000_EnumDecl1 {{{$}} // PASS_COMMON-NEXT: {{^}} case ED1_First{{$}} // PASS_COMMON-NEXT: {{^}} case ED1_Second{{$}} // PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} enum d2100_EnumDecl2 { case ED2_A(Int) case ED2_B(Float) case ED2_C(Int, Float) case ED2_D(x: Int, y: Float) case ED2_E(x: Int, y: (Float, Double)) case ED2_F(x: Int, (y: Float, z: Double)) } // PASS_COMMON: {{^}}enum d2100_EnumDecl2 {{{$}} // PASS_COMMON-NEXT: {{^}} case ED2_A(Int){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_B(Float){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_C(Int, Float){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_D(x: Int, y: Float){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_E(x: Int, y: (Float, Double)){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_F(x: Int, (y: Float, z: Double)){{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} enum d2200_EnumDecl3 { case ED3_A, ED3_B case ED3_C(Int), ED3_D case ED3_E, ED3_F(Int) case ED3_G(Int), ED3_H(Int) case ED3_I(Int), ED3_J(Int), ED3_K } // PASS_2200: {{^}}enum d2200_EnumDecl3 {{{$}} // PASS_2200-NEXT: {{^}} case ED3_A, ED3_B{{$}} // PASS_2200-NEXT: {{^}} case ED3_C(Int), ED3_D{{$}} // PASS_2200-NEXT: {{^}} case ED3_E, ED3_F(Int){{$}} // PASS_2200-NEXT: {{^}} case ED3_G(Int), ED3_H(Int){{$}} // PASS_2200-NEXT: {{^}} case ED3_I(Int), ED3_J(Int), ED3_K{{$}} // PASS_2200-NEXT: {{^}}}{{$}} // PASS_2200_DESERIALIZED: {{^}}enum d2200_EnumDecl3 {{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_A{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_B{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_C(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_D{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_E{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_F(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_G(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_H(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_I(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_J(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_K{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}}}{{$}} enum d2300_EnumDeclWithValues1 : Int { case EDV2_First = 10 case EDV2_Second } // PASS_COMMON: {{^}}enum d2300_EnumDeclWithValues1 : Int {{{$}} // PASS_COMMON-NEXT: {{^}} case EDV2_First{{$}} // PASS_COMMON-NEXT: {{^}} case EDV2_Second{{$}} // PASS_COMMON-NEXT: {{^}} typealias RawValue = Int // PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}} init?(rawValue: Int){{$}} // PASS_COMMON-NEXT: {{^}} var rawValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} enum d2400_EnumDeclWithValues2 : Double { case EDV3_First = 10 case EDV3_Second } // PASS_COMMON: {{^}}enum d2400_EnumDeclWithValues2 : Double {{{$}} // PASS_COMMON-NEXT: {{^}} case EDV3_First{{$}} // PASS_COMMON-NEXT: {{^}} case EDV3_Second{{$}} // PASS_COMMON-NEXT: {{^}} typealias RawValue = Double // PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}} init?(rawValue: Double){{$}} // PASS_COMMON-NEXT: {{^}} var rawValue: Double { get }{{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} //===--- //===--- Custom operator printing. //===--- postfix operator <*> {} // PASS_2500-LABEL: {{^}}postfix operator <*> {{{$}} // PASS_2500-NEXT: {{^}}}{{$}} protocol d2600_ProtocolWithOperator1 { postfix func <*>(_: Int) } // PASS_2500: {{^}}protocol d2600_ProtocolWithOperator1 {{{$}} // PASS_2500-NEXT: {{^}} postfix func <*>(_: Int){{$}} // PASS_2500-NEXT: {{^}}}{{$}} struct d2601_TestAssignment {} infix operator %%% { } func %%%(lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int { return 0 } // PASS_2500-LABEL: {{^}}infix operator %%% { // PASS_2500-NOT: associativity // PASS_2500-NOT: precedence // PASS_2500-NOT: assignment // PASS_2500: {{^}}func %%%(lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int{{$}} infix operator %%< { // PASS_2500-LABEL: {{^}}infix operator %%< {{{$}} associativity left // PASS_2500-NEXT: {{^}} associativity left{{$}} precedence 47 // PASS_2500-NEXT: {{^}} precedence 47{{$}} // PASS_2500-NOT: assignment } infix operator %%> { // PASS_2500-LABEL: {{^}}infix operator %%> {{{$}} associativity right // PASS_2500-NEXT: {{^}} associativity right{{$}} // PASS_2500-NOT: precedence // PASS_2500-NOT: assignment } infix operator %%<> { // PASS_2500-LABEL: {{^}}infix operator %%<> {{{$}} precedence 47 assignment // PASS_2500-NEXT: {{^}} precedence 47{{$}} // PASS_2500-NEXT: {{^}} assignment{{$}} // PASS_2500-NOT: associativity } // PASS_2500: {{^}}}{{$}} //===--- //===--- Printing of deduced associated types. //===--- protocol d2700_ProtocolWithAssociatedType1 { associatedtype TA1 func returnsTA1() -> TA1 } // PASS_COMMON: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}} // PASS_COMMON-NEXT: {{^}} associatedtype TA1{{$}} // PASS_COMMON-NEXT: {{^}} func returnsTA1() -> Self.TA1{{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 { func returnsTA1() -> Int { return 42 } } // PASS_COMMON: {{^}}struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 {{{$}} // PASS_COMMON-NEXT: {{^}} func returnsTA1() -> Int{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} typealias TA1 = Int // PASS_COMMON-NEXT: {{^}}}{{$}} //===--- //===--- Generic parameter list printing. //===--- struct GenericParams1< StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : protocol<FooProtocol, BarProtocol>, StructGenericBaz> { // PASS_ONE_LINE_TYPE-DAG: {{^}}struct GenericParams1<StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : protocol<BarProtocol, FooProtocol>, StructGenericBaz> {{{$}} // FIXME: in protocol compositions protocols are listed in reverse order. // // PASS_ONE_LINE_TYPEREPR-DAG: {{^}}struct GenericParams1<StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : protocol<FooProtocol, BarProtocol>, StructGenericBaz> {{{$}} init< GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : protocol<FooProtocol, BarProtocol>, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) {} // PASS_ONE_LINE_TYPE-DAG: {{^}} init<GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : protocol<BarProtocol, FooProtocol>, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz){{$}} // FIXME: in protocol compositions protocols are listed in reverse order. // // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} init<GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : protocol<FooProtocol, BarProtocol>, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz){{$}} func genericParams1< GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : protocol<FooProtocol, BarProtocol>, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) {} // PASS_ONE_LINE_TYPE-DAG: {{^}} func genericParams1<GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : protocol<BarProtocol, FooProtocol>, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz){{$}} // FIXME: in protocol compositions protocols are listed in reverse order. // // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} func genericParams1<GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : protocol<FooProtocol, BarProtocol>, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz){{$}} } struct GenericParams2<T : FooProtocol where T : BarProtocol> {} // PASS_ONE_LINE-DAG: {{^}}struct GenericParams2<T : FooProtocol where T : BarProtocol> {{{$}} struct GenericParams3<T : FooProtocol where T : BarProtocol, T : QuxProtocol> {} // PASS_ONE_LINE-DAG: {{^}}struct GenericParams3<T : FooProtocol where T : BarProtocol, T : QuxProtocol> {{{$}} struct GenericParams4<T : QuxProtocol where T.Qux : FooProtocol> {} // PASS_ONE_LINE-DAG: {{^}}struct GenericParams4<T : QuxProtocol where T.Qux : FooProtocol> {{{$}} struct GenericParams5<T : QuxProtocol where T.Qux : protocol<FooProtocol, BarProtocol>> {} // PREFER_TYPE_PRINTING: {{^}}struct GenericParams5<T : QuxProtocol where T.Qux : protocol<BarProtocol, FooProtocol>> {{{$}} // FIXME: in protocol compositions protocols are listed in reverse order. // // PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams5<T : QuxProtocol where T.Qux : protocol<FooProtocol, BarProtocol>> {{{$}} struct GenericParams6<T : QuxProtocol, U : QuxProtocol where T.Qux == U.Qux> {} // Because of the same type conformance, 'T.Qux' and 'U.Qux' types are // identical, so they are printed exactly the same way. Printing a TypeRepr // allows us to recover the original spelling. // // PREFER_TYPE_PRINTING: {{^}}struct GenericParams6<T : QuxProtocol, U : QuxProtocol where T.Qux == T.Qux> {{{$}} // PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams6<T : QuxProtocol, U : QuxProtocol where T.Qux == U.Qux> {{{$}} struct GenericParams7<T : QuxProtocol, U : QuxProtocol where T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux> {} // PREFER_TYPE_PRINTING: {{^}}struct GenericParams7<T : QuxProtocol, U : QuxProtocol where T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == T.Qux.Qux> {{{$}} // PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams7<T : QuxProtocol, U : QuxProtocol where T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux> {{{$}} //===--- //===--- Tupe sugar for library types. //===--- struct d2900_TypeSugar1 { // PASS_COMMON-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}} // SYNTHESIZE_SUGAR_ON_TYPES-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}} func f1(x: [Int]) {} // PASS_COMMON-NEXT: {{^}} func f1(x: [Int]){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f1(x: [Int]){{$}} func f2(x: Array<Int>) {} // PASS_COMMON-NEXT: {{^}} func f2(x: Array<Int>){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f2(x: [Int]){{$}} func f3(x: Int?) {} // PASS_COMMON-NEXT: {{^}} func f3(x: Int?){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f3(x: Int?){{$}} func f4(x: Optional<Int>) {} // PASS_COMMON-NEXT: {{^}} func f4(x: Optional<Int>){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f4(x: Int?){{$}} func f5(x: [Int]...) {} // PASS_COMMON-NEXT: {{^}} func f5(x: [Int]...){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f5(x: [Int]...){{$}} func f6(x: Array<Int>...) {} // PASS_COMMON-NEXT: {{^}} func f6(x: Array<Int>...){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f6(x: [Int]...){{$}} func f7(x: [Int : Int]...) {} // PASS_COMMON-NEXT: {{^}} func f7(x: [Int : Int]...){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f7(x: [Int : Int]...){{$}} func f8(x: Dictionary<String, Int>...) {} // PASS_COMMON-NEXT: {{^}} func f8(x: Dictionary<String, Int>...){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f8(x: [String : Int]...){{$}} } // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} // @warn_unused_result attribute public struct ArrayThingy { // PASS_PRINT_AST: @warn_unused_result(mutable_variant: "sort") // PASS_PRINT_AST-NEXT: public func sort() -> ArrayThingy @warn_unused_result(mutable_variant: "sort") public func sort() -> ArrayThingy { return self } public mutating func sort() { } // PASS_PRINT_AST: @warn_unused_result(message: "dummy", mutable_variant: "reverseInPlace") // PASS_PRINT_AST-NEXT: public func reverse() -> ArrayThingy @warn_unused_result(message: "dummy", mutable_variant: "reverseInPlace") public func reverse() -> ArrayThingy { return self } public mutating func reverseInPlace() { } // PASS_PRINT_AST: @warn_unused_result // PASS_PRINT_AST-NEXT: public func mineGold() -> Int @warn_unused_result public func mineGold() -> Int { return 0 } // PASS_PRINT_AST: @warn_unused_result(message: "oops") // PASS_PRINT_AST-NEXT: public func mineCopper() -> Int @warn_unused_result(message: "oops") public func mineCopper() -> Int { return 0 } } // @discardableResult attribute public struct DiscardableThingy { // PASS_PRINT_AST: @discardableResult // PASS_PRINT_AST-NEXT: public init() @discardableResult public init() {} // PASS_PRINT_AST: @discardableResult // PASS_PRINT_AST-NEXT: public func useless() -> Int @discardableResult public func useless() -> Int { return 0 } } // Parameter Attributes. // <rdar://problem/19775868> Swift 1.2b1: Header gen puts @autoclosure in the wrong place // PASS_PRINT_AST: public func ParamAttrs1(@autoclosure a: () -> ()) public func ParamAttrs1(@autoclosure a : () -> ()) { a() } // PASS_PRINT_AST: public func ParamAttrs2(@autoclosure(escaping) a: () -> ()) public func ParamAttrs2(@autoclosure(escaping) a : () -> ()) { a() } // PASS_PRINT_AST: public func ParamAttrs3(@noescape a: () -> ()) public func ParamAttrs3(@noescape a : () -> ()) { a() } // Protocol extensions protocol ProtocolToExtend { associatedtype Assoc } extension ProtocolToExtend where Self.Assoc == Int {} // PREFER_TYPE_REPR_PRINTING: extension ProtocolToExtend where Self.Assoc == Int { #if true #elseif false #else #endif // PASS_PRINT_AST: #if // PASS_PRINT_AST: #elseif // PASS_PRINT_AST: #else // PASS_PRINT_AST: #endif public struct MyPair<A, B> { var a: A, b: B } public typealias MyPairI<B> = MyPair<Int, B> // PASS_PRINT_AST: public typealias MyPairI<B> = MyPair<Int, B> public typealias MyPairAlias<T, U> = MyPair<T, U> // PASS_PRINT_AST: public typealias MyPairAlias<T, U> = MyPair<T, U>
apache-2.0
a392b1cc9d6a462c4890ad2822877d09
36.74653
364
0.642284
3.630392
false
false
false
false
ShenghaiWang/FolioReaderKit
Source/FolioReaderAudioPlayer.swift
3
16463
// // FolioReaderAudioPlayer.swift // FolioReaderKit // // Created by Kevin Jantzer on 1/4/16. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit import AVFoundation import MediaPlayer open class FolioReaderAudioPlayer: NSObject { var isTextToSpeech = false var synthesizer: AVSpeechSynthesizer! var playing = false var player: AVAudioPlayer? var currentHref: String! var currentFragment: String! var currentSmilFile: FRSmilFile! var currentAudioFile: String! var currentBeginTime: Double! var currentEndTime: Double! var playingTimer: Timer! var registeredCommands = false var completionHandler: () -> Void = {} var utteranceRate: Float = 0 // MARK: Init override init() { super.init() UIApplication.shared.beginReceivingRemoteControlEvents() // this is needed to the audio can play even when the "silent/vibrate" toggle is on let session:AVAudioSession = AVAudioSession.sharedInstance() try! session.setCategory(AVAudioSessionCategoryPlayback) try! session.setActive(true) updateNowPlayingInfo() } deinit { UIApplication.shared.endReceivingRemoteControlEvents() } // MARK: Reading speed func setRate(_ rate: Int) { if let player = player { switch rate { case 0: player.rate = 0.5 break case 1: player.rate = 1.0 break case 2: player.rate = 1.5 break case 3: player.rate = 2 break default: break } updateNowPlayingInfo() } if synthesizer != nil { // Need to change between version IOS // http://stackoverflow.com/questions/32761786/ios9-avspeechutterance-rate-for-avspeechsynthesizer-issue if #available(iOS 9, *) { switch rate { case 0: utteranceRate = 0.42 break case 1: utteranceRate = 0.5 break case 2: utteranceRate = 0.53 break case 3: utteranceRate = 0.56 break default: break } } else { switch rate { case 0: utteranceRate = 0 break case 1: utteranceRate = 0.06 break case 2: utteranceRate = 0.15 break case 3: utteranceRate = 0.23 break default: break } } updateNowPlayingInfo() } } // MARK: Play, Pause, Stop controls func stop(immediate: Bool = false) { playing = false if !isTextToSpeech { if let player = player , player.isPlaying { player.stop() } } else { stopSynthesizer(immediate: immediate, completion: nil) } // UIApplication.sharedApplication().idleTimerDisabled = false } func stopSynthesizer(immediate: Bool = false, completion: (() -> Void)? = nil) { synthesizer.stopSpeaking(at: immediate ? .immediate : .word) completion?() } func pause() { playing = false if !isTextToSpeech { if let player = player , player.isPlaying { player.pause() } } else { if synthesizer.isSpeaking { synthesizer.pauseSpeaking(at: .word) } } // UIApplication.sharedApplication().idleTimerDisabled = false } func togglePlay() { isPlaying() ? pause() : play() } func play() { if book.hasAudio() { guard let currentPage = FolioReader.shared.readerCenter?.currentPage else { return } currentPage.webView.js("playAudio()") } else { readCurrentSentence() } // UIApplication.sharedApplication().idleTimerDisabled = true } func isPlaying() -> Bool { return playing } /** Play Audio (href/fragmentID) Begins to play audio for the given chapter (href) and text fragment. If this chapter does not have audio, it will delay for a second, then attempt to play the next chapter */ func playAudio(_ href: String, fragmentID: String) { isTextToSpeech = false stop() let smilFile = book.smilFileForHref(href) // if no smil file for this href and the same href is being requested, we've hit the end. stop playing if smilFile == nil && currentHref != nil && href == currentHref { return } playing = true currentHref = href currentFragment = "#"+fragmentID currentSmilFile = smilFile // if no smil file, delay for a second, then move on to the next chapter if smilFile == nil { Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(_autoPlayNextChapter), userInfo: nil, repeats: false) return } let fragment = smilFile?.parallelAudioForFragment(currentFragment) if fragment != nil { if _playFragment(fragment) { startPlayerTimer() } } } func _autoPlayNextChapter() { // if user has stopped playing, dont play the next chapter if isPlaying() == false { return } playNextChapter() } func playPrevChapter() { stopPlayerTimer() // Wait for "currentPage" to update, then request to play audio FolioReader.shared.readerCenter?.changePageToPrevious { if self.isPlaying() { self.play() } else { self.pause() } } } func playNextChapter() { stopPlayerTimer() // Wait for "currentPage" to update, then request to play audio FolioReader.shared.readerCenter?.changePageToNext { if self.isPlaying() { self.play() } } } /** Play Fragment of audio Once an audio fragment begins playing, the audio clip will continue playing until the player timer detects the audio is out of the fragment timeframe. */ @discardableResult fileprivate func _playFragment(_ smil: FRSmilElement!) -> Bool { if smil == nil { print("no more parallel audio to play") stop() return false } let textFragment = smil.textElement().attributes["src"] let audioFile = smil.audioElement().attributes["src"] currentBeginTime = smil.clipBegin() currentEndTime = smil.clipEnd() // new audio file to play, create the audio player if player == nil || (audioFile != nil && audioFile != currentAudioFile) { currentAudioFile = audioFile let fileURL = currentSmilFile.resource.basePath() + ("/"+audioFile!) let audioData = try? Data(contentsOf: URL(fileURLWithPath: fileURL)) do { player = try AVAudioPlayer(data: audioData!) guard let player = player else { return false } setRate(FolioReader.currentAudioRate) player.enableRate = true player.prepareToPlay() player.delegate = self updateNowPlayingInfo() } catch { print("could not read audio file:", audioFile ?? "nil") return false } } // if player is initialized properly, begin playing guard let player = player else { return false } // the audio may be playing already, so only set the player time if it is NOT already within the fragment timeframe // this is done to mitigate milisecond skips in the audio when changing fragments if player.currentTime < currentBeginTime || ( currentEndTime > 0 && player.currentTime > currentEndTime) { player.currentTime = currentBeginTime; updateNowPlayingInfo() } player.play() // get the fragment ID so we can "mark" it in the webview let textParts = textFragment!.components(separatedBy: "#") let fragmentID = textParts[1]; FolioReader.shared.readerCenter?.audioMark(href: currentHref, fragmentID: fragmentID) return true } /** Next Audio Fragment Gets the next audio fragment in the current smil file, or moves on to the next smil file */ fileprivate func nextAudioFragment() -> FRSmilElement! { let smilFile = book.smilFileForHref(currentHref) if smilFile == nil { return nil } let smil = currentFragment == nil ? smilFile?.parallelAudioForFragment(nil) : smilFile?.nextParallelAudioForFragment(currentFragment) if smil != nil { currentFragment = smil?.textElement().attributes["src"] return smil } currentHref = book.spine.nextChapter(currentHref)!.href currentFragment = nil currentSmilFile = smilFile if currentHref == nil { return nil } return nextAudioFragment() } func playText(_ href: String, text: String) { isTextToSpeech = true playing = true currentHref = href if synthesizer == nil { synthesizer = AVSpeechSynthesizer() synthesizer.delegate = self setRate(FolioReader.currentAudioRate) } let utterance = AVSpeechUtterance(string: text) utterance.rate = utteranceRate utterance.voice = AVSpeechSynthesisVoice(language: book.metadata.language) if synthesizer.isSpeaking { stopSynthesizer() } synthesizer.speak(utterance) updateNowPlayingInfo() } // MARK: TTS Sentence func speakSentence() { guard let readerCenter = FolioReader.shared.readerCenter, let currentPage = readerCenter.currentPage else { return } let sentence = currentPage.webView.js("getSentenceWithIndex('\(book.playbackActiveClass())')") if sentence != nil { let chapter = readerCenter.getCurrentChapter() let href = chapter != nil ? chapter!.href : ""; playText(href!, text: sentence!) } else { if readerCenter.isLastPage() { stop() } else { readerCenter.changePageToNext() } } } func readCurrentSentence() { guard synthesizer != nil else { return speakSentence() } if synthesizer.isPaused { playing = true synthesizer.continueSpeaking() } else { if synthesizer.isSpeaking { stopSynthesizer(immediate: false, completion: { if let currentPage = FolioReader.shared.readerCenter?.currentPage { currentPage.webView.js("resetCurrentSentenceIndex()") } self.speakSentence() }) } else { speakSentence() } } } // MARK: - Audio timing events fileprivate func startPlayerTimer() { // we must add the timer in this mode in order for it to continue working even when the user is scrolling a webview playingTimer = Timer(timeInterval: 0.01, target: self, selector: #selector(playerTimerObserver), userInfo: nil, repeats: true) RunLoop.current.add(playingTimer, forMode: RunLoopMode.commonModes) } fileprivate func stopPlayerTimer() { if playingTimer != nil { playingTimer.invalidate() playingTimer = nil } } func playerTimerObserver() { guard let player = player else { return } if currentEndTime != nil && currentEndTime > 0 && player.currentTime > currentEndTime { _playFragment(nextAudioFragment()) } } // MARK: - Now Playing Info and Controls /** Update Now Playing info Gets the book and audio information and updates on Now Playing Center */ func updateNowPlayingInfo() { var songInfo = [String: AnyObject]() // Get book Artwork if let coverImage = book.coverImage, let artwork = UIImage(contentsOfFile: coverImage.fullHref) { let albumArt = MPMediaItemArtwork(image: artwork) songInfo[MPMediaItemPropertyArtwork] = albumArt } // Get book title if let title = book.title() { songInfo[MPMediaItemPropertyAlbumTitle] = title as AnyObject? } // Get chapter name if let chapter = getCurrentChapterName() { songInfo[MPMediaItemPropertyTitle] = chapter as AnyObject? } // Get author name if let author = book.metadata.creators.first { songInfo[MPMediaItemPropertyArtist] = author.name as AnyObject? } // Set player times if let player = player , !isTextToSpeech { songInfo[MPMediaItemPropertyPlaybackDuration] = player.duration as AnyObject? songInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate as AnyObject? songInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime ] = player.currentTime as AnyObject? } // Set Audio Player info MPNowPlayingInfoCenter.default().nowPlayingInfo = songInfo registerCommandsIfNeeded() } /** Get Current Chapter Name This is done here and not in ReaderCenter because even though `currentHref` is accurate, the `currentPage` in ReaderCenter may not have updated just yet */ func getCurrentChapterName() -> String? { guard let chapter = FolioReader.shared.readerCenter?.getCurrentChapter() else { return nil } currentHref = chapter.href for item in book.flatTableOfContents { if let resource = item.resource , resource.href == currentHref { return item.title } } return nil } /** Register commands if needed, check if it's registered to avoid register twice. */ func registerCommandsIfNeeded() { guard !registeredCommands else { return } let command = MPRemoteCommandCenter.shared() command.previousTrackCommand.isEnabled = true command.previousTrackCommand.addTarget(self, action: #selector(playPrevChapter)) command.nextTrackCommand.isEnabled = true command.nextTrackCommand.addTarget(self, action: #selector(playNextChapter)) command.pauseCommand.isEnabled = true command.pauseCommand.addTarget(self, action: #selector(pause)) command.playCommand.isEnabled = true command.playCommand.addTarget(self, action: #selector(play)) command.togglePlayPauseCommand.isEnabled = true command.togglePlayPauseCommand.addTarget(self, action: #selector(togglePlay)) registeredCommands = true } } // MARK: AVSpeechSynthesizerDelegate extension FolioReaderAudioPlayer: AVSpeechSynthesizerDelegate { public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) { completionHandler() } public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { if isPlaying() { readCurrentSentence() } } } // MARK: AVAudioPlayerDelegate extension FolioReaderAudioPlayer: AVAudioPlayerDelegate { public func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { _playFragment(nextAudioFragment()) } }
bsd-3-clause
878ce7dc6c5f634f0f7391a3037ca675
30.179924
141
0.574379
5.524497
false
false
false
false
thewisecity/declarehome-ios
CookedApp/TableViewControllers/AlertsTableViewController.swift
1
5238
// // AlertsTableViewController.swift // CookedApp // // Created by Dexter Lohnes on 10/21/15. // Copyright © 2015 The Wise City. All rights reserved. // import UIKit class AlertsTableViewController: PFQueryTableViewController { var navDelegate: NavigationDelegate! var statusLabel: UILabel! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.paginationEnabled = true self.objectsPerPage = 10 } override func viewDidLoad() { super.viewDidLoad() self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 80 statusLabel = UILabel() statusLabel.text = "Loading..." view.addSubview(statusLabel) statusLabel.sizeToFit() statusLabel.center = CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2); statusLabel.hidden = true } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) Stats.ScreenAlerts() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func objectsDidLoad(error: NSError?) { super.objectsDidLoad(error) if error != nil { statusLabel.lineBreakMode = .ByWordWrapping statusLabel.numberOfLines = 0 statusLabel.text = "Error while loading. Please try again." statusLabel.sizeToFit() let f = statusLabel.frame statusLabel.frame = CGRectMake(f.origin.x, f.origin.y, view.frame.size.width - 40, f.size.height * 2) statusLabel.center = CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2); statusLabel.hidden = false } else if objects?.count == 0 { statusLabel.lineBreakMode = .ByWordWrapping statusLabel.numberOfLines = 0 statusLabel.text = "No alerts have been posted from your groups" statusLabel.sizeToFit() let f = statusLabel.frame statusLabel.frame = CGRectMake(f.origin.x, f.origin.y, view.frame.size.width - 40, f.size.height * 2) statusLabel.center = CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2); statusLabel.hidden = false } else { statusLabel.hidden = true } } override func queryForTable() -> PFQuery { let query = PFQuery(className: self.parseClassName!) query.orderByDescending("createdAt") query.whereKey(Message._IS_ALERT, equalTo: true) let adminOfQuery = PFUser.currentUser()?.relationForKey("adminOf").query() let memberOfQuery = PFUser.currentUser()?.relationForKey("memberOf").query() let groupsQuery = PFQuery.orQueryWithSubqueries([adminOfQuery!, memberOfQuery!]) query.whereKey(Message._GROUPS, matchesQuery: groupsQuery) query.includeKey(Message._CATEGORY) query.includeKey(Message._AUTHOR) query.includeKey(Message._AUTHOR_ADMIN_ARRAY) query.includeKey(Message._AUTHOR_MEMBER_ARRAY) return query } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? { let cellIdentifier = "MessageCell" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? MessageCell if cell == nil { cell = MessageCell(style: .Subtitle, reuseIdentifier: cellIdentifier) } // Configure the cell to show todo item with a priority at the bottom if let message = object as? Message { cell?.message = message } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print(indexPath.row) print(self.objects?.count) if indexPath.row >= self.objects?.count { loadNextPage() return } let selectedMessage = objectAtIndexPath(indexPath) as? Message let author = selectedMessage?.author navDelegate.performSegueWithId("ViewUserDetailsSegue", sender: author) } // 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?) { super.prepareForSegue(segue, sender: sender) // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. // if let selectedGroup = sender as? Group{ // if let destinationController = segue.destinationViewController as? GroupDetailsViewController { // destinationController.group = selectedGroup // } // } } }
gpl-3.0
d82acca73fad2cd406b66f436ad4eb5b
34.385135
138
0.616956
5.231768
false
false
false
false
SwiftFMI/iOS_2017_2018
Upr/06.01.2018/PhotoLibraryDemo/PhotoLibraryDemo/PhotoLibrary.swift
1
5824
// // PhotoLibrary.swift // PhotoLibraryDemo // // Created by Dragomir Ivanov on 6.01.18. // Copyright © 2018 Swift FMI. All rights reserved. // import Foundation import Photos fileprivate protocol ImageRepresentable { var asset: PHAsset? { get } var size: CGSize { get } } public struct Photo { fileprivate let phAsset: PHAsset } extension Photo: ImageRepresentable { var asset: PHAsset? { return phAsset } var size: CGSize { return CGSize(width: 100, height: 100) } } public struct Album { let photos: [Photo] let title: String var thumbnailPhoto: Photo? { return photos.first } fileprivate init?(collection: PHAssetCollection?) { guard let assetCollection = collection else { return nil } let result = PHAsset.fetchAssets(in: assetCollection, options: nil) guard result.count != 0 else { return nil } var photos = [Photo]() result.enumerateObjects { (asset, index, stop) in photos.append(Photo(phAsset: asset)) } self.photos = photos self.title = assetCollection.localizedTitle ?? "Album" } } extension Album: ImageRepresentable { var asset: PHAsset? { return thumbnailPhoto?.phAsset } var size: CGSize { return CGSize(width: 75, height: 75) } } public final class PhotoLibrary { public static let library = PhotoLibrary() private init() {} private (set) var albums: [Album]? func loadAlbums(completionHandler: @escaping () -> Void) { guard PHPhotoLibrary.authorizationStatus() != .notDetermined else { PHPhotoLibrary.requestAuthorization() { [weak self] status in self?.loadAlbums(completionHandler: completionHandler) } return } DispatchQueue.global().async { [weak self] in var albums = [Album?]() func getSmartAlbum(of type: PHAssetCollectionSubtype) -> PHAssetCollection? { return PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: type, options: nil).firstObject } let all = Album(collection: getSmartAlbum(of: .smartAlbumUserLibrary)) albums.append(all) let favorites = Album(collection: getSmartAlbum(of: .smartAlbumFavorites)) albums.append(favorites) let selfies = Album(collection: getSmartAlbum(of: .smartAlbumSelfPortraits)) albums.append(selfies) let screenshots = Album(collection: getSmartAlbum(of: .smartAlbumScreenshots)) albums.append(screenshots) let userAlbums = PHCollectionList.fetchTopLevelUserCollections(with: nil) userAlbums.enumerateObjects { (collection, index, stop) in let userAlbum = Album(collection: collection as? PHAssetCollection ?? nil) albums.append(userAlbum) } self?.albums = albums.flatMap { $0 } DispatchQueue.main.async { completionHandler() } } } } public extension PhotoLibrary { private static var photoOptions: PHImageRequestOptions = { let options = PHImageRequestOptions() options.deliveryMode = .opportunistic options.isNetworkAccessAllowed = true options.isSynchronous = true return options }() private static let requestQueue = DispatchQueue(label: "photos.demo.queue") static func requestImage(for photo: Photo, targetSize: CGSize? = nil, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) { PhotoLibrary.requestQueue.async { executeImageRequest(for: photo, targetSize: targetSize, options: PhotoLibrary.photoOptions, resultHandler: { (image, info) in DispatchQueue.main.async { resultHandler(image, info) } }) } } private static var thumbnailOptions: PHImageRequestOptions = { let options = PHImageRequestOptions() options.deliveryMode = .opportunistic options.resizeMode = .exact options.isNetworkAccessAllowed = true return options }() static func requestThumbnail(for album: Album, targetSize: CGSize? = nil, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) { guard let asset = album.thumbnailPhoto?.phAsset else { return } let scale = CGAffineTransform(scaleX: CGFloat(1.0) / CGFloat(asset.pixelWidth), y: CGFloat(1.0) / CGFloat(asset.pixelHeight)) let cropSideLength = min(asset.pixelWidth, asset.pixelHeight) let square = CGRect(x: 0, y: 0, width: cropSideLength, height: cropSideLength) let cropRect = square.applying(scale) let options = PhotoLibrary.thumbnailOptions options.normalizedCropRect = cropRect executeImageRequest(for: album, targetSize: targetSize, options: options, resultHandler: resultHandler) } private static func executeImageRequest(for imageRepresentable: ImageRepresentable, targetSize: CGSize? = nil, options: PHImageRequestOptions, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) { guard let asset = imageRepresentable.asset else { return } let size = targetSize ?? imageRepresentable.size PHCachingImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: options, resultHandler: resultHandler) } }
apache-2.0
3d0a8cdbd38be45f88bdbc49323e4b3a
32.465517
215
0.615834
5.293636
false
false
false
false
jeffreybergier/Hipstapaper
Hipstapaper/Packages/V3Model/Sources/V3Model/Tag.swift
1
2761
// // Created by Jeffrey Bergier on 2022/06/17. // // MIT License // // Copyright (c) 2021 Jeffrey Bergier // // 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 struct Tag: Identifiable, Hashable, Equatable { public typealias Selection = Set<Tag.Identifier> public struct Identifier: Hashable, Equatable, Codable, RawRepresentable, Identifiable { public enum Kind: String { case systemAll, systemUnread, user } public var id: String public var kind: Kind = .user public init(_ rawValue: String, kind: Kind = .user) { self.id = rawValue self.kind = kind } public var rawValue: String { self.kind.rawValue + "|.|.|" + self.id } public init?(rawValue: String) { let comps = rawValue.components(separatedBy: "|.|.|") guard comps.count == 2, let kind = Kind(rawValue: comps[0]) else { return nil } self.id = comps[1] self.kind = kind } } public var id: Identifier public var name: String? public var websitesCount: Int? public var dateCreated: Date? public var dateModified: Date? public init(id: Identifier, name: String? = nil, websitesCount: Int? = nil, dateCreated: Date? = nil, dateModified: Date? = nil) { self.id = id self.name = name self.websitesCount = websitesCount self.dateCreated = dateCreated self.dateModified = dateModified } }
mit
7235ed833a4bf182d8e9d39070f12eea
33.08642
92
0.620427
4.586379
false
false
false
false
Finb/V2ex-Swift
Controller/LoginViewController.swift
1
17442
// // LoginViewController.swift // V2ex-Swift // // Created by huangfeng on 1/22/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit import OnePasswordExtension import Kingfisher import SVProgressHUD import Alamofire public typealias LoginSuccessHandel = (String) -> Void class LoginViewController: UIViewController { var successHandel:LoginSuccessHandel? let backgroundImageView = UIImageView() let frostedView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) let userNameTextField:UITextField = { let userNameTextField = UITextField() userNameTextField.autocorrectionType = UITextAutocorrectionType.no userNameTextField.autocapitalizationType = UITextAutocapitalizationType.none userNameTextField.textColor = UIColor.white userNameTextField.backgroundColor = UIColor(white: 1, alpha: 0.1); userNameTextField.font = v2Font(15) userNameTextField.layer.cornerRadius = 3; userNameTextField.layer.borderWidth = 0.5 userNameTextField.keyboardType = .asciiCapable userNameTextField.layer.borderColor = UIColor(white: 1, alpha: 0.8).cgColor; userNameTextField.placeholder = "用户名" userNameTextField.clearButtonMode = .always let userNameIconImageView = UIImageView(image: UIImage(named: "ic_account_circle")!.withRenderingMode(.alwaysTemplate)); userNameIconImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 22) userNameIconImageView.tintColor = UIColor.white userNameIconImageView.contentMode = .scaleAspectFit let userNameIconImageViewPanel = UIView(frame: userNameIconImageView.frame) userNameIconImageViewPanel.addSubview(userNameIconImageView) userNameTextField.leftView = userNameIconImageViewPanel userNameTextField.leftViewMode = .always return userNameTextField }() let passwordTextField:UITextField = { let passwordTextField = UITextField() passwordTextField.textColor = UIColor.white passwordTextField.backgroundColor = UIColor(white: 1, alpha: 0.1); passwordTextField.font = v2Font(15) passwordTextField.layer.cornerRadius = 3; passwordTextField.layer.borderWidth = 0.5 passwordTextField.keyboardType = .asciiCapable passwordTextField.isSecureTextEntry = true passwordTextField.layer.borderColor = UIColor(white: 1, alpha: 0.8).cgColor; passwordTextField.placeholder = "密码" passwordTextField.clearButtonMode = .always let passwordIconImageView = UIImageView(image: UIImage(named: "ic_lock")!.withRenderingMode(.alwaysTemplate)); passwordIconImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 22) passwordIconImageView.contentMode = .scaleAspectFit passwordIconImageView.tintColor = UIColor.white let passwordIconImageViewPanel = UIView(frame: passwordIconImageView.frame) passwordIconImageViewPanel.addSubview(passwordIconImageView) passwordTextField.leftView = passwordIconImageViewPanel passwordTextField.leftViewMode = .always return passwordTextField }() let codeTextField:UITextField = { let codeTextField = UITextField() codeTextField.textColor = UIColor.white codeTextField.backgroundColor = UIColor(white: 1, alpha: 0.1); codeTextField.font = v2Font(15) codeTextField.layer.cornerRadius = 3; codeTextField.layer.borderWidth = 0.5 codeTextField.keyboardType = .asciiCapable codeTextField.layer.borderColor = UIColor(white: 1, alpha: 0.8).cgColor; codeTextField.placeholder = "验证码" codeTextField.clearButtonMode = .always let codeTextFieldImageView = UIImageView(image: UIImage(named: "ic_vpn_key")!.withRenderingMode(.alwaysTemplate)); codeTextFieldImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 22) codeTextFieldImageView.contentMode = .scaleAspectFit codeTextFieldImageView.tintColor = UIColor.white let codeTextFieldImageViewPanel = UIView(frame: codeTextFieldImageView.frame) codeTextFieldImageViewPanel.addSubview(codeTextFieldImageView) codeTextField.leftView = codeTextFieldImageViewPanel codeTextField.leftViewMode = .always return codeTextField }() let codeImageView = UIImageView() let loginButton = UIButton() let cancelButton = UIButton() init() { super.init(nibName: nil, bundle: nil) self.modalPresentationStyle = .fullScreen } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.hideKeyboardWhenTappedAround() //初始化界面 self.setupView() //初始化1Password if OnePasswordExtension.shared().isAppExtensionAvailable() { let onepasswordButton = UIImageView(image: UIImage(named: "onepassword-button")?.withRenderingMode(.alwaysTemplate)) onepasswordButton.isUserInteractionEnabled = true onepasswordButton.frame = CGRect(x: 0, y: 0, width: 34, height: 22) onepasswordButton.contentMode = .scaleAspectFit onepasswordButton.tintColor = UIColor.white self.passwordTextField.rightView = onepasswordButton self.passwordTextField.rightViewMode = .always onepasswordButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(LoginViewController.findLoginFrom1Password))) } //绑定事件 self.loginButton.addTarget(self, action: #selector(LoginViewController.loginClick(_:)), for: .touchUpInside) self.cancelButton.addTarget(self, action: #selector(LoginViewController.cancelClick), for: .touchUpInside) } override func viewDidAppear(_ animated: Bool) { UIView.animate(withDuration: 2, animations: { () -> Void in self.backgroundImageView.alpha=1; }) UIView.animate(withDuration: 20, animations: { () -> Void in self.backgroundImageView.frame = CGRect(x: -1*( 1000 - SCREEN_WIDTH )/2, y: 0, width: SCREEN_HEIGHT+500, height: SCREEN_HEIGHT+500); }) } @objc func findLoginFrom1Password(){ OnePasswordExtension.shared().findLogin(forURLString: "v2ex.com", for: self, sender: nil) { (loginDictionary, errpr) -> Void in if let count = loginDictionary?.count , count > 0 { self.userNameTextField.text = loginDictionary![AppExtensionUsernameKey] as? String self.passwordTextField.text = loginDictionary![AppExtensionPasswordKey] as? String //密码赋值后,点确认按钮 self.loginClick(self.loginButton) } } } @objc func cancelClick (){ self.dismiss(animated: true, completion: nil) } @objc func loginClick(_ sneder:UIButton){ var userName:String var password:String if let len = self.userNameTextField.text?.Lenght , len > 0{ userName = self.userNameTextField.text! ; } else{ self.userNameTextField.becomeFirstResponder() return; } if let len = self.passwordTextField.text?.Lenght , len > 0 { password = self.passwordTextField.text! } else{ self.passwordTextField.becomeFirstResponder() return; } var code:String if let codeText = self.codeTextField.text, codeText.Lenght > 0 { code = codeText } else{ self.codeTextField.becomeFirstResponder() return } V2BeginLoadingWithStatus("正在登录") if let onceStr = onceStr , let usernameStr = usernameStr, let passwordStr = passwordStr, let codeStr = codeStr { UserModel.Login(userName, password: password, once: onceStr, usernameFieldName: usernameStr, passwordFieldName: passwordStr , codeFieldName:codeStr, code:code){ (response:V2ValueResponse<String> , is2FALoggedIn:Bool) -> Void in if response.success { V2Success("登录成功") let username = response.value! //保存下用户名 V2EXSettings.sharedInstance[kUserName] = username //将用户名密码保存进keychain (安全保存) V2UsersKeychain.sharedInstance.addUser(username, password: password) //调用登录成功回调 if let handel = self.successHandel { handel(username) } //获取用户信息 UserModel.getUserInfoByUsername(username,completionHandler: nil) self.dismiss(animated: true){ if is2FALoggedIn { let twoFaViewController = TwoFAViewController() V2Client.sharedInstance.centerViewController!.navigationController?.present(twoFaViewController, animated: true, completion: nil); } } } else{ V2Error(response.message) self.refreshCode() } } return; } else{ V2Error("不知道啥错误") } } var onceStr:String? var usernameStr:String? var passwordStr:String? var codeStr:String? @objc func refreshCode(){ Alamofire.request(V2EXURL+"signin", headers: MOBILE_CLIENT_HEADERS).responseJiHtml{ (response) -> Void in if let jiHtml = response .result.value{ //获取帖子内容 //取出 once 登录时要用 //self.onceStr = jiHtml.xPath("//*[@name='once'][1]")?.first?["value"] self.usernameStr = jiHtml.xPath("//*[@id='Wrapper']/div/div[1]/div[2]/form/table/tr[1]/td[2]/input[@class='sl']")?.first?["name"] self.passwordStr = jiHtml.xPath("//*[@id='Wrapper']/div/div[1]/div[2]/form/table/tr[2]/td[2]/input[@class='sl']")?.first?["name"] self.codeStr = jiHtml.xPath("//*[@id='Wrapper']/div/div[1]/div[2]/form/table/tr[4]/td[2]/input[@class='sl']")?.first?["name"] if let once = jiHtml.xPath("//*[@name='once'][1]")?.first?["value"]{ let codeUrl = "\(V2EXURL)_captcha?once=\(once)" self.onceStr = once Alamofire.request(codeUrl).responseData(completionHandler: { (dataResp) in self.codeImageView.image = UIImage(data: dataResp.data!) }) } else{ SVProgressHUD.showError(withStatus: "刷新验证码失败") } } } } } //MARK: - 点击文本框外收回键盘 extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } } //MARK: - 初始化界面 extension LoginViewController { func setupView(){ self.view.backgroundColor = UIColor.black self.backgroundImageView.image = UIImage(named: "32.jpg") self.backgroundImageView.frame = self.view.frame self.backgroundImageView.contentMode = .scaleToFill self.view.addSubview(self.backgroundImageView) backgroundImageView.alpha = 0 self.frostedView.frame = self.view.frame self.view.addSubview(self.frostedView) var blurEffect:UIBlurEffect.Style = .dark if #available(iOS 13.0, *) { blurEffect = .systemUltraThinMaterialDark } let vibrancy = UIVibrancyEffect(blurEffect: UIBlurEffect(style: blurEffect)) let vibrancyView = UIVisualEffectView(effect: vibrancy) vibrancyView.isUserInteractionEnabled = true vibrancyView.frame = self.frostedView.frame self.frostedView.contentView.addSubview(vibrancyView) let v2exLabel = UILabel() v2exLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 25)!; v2exLabel.text = "Explore" vibrancyView.contentView.addSubview(v2exLabel); v2exLabel.snp.makeConstraints{ (make) -> Void in make.centerX.equalTo(vibrancyView) make.top.equalTo(vibrancyView).offset(NavigationBarHeight) } let v2exSummaryLabel = UILabel() v2exSummaryLabel.font = v2Font(13); v2exSummaryLabel.text = "创意者的工作社区" vibrancyView.contentView.addSubview(v2exSummaryLabel); v2exSummaryLabel.snp.makeConstraints{ (make) -> Void in make.centerX.equalTo(vibrancyView) make.top.equalTo(v2exLabel.snp.bottom).offset(2) } vibrancyView.contentView.addSubview(self.userNameTextField); self.userNameTextField.snp.makeConstraints{ (make) -> Void in make.top.equalTo(v2exSummaryLabel.snp.bottom).offset(25) make.centerX.equalTo(vibrancyView) make.width.equalTo(300) make.height.equalTo(38) } vibrancyView.contentView.addSubview(self.passwordTextField); self.passwordTextField.snp.makeConstraints{ (make) -> Void in make.top.equalTo(self.userNameTextField.snp.bottom).offset(15) make.centerX.equalTo(vibrancyView) make.width.equalTo(300) make.height.equalTo(38) } vibrancyView.contentView.addSubview(self.codeTextField) self.codeTextField.snp.makeConstraints { (make) in make.top.equalTo(self.passwordTextField.snp.bottom).offset(15) make.left.equalTo(passwordTextField) make.width.equalTo(180) make.height.equalTo(38) } self.codeImageView.backgroundColor = UIColor(white: 1, alpha: 0.2) self.codeImageView.layer.cornerRadius = 3; self.codeImageView.clipsToBounds = true self.codeImageView.isUserInteractionEnabled = true self.view.addSubview(self.codeImageView) self.codeImageView.snp.makeConstraints { (make) in make.top.bottom.equalTo(self.codeTextField) make.left.equalTo(self.codeTextField.snp.right).offset(2) make.right.equalTo(self.passwordTextField) } self.codeImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(refreshCode))) self.loginButton.setTitle("登 录", for: .normal) self.loginButton.titleLabel!.font = v2Font(20) self.loginButton.layer.cornerRadius = 3; self.loginButton.layer.borderWidth = 0.5 self.loginButton.layer.borderColor = UIColor(white: 1, alpha: 0.8).cgColor; vibrancyView.contentView.addSubview(self.loginButton); self.loginButton.snp.makeConstraints{ (make) -> Void in make.top.equalTo(self.codeTextField.snp.bottom).offset(20) make.centerX.equalTo(vibrancyView) make.width.equalTo(300) make.height.equalTo(38) } let codeProblem = UILabel() codeProblem.alpha = 0.5 codeProblem.font = v2Font(12) codeProblem.text = "验证码不显示?" codeProblem.isUserInteractionEnabled = true codeProblem.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(codeProblemClick))) vibrancyView.contentView.addSubview(codeProblem); codeProblem.snp.makeConstraints{ (make) -> Void in make.top.equalTo(self.loginButton.snp.bottom).offset(14) make.right.equalTo(self.loginButton) } let footLabel = UILabel() footLabel.alpha = 0.5 footLabel.font = v2Font(12) footLabel.text = "© 2020 Fin" vibrancyView.contentView.addSubview(footLabel); footLabel.snp.makeConstraints{ (make) -> Void in make.bottom.equalTo(vibrancyView).offset(-20) make.centerX.equalTo(vibrancyView) } self.cancelButton.contentMode = .center cancelButton .setImage(UIImage(named: "ic_cancel")!.withRenderingMode(.alwaysTemplate), for: .normal) vibrancyView.contentView.addSubview(cancelButton) cancelButton.snp.makeConstraints{ (make) -> Void in make.centerY.equalTo(footLabel) make.right.equalTo(vibrancyView).offset(-5) make.width.height.equalTo(40) } refreshCode() } @objc func codeProblemClick(){ UIAlertView(title: "验证码不显示?", message: "如果验证码输错次数过多,V2EX将暂时禁止你的登录。", delegate: nil, cancelButtonTitle: "知道了").show() } }
mit
f64287d9f1d2c38cccc2616d68e1242d
41.577114
158
0.630171
4.825486
false
false
false
false
ConanMTHu/animated-tab-bar
RAMAnimatedTabBarController/Animations/FrameAnimation/RAMFrameItemAnimation.swift
1
3389
// RAMFrameItemAnimation.swift // // Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.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 UIKit import QuartzCore class RAMFrameItemAnimation: RAMItemAnimation { var animationImages : Array<CGImage> = Array() var selectedImage : UIImage! @IBInspectable var isDeselectAnimation: Bool = true @IBInspectable var imagesPath: String! override func awakeFromNib() { let path = NSBundle.mainBundle().pathForResource(imagesPath, ofType:"plist") let dict : NSDictionary = NSDictionary(contentsOfFile: path!)! let animationImagesName = dict["images"] as Array<String> createImagesArray(animationImagesName) // selected image var selectedImageName = animationImagesName[animationImagesName.endIndex - 1] selectedImage = UIImage(named: selectedImageName) } func createImagesArray(imageNames : Array<String>) { for name : String in imageNames { let image = UIImage(named: name)?.CGImage animationImages.append(image!) } } override func playAnimation(icon : UIImageView, textLable : UILabel) { playFrameAnimation(icon, images:animationImages) textLable.textColor = textSelectedColor } override func deselectAnimation(icon : UIImageView, textLable : UILabel, defaultTextColor : UIColor) { if isDeselectAnimation { playFrameAnimation(icon, images:animationImages.reverse()) } textLable.textColor = defaultTextColor } override func selectedState(icon : UIImageView, textLable : UILabel) { icon.image = selectedImage textLable.textColor = textSelectedColor } func playFrameAnimation(icon : UIImageView, images : Array<CGImage>) { var frameAnimation = CAKeyframeAnimation(keyPath: "contents") frameAnimation.calculationMode = kCAAnimationDiscrete frameAnimation.duration = NSTimeInterval(duration) frameAnimation.values = images frameAnimation.repeatCount = 1; frameAnimation.removedOnCompletion = false; frameAnimation.fillMode = kCAFillModeForwards; icon.layer.addAnimation(frameAnimation, forKey: "frameAnimation") } }
mit
5785cb9f8b0bad3161c8402ae08c390d
38.418605
106
0.701387
5.270607
false
false
false
false
multinerd/Mia
Mia/Sugar/On/UIBarButtonItem.swift
1
601
import UIKit public extension Container where Host: UIBarButtonItem { func tap(_ action: @escaping Action) { let target = BarButtonItemTarget(host: host, action: action) self.barButtonItemTarget = target } } class BarButtonItemTarget: NSObject { var action: Action? init(host: UIBarButtonItem, action: @escaping Action) { super.init() self.action = action host.target = self host.action = #selector(handleTap(_:)) } // MARK: - Action @objc func handleTap(_ sender: UIBarButtonItem) { action?() } }
mit
5137734d7c1bbf5aad9cce9466bfe72b
17.78125
68
0.620632
4.55303
false
false
false
false
shorlander/firefox-ios
Client/Frontend/Home/HomePanels.swift
6
3089
/* 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 import Shared /** * Data for identifying and constructing a HomePanel. */ struct HomePanelDescriptor { let makeViewController: (_ profile: Profile) -> UIViewController let imageName: String let accessibilityLabel: String let accessibilityIdentifier: String } class HomePanels { let enabledPanels = [ HomePanelDescriptor( makeViewController: { profile in return ActivityStreamPanel(profile: profile) }, imageName: "TopSites", accessibilityLabel: NSLocalizedString("Top sites", comment: "Panel accessibility label"), accessibilityIdentifier: "HomePanels.TopSites"), HomePanelDescriptor( makeViewController: { profile in let bookmarks = BookmarksPanel() bookmarks.profile = profile let controller = UINavigationController(rootViewController: bookmarks) controller.setNavigationBarHidden(true, animated: false) // this re-enables the native swipe to pop gesture on UINavigationController for embedded, navigation bar-less UINavigationControllers // don't ask me why it works though, I've tried to find an answer but can't. // found here, along with many other places: // http://luugiathuy.com/2013/11/ios7-interactivepopgesturerecognizer-for-uinavigationcontroller-with-hidden-navigation-bar/ controller.interactivePopGestureRecognizer?.delegate = nil return controller }, imageName: "Bookmarks", accessibilityLabel: NSLocalizedString("Bookmarks", comment: "Panel accessibility label"), accessibilityIdentifier: "HomePanels.Bookmarks"), HomePanelDescriptor( makeViewController: { profile in let history = HistoryPanel() history.profile = profile let controller = UINavigationController(rootViewController: history) controller.setNavigationBarHidden(true, animated: false) controller.interactivePopGestureRecognizer?.delegate = nil return controller }, imageName: "History", accessibilityLabel: NSLocalizedString("History", comment: "Panel accessibility label"), accessibilityIdentifier: "HomePanels.History"), HomePanelDescriptor( makeViewController: { profile in let controller = ReadingListPanel() controller.profile = profile return controller }, imageName: "ReadingList", accessibilityLabel: NSLocalizedString("Reading list", comment: "Panel accessibility label"), accessibilityIdentifier: "HomePanels.ReadingList"), ] }
mpl-2.0
46598b7ac57e261d35e1771ed691dae5
43.768116
150
0.644545
6.128968
false
false
false
false
sayheyrickjames/codepath-dev
week5/week5-homework-facebook-photos/week5-homework-facebook-photos/BaseTransition.swift
4
3433
// // BaseTransition.swift // transitionDemo // // Created by Timothy Lee on 2/22/15. // Copyright (c) 2015 Timothy Lee. All rights reserved. // import UIKit class BaseTransition: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning { var duration: NSTimeInterval = 0.4 var isPresenting: Bool = true var isInteractive: Bool = false var transitionContext: UIViewControllerContextTransitioning! var interactiveTransition: UIPercentDrivenInteractiveTransition! var percentComplete: CGFloat = 0 { didSet { interactiveTransition.updateInteractiveTransition(percentComplete) } } func animationControllerForPresentedController(presented: UIViewController!, presentingController presenting: UIViewController!, sourceController source: UIViewController!) -> UIViewControllerAnimatedTransitioning! { isPresenting = true return self } func animationControllerForDismissedController(dismissed: UIViewController!) -> UIViewControllerAnimatedTransitioning! { isPresenting = false return self } func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return duration } func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if isInteractive { interactiveTransition = UIPercentDrivenInteractiveTransition() interactiveTransition.completionSpeed = 0.99 } else { interactiveTransition = nil } return interactiveTransition } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { var containerView = transitionContext.containerView() var toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! var fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! self.transitionContext = transitionContext if (isPresenting) { toViewController.view.bounds = fromViewController.view.bounds containerView.addSubview(toViewController.view) presentTransition(containerView, fromViewController: fromViewController, toViewController: toViewController) } else { dismissTransition(containerView, fromViewController: fromViewController, toViewController: toViewController) } } func presentTransition(containerView: UIView, fromViewController: UIViewController, toViewController: UIViewController) { } func dismissTransition(containerView: UIView, fromViewController: UIViewController, toViewController: UIViewController) { } func finish() { if isInteractive { interactiveTransition.finishInteractiveTransition() } if isPresenting == false { var fromViewController = transitionContext?.viewControllerForKey(UITransitionContextFromViewControllerKey)! fromViewController?.view.removeFromSuperview() } transitionContext?.completeTransition(true) } func cancel() { if isInteractive { interactiveTransition.cancelInteractiveTransition() } } }
gpl-2.0
a2b9eb8e49669c39d0ed1ebf87324ddb
36.725275
220
0.716283
7.611973
false
false
false
false
dankogai/swift-numberkit
NumberKit/BigInt.swift
1
25581
// // BigInt.swift // NumberKit // // Created by Matthias Zenger on 12/08/2015. // Copyright © 2015 Matthias Zenger. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Darwin /// Class `BigInt` implements signed, arbitrary-precision integers. `BigInt` objects /// are immutable, i.e. all operations on `BigInt` objects return result objects. /// `BigInt` provides all the signed, integer arithmetic operations from Swift and /// implements the corresponding protocols. To make it easier to define large `BigInt` /// literals, `String` objects can be used for representing such numbers. They get /// implicitly coerced into `BigInt`. /// /// - Note: `BigInt` is internally implemented as a Swift array of UInt32 numbers /// and a boolean to represent the sign. Due to this overhead, for instance, /// representing a `UInt64` value as a `BigInt` will result in an object that /// requires more memory than the corresponding `UInt64` integer. public final class BigInt: Hashable, CustomStringConvertible, CustomDebugStringConvertible { // This is an array of `UInt32` words. The lowest significant word comes first in // the array. let words: [UInt32] // `negative` signals whether the number is positive or negative. let negative: Bool // All internal computations are based on 32-bit words; the base of this representation // is therefore `UInt32.max + 1`. private static let BASE: UInt64 = UInt64(UInt32.max) + 1 // `hiword` extracts the highest 32-bit value of a `UInt64`. private static func hiword(num: UInt64) -> UInt32 { return UInt32((num >> 32) & 0xffffffff) } // `loword` extracts the lowest 32-bit value of a `UInt64`. private static func loword(num: UInt64) -> UInt32 { return UInt32(num & 0xffffffff) } // `joinwords` combines two words into a `UInt64` value. private static func joinwords(lword: UInt32, _ hword: UInt32) -> UInt64 { return (UInt64(hword) << 32) + UInt64(lword) } /// Class `Base` defines a representation and type for the base used in computing /// `String` representations of `BigInt` objects. /// /// - Note: It is currently not possible to define custom `Base` objects. It needs /// to be figured out first what safety checks need to be put in place. public final class Base { private let digitSpace: [Character] private let digitMap: [Character: UInt8] private init(digitSpace: [Character], digitMap: [Character: UInt8]) { self.digitSpace = digitSpace self.digitMap = digitMap } private var radix: Int { return self.digitSpace.count } } /// Representing base 2 (binary) public static let BIN = Base( digitSpace: ["0", "1"], digitMap: ["0": 0, "1": 1] ) /// Representing base 8 (octal) public static let OCT = Base( digitSpace: ["0", "1", "2", "3", "4", "5", "6", "7"], digitMap: ["0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7] ) /// Representing base 10 (decimal) public static let DEC = Base( digitSpace: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], digitMap: ["0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9] ) /// Representing base 16 (hex) public static let HEX = Base( digitSpace: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"], digitMap: ["0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15] ) /// Maps a radix number to the corresponding `Base` object. Only 2, 8, 10, and 16 are /// supported. public static func base(radix: Int) -> Base { switch radix { case 2: return BigInt.BIN case 8: return BigInt.OCT case 10: return BigInt.DEC case 16: return BigInt.HEX default: preconditionFailure("unsupported base \(radix)") } } /// Internal primary constructor. It removes superfluous words and normalizes the /// representation of zero. private init(var _ words: [UInt32], negative: Bool) { while words.count > 1 && words[words.count - 1] == 0 { words.removeLast() } self.words = words self.negative = words.count == 1 && words[0] == 0 ? false : negative } private static let INT64_MAX = UInt64(Int64.max) /// Creates a `BigInt` from the given `UInt64` value public convenience init(_ value: UInt64) { self.init([BigInt.loword(value), BigInt.hiword(value)], negative: false) } /// Creates a `BigInt` from the given `Int64` value public convenience init(_ value: Int64) { let absvalue = value == Int64.min ? BigInt.INT64_MAX + 1 : UInt64(value < 0 ? -value : value) self.init([BigInt.loword(absvalue), BigInt.hiword(absvalue)], negative: value < 0) } /// Creates a `BigInt` from a sequence of digits for a given base. The first digit in the /// array of digits is the least significant one. `negative` is used to indicate negative /// `BigInt` numbers. public convenience init(var _ digits: [UInt8], negative: Bool = false, base: Base = BigInt.DEC) { var words: [UInt32] = [] var iterate: Bool repeat { var sum: UInt64 = 0 var res: [UInt8] = [] var j = 0 while j < digits.count && sum < BigInt.BASE { sum = sum * UInt64(base.radix) + UInt64(digits[j++]) } res.append(UInt8(BigInt.hiword(sum))) iterate = BigInt.hiword(sum) > 0 sum = UInt64(BigInt.loword(sum)) while j < digits.count { sum = sum * UInt64(base.radix) + UInt64(digits[j++]) res.append(UInt8(BigInt.hiword(sum))) iterate = true sum = UInt64(BigInt.loword(sum)) } words.append(BigInt.loword(sum)) digits = res } while iterate self.init(words, negative: negative) } /// Creates a `BigInt` from a string containing a number using the given base. public convenience init?(_ str: String, base: Base = BigInt.DEC) { var negative = false let chars = str.characters var i = chars.startIndex while i < chars.endIndex && chars[i] == " " { i++ } if i < chars.endIndex { if chars[i] == "-" { negative = true i++ } else if chars[i] == "+" { i++ } } if i < chars.endIndex && chars[i] == "0" { while i < chars.endIndex && chars[i] == "0" { i++ } if i == chars.endIndex { self.init(0) return } } var temp: [UInt8] = [] while i < chars.endIndex { if let digit = base.digitMap[chars[i]] { temp.append(digit) i++ } else { break } } while i < chars.endIndex && chars[i] == " " { i++ } guard i == chars.endIndex else { return nil } self.init(temp, negative: negative, base: base) } /// Converts the `BigInt` object into a string using the given base. `BigInt.DEC` is /// used as the default base. public func toString(base base: Base = BigInt.DEC) -> String { // Determine base let b = UInt64(base.digitSpace.count) precondition(b > 1 && b <= 36, "illegal base for BigInt string conversion") // Shortcut handling of zero if self.isZero { return String(base.digitSpace[0]) } // Build representation with base `b` in `str` var str: [UInt8] = [] var word = words[words.count - 1] while word > 0 { str.append(UInt8(word % UInt32(b))) word /= UInt32(b) } var temp: [UInt8] = [] if words.count > 1 { for i in 2...words.count { var carry: UInt64 = 0 // Multiply `str` with `BASE` and store in `temp` temp.removeAll() for s in str { carry += UInt64(s) * BigInt.BASE temp.append(UInt8(carry % b)) carry /= b } while carry > 0 { temp.append(UInt8(carry % b)) carry /= b } // Add `z` to `temp` and store in `str` word = words[words.count - i] var r = 0 str.removeAll() while r < temp.count || word > 0 { if r < temp.count { carry += UInt64(temp[r++]) } carry += UInt64(word) % b str.append(UInt8(carry % b)) carry /= b word /= UInt32(b) } if carry > 0 { str.append(UInt8(carry % b)) } } } // Convert representation in `str` into string var res = negative ? "-" : "" for i in 1...str.count { res.append(base.digitSpace[Int(str[str.count-i])]) } return res } /// Returns a string representation of this `BigInt` number using base 10. public var description: String { return toString() } /// Returns a string representation of this `BigInt` number for debugging purposes. public var debugDescription: String { var res = "{\(words.count): \(words[0])" for i in 1..<words.count { res += ", \(words[i])" } return res + "}" } /// Returns the `BigInt` as a `Int64` value if this is possible. If the number is outside /// the `Int64` range, the property will contain `nil`. public var intValue: Int64? { guard words.count <= 2 else { return nil } var value: UInt64 = UInt64(words[0]) if words.count == 2 { value += UInt64(words[1]) * BigInt.BASE } if negative && value == BigInt.INT64_MAX + 1 { return Int64.min } if value <= BigInt.INT64_MAX { return negative ? -Int64(value) : Int64(value) } return nil } /// Returns the `BigInt` as a `UInt64` value if this is possible. If the number is outside /// the `UInt64` range, the property will contain `nil`. public var uintValue: UInt64? { guard words.count <= 2 && !negative else { return nil } var value: UInt64 = UInt64(words[0]) if words.count == 2 { value += UInt64(words[1]) * BigInt.BASE } return value } /// Returns the `BigInt` as a `Double` value. This might lead to a significant loss of /// precision, but this operation is always possible. public var doubleValue: Double { var res: Double = 0.0 for word in words.reverse() { res = res * Double(BigInt.BASE) + Double(word) } return self.negative ? -res : res } /// The hash value of this `BigInt` object. public var hashValue: Int { var hash: Int = 0 for i in 0..<words.count { hash = (31 &* hash) &+ words[i].hashValue } return hash } /// Returns true if this `BigInt` is negative. public var isNegative: Bool { return negative } /// Returns true if this `BigInt` represents zero. public var isZero: Bool { return words.count == 1 && words[0] == 0 } /// Returns a `BigInt` with swapped sign. public var negate: BigInt { return BigInt(words, negative: !negative) } /// Returns the absolute value of this `BigInt`. public var abs: BigInt { return BigInt(words, negative: false) } /// Returns -1 if `self` is less than `rhs`, /// 0 if `self` is equals to `rhs`, /// +1 if `self` is greater than `rhs` public func compareTo(rhs: BigInt) -> Int { guard self.negative == rhs.negative else { return self.negative ? -1 : 1 } return self.negative ? rhs.compareDigits(self) : compareDigits(rhs) } private func compareDigits(rhs: BigInt) -> Int { guard words.count == rhs.words.count else { return words.count < rhs.words.count ? -1 : 1 } for i in 1...words.count { let a = words[words.count - i] let b = rhs.words[words.count - i] if a != b { return a < b ? -1 : 1 } } return 0 } /// Returns the sum of `self` and `rhs` as a `BigInt`. public func plus(rhs: BigInt) -> BigInt { guard self.negative == rhs.negative else { return self.minus(rhs.negate) } let (b1, b2) = self.words.count < rhs.words.count ? (rhs, self) : (self, rhs) var res = [UInt32]() res.reserveCapacity(b1.words.count) var sum: UInt64 = 0 for i in 0..<b2.words.count { sum += UInt64(b1.words[i]) sum += UInt64(b2.words[i]) res.append(BigInt.loword(sum)) sum = UInt64(BigInt.hiword(sum)) } for i in b2.words.count..<b1.words.count { sum += UInt64(b1.words[i]) res.append(BigInt.loword(sum)) sum = UInt64(BigInt.hiword(sum)) } if sum > 0 { res.append(BigInt.loword(sum)) } return BigInt(res, negative: self.negative) } /// Returns the difference between `self` and `rhs` as a `BigInt`. public func minus(rhs: BigInt) -> BigInt { guard self.negative == rhs.negative else { return self.plus(rhs.negate) } let cmp = compareDigits(rhs) guard cmp != 0 else { return 0 } let negative = cmp < 0 ? !self.negative : self.negative let (b1, b2) = cmp < 0 ? (rhs, self) : (self, rhs) var res = [UInt32]() var carry: UInt64 = 0 for i in 0..<b2.words.count { if UInt64(b1.words[i]) < UInt64(b2.words[i]) + carry { res.append(UInt32(BigInt.BASE + UInt64(b1.words[i]) - UInt64(b2.words[i]) - carry)) carry = 1 } else { res.append(b1.words[i] - b2.words[i] - UInt32(carry)) carry = 0 } } for i in b2.words.count..<b1.words.count { if b1.words[i] < UInt32(carry) { res.append(UInt32.max) carry = 1 } else { res.append(b1.words[i] - UInt32(carry)) carry = 0 } } return BigInt(res, negative: negative) } /// Returns the result of mulitplying `self` with `rhs` as a `BigInt` public func times(rhs: BigInt) -> BigInt { let (b1, b2) = self.words.count < rhs.words.count ? (rhs, self) : (self, rhs) var res = [UInt32](count: b1.words.count + b2.words.count, repeatedValue: 0) for i in 0..<b2.words.count { var sum: UInt64 = 0 for j in 0..<b1.words.count { sum += UInt64(res[i + j]) + UInt64(b1.words[j]) * UInt64(b2.words[i]) res[i + j] = BigInt.loword(sum) sum = UInt64(BigInt.hiword(sum)) } res[i + b1.words.count] = BigInt.loword(sum) } return BigInt(res, negative: b1.negative != b2.negative) } private static func multSub(approx: UInt32, _ divis: [UInt32], inout _ rem: [UInt32], _ from: Int) { var sum: UInt64 = 0 var carry: UInt64 = 0 for j in 0..<divis.count { sum += UInt64(divis[j]) * UInt64(approx) let x = UInt64(loword(sum)) + carry if UInt64(rem[from + j]) < x { rem[from + j] = UInt32(BigInt.BASE + UInt64(rem[from + j]) - x) carry = 1 } else { rem[from + j] = UInt32(UInt64(rem[from + j]) - x) carry = 0 } sum = UInt64(hiword(sum)) } } private static func subIfPossible(divis: [UInt32], inout _ rem: [UInt32], _ from: Int) -> Bool { var i = divis.count while i > 0 && divis[i - 1] >= rem[from + i - 1] { if divis[i - 1] > rem[from + i - 1] { return false } i-- } var carry: UInt64 = 0 for j in 0..<divis.count { let x = UInt64(divis[j]) + carry if UInt64(rem[from + j]) < x { rem[from + j] = UInt32(BigInt.BASE + UInt64(rem[from + j]) - x) carry = 1 } else { rem[from + j] = UInt32(UInt64(rem[from + j]) - x) carry = 0 } } return true } /// Divides `self` by `rhs` and returns the result as a `BigInt`. public func dividedBy(rhs: BigInt) -> (quotient: BigInt, remainder: BigInt) { guard rhs.words.count <= self.words.count else { return (BigInt(0), self.abs) } let neg = self.negative != rhs.negative if rhs.words.count == self.words.count { let cmp = compareTo(rhs) if cmp == 0 { return (BigInt(neg ? -1 : 1), BigInt(0)) } else if cmp < 0 { return (BigInt(0), self.abs) } } var rem = [UInt32](self.words) rem.append(0) var divis = [UInt32](rhs.words) divis.append(0) var sizediff = self.words.count - rhs.words.count let div = UInt64(rhs.words[rhs.words.count - 1]) + 1 var res = [UInt32](count: sizediff + 1, repeatedValue: 0) var divident = rem.count - 2 repeat { var x = BigInt.joinwords(rem[divident], rem[divident + 1]) var approx = x / div res[sizediff] = 0 while approx > 0 { res[sizediff] += UInt32(approx) // Is this cast ok? BigInt.multSub(UInt32(approx), divis, &rem, sizediff) x = BigInt.joinwords(rem[divident], rem[divident + 1]) approx = x / div } if BigInt.subIfPossible(divis, &rem, sizediff) { res[sizediff]++ } divident-- sizediff-- } while sizediff >= 0 return (BigInt(res, negative: neg), BigInt(rem, negative: false)) } /// Raises this `BigInt` value to the power of `exp`. public func toPowerOf(exp: BigInt) -> BigInt { return pow(self, exp) } /// Computes the bitwise `and` between this value and `rhs`. public func and(rhs: BigInt) -> BigInt { let size = min(self.words.count, rhs.words.count) var res = [UInt32]() res.reserveCapacity(size) for i in 0..<size { res.append(self.words[i] & rhs.words[i]) } return BigInt(res, negative: self.negative && rhs.negative) } /// Computes the bitwise `or` between this value and `rhs`. public func or(rhs: BigInt) -> BigInt { let size = max(self.words.count, rhs.words.count) var res = [UInt32]() res.reserveCapacity(size) for i in 0..<size { let fst = i < self.words.count ? self.words[i] : 0 let snd = i < rhs.words.count ? rhs.words[i] : 0 res.append(fst | snd) } return BigInt(res, negative: self.negative || rhs.negative) } /// Computes the bitwise `xor` between this value and `rhs`. public func xor(rhs: BigInt) -> BigInt { let size = max(self.words.count, rhs.words.count) var res = [UInt32]() res.reserveCapacity(size) for i in 0..<size { let fst = i < self.words.count ? self.words[i] : 0 let snd = i < rhs.words.count ? rhs.words[i] : 0 res.append(fst ^ snd) } return BigInt(res, negative: self.negative || rhs.negative) } /// Inverts the bits in this `BigInt`. public var invert: BigInt { var res = [UInt32]() res.reserveCapacity(self.words.count) for word in self.words { res.append(~word) } return BigInt(res, negative: !self.negative) } } /// This extension implements all the boilerplate to make `BigInt` compatible /// to the applicable Swift 2 protocols. `BigInt` is convertible from integer literals, /// convertible from Strings, it's a signed number, equatable, comparable, and implements /// all integer arithmetic functions. extension BigInt: IntegerLiteralConvertible, StringLiteralConvertible, Equatable, IntegerArithmeticType, SignedIntegerType { public typealias Distance = BigInt public convenience init(_ value: UInt) { self.init(Int64(value)) } public convenience init(_ value: UInt8) { self.init(Int64(value)) } public convenience init(_ value: UInt16) { self.init(Int64(value)) } public convenience init(_ value: UInt32) { self.init(Int64(value)) } public convenience init(_ value: Int) { self.init(Int64(value)) } public convenience init(_ value: Int8) { self.init(Int64(value)) } public convenience init(_ value: Int16) { self.init(Int64(value)) } public convenience init(_ value: Int32) { self.init(Int64(value)) } public convenience init(integerLiteral value: Int64) { self.init(value) } public convenience init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) { self.init(Int64(_builtinIntegerLiteral: value)) } public convenience init(stringLiteral value: String) { if let bi = BigInt(value) { self.init(bi.words, negative: bi.negative) } else { self.init(0) } } public convenience init( extendedGraphemeClusterLiteral value: String.ExtendedGraphemeClusterLiteralType) { self.init(stringLiteral: String(value)) } public convenience init( unicodeScalarLiteral value: String.UnicodeScalarLiteralType) { self.init(stringLiteral: String(value)) } public static func addWithOverflow(lhs: BigInt, _ rhs: BigInt) -> (BigInt, overflow: Bool) { return (lhs.plus(rhs), overflow: false) } public static func subtractWithOverflow(lhs: BigInt, _ rhs: BigInt) -> (BigInt, overflow: Bool) { return (lhs.minus(rhs), overflow: false) } public static func multiplyWithOverflow(lhs: BigInt, _ rhs: BigInt) -> (BigInt, overflow: Bool) { return (lhs.times(rhs), overflow: false) } public static func divideWithOverflow(lhs: BigInt, _ rhs: BigInt) -> (BigInt, overflow: Bool) { let res = lhs.dividedBy(rhs) return (res.quotient, overflow: false) } public static func remainderWithOverflow(lhs: BigInt, _ rhs: BigInt) -> (BigInt, overflow: Bool) { let res = lhs.dividedBy(rhs) return (res.remainder, overflow: false) } /// The empty bitset. public static var allZeros: BigInt { return BigInt(0) } /// Returns this number as an `IntMax` number public func toIntMax() -> IntMax { if let res = self.intValue { return res } preconditionFailure("`BigInt` value cannot be converted to `IntMax`") } /// This is in preparation for making `BigInt` implement `SignedIntegerType`. public func advancedBy(n: BigInt) -> BigInt { return self.plus(n) } /// This is in preparation for making `BigInt` implement `SignedIntegerType`. public func distanceTo(other: BigInt) -> BigInt { return other.minus(self) } /// This is in preparation for making `BigInt` implement `SignedIntegerType`. /// Returns the next consecutive value after `self`. /// /// - Requires: The next value is representable. public func successor() -> BigInt { return self.plus(1) } /// This is in preparation for making `BigInt` implement `SignedIntegerType`. /// Returns the previous consecutive value before `self`. /// /// - Requires: `self` has a well-defined predecessor. public func predecessor() -> BigInt { return self.minus(1) } } /// Returns the sum of `lhs` and `rhs` /// /// - Note: Without this declaration, the compiler complains that `+` is declared /// multiple times. public func +(lhs: BigInt, rhs: BigInt) -> BigInt { return lhs.plus(rhs) } /// Returns the difference between `lhs` and `rhs` /// /// - Note: Without this declaration, the compiler complains that `+` is declared /// multiple times. public func -(lhs: BigInt, rhs: BigInt) -> BigInt { return lhs.minus(rhs) } /// Adds `rhs` to `lhs` and stores the result in `lhs`. /// /// - Note: Without this declaration, the compiler complains that `+` is declared /// multiple times. public func +=(inout lhs: BigInt, rhs: BigInt) { lhs = lhs.plus(rhs) } /// Returns true if `lhs` is less than `rhs`, false otherwise. public func <(lhs: BigInt, rhs: BigInt) -> Bool { return lhs.compareTo(rhs) < 0 } /// Returns true if `lhs` is less than or equals `rhs`, false otherwise. public func <=(lhs: BigInt, rhs: BigInt) -> Bool { return lhs.compareTo(rhs) <= 0 } /// Returns true if `lhs` is greater or equals `rhs`, false otherwise. public func >=(lhs: BigInt, rhs: BigInt) -> Bool { return lhs.compareTo(rhs) >= 0 } /// Returns true if `lhs` is greater than equals `rhs`, false otherwise. public func >(lhs: BigInt, rhs: BigInt) -> Bool { return lhs.compareTo(rhs) > 0 } /// Returns true if `lhs` is equals `rhs`, false otherwise. public func ==(lhs: BigInt, rhs: BigInt) -> Bool { return lhs.compareTo(rhs) == 0 } /// Returns true if `lhs` is not equals `rhs`, false otherwise. public func !=(lhs: BigInt, rhs: BigInt) -> Bool { return lhs.compareTo(rhs) != 0 } /// Negates `self`. public prefix func -(num: BigInt) -> BigInt { return num.negate } /// Returns the intersection of bits set in `lhs` and `rhs`. public func &(lhs: BigInt, rhs: BigInt) -> BigInt { return lhs.and(rhs) } /// Returns the union of bits set in `lhs` and `rhs`. public func |(lhs: BigInt, rhs: BigInt) -> BigInt { return lhs.or(rhs) } /// Returns the bits that are set in exactly one of `lhs` and `rhs`. public func ^(lhs: BigInt, rhs: BigInt) -> BigInt { return lhs.xor(rhs) } /// Returns the bitwise inverted BigInt public prefix func ~(x: BigInt) -> BigInt { return x.invert } /// Returns the maximum of `fst` and `snd`. public func max(fst: BigInt, snd: BigInt) -> BigInt { return fst.compareTo(snd) >= 0 ? fst : snd } /// Returns the minimum of `fst` and `snd`. public func min(fst: BigInt, snd: BigInt) -> BigInt { return fst.compareTo(snd) <= 0 ? fst : snd }
apache-2.0
4671e8320c57db47f816caa9e3a3d14f
30.271394
100
0.602346
3.542936
false
false
false
false
onmyway133/Resolver
Pod/Classes/Container.swift
1
789
// // Container.swift // Pods // // Created by Khoa Pham on 12/18/15. // // import Foundation struct Container { var registrations = [RegistrationKey: RegistrationType]() mutating func register<F>(tag tag: String? = nil, factory: F) { let key = RegistrationKey(tag: tag ?? "", factoryType: F.self) let registration = Registration<F>(factory: factory) registrations[key] = registration } func resolve<T, F>(tag tag: String? = nil, builder: F -> T) throws -> T { let key = RegistrationKey(tag: tag ?? "", factoryType: F.self) if let registration = registrations[key] as? Registration<F> { return builder(registration.factory) } else { throw ResolverError.RegistrationNotFound } } }
mit
1ccfa0a7e35de77457813e067f5a84cc
25.3
77
0.617237
3.984848
false
false
false
false
julien-c/swifter
Sources/Swifter/DemoServer.swift
1
3015
// // DemoServer.swift // Swifter // Copyright (c) 2015 Damian Kołakowski. All rights reserved. // import Foundation public func demoServer(publicDir: String?) -> HttpServer { let server = HttpServer() if let publicDir = publicDir { server["/resources/:file"] = HttpHandlers.directory(publicDir) } server["/files/:path"] = HttpHandlers.directoryBrowser("~/") server["/"] = { r in var listPage = "Available services:<br><ul>" listPage += server.routes.map({ "<li><a href=\"\($0)\">\($0)</a></li>"}).joinWithSeparator("") return .OK(.Html(listPage)) } server["/magic"] = { .OK(.Html("You asked for " + $0.url)) } server["/test/:param1/:param2"] = { r in var headersInfo = "" for (name, value) in r.headers { headersInfo += "\(name) : \(value)<br>" } var queryParamsInfo = "" for (name, value) in r.urlParams { queryParamsInfo += "\(name) : \(value)<br>" } var pathParamsInfo = "" for token in r.params { pathParamsInfo += "\(token.0) : \(token.1)<br>" } return .OK(.Html("<h3>Address: \(r.address)</h3><h3>Url:</h3> \(r.url)<h3>Method: \(r.method)</h3><h3>Headers:</h3>\(headersInfo)<h3>Query:</h3>\(queryParamsInfo)<h3>Path params:</h3>\(pathParamsInfo)")) } server["/login"] = { r in switch r.method.uppercaseString { case "GET": if let rootDir = publicDir { if let html = NSData(contentsOfFile:"\(rootDir)/login.html") { var array = [UInt8](count: html.length, repeatedValue: 0) html.getBytes(&array, length: html.length) return HttpResponse.RAW(200, "OK", nil, array) } else { return .NotFound } } case "POST": let formFields = r.parseForm() return HttpResponse.OK(.Html(formFields.map({ "\($0.0) = \($0.1)" }).joinWithSeparator("<br>"))) default: return .NotFound } return .NotFound } server["/demo"] = { r in return .OK(.Html("<center><h2>Hello Swift</h2><img src=\"https://devimages.apple.com.edgekey.net/swift/images/swift-hero_2x.png\"/><br></center>")) } server["/raw"] = { request in return HttpResponse.RAW(200, "OK", ["XXX-Custom-Header": "value"], [UInt8]("Sample Response".utf8)) } server["/json"] = { request in let jsonObject: NSDictionary = [NSString(string: "foo"): NSNumber(int: 3), NSString(string: "bar"): NSString(string: "baz")] return .OK(.Json(jsonObject)) } server["/redirect"] = { request in return .MovedPermanently("http://www.google.com") } server["/long"] = { request in var longResponse = "" for k in 0..<1000 { longResponse += "(\(k)),->" } return .OK(.Html(longResponse)) } return server }
bsd-3-clause
23fe391165b13b0d4b9d91c52d6ba715
33.25
211
0.534174
3.909209
false
false
false
false
gkaimakas/ReactiveBluetooth
ReactiveBluetooth/Classes/CBPeripheral/CBPeripheral+ConnectionOption.swift
1
2053
// // CBPeripheral+ConnectionOption.swift // ReactiveCoreBluetooth // // Created by George Kaimakas on 02/03/2018. // import CoreBluetooth extension CBPeripheral { public enum ConnectionOption: Equatable, Hashable { public static func ==(lhs: ConnectionOption, rhs: ConnectionOption) -> Bool { switch (lhs, rhs){ case (.notifyOnConnection(let a), .notifyOnConnection(let b)): return a == b case (.notifyOnDisconnection(let a), .notifyOnDisconnection(let b)): return a == b case (.notifyOnNotification(let a), .notifyOnNotification(let b)): return a == b default: return false } } public var hashValue: Int { switch self { case .notifyOnConnection(_): return 4_000 case .notifyOnDisconnection(_): return 40_000 case .notifyOnNotification(_): return 400_000 } } public var key: String { switch self { case .notifyOnConnection(_): return CBConnectPeripheralOptionNotifyOnConnectionKey case .notifyOnDisconnection(_): return CBConnectPeripheralOptionNotifyOnDisconnectionKey case .notifyOnNotification(_): return CBConnectPeripheralOptionNotifyOnNotificationKey } } public var value: Any { switch self { case .notifyOnConnection(let value): return value as Any case .notifyOnDisconnection(let value): return value as Any case .notifyOnNotification(let value): return value as Any } } case notifyOnConnection(Bool) case notifyOnDisconnection(Bool) case notifyOnNotification(Bool) } } extension Set where Element == CBPeripheral.ConnectionOption { public func merge() -> [String: Any] { return reduce([String: Any]() ) { (partialResult, item) -> [String: Any] in var result = partialResult result[item.key] = item.value return result } } }
mit
6f7e249039a41a651465564871b493d0
33.216667
100
0.616171
5.21066
false
false
false
false
castial/Quick-Start-iOS
Quick-Start-iOS/Utils/Constants/Constants.swift
1
766
// // Constants.swift // Quick-Start-iOS // // Created by work on 2016/10/14. // Copyright © 2016年 hyyy. All rights reserved. // import UIKit class Constants: NSObject { struct Rect { static let statusBarHeight = UIApplication.shared.statusBarFrame.size.height // 状态栏高度 static let navHeight: CGFloat = 44 // 默认导航栏高度 static let tabBarHeight: CGFloat = 49 // 默认TabBar高度 static let ScreenWidth = UIScreen.main.bounds.size.width // 屏幕宽度 static let ScreenHeight = UIScreen.main.bounds.size.height // 屏幕高度 } struct Notification { static let DISPATCH_AD_PAGE = NSNotification.Name("dispatch_ad_page") // 广告跳转通知 } }
mit
7928b9488a927af9e56b65f8a0cd526c
28.291667
96
0.650071
3.949438
false
false
false
false
FirebaseExtended/firebase-video-samples
fundamentals/apple/auth-sign-in-with-apple/starter/Favourites/Shared/Auth/AuthenticationViewModel.swift
1
6808
// // AuthenticationViewModel.swift // Favourites // // Created by Peter Friese on 08.07.2022 // Copyright © 2022 Google LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import FirebaseAuth // For Sign in with Apple import AuthenticationServices import CryptoKit enum AuthenticationState { case unauthenticated case authenticating case authenticated } enum AuthenticationFlow { case login case signUp } @MainActor class AuthenticationViewModel: ObservableObject { @Published var email = "" @Published var password = "" @Published var confirmPassword = "" @Published var flow: AuthenticationFlow = .login @Published var isValid = false @Published var authenticationState: AuthenticationState = .unauthenticated @Published var errorMessage = "" @Published var user: User? @Published var displayName = "" private var currentNonce: String? init() { registerAuthStateHandler() verifySignInWithAppleAuthenticationState() $flow .combineLatest($email, $password, $confirmPassword) .map { flow, email, password, confirmPassword in flow == .login ? !(email.isEmpty || password.isEmpty) : !(email.isEmpty || password.isEmpty || confirmPassword.isEmpty) } .assign(to: &$isValid) } private var authStateHandler: AuthStateDidChangeListenerHandle? func registerAuthStateHandler() { if authStateHandler == nil { authStateHandler = Auth.auth().addStateDidChangeListener { auth, user in self.user = user self.authenticationState = user == nil ? .unauthenticated : .authenticated self.displayName = user?.displayName ?? user?.email ?? "" } } } func switchFlow() { flow = flow == .login ? .signUp : .login errorMessage = "" } private func wait() async { do { print("Wait") try await Task.sleep(nanoseconds: 1_000_000_000) print("Done") } catch { } } func reset() { flow = .login email = "" password = "" confirmPassword = "" } } // MARK: - Email and Password Authentication extension AuthenticationViewModel { func signInWithEmailPassword() async -> Bool { authenticationState = .authenticating do { try await Auth.auth().signIn(withEmail: self.email, password: self.password) return true } catch { print(error) errorMessage = error.localizedDescription authenticationState = .unauthenticated return false } } func signUpWithEmailPassword() async -> Bool { authenticationState = .authenticating do { try await Auth.auth().createUser(withEmail: email, password: password) return true } catch { print(error) errorMessage = error.localizedDescription authenticationState = .unauthenticated return false } } func signOut() { do { try Auth.auth().signOut() } catch { print(error) errorMessage = error.localizedDescription } } func deleteAccount() async -> Bool { do { try await user?.delete() return true } catch { errorMessage = error.localizedDescription return false } } } // MARK: Sign in with Apple extension AuthenticationViewModel { func handleSignInWithAppleRequest(_ request: ASAuthorizationAppleIDRequest) { } func handleSignInWithAppleCompletion(_ result: Result<ASAuthorization, Error>) { } func updateDisplayName(for user: User, with appleIDCredential: ASAuthorizationAppleIDCredential, force: Bool = false) async { if let currentDisplayName = Auth.auth().currentUser?.displayName, currentDisplayName.isEmpty { let changeRequest = user.createProfileChangeRequest() changeRequest.displayName = appleIDCredential.displayName() do { try await changeRequest.commitChanges() self.displayName = Auth.auth().currentUser?.displayName ?? "" } catch { print("Unable to update the user's displayname: \(error.localizedDescription)") errorMessage = error.localizedDescription } } } func verifySignInWithAppleAuthenticationState() { let appleIDProvider = ASAuthorizationAppleIDProvider() let providerData = Auth.auth().currentUser?.providerData if let appleProviderData = providerData?.first(where: { $0.providerID == "apple.com" }) { Task { do { let credentialState = try await appleIDProvider.credentialState(forUserID: appleProviderData.uid) switch credentialState { case .authorized: break // The Apple ID credential is valid. case .revoked, .notFound: // The Apple ID credential is either revoked or was not found, so show the sign-in UI. self.signOut() default: break } } catch { } } } } } extension ASAuthorizationAppleIDCredential { func displayName() -> String { return [self.fullName?.givenName, self.fullName?.familyName] .compactMap( {$0}) .joined(separator: " ") } } // Adapted from https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-cryptographically-random-nonce private func randomNonceString(length: Int = 32) -> String { precondition(length > 0) let charset: [Character] = Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._") var result = "" var remainingLength = length while remainingLength > 0 { let randoms: [UInt8] = (0 ..< 16).map { _ in var random: UInt8 = 0 let errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random) if errorCode != errSecSuccess { fatalError( "Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)" ) } return random } randoms.forEach { random in if remainingLength == 0 { return } if random < charset.count { result.append(charset[Int(random)]) remainingLength -= 1 } } } return result } private func sha256(_ input: String) -> String { let inputData = Data(input.utf8) let hashedData = SHA256.hash(data: inputData) let hashString = hashedData.compactMap { String(format: "%02x", $0) }.joined() return hashString }
apache-2.0
9b00789c7278d368506989c3a35812c6
25.589844
127
0.666079
4.534977
false
false
false
false
Webtrekk/webtrekk-ios-sdk
Source/Internal/Reachability/Reachability.swift
1
11115
/* Copyright (c) 2014, Ashley Mills 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 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. */ // TODO: Although not part of watchOS target, still generates an error on cocoapods lib lint #if !os(watchOS) import SystemConfiguration import Foundation public enum ReachabilityError: Error { case FailedToCreateWithAddress(sockaddr_in) case FailedToCreateWithHostname(String) case UnableToSetCallback case UnableToSetDispatchQueue case UnableToGetInitialFlags } @available(*, unavailable, renamed: "Notification.Name.reachabilityChanged") public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification") public extension Notification.Name { static let reachabilityChanged = Notification.Name("reachabilityChanged") } public class Reachability { public typealias NetworkReachable = (Reachability) -> Void public typealias NetworkUnreachable = (Reachability) -> Void @available(*, unavailable, renamed: "Connection") public enum NetworkStatus: CustomStringConvertible { case notReachable, reachableViaWiFi, reachableViaWWAN public var description: String { switch self { case .reachableViaWWAN: return "Cellular" case .reachableViaWiFi: return "WiFi" case .notReachable: return "No Connection" } } } public enum Connection: CustomStringConvertible { case none, wifi, cellular public var description: String { switch self { case .cellular: return "Cellular" case .wifi: return "WiFi" case .none: return "No Connection" } } } public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? @available(*, deprecated, renamed: "allowsCellularConnection") public let reachableOnWWAN: Bool = true /// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`) public var allowsCellularConnection: Bool // The notification center on which "reachability changed" events are being posted public var notificationCenter: NotificationCenter = NotificationCenter.default @available(*, deprecated, renamed: "connection.description") public var currentReachabilityString: String { return "\(connection)" } @available(*, unavailable, renamed: "connection") public var currentReachabilityStatus: Connection { return connection } public var connection: Connection { if flags == nil { try? setReachabilityFlags() } switch flags?.connection { case .none?, nil: return .none case .cellular?: return allowsCellularConnection ? .cellular : .none case .wifi?: return .wifi } } fileprivate var isRunningOnDevice: Bool = { #if targetEnvironment(simulator) return false #else return true #endif }() fileprivate var notifierRunning = false fileprivate let reachabilityRef: SCNetworkReachability fileprivate let reachabilitySerialQueue: DispatchQueue fileprivate(set) var flags: SCNetworkReachabilityFlags? { didSet { guard flags != oldValue else { return } reachabilityChanged() } } required public init(reachabilityRef: SCNetworkReachability, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { self.allowsCellularConnection = true self.reachabilityRef = reachabilityRef self.reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", qos: queueQoS, target: targetQueue) } public convenience init?(hostname: String, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil } self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue) } public convenience init?(queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { var zeroAddress = sockaddr() zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size) zeroAddress.sa_family = sa_family_t(AF_INET) guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil } self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue) } deinit { stopNotifier() } } public extension Reachability { // MARK: - *** Notifier methods *** func startNotifier() throws { guard !notifierRunning else { return } let callback: SCNetworkReachabilityCallBack = { (reachability, flags, info) in guard let info = info else { return } let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue() reachability.flags = flags } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque()) if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) { stopNotifier() throw ReachabilityError.UnableToSetCallback } if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) { stopNotifier() throw ReachabilityError.UnableToSetDispatchQueue } // Perform an initial check try setReachabilityFlags() notifierRunning = true } func stopNotifier() { defer { notifierRunning = false } SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } // MARK: - *** Connection test methods *** @available(*, message: "Please use `connection != .none`") var isReachable: Bool { return connection != .none } @available(*, message: "Please use `connection == .cellular`") var isReachableViaWWAN: Bool { // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return connection == .cellular } @available(*, message: "Please use `connection == .wifi`") var isReachableViaWiFi: Bool { return connection == .wifi } var description: String { guard let flags = flags else { return "unavailable flags" } let W = isRunningOnDevice ? (flags.isOnWWANFlagSet ? "W" : "-") : "X" let R = flags.isReachableFlagSet ? "R" : "-" let c = flags.isConnectionRequiredFlagSet ? "c" : "-" let t = flags.isTransientConnectionFlagSet ? "t" : "-" let i = flags.isInterventionRequiredFlagSet ? "i" : "-" let C = flags.isConnectionOnTrafficFlagSet ? "C" : "-" let D = flags.isConnectionOnDemandFlagSet ? "D" : "-" let l = flags.isLocalAddressFlagSet ? "l" : "-" let d = flags.isDirectFlagSet ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } } fileprivate extension Reachability { func setReachabilityFlags() throws { try reachabilitySerialQueue.sync { [unowned self] in var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags) { self.stopNotifier() throw ReachabilityError.UnableToGetInitialFlags } self.flags = flags } } func reachabilityChanged() { let block = connection != .none ? whenReachable : whenUnreachable DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } block?(strongSelf) strongSelf.notificationCenter.post(name: .reachabilityChanged, object: strongSelf) } } } extension SCNetworkReachabilityFlags { typealias Connection = Reachability.Connection var connection: Connection { guard isReachableFlagSet else { return .none } // If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi #if targetEnvironment(simulator) return .wifi #else var connection = Connection.none if !isConnectionRequiredFlagSet { connection = .wifi } if isConnectionOnTrafficOrDemandFlagSet { if !isInterventionRequiredFlagSet { connection = .wifi } } if isOnWWANFlagSet { connection = .cellular } return connection #endif } var isOnWWANFlagSet: Bool { #if os(iOS) return contains(.isWWAN) #else return false #endif } var isReachableFlagSet: Bool { return contains(.reachable) } var isConnectionRequiredFlagSet: Bool { return contains(.connectionRequired) } var isInterventionRequiredFlagSet: Bool { return contains(.interventionRequired) } var isConnectionOnTrafficFlagSet: Bool { return contains(.connectionOnTraffic) } var isConnectionOnDemandFlagSet: Bool { return contains(.connectionOnDemand) } var isConnectionOnTrafficOrDemandFlagSet: Bool { return !intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty } var isTransientConnectionFlagSet: Bool { return contains(.transientConnection) } var isLocalAddressFlagSet: Bool { return contains(.isLocalAddress) } var isDirectFlagSet: Bool { return contains(.isDirect) } var isConnectionRequiredAndTransientFlagSet: Bool { return intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection] } } #endif
mit
06cf4ba8673348f1fb12d4295e3ef491
33.95283
135
0.674764
5.480769
false
false
false
false
JeeLiu/tispr-card-stack
TisprCardStackExample/TisprCardStackExample/TisprCardStackDemoViewCell.swift
5
1847
/* Copyright 2015 BuddyHopp, 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. */ // // TisprCardStackDemoViewCell.swift // TisprCardStack // // Created by Andrei Pitsko on 7/12/15. // import UIKit import TisprCardStack class TisprCardStackDemoViewCell: TisprCardStackViewCell { @IBOutlet weak var text: UILabel! @IBOutlet weak var voteSmile: UIImageView! override func awakeFromNib() { super.awakeFromNib() layer.cornerRadius = 12 clipsToBounds = false } override var center: CGPoint { didSet { updateSmileVote() } } override internal func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes!) { super.applyLayoutAttributes(layoutAttributes) updateSmileVote() } func updateSmileVote() { let rotation = atan2(transform.b, transform.a) * 100 var smileImageName = "smile_neutral" if rotation > 15 { smileImageName = "smile_face_2" } else if rotation > 0 { smileImageName = "smile_face_1" } else if rotation < -15 { smileImageName = "smile_rotten_2" } else if rotation < 0 { smileImageName = "smile_rotten_1" } voteSmile.image = UIImage(named: smileImageName) } }
apache-2.0
0ead46a119cc8d27dbb9c039f93970d5
25.782609
103
0.656741
4.408115
false
false
false
false
yeziahehe/Gank
Pods/LeanCloud/Sources/Storage/DataType/Dictionary.swift
1
5892
// // LCDictionary.swift // LeanCloud // // Created by Tang Tianyong on 2/27/16. // Copyright © 2016 LeanCloud. All rights reserved. // import Foundation /** LeanCloud dictionary type. It is a wrapper of `Swift.Dictionary` type, used to store a dictionary value. */ @dynamicMemberLookup public final class LCDictionary: NSObject, LCValue, LCValueExtension, Collection, ExpressibleByDictionaryLiteral { public typealias Key = String public typealias Value = LCValue public typealias Index = DictionaryIndex<Key, Value> public private(set) var value: [Key: Value] = [:] var elementDidChange: ((Key, Value?) -> Void)? public override init() { super.init() } public convenience init(_ value: [Key: Value]) { self.init() self.value = value } public convenience init(_ value: [Key: LCValueConvertible]) { self.init() self.value = value.mapValue { value in value.lcValue } } /** Create copy of dictionary. - parameter dictionary: The dictionary to be copied. */ public convenience init(_ dictionary: LCDictionary) { self.init() self.value = dictionary.value } public convenience required init(dictionaryLiteral elements: (Key, Value)...) { self.init(Dictionary<Key, Value>(elements: elements)) } public convenience init(unsafeObject: Any) throws { self.init() guard let object = unsafeObject as? [Key: Any] else { throw LCError( code: .malformedData, reason: "Failed to construct LCDictionary with non-dictionary object.") } value = try object.mapValue { value in try ObjectProfiler.shared.object(jsonValue: value) } } public required init?(coder aDecoder: NSCoder) { /* Note: We have to make type casting twice here, or it will crash for unknown reason. It seems that it's a bug of Swift. */ value = (aDecoder.decodeObject(forKey: "value") as? [String: AnyObject] as? [String: LCValue]) ?? [:] } public func encode(with aCoder: NSCoder) { aCoder.encode(value, forKey: "value") } public func copy(with zone: NSZone?) -> Any { return LCDictionary(value) } public override func isEqual(_ object: Any?) -> Bool { if let object = object as? LCDictionary { return object === self || object.value == value } else { return false } } public func makeIterator() -> DictionaryIterator<Key, Value> { return value.makeIterator() } public var startIndex: DictionaryIndex<Key, Value> { return value.startIndex } public var endIndex: DictionaryIndex<Key, Value> { return value.endIndex } public func index(after i: DictionaryIndex<Key, Value>) -> DictionaryIndex<Key, Value> { return value.index(after: i) } public subscript(position: DictionaryIndex<Key, Value>) -> (key: Key, value: Value) { return value[position] } public subscript(key: Key) -> Value? { get { return value[key] } set { value[key] = newValue elementDidChange?(key, newValue) } } public subscript(dynamicMember key: String) -> LCValueConvertible? { get { return self[key] } set { self[key] = newValue?.lcValue } } /** Removes the given key and its associated value from dictionary. - parameter key: The key to remove along with its associated value. - returns: The value that was removed, or `nil` if the key was not found. */ @discardableResult public func removeValue(forKey key: Key) -> Value? { return value.removeValue(forKey: key) } func set(_ key: String, _ value: LCValue?) { self.value[key] = value } public var jsonValue: Any { return value.compactMapValue { value in value.jsonValue } } func formattedJSONString(indentLevel: Int, numberOfSpacesForOneIndentLevel: Int = 4) -> String { if value.isEmpty { return "{}" } let lastIndent = " " * (numberOfSpacesForOneIndentLevel * indentLevel) let bodyIndent = " " * (numberOfSpacesForOneIndentLevel * (indentLevel + 1)) let body = value .map { (key, value) in (key, (value as! LCValueExtension).formattedJSONString(indentLevel: indentLevel + 1, numberOfSpacesForOneIndentLevel: numberOfSpacesForOneIndentLevel)) } .sorted { (left, right) in left.0 < right.0 } .map { (key, value) in "\"\(key.doubleQuoteEscapedString)\": \(value)" } .joined(separator: ",\n" + bodyIndent) return "{\n\(bodyIndent)\(body)\n\(lastIndent)}" } public var jsonString: String { return formattedJSONString(indentLevel: 0) } public var rawValue: LCValueConvertible { let dictionary = value.mapValue { value in value.rawValue } return dictionary as! LCValueConvertible } var lconValue: Any? { return value.compactMapValue { value in (value as? LCValueExtension)?.lconValue } } static func instance() -> LCValue { return self.init([:]) } func forEachChild(_ body: (_ child: LCValue) throws -> Void) rethrows { try forEach { (_, element) in try body(element) } } func add(_ other: LCValue) throws -> LCValue { throw LCError(code: .invalidType, reason: "Object cannot be added.") } func concatenate(_ other: LCValue, unique: Bool) throws -> LCValue { throw LCError(code: .invalidType, reason: "Object cannot be concatenated.") } func differ(_ other: LCValue) throws -> LCValue { throw LCError(code: .invalidType, reason: "Object cannot be differed.") } }
gpl-3.0
f8590c42e39d97e8b5f34634a069c950
29.210256
192
0.615855
4.476444
false
false
false
false
sebreh/SquarePants
SquarePants/LazyProperty.swift
1
2504
// // LazyProperty.swift // SquarePants // // Created by Sebastian Rehnby on 28/08/15. // Copyright © 2015 Sebastian Rehnby. All rights reserved. // import UIKit public protocol LazyPropertyType { associatedtype ValueType var value: ValueType { get } } public struct LazyProperty<T>: LazyPropertyType { public typealias ValueType = T public var value: T { return evaluate() } fileprivate let evaluate: () -> T init(_ evaluate: @escaping () -> T) { self.evaluate = evaluate } } public extension LazyPropertyType { func map<U>(_ transform: @escaping (ValueType) -> U) -> LazyProperty<U> { return LazyProperty<U> { return transform(self.value) } } func flatMap<U>(_ transform: @escaping (ValueType) -> LazyProperty<U?>?) -> LazyProperty<U?> { return LazyProperty<U?> { return transform(self.value)?.value } } } // MARK: Extensions public extension LazyPropertyType where ValueType == UIView? { var superview: LazyProperty<UIView?> { return map { $0?.superview } } var frame: LazyProperty<CGRect?> { return map { $0?.frame } } var center: LazyProperty<CGPoint?> { return map { $0?.center } } var sp_contentCenter: LazyProperty<CGPoint?> { return flatMap { $0?.sp_contentCenter } } var alpha: LazyProperty<CGFloat?> { return map { $0?.alpha } } var transform: LazyProperty<CGAffineTransform?> { return map { $0?.transform } } } public extension LazyPropertyType where ValueType == CGRect { func withInsets(_ insets: UIEdgeInsets) -> LazyProperty<CGRect> { return map { UIEdgeInsetsInsetRect($0, insets) } } func withInset(_ inset: CGFloat) -> LazyProperty<CGRect> { return map { rect in let insets = UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset) return UIEdgeInsetsInsetRect(rect, insets) } } } public extension LazyPropertyType where ValueType == CGRect? { func withInsets(_ insets: UIEdgeInsets) -> LazyProperty<CGRect?> { return map { rect in if let rect = rect { return UIEdgeInsetsInsetRect(rect, insets) } else { return nil } } } func withInset(_ inset: CGFloat) -> LazyProperty<CGRect?> { return map { rect in if let rect = rect { let insets = UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset) return UIEdgeInsetsInsetRect(rect, insets) } else { return nil } } } }
mit
a11af315034a6c890fa304d9f7a2863a
21.54955
96
0.639233
4.076547
false
false
false
false
TwoRingSoft/SemVer
Vrsnr/File Types/PlistFile.swift
1
1930
// // PlistFile.swift // Vrsnr // // Created by Andrew McKnight on 7/9/16. // Copyright © 2016 Two Ring Software. All rights reserved. // import Foundation public struct PlistFile { public let path: String } extension PlistFile: File { public func getPath() -> String { return path } public static func defaultKeyForVersionType(_ type: VersionType) -> String { switch(type) { case .Numeric: return "CFBundleVersion" case .Semantic: return "CFBundleShortVersionString" } } public func defaultKeyForVersionType(_ type: VersionType) -> String { return PlistFile.defaultKeyForVersionType(type) } public func versionStringForKey(_ key: String?, versionType: VersionType) -> String? { guard let data = NSDictionary(contentsOfFile: self.path) else { return nil } if key == nil { return data[defaultKeyForVersionType(versionType)] as? String } else { return data[key!] as? String } } public func replaceVersionString<V>(_ original: V, new: V, key: String?) throws where V: Version { guard let dictionary = NSDictionary(contentsOfFile: self.path) else { throw NSError(domain: errorDomain, code: Int(ErrorCode.couldNotReadFile.rawValue), userInfo: [ NSLocalizedDescriptionKey: "Failed to read current state of file for updating." ]) } if key == nil { dictionary.setValue(new.description, forKey: defaultKeyForVersionType(new.type)) } else { dictionary.setValue(new.description, forKey: key!) } if !dictionary.write(toFile: self.path, atomically: true) { throw NSError(domain: errorDomain, code: Int(ErrorCode.unwritableFile.rawValue), userInfo: [ NSLocalizedDescriptionKey: "Failed to write updated version to file" ]) } } }
apache-2.0
2eb8015ed27e39baaf84cfcec2b7ed2c
29.140625
189
0.638154
4.507009
false
false
false
false
VolodymyrShlikhta/InstaClone
InstaClone/SignInViewController.swift
1
2700
// // SignInViewController.swift // InstaClone // // Created by Relorie on 6/4/17. // Copyright © 2017 Relorie. All rights reserved. // import UIKit import FirebaseAuth import SVProgressHUD class SignInViewController: UIViewController { @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var signInButton: UIButton! override func viewDidLoad() { super.viewDidLoad() Utilities.configureTextFieldsAppearence([emailTextField, passwordTextField]) handleTextFields() signInButton.isEnabled = false signInButton.tintColor = .lightGray } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if Auth.auth().currentUser != nil { let currentUserUid = Auth.auth().currentUser?.uid Utilities.getFromDatabaseUserInfo(forUser: CurrentUser.sharedInstance, withUid: currentUserUid!) self.performSegue(withIdentifier: "signInToTabbsVC", sender: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } @IBAction func performSignIn(_ sender: UIButton) { view.endEditing(true) SVProgressHUD.show(withStatus: "Logging in...") AuthService.signIn(email: emailTextField.text!, password: passwordTextField.text!, onSuccess: { self.performSegue(withIdentifier: "signInToTabbsVC", sender: nil); SVProgressHUD.showSuccess(withStatus: "Welcome")}, onError: { error in SVProgressHUD.showError(withStatus: "\(error!)")} ) } func handleTextFields() { emailTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: UIControlEvents.editingChanged) passwordTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: UIControlEvents.editingChanged) } @objc func textFieldDidChange() { guard let email = emailTextField.text, !email.isEmpty, let password = passwordTextField.text, !password.isEmpty else { signInButton.setTitleColor(UIColor.lightText, for: UIControlState.normal) signInButton.isEnabled = false return } signInButton.setTitleColor(UIColor.white, for: UIControlState.normal) signInButton.isEnabled = true } }
mit
d6b58f5fc057011918cf9fea75822184
37.557143
122
0.64987
5.408818
false
false
false
false
Shvier/Dota2Helper
Dota2Helper/Dota2Helper/Global/Network/DHNetworkRequestManager.swift
1
4017
// // DHNetworkRequestManager.swift // Dota2Helper // // Created by Shvier on 9/19/16. // Copyright © 2016 Shvier. All rights reserved. // import UIKit enum RequestType { case POST case GET case DEFAULT } class DHNetworkRequestManager: NSObject { static let sharedInstance = DHNetworkRequestManager() func requestWithUrl(type: RequestType, urlHeader: URL?, parameters: Any?, completion: @escaping (Data?, URLResponse?, Error?) -> Void) { let request: URLRequest? switch type { case .POST: request = convertUrlToPOSTRequest(urlHeader: urlHeader, parameters: parameters as! NSDictionary?) break; case .GET: request = convertUrlToGETRequset(urlHeader: urlHeader, parameters: parameters as! NSDictionary?) break; default: request = convertUrlToDEFAULTRequset(urlHeader: urlHeader, parameters: parameters as! NSArray?) break; } let sessionConfig: URLSessionConfiguration = URLSessionConfiguration.default let session: URLSession = URLSession(configuration: sessionConfig) let dataTask: URLSessionDataTask = session.dataTask(with: request!, completionHandler: completion) dataTask.resume() } func convertUrlParametersToPOSTUrl(parameters: NSDictionary?) -> String { if parameters != nil { let paramList = NSMutableArray() for subDict in parameters! { let tmpString = "\(subDict.0)=\(subDict.1)" paramList.add(tmpString) } let paramString = paramList.componentsJoined(by: "&") return paramString } else { return "" } } func convertUrlParametersToGETUrl(parameters: NSDictionary?) -> String { if parameters != nil { let paramList = NSMutableArray() for subDict in parameters! { let tmpString = "\(subDict.0)=\(subDict.1)" paramList.add(tmpString) } let paramString = paramList.componentsJoined(by: "&") return paramString } else { return "" } } func convertUrlParametersToDEFAULTUrl(parameters: NSArray?) -> String { if parameters != nil { let paramList = NSMutableArray() for subString in parameters! { paramList.add(subString as! String) } let paramString = paramList.componentsJoined(by: "/") return paramString } else { return "" } } func convertUrlToPOSTRequest(urlHeader: URL?, parameters: NSDictionary?) -> URLRequest { var request = URLRequest(url: urlHeader!) if (parameters != nil) && (parameters?.count)! > 0 { request.httpMethod = "POST" let paramString = convertUrlParametersToPOSTUrl(parameters: parameters!) let paramData = paramString.data(using: String.Encoding.utf8) request.httpBody = paramData } else { request.httpMethod = "GET" } return request } func convertUrlToGETRequset(urlHeader: URL?, parameters: NSDictionary?) -> URLRequest { let paramString = convertUrlParametersToGETUrl(parameters: parameters) let urlString: String = urlHeader!.absoluteString + "?" + paramString let url: URL = URL(string: urlString)! var request: URLRequest = URLRequest(url: url) request.httpMethod = "GET" return request; } func convertUrlToDEFAULTRequset(urlHeader: URL?, parameters: NSArray?) -> URLRequest { let paramString = convertUrlParametersToDEFAULTUrl(parameters: parameters) let urlString: String = urlHeader!.absoluteString + paramString let url: URL = URL(string: urlString)! var request: URLRequest = URLRequest(url: url) request.httpMethod = "GET" return request; } }
apache-2.0
2637d3f0261c1ef5371a08220c347075
34.857143
140
0.611554
5.064313
false
false
false
false
marcusellison/lil-twitter
lil-twitter/ContainerViewController.swift
1
7883
// // ContainerViewController.swift // lil-twitter // // Created by Marcus J. Ellison on 5/31/15. // Copyright (c) 2015 Marcus J. Ellison. All rights reserved. // import UIKit enum SlideOutState { case BothCollapsed case LeftPanelExpanded case RightPanelExpanded } class ContainerViewController: UIViewController, MenuControllerDelegate, TweetCellDelegate { private var profileViewController: ProfileViewController! private var sidePanelViewController: SidePanelViewController! private var mentionsViewController: MentionsViewController! var centerNavigationController: UINavigationController! var centerViewController: TweetsViewController! var currentState: SlideOutState = .BothCollapsed { didSet { let shouldShowShadow = currentState != .BothCollapsed showShadowForCenterViewController(shouldShowShadow) } } var leftViewController: SidePanelViewController? let centerPanelExpandedOffset: CGFloat = 100 override func viewDidLoad() { super.viewDidLoad() centerViewController = UIStoryboard.centerViewController() centerViewController.tweetDelegate = self; centerNavigationController = UINavigationController(rootViewController: centerViewController) centerNavigationController.navigationBar.barTintColor = UIColor(red: 0.33, green: 0.674, blue: 0.933, alpha: 0) profileViewController = UIStoryboard.profileViewController() profileViewController.delegate = self mentionsViewController = UIStoryboard.mentionsViewController() mentionsViewController.delegate = self displayVC(centerNavigationController) // add gesture recognizer // var tapGesture = UITapGestureRecognizer(target: self, action: "handleTapGesture:") // tapGesture.delegate = self // view.addGestureRecognizer(tapGesture) // // func handleTapGesture(sender: UITapGestureRecognizer) { // println("handleTap") // // if (sender.state == .Ended) { // animateLeftPanel(shouldExpand: false) // } // } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } /* Main View Controller Delegate */ extension ContainerViewController: TweetsViewControllerDelegate { func toggleLeftPanel() { println("adding left panel") let notAlreadyExpanded = (currentState != .LeftPanelExpanded) println(notAlreadyExpanded) if notAlreadyExpanded { addLeftPanelViewController() } animateLeftPanel(shouldExpand: notAlreadyExpanded) } func addLeftPanelViewController() { if (leftViewController == nil) { leftViewController = UIStoryboard.leftViewController() addChildSidePanelController(leftViewController!) leftViewController?.delegate = self } } func addChildSidePanelController(sidePanelController: SidePanelViewController) { view.insertSubview(sidePanelController.view, atIndex: 0) addChildViewController(sidePanelController) sidePanelController.didMoveToParentViewController(self) println("insert child view controller") } func animateLeftPanel(#shouldExpand: Bool) { if (shouldExpand) { println("should open") currentState = .LeftPanelExpanded animateCenterPanelXPosition(targetPosition: CGRectGetWidth(centerNavigationController.view.frame) - centerPanelExpandedOffset) } else { animateCenterPanelXPosition(targetPosition: 0) { finished in self.currentState = .BothCollapsed println("\(self.leftViewController)") // self.leftViewController!.view.removeFromSuperview() self.leftViewController = nil; } } } func animateCenterPanelXPosition(#targetPosition: CGFloat, completion: ((Bool) -> Void)! = nil) { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .CurveEaseInOut, animations: { self.centerNavigationController.view.frame.origin.x = targetPosition }, completion: completion) } func showShadowForCenterViewController(shouldShowShadow: Bool) { if (shouldShowShadow) { centerNavigationController.view.layer.shadowOpacity = 0.8 } else { centerNavigationController.view.layer.shadowOpacity = 0.0 } } ///////////The Code of the Code!!!///////// // Add gestures // var tapGesture = UITapGestureRecognizer(target: self, action: "handleTapGesture:") // tapGesture.delegate = self // containerView.addGestureRecognizer(tapGesture) func showMentions() { displayVC(mentionsViewController) animateLeftPanel(shouldExpand: false) } func showProfile() { profileViewController.user = User.currentUser displayVC(profileViewController) animateLeftPanel(shouldExpand: false) } func showTimeline() { displayVC(centerNavigationController) //added instantiation - is this correct? animateLeftPanel(shouldExpand: false) } func displayVC(vc: UIViewController) { addChildViewController(vc) vc.view.frame = view.bounds view.addSubview(vc.view) vc.didMoveToParentViewController(self) } func userTapped(user: User) { println("code working here") } ///////////The Code of the Code!!!///////// } private extension UIStoryboard { class func mainStoryboard() -> UIStoryboard { return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) } class func leftViewController() -> SidePanelViewController? { return mainStoryboard().instantiateViewControllerWithIdentifier("LeftViewController") as? SidePanelViewController } class func centerViewController() -> TweetsViewController? { println("instantiated") return mainStoryboard().instantiateViewControllerWithIdentifier("TweetsViewController") as? TweetsViewController } // SETUP Profile class func profileViewController() -> ProfileViewController? { println("instantiating profile view") // profileViewController = storyboard?.instantiateViewControllerWithIdentifier("ProfileViewController") as ProfileViewController // profileViewController.isModal = false // profileViewController.delegate = self return mainStoryboard().instantiateViewControllerWithIdentifier("ProfileViewController") as? ProfileViewController } class func mentionsViewController() -> MentionsViewController? { println("instantiating profile view") // profileViewController = storyboard?.instantiateViewControllerWithIdentifier("ProfileViewController") as ProfileViewController // profileViewController.isModal = false // profileViewController.delegate = self return mainStoryboard().instantiateViewControllerWithIdentifier("MentionsViewController") as? MentionsViewController } }
mit
f3b458b76fc049c5a0588ad0f2d79433
33.880531
144
0.671445
5.904869
false
false
false
false
teamVCH/sway
sway/RecordingControlView.swift
1
2974
// // RecordingControlView.swift // AudioTest // // Created by Christopher McMahon on 10/16/15. // Copyright © 2015 codepath. All rights reserved. // import UIKit protocol RecordingControlViewDelegate { func setBackingAudio(view: RecordingControlView, url: NSURL) func startRecording(view: RecordingControlView, playBackingAudio: Bool) func stopRecording(view: RecordingControlView) func startPlaying(view: RecordingControlView) func stopPlaying(view: RecordingControlView) func bounce(view: RecordingControlView) } class RecordingControlView: UIView { @IBOutlet weak var recordButton: UIButton! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var currentTimeLabel: UILabel! @IBOutlet weak var playBackingAudioWhileRecordingSwitch: UIButton! @IBOutlet weak var bounceButton: UIButton! var delegate: RecordingControlViewDelegate? var isRecording: Bool = false { didSet { recordButton.selected = isRecording playButton.enabled = !isRecording } } var isPlaying: Bool = false { didSet { playButton.selected = isPlaying recordButton.enabled = !isPlaying } } var currentTime: NSTimeInterval = 0 { didSet { currentTimeLabel.text = Recording.formatTime(currentTime, includeMs: true) } } @IBAction func onTapRecord(sender: UIButton) { if sender.selected { delegate?.stopRecording(self) isRecording = false } else { delegate?.startRecording(self, playBackingAudio: playBackingAudioWhileRecordingSwitch.selected) isRecording = true } } @IBAction func onTapHeadphones(sender: UIButton) { print("headphones: \(sender.selected)") sender.selected = !sender.selected sender.tintColor = sender.selected ? UIColor.blueColor() : UIColor.blackColor() } @IBAction func onTapPlay(sender: UIButton) { //UIBarButtonPause_2x if sender.selected { delegate?.stopPlaying(self) isPlaying = false } else { delegate?.startPlaying(self) isPlaying = true } } @IBAction func onTapBounce(sender: UIButton) { delegate?.bounce(self) } override func awakeFromNib() { super.awakeFromNib() let image = UIImage(named: "headphones")?.imageWithRenderingMode(.AlwaysTemplate) playBackingAudioWhileRecordingSwitch.setImage(image, forState: .Normal) playBackingAudioWhileRecordingSwitch.setImage(image, forState: .Selected) } /* // just for demo purposes; this will happen automatically in collaborate mode @IBAction func loadBackingTrack(sender: AnyObject) { delegate?.setBackingAudio(self, url: defaultBackingAudio) } */ }
mit
358fd42e4790f3069e3881a39d0a859b
27.04717
107
0.642449
5.038983
false
false
false
false
aryehToDog/DYZB
DYZB/DYZB/Class/Home/View/WKAmuseMenuViewCell.swift
1
1898
// // WKAmuseMenuViewCell.swift // DYZB // // Created by 阿拉斯加的狗 on 2017/9/3. // Copyright © 2017年 阿拉斯加的🐶. All rights reserved. // import UIKit fileprivate let kGameViewCellId = "kGameViewCellId" class WKAmuseMenuViewCell: UICollectionViewCell { var anchorGroupModel: [WKAnchorGroup]? { didSet { collectionView.reloadData() } } @IBOutlet weak var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "WKGameViewCell", bundle: nil), forCellWithReuseIdentifier: kGameViewCellId) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout let itemW:CGFloat = self.frame.size.width / 4 let itemH:CGFloat = self.frame.size.height / 2 layout.itemSize = CGSize(width: itemW, height: itemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 collectionView.dataSource = self } } extension WKAmuseMenuViewCell: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // let modelGroup = anchorGroupModel[section] return self.anchorGroupModel!.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameViewCellId, for: indexPath) as! WKGameViewCell cell.groupM = self.anchorGroupModel?[indexPath.item] cell.clipsToBounds = true return cell } }
apache-2.0
4adf3d3ac96cf20c62b0167285b15c37
28.21875
126
0.652406
5.29745
false
false
false
false
marekhac/WczasyNadBialym-iOS
WczasyNadBialym/WczasyNadBialym/ViewControllers/Service/ServiceList/ServiceListViewController.swift
1
2512
// // ServiceListViewController.swift // WczasyNadBialym // // Created by Marek Hać on 26.04.2017. // Copyright © 2017 Marek Hać. All rights reserved. // import UIKit import SVProgressHUD class ServiceListViewController: UITableViewController { let backgroundImageName = "background_blue" // these values will be assigned by parent view controller in prepare for segue var categoryNameShort: String = "" var categoryNameLong: String = "" lazy var viewModel: ServiceListViewModel = { return ServiceListViewModel() }() // init view model func initViewModel () { // initialize callback closures // used [weak self] to avoid retain cycle viewModel.categoryNameShort = self.categoryNameShort viewModel.reloadTableViewClosure = { [weak self] () in DispatchQueue.main.async { self?.tableView.reloadData() SVProgressHUD.dismiss() } } viewModel.fetchServices(for: categoryNameShort) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.addBlurSubview(image: backgroundImageName) } override func viewDidLoad() { super.viewDidLoad() self.tableView.dataSource = viewModel self.tableView.delegate = viewModel self.navigationItem.title = self.categoryNameLong SVProgressHUD.show() initViewModel() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let selectedCell = sender as? ServiceListCell { if segue.identifier == "showServiceDetails" { let controller = (segue.destination as! UINavigationController).topViewController as! ServiceDetailsViewController controller.selectedServiceId = String(selectedCell.serviceId!) controller.selectedServiceType = self.categoryNameShort controller.backgroundImage = selectedCell.realServiceImage; controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true } } } }
gpl-3.0
98c094a94dce345c7482b578c8ca8b20
30.3625
130
0.639299
5.794457
false
false
false
false
AynurGaliev/Books-Shop
Sources/App/Models/Credential.swift
1
2936
import Vapor import Fluent import Foundation final class Credential: Model { private static let tokenTime: TimeInterval = 86400 //MARK: - Attributes var id: Node? var password: String var login: String var expiration_date: String? var token: String? //MARK: - Relationships var userId: Node? //MARK: - Private variables var exists: Bool = false convenience init(node: Node, userId: Node, in context: Context) throws { try self.init(node: node, in: context) self.userId = userId } init(password: String, login: String) { self.password = password self.login = login } init(node: Node, in context: Context) throws { self.id = try node.extract("id") self.password = try node.extract("password") self.login = try node.extract("login") self.expiration_date = try node.extract("expiration_date") self.token = try node.extract("token") self.userId = try node.extract("user_id") } func isTokenValid() throws -> Bool { guard let date = self.expiration_date, let expirationDate = ISO8601DateFormatter.date(from: date) else { throw Abort.badRequest } return Date() < expirationDate } func makeJSON() throws -> JSON { let node = try Node(node: [ "token" : self.token, "expiration_date" : self.expiration_date ]) return JSON(node) } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": self.id, "password": self.password, "login": self.login, "user_id": self.userId, "token": self.token, "expiration_date": self.expiration_date ]) } class func renewToken(credential: inout Credential) throws { credential.token = UUID().uuidString credential.expiration_date = Date().addingTimeInterval(Credential.tokenTime).ISO8601FormatString } } extension Credential: Preparation { static func prepare(_ database: Database) throws { try database.create("credentials") { (creator) in creator.id() creator.string("password", length: nil, optional: false, unique: true, default: nil) creator.string("login", length: nil, optional: false, unique: true, default: nil) creator.string("token", length: nil, optional: true, unique: false, default: nil) creator.string("expiration_date", length: nil, optional: true, unique: false, default: nil) creator.parent(User.self, optional: false, unique: true, default: nil) } } static func revert(_ database: Database) throws { try database.delete("credentials") } }
mit
3546d1f3cc7890199bad2055af951ff0
31.988764
137
0.582084
4.516923
false
false
false
false
blkbrds/intern09_final_project_tung_bien
MyApp/Model/Schema/CartItem.swift
1
491
// // CartItem.swift // MyApp // // Created by AST on 8/9/17. // Copyright © 2017 Asian Tech Co., Ltd. All rights reserved. // import Foundation import RealmS import RealmSwift final class CartItem: Object { dynamic var id = 0 dynamic var name = "" dynamic var thumbnailImage = "" dynamic var detail = "" dynamic var price = 0.0 dynamic var quantity = 1 dynamic var unit = "" override class func primaryKey() -> String? { return "id" } }
mit
baacd04a7e495cb1786a965637f564a1
17.846154
62
0.62449
3.888889
false
false
false
false
teambition/SwipeableTableViewCell
SwipeableTableViewCellExample/BackgroundViewExampleViewController.swift
1
5193
// // BackgroundViewExampleViewController.swift // SwipeableTableViewCellExample // // Created by 洪鑫 on 16/6/5. // Copyright © 2016年 Teambition. All rights reserved. // import UIKit import SwipeableTableViewCell class BackgroundViewExampleViewController: UITableViewController { fileprivate(set) var pushEnabled = false // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() setupUI() } // MARK: - Helper fileprivate func setupUI() { tableView.tableFooterView = UIView() let switchView: UIView = { let titleView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 150, height: 40))) titleView.backgroundColor = .clear let titleLabel = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: 99, height: 40))) titleLabel.backgroundColor = .clear titleLabel.text = "Push Enabled" titleLabel.font = .systemFont(ofSize: 14) titleLabel.textColor = .red titleView.addSubview(titleLabel) let pushSwitch = UISwitch() pushSwitch.frame.origin.x = 99 pushSwitch.frame.origin.y = (40 - pushSwitch.frame.height) / 2 pushSwitch.isOn = false pushSwitch.addTarget(self, action: #selector(pushSwitchValueChanged(_:)), for: .valueChanged) titleView.addSubview(pushSwitch) return titleView }() navigationItem.rightBarButtonItem = UIBarButtonItem(customView: switchView) if #available(iOS 9, *) { if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self, sourceView: view) } } } @objc func pushSwitchValueChanged(_ sender: UISwitch) { pushEnabled = sender.isOn } // MARK: - Table view data source and delegate override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 65 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "SwipeableCell with background view" case 1: return "UITableViewCell with background view" default: return nil } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: kBackgroundViewSwipeableCellID, for: indexPath) as! BackgroundViewSwipeableCell let delete = NSAttributedString(string: "删除", attributes: [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 15)]) var deleteAction = SwipeableCellAction(title: delete, image: UIImage(named: "delete-icon"), backgroundColor: UIColor(red: 255 / 255, green: 90 / 255, blue: 29 / 255, alpha: 1)) { print("删除") } let later = NSAttributedString(string: "稍后处理", attributes: [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 15)]) var laterAction = SwipeableCellAction(title: later, image: UIImage(named: "later-icon"), backgroundColor: UIColor(red: 3 / 255, green: 169 / 255, blue: 244 / 255, alpha: 1)) { print("稍后处理") } deleteAction.width = 100 deleteAction.verticalSpace = 6 laterAction.width = 100 laterAction.verticalSpace = 6 cell.actions = [deleteAction, laterAction] return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: kBackgroundViewCellID, for: indexPath) as! BackgroundViewCell return cell } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if pushEnabled { performSegue(withIdentifier: "PushToViewController", sender: self) tableView.deselectRow(at: indexPath, animated: true) } } } @available(iOS 9.0, *) extension BackgroundViewExampleViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = tableView.indexPathForRow(at: location), let cell = tableView.cellForRow(at: indexPath) else { return nil } let previewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController") previewController.preferredContentSize = .zero previewingContext.sourceRect = cell.frame return previewController } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { show(viewControllerToCommit, sender: self) } }
mit
72a4f6fbc38da666f7ad1c4a22aad7cd
41.661157
191
0.66079
5.198389
false
false
false
false
fe9lix/Muon
MuonTests/FeedParserSpec.swift
2
2117
import Quick import Nimble import Muon let feed = "<rss><channel></channel></rss>" class FeedParserSpec: QuickSpec { override func spec() { var subject : FeedParser! = nil describe("Initializing a feedparser with empty string") { beforeEach { subject = FeedParser(string: "") } it("call onFailure if main is called") { let expectation = self.expectationWithDescription("errorShouldBeCalled") subject.failure {error in expect(error.localizedDescription).to(equal("No Feed Found")) expectation.fulfill() } subject.main() self.waitForExpectationsWithTimeout(1, handler: { _ in }) } } describe("Initializing a feedparser with a feed") { beforeEach { subject = FeedParser(string: feed) } it("should succeed when main is called") { var feed: Feed? = nil subject.success { feed = $0 } subject.main() expect(feed).toEventuallyNot(beNil()) } } describe("Initializing a feedparser without data") { beforeEach { subject = FeedParser() } it("immediately call onFailure if main is called") { var error: NSError? = nil subject.failure { error = $0 } subject.main() expect(error).toNot(beNil()) expect(error?.localizedDescription).to(equal("Must be configured with data")) } describe("after configuring") { beforeEach { subject.configureWithString(feed) } it("should succeed when main is called") { var feed: Feed? = nil subject.success { feed = $0 } subject.main() expect(feed).toEventuallyNot(beNil()) } } } } }
mit
1da8633048e6c94740122136ccd6f753
30.597015
93
0.487955
5.645333
false
false
false
false
shoheiyokoyama/Gemini
Example/Gemini/ViewControllers/RollRotationViewController.swift
1
4464
import UIKit import Gemini final class RollRotationViewController: UIViewController { @IBOutlet private weak var collectionView: GeminiCollectionView! { didSet { let nib = UINib(nibName: cellIdentifier, bundle: nil) collectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier) collectionView.backgroundColor = .clear collectionView.delegate = self collectionView.dataSource = self if #available(iOS 11.0, *) { collectionView.contentInsetAdjustmentBehavior = .never } collectionView.gemini .rollRotationAnimation() .rollEffect(rotationEffect) .scale(0.7) } } private let cellIdentifier = String(describing: ImageCollectionViewCell.self) private var rotationEffect = RollRotationEffect.rollUp private var scrollDirection = UICollectionView.ScrollDirection.horizontal private let images = Resource.image.images static func make(scrollDirection: UICollectionView.ScrollDirection, effect: RollRotationEffect) -> RollRotationViewController { let storyboard = UIStoryboard(name: "RollRotationViewController", bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: "RollRotationViewController") as! RollRotationViewController viewController.rotationEffect = effect viewController.scrollDirection = scrollDirection return viewController } override func viewDidLoad() { super.viewDidLoad() let layout = UICollectionViewPagingFlowLayout() layout.scrollDirection = scrollDirection layout.itemSize = CGSize(width: view.bounds.width - 60, height: view.bounds.height - 100) layout.sectionInset = UIEdgeInsets(top: 50, left: 30, bottom: 50, right: 30) layout.minimumLineSpacing = 30 layout.minimumInteritemSpacing = 30 collectionView.collectionViewLayout = layout collectionView.decelerationRate = UIScrollView.DecelerationRate.fast navigationController?.setNavigationBarHidden(true, animated: false) let gesture = UITapGestureRecognizer(target: self, action: #selector(toggleNavigationBarHidden(_:))) gesture.cancelsTouchesInView = false view.addGestureRecognizer(gesture) let startColor = UIColor(red: 29 / 255, green: 44 / 255, blue: 76 / 255, alpha: 1) let endColor = UIColor(red: 3 / 255, green: 7 / 255, blue: 20 / 255, alpha: 1) let colors: [CGColor] = [startColor.cgColor, endColor.cgColor] let gradientLayer = CAGradientLayer() gradientLayer.colors = colors gradientLayer.frame.size = view.bounds.size view.layer.insertSublayer(gradientLayer, at: 0) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } @objc private func toggleNavigationBarHidden(_ gestureRecognizer: UITapGestureRecognizer) { let isNavigationBarHidden = navigationController?.isNavigationBarHidden ?? true navigationController?.setNavigationBarHidden(!isNavigationBarHidden, animated: true) } } // MARK: - UIScrollViewDelegate extension RollRotationViewController { func scrollViewDidScroll(_ scrollView: UIScrollView) { collectionView.animateVisibleCells() } } // MARK: - UICollectionViewDelegate extension RollRotationViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let cell = cell as? GeminiCell { self.collectionView.animateCell(cell) } } } // MARK: - UICollectionViewDataSource extension RollRotationViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ImageCollectionViewCell cell.configure(with: images[indexPath.row]) self.collectionView.animateCell(cell) return cell } }
mit
edb85e41101785ac5faa30a40b44e194
40.333333
142
0.711694
5.730424
false
false
false
false
digipost/ios
Digipost/InvoiceBankViewController.swift
1
4218
// // Copyright (C) Posten Norge AS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation class InvoiceBankViewController: UIViewController{ var invoiceBank : InvoiceBank = InvoiceBank() @IBOutlet weak var invoiceBankLogo: UIImageView!{ didSet{ if let logo = UIImage(named:"\(invoiceBank.logo)-large"){ self.invoiceBankLogo.image = logo } } } @IBOutlet weak var invoiceBankName: UILabel! { didSet { if(UIImage(named:"\(invoiceBank.logo)-large") == nil) { self.invoiceBankName.text = invoiceBank.name } } } @IBOutlet weak var invoiceBankContent: UILabel!{ didSet{ let invoiceBankContentString = invoiceBank.activeType2Agreement ? "invoice bank enabled content" : "invoice bank disabled content" self.invoiceBankContent.text = NSLocalizedString(invoiceBankContentString, comment:"invoice bank content") self.invoiceBankContent.sizeToFit() self.invoiceBankContent.lineBreakMode = NSLineBreakMode.byWordWrapping } } @IBOutlet weak var invoiceBankTitle: UILabel!{ didSet{ let invoiceBankTitleString = invoiceBank.activeType2Agreement ? "invoice bank enabled title" : "invoice bank disabled title" self.invoiceBankTitle.text = NSLocalizedString(invoiceBankTitleString, comment:"invoice bank title") } } @IBOutlet weak var openBankUrlButton: UIButton!{ didSet{ if(invoiceBank.haveRegistrationUrl()){ let openBankUrlButtonString = NSLocalizedString("invoice bank button link prefix", comment: "invoice bank button link") + invoiceBank.name + NSLocalizedString("invoice bank button link postfix", comment: "Invoice bank button link") self.openBankUrlButton.setTitle(openBankUrlButtonString, for: UIControlState()) }else{ self.openBankUrlButton.isHidden = true } } } @IBOutlet weak var invoiceBankReadMoreText: UIButton!{ didSet{ let invoiceBankReadMoreLinkString = invoiceBank.activeType2Agreement ? "invoice bank enabled read more link" : "invoice bank disabled read more link" self.invoiceBankReadMoreText.setTitle(NSLocalizedString(invoiceBankReadMoreLinkString, comment:"invoice bank read more link"), for:UIControlState()) } } @IBAction func openBankUrl(_ sender: AnyObject) { GAEvents.event(category: "faktura-avtale-oppsett-kontekst-basert", action: "klikk-oppsett-avtale-type-2-link", label: invoiceBank.name, value: nil) UIApplication.shared.openURL(URL(string:invoiceBank.registrationUrl)!) //Opens external bank website, should be opened in external browser } @IBAction func invoiceBankReadMore(_ sender: AnyObject) { if(invoiceBank.activeType2Agreement){ GAEvents.event(category: "faktura-avtale-oppsett-kontekst-basert", action: "klikk-digipost-faktura-åpne-sider", label: invoiceBank.name, value: nil) openExternalUrl(url: "https://digipost.no/faktura") }else{ GAEvents.event(category: "faktura-avtale-oppsett-kontekst-basert", action: "klikk-oppsett-avtale-type-1-link", label: invoiceBank.name, value: nil) openExternalUrl(url: "https://digipost.no/app/post#/faktura") } } func openExternalUrl(url: String){ if #available(iOS 9.0, *) { let svc = SFSafariViewController(url: NSURL(string: url)! as URL) self.present(svc, animated: true, completion: nil) } } }
apache-2.0
2473541b695822b462298da8bcacae9e
42.927083
247
0.670382
4.311861
false
false
false
false
meninsilicium/apple-swifty
JSON.playground/contents.swift
1
1873
//: # Swifty.JSON import Swift import Swifty import Foundation import Darwin //: # JSON examples //: A json as a string let json_string = "{ \"coordinate\" : { \"latitude\" : 46.2050295, \"longitude\" : 6.1440885, \"city\" : \"Geneva\" }, \"source\" : \"string\" }" //: ## Initialization //: with a raw string or NSData var json: JSONValue = [:] if let maybe_json = JSON.decode( json_string ).value { json = maybe_json } json.prettyprint() //: with literals json = [ "coordinate" : [ "latitude" : 46.2050295, "longitude" : 6.144, "city" : "Geneva" ], "source" : "literals" ] json.prettyprint() //: ## Read //: with direct access var json_longitude = json[ "coordinate", "longitude" ]?.double ?? 0 var json_latitude = json[ "coordinate", "latitude" ]?.double ?? 0 //: with a path var json_path: JSONPath = [ "coordinate", "latitude" ] var json_latitude_number = json[ json_path ]?.number ?? 0 json_latitude = json[ json_path ]?.double ?? 0 var json_city = json[ JSONPath( "coordinate", "city" ) ]?.string ?? "" //: ## Validation var json_validation = JSONValidation() // assess [ "coordinate", "latitude" ] json_validation.assess( json_path, optional: false ) { ( validation, json ) -> Bool in switch json { case .JSONNumber, .JSONDouble, .JSONInteger: let value = json.double return (value >= -180) || (value <= 180) default: return false } } // assess [ "coordinate", "longitude" ] json_validation.assess( [ "coordinate", "longitude" ], optional: true ) { ( validation, json ) -> Bool in switch json { case .JSONNumber, .JSONDouble, .JSONInteger: let value = json.double return (value >= -180) || (value <= 180) default: return false } } //: Validate let valid = json.validate( json_validation ) json_validation.validate( json ) //----------------------------------------------------------------
mpl-2.0
24fe5189b5ab29cbeb686b1eaf7e958c
18.510417
145
0.611853
3.246101
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Service/Network/BBS3.swift
1
3543
// // BBS3 // // creds = AmazonCredentials(...) // data = NSData() // uploader = ElloS3(credentials: credentials, data: data) // .onSuccess() { (response : NSData) in } // .onFailure() { (error : NSError) in } // // NOT yet supported: // //.onProgress() { (progress : Float) in } // .start() import Foundation public class BBS3 { let filename: String let data: NSData let contentType: String let credentials: AmazonCredentials typealias SuccessHandler = (_ response: NSData) -> Void typealias FailureHandler = (_ error: NSError) -> Void typealias ProgressHandler = (_ progress: Float) -> Void private var successHandler: SuccessHandler? private var failureHandler: FailureHandler? private var progressHandler: ProgressHandler? public init(credentials: AmazonCredentials, filename: String, data: NSData, contentType: String) { self.filename = filename self.data = data self.contentType = contentType self.credentials = credentials } func onSuccess(handler: @escaping SuccessHandler) -> Self { self.successHandler = handler return self } func onFailure(handler: @escaping FailureHandler) -> Self { self.failureHandler = handler return self } func onProgress(handler: @escaping ProgressHandler) -> Self { self.progressHandler = handler return self } // this is just the uploading code, the initialization and handler code is // mostly the same func start() -> Self { let key = "\(credentials.prefix)/\(filename)" let url = NSURL(string: credentials.endpoint)! let builder = MultipartRequestBuilder(url: url, capacity: data.length) builder.addParam(name: "key", value: key) builder.addParam(name: "AWSAccessKeyId", value: credentials.accessKey) builder.addParam(name: "acl", value: "public-read") builder.addParam(name: "success_action_status", value: "201") builder.addParam(name: "policy", value: credentials.policy) builder.addParam(name: "signature", value: credentials.signature) builder.addParam(name: "Content-Type", value: self.contentType) // builder.addParam("Content-MD5", value: md5(data)) builder.addFile(name: "file", filename: filename, data: data, contentType: contentType) let request = builder.buildRequest() let session = URLSession.shared let task = session.dataTaskWithRequest(request as URLRequest) { (data: NSData?, response: URLResponse?, error: NSError?) in nextTick { let httpResponse = response as? NSHTTPURLResponse if let error = error { self.failureHandler?(error: error) } else if httpResponse?.statusCode >= 200 && httpResponse?.statusCode < 300 { if let data = data { self.successHandler?(response: data) } else { self.failureHandler?(error: NSError(domain: ElloErrorDomain, code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: "failure"])) } } else { self.failureHandler?(error: NSError(domain: ElloErrorDomain, code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: "failure"])) } } } task.resume() return self } }
mit
400989dc7d89c37e8df0a2e308a8aef3
36.294737
151
0.604572
4.927677
false
false
false
false
imobilize/Molib
Molib/Classes/Networking/DownloadManager/DownloaderOperation.swift
1
2884
import Foundation protocol DownloaderOperationDelegate { func downloaderOperationDidUpdateProgress(progress: Float, forTask: DownloaderTask) func downloaderOperationDidStartDownload(forTask: DownloaderTask) func downloaderOperationDidFailDownload(withError: Error, forTask: DownloaderTask) func downloaderOperationDidComplete(forTask: DownloaderTask) } class DownloaderOperation: Operation { var delegate: DownloaderOperationDelegate? private let downloaderTask: DownloaderTask private let networkOperationService: NetworkRequestService private var networkDownloadOperation: NetworkDownloadOperation? init(downloaderTask: DownloaderTask, networkOperationService: NetworkRequestService) { self.downloaderTask = downloaderTask self.networkOperationService = networkOperationService } override func main() { delegate?.downloaderOperationDidStartDownload(forTask: downloaderTask) let semaphore = DispatchSemaphore(value: 0) let downloadRequest = DataDownloadTask(downloaderTask: downloaderTask) { [weak self](_, errorOptional) in semaphore.signal() if let strongSelf = self { if let error = errorOptional { strongSelf.delegate?.downloaderOperationDidFailDownload(withError: error, forTask: strongSelf.downloaderTask) } else { strongSelf.delegate?.downloaderOperationDidComplete(forTask: strongSelf.downloaderTask) } } } networkDownloadOperation = networkOperationService.enqueueNetworkDownloadRequest(request: downloadRequest) networkDownloadOperation?.registerProgressUpdate(progressUpdate: handleProgressUpdate) semaphore.wait() } override func cancel() { networkDownloadOperation?.cancel() } func pause() { networkDownloadOperation?.pause() } func resume() { networkDownloadOperation?.resume() } func handleProgressUpdate(progress: Float) { delegate?.downloaderOperationDidUpdateProgress(progress: progress, forTask: downloaderTask) } func matchesDownloaderTask(task: DownloaderTask) -> Bool { return downloaderTask == task } override func isEqual(_ object: Any?) -> Bool { if let operation = object as? DownloaderOperation { return operation.downloaderTask.downloadURL == self.downloaderTask.downloadURL } return false } } extension DataDownloadTask { init(downloaderTask: DownloaderTask, taskCompletion: @escaping DataResponseCompletion) { self.fileName = downloaderTask.fileName self.downloadLocationURL = downloaderTask.downloadDestinationURL self.urlRequest = URLRequest(url: downloaderTask.downloadURL) self.taskCompletion = taskCompletion } }
apache-2.0
c9b1ee93112bb5be5566a60c60dfba11
31.404494
129
0.716366
5.589147
false
false
false
false
tapwork/WikiLocation
WikiManager/WikiArticle.swift
1
1496
// // WikiArticle.swift // WikiLocation // // Created by Christian Menschel on 29.06.14. // Copyright (c) 2014 enterprise. All rights reserved. // import Foundation public class WikiArticle : NSObject { //Mark: - Properties public let distance:String! public let identifier:Int! public let latitutde:Double! public let longitude:Double! public let url:NSURL! public let title:String! //MARK: - Init init(json:Dictionary<String,AnyObject>) { super.init() if let title = json["title"] as? NSString { self.title = title } if let distance = json["dist"] as? NSNumber { self.distance = NSString(format: "Distance: %.2f Meter", distance.doubleValue) } if let id = json["pageid"] as? NSNumber { self.identifier = id.integerValue } if let latitutde = json["lat"] as? NSNumber { self.latitutde = latitutde.doubleValue } if let longitude = json["lon"] as? NSNumber { self.longitude = longitude.doubleValue } self.url = NSURL(string: "http://en.wikipedia.org/wiki?curid=\(self.identifier)") } //MARK: - Equality func hash() -> Int { return self.title.hash } override public func isEqual(object: AnyObject!) -> Bool { if self === object || self.hash == object.hash { return true } return false } }
mit
64d7e4bedd529131be7f95db9e8f1b4b
26.218182
90
0.572193
4.144044
false
false
false
false
LiskUser1234/SwiftyLisk
Lisk/Multisignature/MultisignatureAPI.swift
1
6352
/* The MIT License Copyright (C) 2017 LiskUser1234 - Github: https://github.com/liskuser1234 Please vote LiskUser1234 for delegate to support this project. For donations: - Lisk: 6137947831033853925L - Bitcoin: 1NCTZwBJF7ZFpwPeQKiSgci9r2pQV3G7RG 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 class MultisignatureAPI { private static let moduleName = "multisignatures" /// Create a multisig account /// /// - Parameters: /// - passphrase: The passphrase to sign the account's transactions /// - publicKey: Optional: The expected public key of the account derived from `passphrase` /// - secondPassphrase: Optional: the second passphrase to sign the account's transactions /// - minimumSignatures: The minimum amount of signatures to approve a transaction /// - lifetime: The interval of time within which the minimum amount of signatures per transaction must be recieved /// - keysgroup: Array of public keys that can sign any of the account's tranasactions. Each public key must have a "+" prefix. /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#create-multi-signature-account open class func create(passphrase: String, publicKey: String?, secondPassphrase: String?, minimumSignatures: Int, lifetime: Int, keysgroup: [String], callback: @escaping Callback) { var data = [ "secret": passphrase, "lifetime": String(lifetime), "min": String(minimumSignatures), "keysgroup": keysgroup ] as [String : Any] if let secondPassphrase = secondPassphrase { data["secondSecret"] = secondPassphrase } if let publicKey = publicKey { data["publicKey"] = publicKey } Api.request(module: moduleName, submodule: nil, method: .put, json: data, callback: callback) } /// Gets data relative to the multisig account with the given public key. /// /// - Parameters: /// - publicKey: The public key of the multisig account for which data will be retrieved /// - callback: The function that will be called with information about the request open class func getAccounts(publicKey: String, callback: @escaping Callback) { let data = [ "publicKey" : publicKey ] Api.request(module: moduleName, submodule: "accounts", method: .get, query: data, callback: callback) } /// Signs a pending multisig transaction. /// /// - Parameters: /// - passphrase: The passphrase of the signer /// - publicKey: Optional: the public key of the signer, to check whether the passphrase's public key matches the expected public key /// - secondPassphrase: Optional: the second passphrase of the signer /// - transactionId: The id of the multisig transaction to sign /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#sign-transaction open class func sign(passphrase: String, publicKey: String?, secondPassphrase: String?, transactionId: String, callback: @escaping Callback) { var data = [ "secret": passphrase, "transactionId": transactionId ] if let publicKey = publicKey { data["publicKey"] = publicKey } if let secondPassphrase = secondPassphrase { data["secondPassphrase"] = secondPassphrase } Api.request(module: moduleName, submodule: "sign", method: .post, json: data, callback: callback) } /// Gets all pending transactions of the multisig account with the given public key /// /// - Parameters: /// - publicKey: The public key of the account whose pending transactions will be retrieved /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#get-pending-multi-signature-transactions open class func getPendingTransasctions(publicKey: String, callback: @escaping Callback) { let data = [ "publicKey": publicKey ] Api.request(module: moduleName, submodule: "pending", method: .get, query: data, callback: callback) } }
mit
e5a5680d10508a6b80cb6ace381e024e
40.246753
139
0.610674
5.106109
false
false
false
false
kdw9/TIY-Assignments
MuttCutts/MuttCutts/MapViewController.swift
1
1669
// // ViewController.swift // MuttCutts // // Created by Keron Williams on 10/28/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import MapKit import CoreLocation class MapViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() let tiyOrlando = CLLocationCoordiante2DMake(28.540923, -81.38216) let tiyOrlandoAnnotation.coordinate = tiyOrlando tiyOrlandoAnnotation.coordinate = tiyOrlando tiyOrlandoAnnotation.title = "The Iron Yard" tiyOrlandoAnnotation.subtitle = "Orlando" let annotations = [tiyOrlandoAnnotation] mapView.addAnnotation(annotations) let viewRegion = MKCoodinateRegionMakeWithDistance (tiyOrlando, 2000, 2000) mapView.setRegion(viewRegion, animate: true) let tiyTampa = CLLocationCoordiante2DMake(27.770068, -82.63642) let tiyTampaAnnotation.coordinate = tiyOrlando tiyTampaAnnotation.coordinate = tiyOrlando tiyTampaAnnotation.title = "The Iron Yard" tiyTampaAnnotation.subtitle = "Tampa" let annotations = [tiyTampaAnnotation] mapView.addAnnotation(annotations) mapView.showAnnotations(annotations,animate) //let viewRegion = MKCoodinateRegionMakeWithDistance (tiyTampa, 2000, 2000) mapView.setRegion(viewRegion, animate: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
cc0-1.0
d9274b9ba59a872d4d8532df7fe70a21
27.758621
73
0.672662
4.138958
false
false
false
false
nkirby/Humber
_lib/HMGithub/_src/Realm/GithubOverviewItem.swift
1
741
// ======================================================= // HMGithub // Nathaniel Kirby // ======================================================= import Foundation import RealmSwift // ======================================================= public class GithubOverviewItem: Object { public dynamic var itemID = "" public dynamic var sortOrder = 0 public dynamic var type = "" public dynamic var title = "" public dynamic var value = 0 public dynamic var query = "" public dynamic var repoName = "" public dynamic var repoOwner = "" public dynamic var action = "" public dynamic var threshold = -1 public override class func primaryKey() -> String { return "itemID" } }
mit
6a72d6748d69ff86b0d31d8dfe55efcc
26.444444
58
0.497976
5.928
false
false
false
false
hffmnn/Swiftz
SwiftzTests/ThoseSpec.swift
2
575
// // ThoseSpec.swift // swiftz // // Created by Robert Widmann on 1/19/15. // Copyright (c) 2015 TypeLift. All rights reserved. // import XCTest import Swiftz class ThoseSpec : XCTestCase { func testThose() { let this = Those<String, Int>.this("String") let that = Those<String, Int>.that(1) let both = Those<String, Int>.these("String", r: 1) XCTAssert((this.isThis() && that.isThat() && both.isThese()) == true, "") XCTAssert(this.toTuple("String", r: 1) == that.toTuple("String", r: 1), "") XCTAssert(both.bimap(identity, identity) == both, "") } }
bsd-3-clause
52693f697c7bb062a51c53709caacf9b
24
77
0.641739
3.010471
false
true
false
false
imzyf/99-projects-of-swift
031-stopwatch/031-stopwatch/ViewController.swift
1
3284
// // ViewController.swift // 031-stopwatch // // Created by moma on 2018/3/28. // Copyright © 2018年 yifans. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: - UI components @IBOutlet weak var timerLabel: UILabel! @IBOutlet weak var lapTimerLabel: UILabel! @IBOutlet weak var playPauseButton: UIButton! @IBOutlet weak var lapRestButton: UIButton! @IBOutlet weak var lapsTableView: UITableView! // MARK: - Variables fileprivate let mainStopwatch: Stopwatch = Stopwatch() fileprivate let lapStopwatch: Stopwatch = Stopwatch() fileprivate var isPlay: Bool = false fileprivate var laps: [String] = [] let stepTimeInterval: CGFloat = 0.035 override func viewDidLoad() { super.viewDidLoad() // 闭包设置 button 样式 let initCircleButton: (UIButton) -> Void = { button in button.layer.cornerRadius = 0.5 * button.bounds.size.width } initCircleButton(playPauseButton) initCircleButton(lapRestButton) playPauseButton.setTitle("Stop", for: .selected) lapRestButton.isEnabled = false } @IBAction func playPauseTimer(_ sender: UIButton) { if sender.isSelected { // stop mainStopwatch.timer.invalidate() } else { // start lapRestButton.isEnabled = true mainStopwatch.timer = Timer.scheduledTimer(withTimeInterval: TimeInterval(self.stepTimeInterval), repeats: true) { (time) in self.updateTimer(self.mainStopwatch, label: self.timerLabel) } sender.isSelected = !sender.isSelected // // Timer.scheduledTimer(timeInterval: 0.035, target: self, selector: Selector.updateMainTimer, userInfo: nil, repeats: true) // } } func updateTimer(_ stopwatch: Stopwatch, label: UILabel) { stopwatch.counter = stopwatch.counter + stepTimeInterval let minutes = Int(stopwatch.counter / 60) let minuteText = minutes < 10 ? "0\(minutes)" : "\(minutes)" let seconds = stopwatch.counter.truncatingRemainder(dividingBy: 60) let secondeText = seconds < 10 ? String(format: "0%.2f", seconds) : String(format: "%.2f", seconds) label.text = minuteText + ":" + secondeText } } // MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return laps.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) // if let labelNum = cell.viewWithTag(11) as? UILabel { // labelNum.text = "Lap \(laps.count - (indexPath as NSIndexPath).row)" // } // if let labelTimer = cell.viewWithTag(12) as? UILabel { // labelTimer.text = laps[laps.count - (indexPath as NSIndexPath).row - 1] // } return cell } }
mit
1f8d61e743aa10ccbc28af6ffd66015b
31.69
139
0.609055
4.730825
false
false
false
false
SuPair/firefox-ios
Client/Application/LeanplumIntegration.swift
1
15188
/* 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 AdSupport import Shared import Leanplum private let LPAppIdKey = "LeanplumAppId" private let LPProductionKeyKey = "LeanplumProductionKey" private let LPDevelopmentKeyKey = "LeanplumDevelopmentKey" private let AppRequestedUserNotificationsPrefKey = "applicationDidRequestUserNotificationPermissionPrefKey" private let FxaDevicesCountPrefKey = "FxaDevicesCount" // FxA Custom Leanplum message template for A/B testing push notifications. private struct LPMessage { static let FxAPrePush = "FxA Prepush v1" static let ArgAcceptAction = "Accept action" static let ArgCancelAction = "Cancel action" static let ArgTitleText = "Title.Text" static let ArgTitleColor = "Title.Color" static let ArgMessageText = "Message.Text" static let ArgMessageColor = "Message.Color" static let ArgAcceptButtonText = "Accept button.Text" static let ArgCancelButtonText = "Cancel button.Text" static let ArgCancelButtonTextColor = "Cancel button.Text color" // These defaults are not localized and will be overridden through Leanplum static let DefaultAskToAskTitle = "Firefox Sync Requires Push" static let DefaultAskToAskMessage = "Firefox will stay in sync faster with Push Notifications enabled." static let DefaultOkButtonText = "Enable Push" static let DefaultLaterButtonText = "Don’t Enable" } private let log = Logger.browserLogger enum LPEvent: String { case firstRun = "E_First_Run" case secondRun = "E_Second_Run" case openedApp = "E_Opened_App" case dismissedOnboarding = "E_Dismissed_Onboarding" case dismissedOnboardingShowLogin = "E_Dismissed_Onboarding_Showed_Login" case openedLogins = "Opened Login Manager" case openedBookmark = "E_Opened_Bookmark" case openedNewTab = "E_Opened_New_Tab" case openedPocketStory = "E_Opened_Pocket_Story" case interactWithURLBar = "E_Interact_With_Search_URL_Area" case savedBookmark = "E_Saved_Bookmark" case openedTelephoneLink = "Opened Telephone Link" case openedMailtoLink = "E_Opened_Mailto_Link" case saveImage = "E_Download_Media_Saved_Image" case savedLoginAndPassword = "E_Saved_Login_And_Password" case clearPrivateData = "E_Cleared_Private_Data" case downloadedFocus = "E_User_Downloaded_Focus" case downloadedPocket = "E_User_Downloaded_Pocket" case userSharedWebpage = "E_User_Tapped_Share_Button" case signsInFxa = "E_User_Signed_In_To_FxA" case useReaderView = "E_User_Used_Reader_View" case trackingProtectionSettings = "E_Tracking_Protection_Settings_Changed" case fxaSyncedNewDevice = "E_FXA_Synced_New_Device" case onboardingTestLoadedTooSlow = "E_Onboarding_Was_Swiped_Before_AB_Test_Could_Start" } struct LPAttributeKey { static let focusInstalled = "Focus Installed" static let klarInstalled = "Klar Installed" static let signedInSync = "Signed In Sync" static let mailtoIsDefault = "Mailto Is Default" static let pocketInstalled = "Pocket Installed" static let telemetryOptIn = "Telemetry Opt In" static let fxaAccountVerified = "FxA account is verified" static let fxaDeviceCount = "Number of devices in FxA account" } struct MozillaAppSchemes { static let focus = "firefox-focus" static let focusDE = "firefox-klar" static let pocket = "pocket" } private let supportedLocales = ["en_US", "de_DE", "en_GB", "en_CA", "en_AU", "zh_TW", "en_HK", "en_SG", "fr_FR", "it_IT", "id_ID", "id_ID", "pt_BR", "pl_PL", "ru_RU", "es_ES", "es_MX"] private struct LPSettings { var appId: String var developmentKey: String var productionKey: String } class LeanPlumClient { static let shared = LeanPlumClient() // Setup private weak var profile: Profile? private var prefs: Prefs? { return profile?.prefs } private var enabled: Bool = true // This defines an external Leanplum varible to enable/disable FxA prepush dialogs. // The primary result is having a feature flag controlled by Leanplum, and falling back // to prompting with native push permissions. private var useFxAPrePush: LPVar = LPVar.define("useFxAPrePush", with: false) var enablePocketVideo: LPVar = LPVar.define("pocketVideo", with: false) var enableDragDrop: LPVar = LPVar.define("tabTrayDrag", with: false) var introScreenVars = LPVar.define("IntroScreen", with: IntroCard.defaultCards().compactMap({ $0.asDictonary() })) private func isPrivateMode() -> Bool { // Need to be run on main thread since isInPrivateMode requires to be on the main thread. assert(Thread.isMainThread) return UIApplication.isInPrivateMode } func isLPEnabled() -> Bool { return enabled && Leanplum.hasStarted() } static func shouldEnable(profile: Profile) -> Bool { return AppConstants.MOZ_ENABLE_LEANPLUM && (profile.prefs.boolForKey(AppConstants.PrefSendUsageData) ?? true) } func setup(profile: Profile) { self.profile = profile } func recordSyncedClients(with profile: Profile?) { guard let profile = profile as? BrowserProfile else { return } profile.remoteClientsAndTabs.getClients() >>== { clients in let oldCount = self.prefs?.intForKey(FxaDevicesCountPrefKey) ?? 0 if clients.count > oldCount { self.track(event: .fxaSyncedNewDevice) } self.prefs?.setInt(Int32(clients.count), forKey: FxaDevicesCountPrefKey) Leanplum.setUserAttributes([LPAttributeKey.fxaDeviceCount: clients.count]) } } fileprivate func start() { guard let settings = getSettings(), supportedLocales.contains(Locale.current.identifier), !Leanplum.hasStarted() else { enabled = false log.error("LeanplumIntegration - Could not be started") return } if UIDevice.current.name.contains("MozMMADev") { log.info("LeanplumIntegration - Setting up for Development") Leanplum.setDeviceId(UIDevice.current.identifierForVendor?.uuidString) Leanplum.setAppId(settings.appId, withDevelopmentKey: settings.developmentKey) } else { log.info("LeanplumIntegration - Setting up for Production") Leanplum.setAppId(settings.appId, withProductionKey: settings.productionKey) } Leanplum.syncResourcesAsync(true) let attributes: [AnyHashable: Any] = [ LPAttributeKey.mailtoIsDefault: mailtoIsDefault(), LPAttributeKey.focusInstalled: focusInstalled(), LPAttributeKey.klarInstalled: klarInstalled(), LPAttributeKey.pocketInstalled: pocketInstalled(), LPAttributeKey.signedInSync: profile?.hasAccount() ?? false, LPAttributeKey.fxaAccountVerified: profile?.hasSyncableAccount() ?? false ] self.setupCustomTemplates() Leanplum.start(withUserId: nil, userAttributes: attributes, responseHandler: { _ in self.track(event: .openedApp) // We need to check if the app is a clean install to use for // preventing the What's New URL from appearing. if self.prefs?.intForKey(PrefsKeys.IntroSeen) == nil { self.prefs?.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey) self.track(event: .firstRun) } else if self.prefs?.boolForKey("SecondRun") == nil { self.prefs?.setBool(true, forKey: "SecondRun") self.track(event: .secondRun) } self.checkIfAppWasInstalled(key: PrefsKeys.HasFocusInstalled, isAppInstalled: self.focusInstalled(), lpEvent: .downloadedFocus) self.checkIfAppWasInstalled(key: PrefsKeys.HasPocketInstalled, isAppInstalled: self.pocketInstalled(), lpEvent: .downloadedPocket) self.recordSyncedClients(with: self.profile) }) } // Events func track(event: LPEvent, withParameters parameters: [String: String]? = nil) { guard isLPEnabled() else { return } ensureMainThread { guard !self.isPrivateMode() else { return } if let params = parameters { Leanplum.track(event.rawValue, withParameters: params) } else { Leanplum.track(event.rawValue) } } } func set(attributes: [AnyHashable: Any]) { guard isLPEnabled() else { return } ensureMainThread { if !self.isPrivateMode() { Leanplum.setUserAttributes(attributes) } } } func set(enabled: Bool) { // Setting up Test Mode stops sending things to server. if enabled { start() } self.enabled = enabled Leanplum.setTestModeEnabled(!enabled) } func isFxAPrePushEnabled() -> Bool { return AppConstants.MOZ_FXA_LEANPLUM_AB_PUSH_TEST && useFxAPrePush.boolValue() } /* This is used to determine if an app was installed after firefox was installed */ private func checkIfAppWasInstalled(key: String, isAppInstalled: Bool, lpEvent: LPEvent) { // if no key is present. create one and set it. // if the app is already installed then the flag will set true and the second block will never run if self.prefs?.boolForKey(key) == nil { self.prefs?.setBool(isAppInstalled, forKey: key) } // on a subsquent launch if the app is installed and the key is false then switch the flag to true if !(self.prefs?.boolForKey(key) ?? false), isAppInstalled { self.prefs?.setBool(isAppInstalled, forKey: key) self.track(event: lpEvent) } } private func canOpenApp(scheme: String) -> Bool { return URL(string: "\(scheme)://").flatMap { UIApplication.shared.canOpenURL($0) } ?? false } private func focusInstalled() -> Bool { return canOpenApp(scheme: MozillaAppSchemes.focus) } private func klarInstalled() -> Bool { return canOpenApp(scheme: MozillaAppSchemes.focusDE) } private func pocketInstalled() -> Bool { return canOpenApp(scheme: MozillaAppSchemes.pocket) } private func mailtoIsDefault() -> Bool { return (prefs?.stringForKey(PrefsKeys.KeyMailToOption) ?? "mailto:") == "mailto:" } private func getSettings() -> LPSettings? { let bundle = Bundle.main guard let appId = bundle.object(forInfoDictionaryKey: LPAppIdKey) as? String, let productionKey = bundle.object(forInfoDictionaryKey: LPProductionKeyKey) as? String, let developmentKey = bundle.object(forInfoDictionaryKey: LPDevelopmentKeyKey) as? String else { return nil } return LPSettings(appId: appId, developmentKey: developmentKey, productionKey: productionKey) } // This must be called before `Leanplum.start` in order to correctly setup // custom message templates. private func setupCustomTemplates() { // These properties are exposed through the Leanplum web interface. // Ref: https://github.com/Leanplum/Leanplum-iOS-Samples/blob/master/iOS_customMessageTemplates/iOS_customMessageTemplates/LPMessageTemplates.m let args: [LPActionArg] = [ LPActionArg(named: LPMessage.ArgTitleText, with: LPMessage.DefaultAskToAskTitle), LPActionArg(named: LPMessage.ArgTitleColor, with: UIColor.black), LPActionArg(named: LPMessage.ArgMessageText, with: LPMessage.DefaultAskToAskMessage), LPActionArg(named: LPMessage.ArgMessageColor, with: UIColor.black), LPActionArg(named: LPMessage.ArgAcceptButtonText, with: LPMessage.DefaultOkButtonText), LPActionArg(named: LPMessage.ArgCancelAction, withAction: nil), LPActionArg(named: LPMessage.ArgCancelButtonText, with: LPMessage.DefaultLaterButtonText), LPActionArg(named: LPMessage.ArgCancelButtonTextColor, with: UIColor.Photon.Grey50) ] let responder: LeanplumActionBlock = { (context) -> Bool in // Before proceeding, double check that Leanplum FxA prepush config value has been enabled. if !self.isFxAPrePushEnabled() { return false } guard let context = context else { return false } // Don't display permission screen if they have already allowed/disabled push permissions if self.prefs?.boolForKey(AppRequestedUserNotificationsPrefKey) ?? false { FxALoginHelper.sharedInstance.readyForSyncing() return false } // Present Alert View onto the current top view controller let rootViewController = UIApplication.topViewController() let alert = UIAlertController(title: context.stringNamed(LPMessage.ArgTitleText), message: context.stringNamed(LPMessage.ArgMessageText), preferredStyle: .alert) alert.addAction(UIAlertAction(title: context.stringNamed(LPMessage.ArgCancelButtonText), style: .cancel, handler: { (action) -> Void in // Log cancel event and call ready for syncing context.runTrackedActionNamed(LPMessage.ArgCancelAction) FxALoginHelper.sharedInstance.readyForSyncing() })) alert.addAction(UIAlertAction(title: context.stringNamed(LPMessage.ArgAcceptButtonText), style: .default, handler: { (action) -> Void in // Log accept event and present push permission modal context.runTrackedActionNamed(LPMessage.ArgAcceptAction) FxALoginHelper.sharedInstance.requestUserNotifications(UIApplication.shared) self.prefs?.setBool(true, forKey: AppRequestedUserNotificationsPrefKey) })) rootViewController?.present(alert, animated: true, completion: nil) return true } // Register or update the custom Leanplum message Leanplum.defineAction(LPMessage.FxAPrePush, of: kLeanplumActionKindMessage, withArguments: args, withOptions: [:], withResponder: responder) } } extension UIApplication { // Extension to get the current top most view controller class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(base: nav.visibleViewController) } if let tab = base as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(base: selected) } } if let presented = base?.presentedViewController { return topViewController(base: presented) } return base } }
mpl-2.0
569101b4f70659c3c592a45d9123ab28
42.763689
173
0.674108
4.554889
false
false
false
false
orta/RxSwift
RxSwift/RxSwift/Observables/Implementations/Switch.swift
1
4221
// // Switch.swift // Rx // // Created by Krunoslav Zaher on 3/12/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Switch_<ElementType> : Sink<ElementType>, ObserverType { typealias Element = Observable<ElementType> typealias SwitchState = ( subscription: SingleAssignmentDisposable, innerSubscription: SerialDisposable, stopped: Bool, latest: Int, hasLatest: Bool ) let parent: Switch<ElementType> var lock = NSRecursiveLock() var switchState: SwitchState init(parent: Switch<ElementType>, observer: ObserverOf<ElementType>, cancel: Disposable) { self.parent = parent self.switchState = ( subscription: SingleAssignmentDisposable(), innerSubscription: SerialDisposable(), stopped: false, latest: 0, hasLatest: false ) super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let subscription = self.parent.sources.subscribe(self) let switchState = self.switchState switchState.subscription.setDisposable(subscription) return CompositeDisposable(switchState.subscription, switchState.innerSubscription) } func on(event: Event<Element>) { switch event { case .Next(let observable): let latest: Int = self.lock.calculateLocked { self.switchState.hasLatest = true self.switchState.latest = self.switchState.latest + 1 return self.switchState.latest } let d = SingleAssignmentDisposable() self.switchState.innerSubscription.setDisposable(d) let observer = SwitchIter(parent: self, id: latest, _self: d) let disposable = observable.value.subscribe(observer) d.setDisposable(disposable) case .Error(let error): self.lock.performLocked { self.observer.on(.Error(error)) self.dispose() } case .Completed: self.lock.performLocked { self.switchState.stopped = true self.switchState.subscription.dispose() if !self.switchState.hasLatest { self.observer.on(.Completed) self.dispose() } } } } } class SwitchIter<ElementType> : ObserverType { typealias Element = ElementType let parent: Switch_<Element> let id: Int let _self: Disposable init(parent: Switch_<Element>, id: Int, _self: Disposable) { self.parent = parent self.id = id self._self = _self } func on(event: Event<ElementType>) { return parent.lock.calculateLocked { state in let switchState = self.parent.switchState switch event { case .Next: break case .Error: fallthrough case .Completed: self._self.dispose() } if switchState.latest != self.id { return } let observer = self.parent.observer switch event { case .Next: observer.on(event) case .Error: observer.on(event) self.parent.dispose() case .Completed: parent.switchState.hasLatest = false if switchState.stopped { observer.on(event) self.parent.dispose() } } } } } class Switch<Element> : Producer<Element> { let sources: Observable<Observable<Element>> init(sources: Observable<Observable<Element>>) { self.sources = sources } override func run(observer: ObserverOf<Element>, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = Switch_(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } }
mit
bbd70bf0366a3882313741dbf8319ead
29.594203
119
0.552239
5.166463
false
true
false
false
airbnb/lottie-ios
Sources/Private/MainThread/NodeRenderSystem/Nodes/PathNodes/ShapeNode.swift
3
1504
// // PathNode.swift // lottie-swift // // Created by Brandon Withrow on 1/16/19. // import CoreGraphics import Foundation // MARK: - ShapeNodeProperties final class ShapeNodeProperties: NodePropertyMap, KeypathSearchable { // MARK: Lifecycle init(shape: Shape) { keypathName = shape.name path = NodeProperty(provider: KeyframeInterpolator(keyframes: shape.path.keyframes)) keypathProperties = [ "Path" : path, ] properties = Array(keypathProperties.values) } // MARK: Internal var keypathName: String let path: NodeProperty<BezierPath> let keypathProperties: [String: AnyNodeProperty] let properties: [AnyNodeProperty] } // MARK: - ShapeNode final class ShapeNode: AnimatorNode, PathNode { // MARK: Lifecycle init(parentNode: AnimatorNode?, shape: Shape) { pathOutput = PathOutputNode(parent: parentNode?.outputNode) properties = ShapeNodeProperties(shape: shape) self.parentNode = parentNode } // MARK: Internal let properties: ShapeNodeProperties let pathOutput: PathOutputNode let parentNode: AnimatorNode? var hasLocalUpdates = false var hasUpstreamUpdates = false var lastUpdateFrame: CGFloat? = nil // MARK: Animator Node var propertyMap: NodePropertyMap & KeypathSearchable { properties } var isEnabled = true { didSet { pathOutput.isEnabled = isEnabled } } func rebuildOutputs(frame: CGFloat) { pathOutput.setPath(properties.path.value, updateFrame: frame) } }
apache-2.0
131398165a99f9a164cca56b0804f571
19.324324
88
0.714096
4.35942
false
false
false
false
codeOfRobin/ShadowKit
TestingModalPresentation/TestingModalPresentation/ViewController.swift
1
5805
// // ViewController.swift // TestingModalPresentation // // Created by Mayur on 05/04/17. // Copyright © 2017 Mayur. All rights reserved. // import UIKit import UIKit class CardPresentationController: UIPresentationController { let tappableDismissView: UIView override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { self.tappableDismissView = UIView() super.init(presentedViewController: presentedViewController, presenting: presentingViewController) let tapGR = UITapGestureRecognizer(target: self, action: #selector(self.dismissViewTapped)) tappableDismissView.addGestureRecognizer(tapGR) tappableDismissView.backgroundColor = .clear } //This method handles the dismissal of the current view controller, bringing the previous one forward, when the user taps outside func dismissViewTapped() { presentingViewController.dismiss(animated: true) { print("dismissed") print(self.presentingViewController) } } override func presentationTransitionWillBegin() { guard let fromView = self.presentingViewController.view else { return } let behindTransform = CGAffineTransform(scaleX: 0.9, y: 0.9) containerView?.addSubview(fromView) tappableDismissView.frame = CGRect(x: 0, y: 0, width: containerView?.frame.width ?? 0, height: CardPresentationManager.cardOffset) containerView?.addSubview(tappableDismissView) presentedViewController.transitionCoordinator?.animate(alongsideTransition: { (context) in fromView.transform = behindTransform }, completion: { context in }) } override func dismissalTransitionWillBegin() { guard let toView = self.presentingViewController.view else { return } self.containerView?.addSubview(toView) presentingViewController.transitionCoordinator?.animate(alongsideTransition: { (context) in toView.transform = .identity }, completion: { (context) in UIApplication.shared.keyWindow!.addSubview(toView) }) } override func dismissalTransitionDidEnd(_ completed: Bool) { self.tappableDismissView.removeFromSuperview() } } class CardTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate { func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { let pres = CardPresentationController(presentedViewController: presented, presenting: presenting) return pres } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return CardPresentationManager() } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return CardDismissalManager() } } class CardPresentationManager: NSObject, UIViewControllerAnimatedTransitioning { static let cardOffset = CGFloat(60) static let scaleFactor = 0.9 public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else { return } let bottomTransform = CGAffineTransform(translationX: 0, y: container.frame.height) toView.transform = bottomTransform let duration = self.transitionDuration(using: transitionContext) container.addSubview(toView) UIView.animate(withDuration: duration, animations: { toView.frame = CGRect(x: 0, y: CardPresentationManager.cardOffset, width: container.frame.width, height: container.frame.height - CardPresentationManager.cardOffset) }) { (completed) in transitionContext.completeTransition(completed) } } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } } class CardDismissalManager: NSObject, UIViewControllerAnimatedTransitioning { public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView guard let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) else { return } let duration = self.transitionDuration(using: transitionContext) fromView.frame = CGRect(x: 0, y: CardPresentationManager.cardOffset, width: container.frame.width, height: container.frame.height - CardPresentationManager.cardOffset) container.addSubview(fromView) UIView.animate(withDuration: duration, animations: { fromView.frame = CGRect(x: 0, y: container.frame.height, width: fromView.frame.width, height: fromView.frame.height) }) { (completed) in transitionContext.completeTransition(completed) } } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } } class ViewController: UIViewController { @IBAction func didTap(_ sender: UIButton) { let conversationNav = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ToPresentVC") as! ToPresentVC let cardTransitionDelegate = CardTransitioningDelegate() conversationNav.modalPresentationStyle = .custom conversationNav.transitioningDelegate = cardTransitionDelegate self.present(conversationNav, animated: true) { } } }
mit
3adb14e7e1c05bec616a582620f2fede
47.773109
177
0.729841
5.718227
false
false
false
false
CaueAlvesSilva/DropDownAlert
DropDownAlert/DropDownAlert/DropDownView/DropDownView.swift
1
3005
// // DropDownView.swift // DropDownAlert // // Created by Cauê Silva on 06/06/17. // Copyright © 2017 Caue Alves. All rights reserved. // import Foundation import UIKit class DropDownView: UIView { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var messageLabel: UILabel! private var timer: Timer? private var visibleTime: TimeInterval = 4.0 private var animationDuration: TimeInterval = 0.8 private var animationDelay: TimeInterval = 0 private var springDamping: CGFloat = 0.9 private var springVelocity: CGFloat = 0.2 var alertHeight: CGFloat { return frame.height } override func awakeFromNib() { super.awakeFromNib() setAccessibilityIDs() addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.stopAnimation))) } private func setAccessibilityIDs() { accessibilityIdentifier = "DropDownAlert.view" messageLabel.accessibilityIdentifier = "DropDownAlert.alertImageView" iconImageView.accessibilityIdentifier = "DropDownAlert.alertMessageLabel" } func startAnimation(alertDTO: DropDownAlertLayout) { let dto = alertDTO.layoutDTO backgroundColor = dto.backgroundColor messageLabel.text = dto.message messageLabel.textColor = dto.messageColor iconImageView.image = dto.image iconImageView.tintColor = dto.messageColor self.visibleTime = dto.visibleTime startAnimation() } private func startAnimation() { print("# \(self.classForCoder): \(#function)") DispatchQueue.main.safeAsync { self.setAlertPosition(shouldDisplay: false) UIView.animate(withDuration: self.animationDuration, delay: self.animationDelay, usingSpringWithDamping: self.springDamping, initialSpringVelocity: self.springVelocity, options: [], animations: { self.setAlertPosition(shouldDisplay: true) }, completion: nil) self.timer = Timer.scheduledTimer(timeInterval: self.visibleTime, target: self, selector: #selector(self.stopAnimation), userInfo: nil, repeats: false) } } func stopAnimation() { print("# \(self.classForCoder): \(#function)") timer?.invalidate() DispatchQueue.main.safeAsync { UIView.animate(withDuration: self.animationDuration, animations: { self.setAlertPosition(shouldDisplay: false) }, completion: { _ in DispatchQueue.main.safeAsync { self.removeFromSuperview() } }) } } private func setAlertPosition(shouldDisplay: Bool) { var frame = self.frame frame.origin.y = shouldDisplay ? 0 : -self.frame.size.width self.frame = frame } }
mit
0ae7b42ca9f6adef5ff97af52bbdb4c1
34.329412
163
0.626041
5.333925
false
false
false
false
scottrhoyt/Jolt
Jolt/Source/FloatingTypeExtensions/FloatingTypeFFTExtensions.swift
1
2345
// // FloatingTypeFFTExtensions.swift // Jolt // // Created by Scott Hoyt on 9/10/15. // Copyright © 2015 Scott Hoyt. All rights reserved. // import Accelerate // TODO: Write FFT Tests extension Double : VectorFFT { static public func fft(input: [Double]) -> [Double] { var real = [Double](input) var imaginary = [Double](count: input.count, repeatedValue: 0.0) var splitComplex = DSPDoubleSplitComplex(realp: &real, imagp: &imaginary) let length = vDSP_Length(Foundation.floor(Foundation.log2(Float(input.count)))) let radix = FFTRadix(kFFTRadix2) let weights = vDSP_create_fftsetupD(length, radix) vDSP_fft_zipD(weights, &splitComplex, 1, length, FFTDirection(FFT_FORWARD)) var magnitudes = [Double](count: input.count, repeatedValue: 0.0) vDSP_zvmagsD(&splitComplex, 1, &magnitudes, 1, vDSP_Length(input.count)) var normalizedMagnitudes = [Double](count: input.count, repeatedValue: 0.0) // TODO: Should change? vDSP_vsmulD(Double.sqrt(magnitudes), 1, [2.0 / Double(input.count)], &normalizedMagnitudes, 1, vDSP_Length(input.count)) vDSP_destroy_fftsetupD(weights) return normalizedMagnitudes } } extension Float : VectorFFT { static public func fft(input: [Float]) -> [Float] { var real = [Float](input) var imaginary = [Float](count: input.count, repeatedValue: 0.0) var splitComplex = DSPSplitComplex(realp: &real, imagp: &imaginary) let length = vDSP_Length(Foundation.floor(Foundation.log2(Float(input.count)))) let radix = FFTRadix(kFFTRadix2) let weights = vDSP_create_fftsetup(length, radix) vDSP_fft_zip(weights, &splitComplex, 1, length, FFTDirection(FFT_FORWARD)) var magnitudes = [Float](count: input.count, repeatedValue: 0.0) vDSP_zvmags(&splitComplex, 1, &magnitudes, 1, vDSP_Length(input.count)) var normalizedMagnitudes = [Float](count: input.count, repeatedValue: 0.0) // TODO: Should change? vDSP_vsmul(Float.sqrt(magnitudes), 1, [2.0 / Float(input.count)], &normalizedMagnitudes, 1, vDSP_Length(input.count)) vDSP_destroy_fftsetup(weights) return normalizedMagnitudes } }
mit
e9b3925219fd101761fb91c04ace409b
36.222222
128
0.640358
3.959459
false
false
false
false
mshhmzh/firefox-ios
Client/Frontend/Browser/ContextMenuHelper.swift
4
4576
/* 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 WebKit protocol ContextMenuHelperDelegate: class { func contextMenuHelper(contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UILongPressGestureRecognizer) } class ContextMenuHelper: NSObject, TabHelper, UIGestureRecognizerDelegate { private weak var tab: Tab? weak var delegate: ContextMenuHelperDelegate? private let gestureRecognizer = UILongPressGestureRecognizer() private weak var selectionGestureRecognizer: UIGestureRecognizer? struct Elements { let link: NSURL? let image: NSURL? } class func name() -> String { return "ContextMenuHelper" } /// Clicking an element with VoiceOver fires touchstart, but not touchend, causing the context /// menu to appear when it shouldn't (filed as rdar://22256909). As a workaround, disable the custom /// context menu for VoiceOver users. private var showCustomContextMenu: Bool { return !UIAccessibilityIsVoiceOverRunning() } required init(tab: Tab) { super.init() self.tab = tab let path = NSBundle.mainBundle().pathForResource("ContextMenu", ofType: "js")! let source = try! NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: false) tab.webView!.configuration.userContentController.addUserScript(userScript) // Add a gesture recognizer that disables the built-in context menu gesture recognizer. gestureRecognizer.delegate = self tab.webView!.addGestureRecognizer(gestureRecognizer) } func scriptMessageHandlerName() -> String? { return "contextMenuMessageHandler" } func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if !showCustomContextMenu { return } let data = message.body as! [String: AnyObject] // On sites where <a> elements have child text elements, the text selection delegate can be triggered // when we show a context menu. To prevent this, cancel the text selection delegate if we know the // user is long-pressing a link. if let handled = data["handled"] as? Bool where handled { // Setting `enabled = false` cancels the current gesture for this recognizer. selectionGestureRecognizer?.enabled = false selectionGestureRecognizer?.enabled = true } var linkURL: NSURL? if let urlString = data["link"] as? String { linkURL = NSURL(string: urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLAllowedCharacterSet())!) } var imageURL: NSURL? if let urlString = data["image"] as? String { imageURL = NSURL(string: urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLAllowedCharacterSet())!) } if linkURL != nil || imageURL != nil { let elements = Elements(link: linkURL, image: imageURL) delegate?.contextMenuHelper(self, didLongPressElements: elements, gestureRecognizer: gestureRecognizer) } } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { // Hack to detect the built-in text selection gesture recognizer. if let otherDelegate = otherGestureRecognizer.delegate where String(otherDelegate).contains("_UIKeyboardBasedNonEditableTextSelectionGestureController") { selectionGestureRecognizer = otherGestureRecognizer } // Hack to detect the built-in context menu gesture recognizer. return otherGestureRecognizer is UILongPressGestureRecognizer && otherGestureRecognizer.delegate?.description.rangeOfString("WKContentView") != nil } func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { return showCustomContextMenu } }
mpl-2.0
c849270c88acc8a42b852bdf9658e270
44.77
172
0.722465
5.912145
false
false
false
false
mozilla-mobile/firefox-ios
Shared/NSUserDefaultsPrefs.swift
2
5096
// 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 open class NSUserDefaultsPrefs: Prefs { fileprivate let prefixWithDot: String fileprivate let userDefaults: UserDefaults open func getBranchPrefix() -> String { return self.prefixWithDot } public init(prefix: String, userDefaults: UserDefaults) { self.prefixWithDot = prefix + (prefix.hasSuffix(".") ? "" : ".") self.userDefaults = userDefaults } public init(prefix: String) { self.prefixWithDot = prefix + (prefix.hasSuffix(".") ? "" : ".") self.userDefaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)! } open func branch(_ branch: String) -> Prefs { let prefix = self.prefixWithDot + branch + "." return NSUserDefaultsPrefs(prefix: prefix, userDefaults: self.userDefaults) } // Preferences are qualified by the profile's local name. // Connecting a profile to a Firefox Account, or changing to another, won't alter this. fileprivate func qualifyKey(_ key: String) -> String { return self.prefixWithDot + key } open func setInt(_ value: Int32, forKey defaultName: String) { // Why aren't you using userDefaults.setInteger? // Because userDefaults.getInteger returns a non-optional; it's impossible // to tell whether there's a value set, and you thus can't distinguish // between "not present" and zero. // Yeah, NSUserDefaults is meant to be used for storing "defaults", not data. setObject(NSNumber(value: value), forKey: defaultName) } open func setTimestamp(_ value: Timestamp, forKey defaultName: String) { setLong(value, forKey: defaultName) } open func setLong(_ value: UInt64, forKey defaultName: String) { setObject(NSNumber(value: value), forKey: defaultName) } open func setLong(_ value: Int64, forKey defaultName: String) { setObject(NSNumber(value: value), forKey: defaultName) } open func setString(_ value: String, forKey defaultName: String) { setObject(value as AnyObject?, forKey: defaultName) } open func setObject(_ value: Any?, forKey defaultName: String) { userDefaults.set(value, forKey: qualifyKey(defaultName)) } open func stringForKey(_ defaultName: String) -> String? { // stringForKey converts numbers to strings, which is almost always a bug. return userDefaults.object(forKey: qualifyKey(defaultName)) as? String } open func setBool(_ value: Bool, forKey defaultName: String) { setObject(NSNumber(value: value as Bool), forKey: defaultName) } open func boolForKey(_ defaultName: String) -> Bool? { // boolForKey just returns false if the key doesn't exist. We need to // distinguish between false and non-existent keys, so use objectForKey // and cast the result instead. let number = userDefaults.object(forKey: qualifyKey(defaultName)) as? NSNumber return number?.boolValue } fileprivate func nsNumberForKey(_ defaultName: String) -> NSNumber? { return userDefaults.object(forKey: qualifyKey(defaultName)) as? NSNumber } open func unsignedLongForKey(_ defaultName: String) -> UInt64? { return nsNumberForKey(defaultName)?.uint64Value } open func timestampForKey(_ defaultName: String) -> Timestamp? { return unsignedLongForKey(defaultName) } open func longForKey(_ defaultName: String) -> Int64? { return nsNumberForKey(defaultName)?.int64Value } open func objectForKey<T: Any>(_ defaultName: String) -> T? { return userDefaults.object(forKey: qualifyKey(defaultName)) as? T } open func intForKey(_ defaultName: String) -> Int32? { return nsNumberForKey(defaultName)?.int32Value } open func stringArrayForKey(_ defaultName: String) -> [String]? { let objects = userDefaults.stringArray(forKey: qualifyKey(defaultName)) if let strings = objects { return strings } return nil } open func arrayForKey(_ defaultName: String) -> [Any]? { return userDefaults.array(forKey: qualifyKey(defaultName)) as [Any]? } open func dictionaryForKey(_ defaultName: String) -> [String: Any]? { return userDefaults.dictionary(forKey: qualifyKey(defaultName)) as [String: Any]? } open func removeObjectForKey(_ defaultName: String) { userDefaults.removeObject(forKey: qualifyKey(defaultName)) } open func clearAll() { // TODO: userDefaults.removePersistentDomainForName() has no effect for app group suites. // iOS Bug? Iterate and remove each manually for now. for key in userDefaults.dictionaryRepresentation().keys { if key.hasPrefix(prefixWithDot) { userDefaults.removeObject(forKey: key) } } } }
mpl-2.0
73369d290743ec732a7b8712b2e0c15f
36.470588
97
0.667386
4.853333
false
false
false
false
drawRect/Instagram_Stories
InstagramStories/Source/ImageStorer/IGImageRequestable.swift
1
1776
// // IGSetImage.swift // InstagramStories // // Created by Boominadha Prakash on 02/04/19. // Copyright © 2019 DrawRect. All rights reserved. // import Foundation import UIKit public typealias ImageResponse = (IGResult<UIImage, Error>) -> Void protocol IGImageRequestable { func setImage(urlString: String, placeHolderImage: UIImage?, completionBlock: ImageResponse?) } extension IGImageRequestable where Self: UIImageView { func setImage(urlString: String, placeHolderImage: UIImage? = nil, completionBlock: ImageResponse?) { self.image = (placeHolderImage != nil) ? placeHolderImage! : nil self.showActivityIndicator() if let cachedImage = IGCache.shared.object(forKey: urlString as AnyObject) as? UIImage { self.hideActivityIndicator() DispatchQueue.main.async { self.image = cachedImage } guard let completion = completionBlock else { return } return completion(.success(cachedImage)) }else { IGURLSession.default.downloadImage(using: urlString) { [weak self] (response) in guard let strongSelf = self else { return } strongSelf.hideActivityIndicator() switch response { case .success(let image): DispatchQueue.main.async { strongSelf.image = image } guard let completion = completionBlock else { return } return completion(.success(image)) case .failure(let error): guard let completion = completionBlock else { return } return completion(.failure(error)) } } } } }
mit
660a777680fb5ff3ddb7bd21d3dacb57
34.5
105
0.601127
5.362538
false
false
false
false
callam/Heimdall.swift
HeimdallTests/OAuthAccessTokenSpec.swift
5
6737
import Argo import Heimdall import Nimble import Quick import Result class OAuthAccessTokenSpec: QuickSpec { override func spec() { describe("-copy") { let accessToken = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", expiresAt: NSDate(timeIntervalSince1970: 0), refreshToken: "refreshToken") it("returns a copy of an access token") { let result: OAuthAccessToken = accessToken.copy() expect(result).toNot(beIdenticalTo(accessToken)) } context("when providing a new access token") { let result = accessToken.copy(accessToken: "accessToken2") it("sets the provided access token on the new access token") { expect(result.accessToken).to(equal("accessToken2")) } it("sets the original token type on the new access token") { expect(result.tokenType).to(equal(accessToken.tokenType)) } it("sets the original expiration date on the new access token") { expect(result.expiresAt).to(equal(accessToken.expiresAt)) } it("sets the original refreh token on the new access token") { expect(result.refreshToken).to(equal(accessToken.refreshToken)) } } context("when providing a new token type") { let result = accessToken.copy(tokenType: "tokenType2") it("sets the original access token on the new access token") { expect(result.accessToken).to(equal(accessToken.accessToken)) } it("sets the provided token type on the new access token") { expect(result.tokenType).to(equal("tokenType2")) } it("sets the original expiration date on the new access token") { expect(result.expiresAt).to(equal(accessToken.expiresAt)) } it("sets the original refreh token on the new access token") { expect(result.refreshToken).to(equal(accessToken.refreshToken)) } } context("when providing a new expiration date") { let result = accessToken.copy(expiresAt: NSDate(timeIntervalSince1970: 1)) it("sets the original access token on the new access token") { expect(result.accessToken).to(equal(accessToken.accessToken)) } it("sets the original token type on the new access token") { expect(result.tokenType).to(equal(accessToken.tokenType)) } it("sets the provided expiration date on the new access token") { expect(result.expiresAt).to(equal(NSDate(timeIntervalSince1970: 1))) } it("sets the original refreh token on the new access token") { expect(result.refreshToken).to(equal(accessToken.refreshToken)) } } context("when providing a new refresh token") { let result = accessToken.copy(refreshToken: "refreshToken2") it("sets the original access token on the new access token") { expect(result.accessToken).to(equal(accessToken.accessToken)) } it("sets the original token type on the new access token") { expect(result.tokenType).to(equal(accessToken.tokenType)) } it("sets the original expiration date on the new access token") { expect(result.expiresAt).to(equal(accessToken.expiresAt)) } it("sets the provided refresh token on the new access token") { expect(result.refreshToken).to(equal("refreshToken2")) } } } describe("<Equatable> ==") { it("returns true if access tokens are equal") { let lhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType") let rhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType") expect(lhs == rhs).to(beTrue()) } it("returns false if access tokens are not equal") { let lhs = OAuthAccessToken(accessToken: "accessTokena", tokenType: "tokenType") let rhs = OAuthAccessToken(accessToken: "accessTokenb", tokenType: "tokenType") expect(lhs == rhs).to(beFalse()) } it("returns false if token types are not equal") { let lhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenTypea") let rhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenTypeb") expect(lhs == rhs).to(beFalse()) } it("returns false if expiration times are not equal") { let lhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", expiresAt: NSDate(timeIntervalSinceNow: 1)) let rhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", expiresAt: NSDate(timeIntervalSinceNow: -1)) expect(lhs == rhs).to(beFalse()) } it("returns false if refresh tokens are not equal") { let lhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", refreshToken: "refreshTokena") let rhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", refreshToken: "refreshTokenb") expect(lhs == rhs).to(beFalse()) } } describe("+decode") { context("without an expiration date") { it("creates a valid access token") { let accessToken = OAuthAccessToken.decode(.Object([ "access_token": .String("accessToken"), "token_type": .String("tokenType") ])) expect(accessToken.value).toNot(beNil()) expect(accessToken.value?.accessToken).to(equal("accessToken")) expect(accessToken.value?.tokenType).to(equal("tokenType")) expect(accessToken.value?.expiresAt).to(beNil()) expect(accessToken.value?.refreshToken).to(beNil()) } } } } }
apache-2.0
968cf5f41465df41841ed06573b1b056
42.185897
139
0.546237
5.604825
false
false
false
false
1738004401/Swift3.0--
SwiftCW/SwiftCW/Views/Home/SWHomeViewControllers.swift
1
3494
// // SWHomeViewControllers.swift // SwiftCW // // Created by YiXue on 17/3/16. // Copyright © 2017年 赵刘磊. All rights reserved. // import UIKit import SnapKit import AFNetworking class SWHomeViewControllers:BaseViewController { let tableView:UITableView = { let tableView = UITableView() // tableView.register(SWHomeTableViewCell.self, forCellReuseIdentifier: kCellIdentifier_SWHomeTableViewCell) return tableView }() lazy var layouts:[WBStatusLayout] = { return [WBStatusLayout]() }() override func viewDidLoad() { super.viewDidLoad() setupUI() loadHttp(type: RefreshType.refreshTypeTop) } private func setupUI() { tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = UITableViewCellSeparatorStyle.none view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.top.equalTo(kNavgation_Status_Height) make.left.right.equalTo(0) make.bottom.equalTo(-kTabbar_Height) } } private func loadHttp(type:RefreshType){ switch type { case .refreshTypeTop: break case .refreshTypeBottom: break } //2.0 拼接参数 let url = URL(string: "https://api.weibo.com/") let manager = AFHTTPSessionManager.init(baseURL: url) manager.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as? Set<String> var params = ["access_token":SWUser.curUser()?.access_token] ; params["since_id"] = "\(0)"; let path = "2/statuses/home_timeline.json"; manager.get(path, parameters: params, progress: { (_) in }, success: { (task:URLSessionDataTask, json) in let dict = json as? NSDictionary; let item:WBTimelineItem = WBTimelineItem.model(withJSON: json)! for status in (item.statuses)!{ let layout:WBStatusLayout = WBStatusLayout.init(status: status, style: WBLayoutStyle.timeline) self.layouts.append(layout) } self.tableView.reloadData() }) { (_, error) in print(error) } } } extension SWHomeViewControllers:UITableViewDataSource,UITableViewDelegate{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return layouts.count; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCell(withIdentifier: kCellIdentifier_SWHomeTableViewCell, for: indexPath) let cellID = "cell" var cell:WBStatusCell? = tableView.dequeueReusableCell(withIdentifier: cellID) as! WBStatusCell? if (cell == nil) { cell = WBStatusCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellID) } cell?.setLayout(layouts[indexPath.row] ) return cell! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return layouts[indexPath.row].height } }
mit
b1f5da6bd2c8e97744a0ac3f918b91da
30.324324
156
0.595053
4.960057
false
false
false
false
wj2061/ios7ptl-swift3.0
ch22-KVC/KVO/KVO/KVCTableViewController.swift
1
2931
// // KVCTableViewController.swift // KVO // // Created by wj on 15/11/29. // Copyright © 2015年 wj. All rights reserved. // import UIKit class KVCTableViewController: UITableViewController { dynamic var now:Date = Date() var timer : Timer? override func viewDidLoad() { super.viewDidLoad() timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(KVCTableViewController.updateNow), userInfo: nil, repeats: true) } func updateNow(){ now = Date() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 100 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! KVCTableViewCell cell.property = "now" cell.object = self return cell } deinit{ timer?.invalidate() timer = nil } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> 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, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .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, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // 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
71940b1c79fbf1f38756a9ad1eb57f36
30.148936
157
0.664276
5.109948
false
false
false
false
jay18001/brickkit-ios
Example/Source/Examples/Interactive/HideBrickViewController.swift
1
3746
// // HideBrickViewController.swift // BrickKit // // Created by Ruben Cagnie on 6/16/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import BrickKit class HideBrickViewController: BrickApp.BaseBrickController { override class var brickTitle: String { return "Hide Bricks" } override class var subTitle: String { return "Example of hiding bricks" } struct Identifiers { static let HideBrickButton = "HideBrickButton" static let HideSectionButton = "HideSectionButton" static let SimpleBrick = "SimpleBrick" static let SimpleSection = "SimpleSection" } var hideBrickButton: ButtonBrick! var hideSectionButton: ButtonBrick! var brickHidden = false var sectionHidden = false override func viewDidLoad() { super.viewDidLoad() self.registerBrickClass(ButtonBrick.self) self.registerBrickClass(LabelBrick.self) self.layout.hideBehaviorDataSource = self hideBrickButton = ButtonBrick(HideBrickViewController.Identifiers.HideBrickButton, backgroundColor: .brickGray1, title: titleForHideBrickButton) { [weak self] _ in self?.hideBrick() } hideSectionButton = ButtonBrick(HideBrickViewController.Identifiers.HideSectionButton, backgroundColor: .brickGray1, title: titleForHideSectionButton) { [weak self] _ in self?.hideSection() } self.collectionView?.backgroundColor = .brickBackground let section = BrickSection(bricks: [ LabelBrick(HideBrickViewController.Identifiers.SimpleBrick, backgroundColor: .brickGray3, dataSource: LabelBrickCellModel(text: "BRICK", configureCellBlock: LabelBrickCell.configure)), hideBrickButton, BrickSection(HideBrickViewController.Identifiers.SimpleSection, backgroundColor: .brickGray3, bricks: [ LabelBrick(width: .ratio(ratio: 0.5), backgroundColor: .brickGray5, dataSource: LabelBrickCellModel(text: "BRICK", configureCellBlock: LabelBrickCell.configure)), LabelBrick(width: .ratio(ratio: 0.5), backgroundColor: .brickGray5, dataSource: LabelBrickCellModel(text: "BRICK", configureCellBlock: LabelBrickCell.configure)), ]), hideSectionButton ], inset: 10, edgeInsets: UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)) self.setSection(section) } var titleForHideBrickButton: String { return "\(brickHidden ? "Show" : "Hide") Brick".uppercased() } var titleForHideSectionButton: String { return "\(sectionHidden ? "Show" : "Hide") Section".uppercased() } func hideBrick() { brickHidden = !brickHidden hideBrickButton.title = titleForHideBrickButton brickCollectionView.invalidateVisibility() reloadBricksWithIdentifiers([HideBrickViewController.Identifiers.HideBrickButton]) } func hideSection() { sectionHidden = !sectionHidden hideSectionButton.title = titleForHideSectionButton brickCollectionView.invalidateVisibility() reloadBricksWithIdentifiers([HideBrickViewController.Identifiers.HideSectionButton]) } } extension HideBrickViewController: HideBehaviorDataSource { func hideBehaviorDataSource(shouldHideItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> Bool { switch identifier { case HideBrickViewController.Identifiers.SimpleBrick: return brickHidden case HideBrickViewController.Identifiers.SimpleSection: return sectionHidden default: return false } } }
apache-2.0
bbd8d4a63472510faf17a2f58e00ce8f
35.715686
196
0.703338
5.053981
false
true
false
false
wokalski/Hourglass
Hourglass/State.swift
1
2020
import Foundation import EventKit typealias TaskIndex = [TaskID : Task] struct EventLogTarget { let calendar: EKCalendar let eventStore: EKEventStore } struct State { let currentSession: Session? let tasks: TaskIndex let selected: IndexPath? let logTarget: EventLogTarget? static let initialState = State(currentSession: nil, tasks: [:], selected: nil, logTarget: nil) } extension State { func set(visibleCells: [TaskID: IndexPath]) -> State { return State( currentSession: currentSession, tasks: tasks, selected: selected, logTarget: logTarget) } func set(currentSession: Session?) -> State { return State( currentSession: currentSession, tasks: tasks, selected: selected, logTarget: logTarget) } func set(tasks: [Int : Task]) -> State { return State( currentSession: currentSession, tasks: tasks, selected: selected, logTarget: logTarget) } func set(selected: IndexPath?) -> State { return State( currentSession: currentSession, tasks: tasks, selected: selected, logTarget: logTarget) } func set(logTarget: EventLogTarget?) -> State { return State( currentSession: currentSession, tasks: tasks, selected: selected, logTarget: logTarget) } } extension State { var selectedTask: Task? { get { guard let indexPath = selected else { return nil } return taskAtIndexPath(indexPath) } } func taskAtIndexPath(_ indexPath: IndexPath) -> Task? { if indexPath.section == 0 { return Array(tasks.values)[indexPath.item] } return nil } }
mit
6cdf17b4ffe40ccf6b396dbbe27275e8
24.56962
59
0.539604
5.192802
false
false
false
false
practicalswift/swift
stdlib/public/core/ContiguousArrayBuffer.swift
3
23693
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims /// Class used whose sole instance is used as storage for empty /// arrays. The instance is defined in the runtime and statically /// initialized. See stdlib/runtime/GlobalObjects.cpp for details. /// Because it's statically referenced, it requires non-lazy realization /// by the Objective-C runtime. /// /// NOTE: older runtimes called this _EmptyArrayStorage. The two must /// coexist, so it was renamed. The old name must not be used in the new /// runtime. @_fixed_layout @usableFromInline @_objc_non_lazy_realization internal final class __EmptyArrayStorage : __ContiguousArrayStorageBase { @inlinable @nonobjc internal init(_doNotCallMe: ()) { _internalInvariantFailure("creating instance of __EmptyArrayStorage") } #if _runtime(_ObjC) override internal func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { return try body(UnsafeBufferPointer(start: nil, count: 0)) } @nonobjc override internal func _getNonVerbatimBridgedCount() -> Int { return 0 } override internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer { return _BridgingBuffer(0) } #endif @inlinable override internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool { return false } /// A type that every element in the array is. @inlinable override internal var staticElementType: Any.Type { return Void.self } } /// The empty array prototype. We use the same object for all empty /// `[Native]Array<Element>`s. @inlinable internal var _emptyArrayStorage : __EmptyArrayStorage { return Builtin.bridgeFromRawPointer( Builtin.addressof(&_swiftEmptyArrayStorage)) } // The class that implements the storage for a ContiguousArray<Element> @_fixed_layout @usableFromInline internal final class _ContiguousArrayStorage< Element > : __ContiguousArrayStorageBase { @inlinable deinit { _elementPointer.deinitialize(count: countAndCapacity.count) _fixLifetime(self) } #if _runtime(_ObjC) /// If the `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements and return the result. /// Otherwise, return `nil`. internal final override func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { var result: R? try self._withVerbatimBridgedUnsafeBufferImpl { result = try body($0) } return result } /// If `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements. internal final func _withVerbatimBridgedUnsafeBufferImpl( _ body: (UnsafeBufferPointer<AnyObject>) throws -> Void ) rethrows { if _isBridgedVerbatimToObjectiveC(Element.self) { let count = countAndCapacity.count let elements = UnsafeRawPointer(_elementPointer) .assumingMemoryBound(to: AnyObject.self) defer { _fixLifetime(self) } try body(UnsafeBufferPointer(start: elements, count: count)) } } /// Returns the number of elements in the array. /// /// - Precondition: `Element` is bridged non-verbatim. @nonobjc override internal func _getNonVerbatimBridgedCount() -> Int { _internalInvariant( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") return countAndCapacity.count } /// Bridge array elements and return a new buffer that owns them. /// /// - Precondition: `Element` is bridged non-verbatim. override internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer { _internalInvariant( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") let count = countAndCapacity.count let result = _BridgingBuffer(count) let resultPtr = result.baseAddress let p = _elementPointer for i in 0..<count { (resultPtr + i).initialize(to: _bridgeAnythingToObjectiveC(p[i])) } _fixLifetime(self) return result } #endif /// Returns `true` if the `proposedElementType` is `Element` or a subclass of /// `Element`. We can't store anything else without violating type /// safety; for example, the destructor has static knowledge that /// all of the elements can be destroyed as `Element`. @inlinable internal override func canStoreElements( ofDynamicType proposedElementType: Any.Type ) -> Bool { #if _runtime(_ObjC) return proposedElementType is Element.Type #else // FIXME: Dynamic casts don't currently work without objc. // rdar://problem/18801510 return false #endif } /// A type that every element in the array is. @inlinable internal override var staticElementType: Any.Type { return Element.self } @inlinable internal final var _elementPointer : UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self)) } } @usableFromInline @_fixed_layout internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol { /// Make a buffer with uninitialized elements. After using this /// method, you must either initialize the `count` elements at the /// result's `.firstElementAddress` or set the result's `.count` /// to zero. @inlinable internal init( _uninitializedCount uninitializedCount: Int, minimumCapacity: Int ) { let realMinimumCapacity = Swift.max(uninitializedCount, minimumCapacity) if realMinimumCapacity == 0 { self = _ContiguousArrayBuffer<Element>() } else { _storage = Builtin.allocWithTailElems_1( _ContiguousArrayStorage<Element>.self, realMinimumCapacity._builtinWordValue, Element.self) let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_storage)) let endAddr = storageAddr + _swift_stdlib_malloc_size(storageAddr) let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress _initStorageHeader( count: uninitializedCount, capacity: realCapacity) } } /// Initialize using the given uninitialized `storage`. /// The storage is assumed to be uninitialized. The returned buffer has the /// body part of the storage initialized, but not the elements. /// /// - Warning: The result has uninitialized elements. /// /// - Warning: storage may have been stack-allocated, so it's /// crucial not to call, e.g., `malloc_size` on it. @inlinable internal init(count: Int, storage: _ContiguousArrayStorage<Element>) { _storage = storage _initStorageHeader(count: count, capacity: count) } @inlinable internal init(_ storage: __ContiguousArrayStorageBase) { _storage = storage } /// Initialize the body part of our storage. /// /// - Warning: does not initialize elements @inlinable internal func _initStorageHeader(count: Int, capacity: Int) { #if _runtime(_ObjC) let verbatim = _isBridgedVerbatimToObjectiveC(Element.self) #else let verbatim = false #endif // We can initialize by assignment because _ArrayBody is a trivial type, // i.e. contains no references. _storage.countAndCapacity = _ArrayBody( count: count, capacity: capacity, elementTypeIsBridgedVerbatim: verbatim) } /// True, if the array is native and does not need a deferred type check. @inlinable internal var arrayPropertyIsNativeTypeChecked: Bool { return true } /// A pointer to the first element. @inlinable internal var firstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(_storage, Element.self)) } @inlinable internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return firstElementAddress } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. @inlinable internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. @inlinable internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } //===--- _ArrayBufferProtocol conformance -----------------------------------===// /// Create an empty buffer. @inlinable internal init() { _storage = _emptyArrayStorage } @inlinable internal init(_buffer buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) { _internalInvariant(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") self = buffer } @inlinable internal mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> _ContiguousArrayBuffer<Element>? { if _fastPath(isUniquelyReferenced() && capacity >= minimumCapacity) { return self } return nil } @inlinable internal mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @inlinable internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? { return self } @inlinable @inline(__always) internal func getElement(_ i: Int) -> Element { _internalInvariant(i >= 0 && i < count, "Array index out of range") return firstElementAddress[i] } /// Get or set the value of the ith element. @inlinable internal subscript(i: Int) -> Element { @inline(__always) get { return getElement(i) } @inline(__always) nonmutating set { _internalInvariant(i >= 0 && i < count, "Array index out of range") // FIXME: Manually swap because it makes the ARC optimizer happy. See // <rdar://problem/16831852> check retain/release order // firstElementAddress[i] = newValue var nv = newValue let tmp = nv nv = firstElementAddress[i] firstElementAddress[i] = tmp } } /// The number of elements the buffer stores. @inlinable internal var count: Int { get { return _storage.countAndCapacity.count } nonmutating set { _internalInvariant(newValue >= 0) _internalInvariant( newValue <= capacity, "Can't grow an array buffer past its capacity") _storage.countAndCapacity.count = newValue } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @inline(__always) internal func _checkValidSubscript(_ index : Int) { _precondition( (index >= 0) && (index < count), "Index out of range" ) } /// The number of elements the buffer can store without reallocation. @inlinable internal var capacity: Int { return _storage.countAndCapacity.capacity } /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @inlinable @discardableResult internal __consuming func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _internalInvariant(bounds.lowerBound >= 0) _internalInvariant(bounds.upperBound >= bounds.lowerBound) _internalInvariant(bounds.upperBound <= count) let initializedCount = bounds.upperBound - bounds.lowerBound target.initialize( from: firstElementAddress + bounds.lowerBound, count: initializedCount) _fixLifetime(owner) return target + initializedCount } public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { // This customization point is not implemented for internal types. // Accidentally calling it would be a catastrophic performance bug. fatalError("unsupported") } /// Returns a `_SliceBuffer` containing the given `bounds` of values /// from this buffer. @inlinable internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get { return _SliceBuffer( owner: _storage, subscriptBaseAddress: subscriptBaseAddress, indices: bounds, hasNativeBuffer: true) } set { fatalError("not implemented") } } /// Returns `true` iff this buffer's storage is uniquely-referenced. /// /// - Note: This does not mean the buffer is mutable. Other factors /// may need to be considered, such as whether the buffer could be /// some immutable Cocoa container. @inlinable internal mutating func isUniquelyReferenced() -> Bool { return _isUnique(&_storage) } #if _runtime(_ObjC) /// Convert to an NSArray. /// /// - Precondition: `Element` is bridged to Objective-C. /// /// - Complexity: O(1). @inlinable internal __consuming func _asCocoaArray() -> AnyObject { if count == 0 { return _emptyArrayStorage } if _isBridgedVerbatimToObjectiveC(Element.self) { return _storage } return __SwiftDeferredNSArray(_nativeStorage: _storage) } #endif /// An object that keeps the elements stored in this buffer alive. @inlinable internal var owner: AnyObject { return _storage } /// An object that keeps the elements stored in this buffer alive. @inlinable internal var nativeOwner: AnyObject { return _storage } /// A value that identifies the storage used by the buffer. /// /// Two buffers address the same elements when they have the same /// identity and count. @inlinable internal var identity: UnsafeRawPointer { return UnsafeRawPointer(firstElementAddress) } /// Returns `true` iff we have storage for elements of the given /// `proposedElementType`. If not, we'll be treated as immutable. @inlinable func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool { return _storage.canStoreElements(ofDynamicType: proposedElementType) } /// Returns `true` if the buffer stores only elements of type `U`. /// /// - Precondition: `U` is a class or `@objc` existential. /// /// - Complexity: O(*n*) @inlinable internal func storesOnlyElementsOfType<U>( _: U.Type ) -> Bool { _internalInvariant(_isClassOrObjCExistential(U.self)) if _fastPath(_storage.staticElementType is U.Type) { // Done in O(1) return true } // Check the elements for x in self { if !(x is U) { return false } } return true } @usableFromInline internal var _storage: __ContiguousArrayStorageBase } /// Append the elements of `rhs` to `lhs`. @inlinable internal func += <Element, C : Collection>( lhs: inout _ContiguousArrayBuffer<Element>, rhs: __owned C ) where C.Element == Element { let oldCount = lhs.count let newCount = oldCount + numericCast(rhs.count) let buf: UnsafeMutableBufferPointer<Element> if _fastPath(newCount <= lhs.capacity) { buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count)) lhs.count = newCount } else { var newLHS = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCount, minimumCapacity: _growArrayCapacity(lhs.capacity)) newLHS.firstElementAddress.moveInitialize( from: lhs.firstElementAddress, count: oldCount) lhs.count = 0 (lhs, newLHS) = (newLHS, lhs) buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count)) } var (remainders,writtenUpTo) = buf.initialize(from: rhs) // ensure that exactly rhs.count elements were written _precondition(remainders.next() == nil, "rhs underreported its count") _precondition(writtenUpTo == buf.endIndex, "rhs overreported its count") } extension _ContiguousArrayBuffer : RandomAccessCollection { /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable internal var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `index(after:)`. @inlinable internal var endIndex: Int { return count } @usableFromInline internal typealias Indices = Range<Int> } extension Sequence { @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { return _copySequenceToContiguousArray(self) } } @inlinable internal func _copySequenceToContiguousArray< S : Sequence >(_ source: S) -> ContiguousArray<S.Element> { let initialCapacity = source.underestimatedCount var builder = _UnsafePartiallyInitializedContiguousArrayBuffer<S.Element>( initialCapacity: initialCapacity) var iterator = source.makeIterator() // FIXME(performance): use _copyContents(initializing:). // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { builder.addWithExistingCapacity(iterator.next()!) } // Add remaining elements, if any. while let element = iterator.next() { builder.add(element) } return builder.finish() } extension Collection { @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { return _copyCollectionToContiguousArray(self) } } extension _ContiguousArrayBuffer { @inlinable internal __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { return ContiguousArray(_buffer: self) } } /// This is a fast implementation of _copyToContiguousArray() for collections. /// /// It avoids the extra retain, release overhead from storing the /// ContiguousArrayBuffer into /// _UnsafePartiallyInitializedContiguousArrayBuffer. Since we do not support /// ARC loops, the extra retain, release overhead cannot be eliminated which /// makes assigning ranges very slow. Once this has been implemented, this code /// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer. @inlinable internal func _copyCollectionToContiguousArray< C : Collection >(_ source: C) -> ContiguousArray<C.Element> { let count: Int = numericCast(source.count) if count == 0 { return ContiguousArray() } let result = _ContiguousArrayBuffer<C.Element>( _uninitializedCount: count, minimumCapacity: 0) let p = UnsafeMutableBufferPointer(start: result.firstElementAddress, count: count) var (itr, end) = source._copyContents(initializing: p) _debugPrecondition(itr.next() == nil, "invalid Collection: more than 'count' elements in collection") // We also have to check the evil shrink case in release builds, because // it can result in uninitialized array elements and therefore undefined // behavior. _precondition(end == p.endIndex, "invalid Collection: less than 'count' elements in collection") return ContiguousArray(_buffer: result) } /// A "builder" interface for initializing array buffers. /// /// This presents a "builder" interface for initializing an array buffer /// element-by-element. The type is unsafe because it cannot be deinitialized /// until the buffer has been finalized by a call to `finish`. @usableFromInline @_fixed_layout internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> { @usableFromInline internal var result: _ContiguousArrayBuffer<Element> @usableFromInline internal var p: UnsafeMutablePointer<Element> @usableFromInline internal var remainingCapacity: Int /// Initialize the buffer with an initial size of `initialCapacity` /// elements. @inlinable @inline(__always) // For performance reasons. internal init(initialCapacity: Int) { if initialCapacity == 0 { result = _ContiguousArrayBuffer() } else { result = _ContiguousArrayBuffer( _uninitializedCount: initialCapacity, minimumCapacity: 0) } p = result.firstElementAddress remainingCapacity = result.capacity } /// Add an element to the buffer, reallocating if necessary. @inlinable @inline(__always) // For performance reasons. internal mutating func add(_ element: Element) { if remainingCapacity == 0 { // Reallocate. let newCapacity = max(_growArrayCapacity(result.capacity), 1) var newResult = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCapacity, minimumCapacity: 0) p = newResult.firstElementAddress + result.capacity remainingCapacity = newResult.capacity - result.capacity if !result.isEmpty { // This check prevents a data race writting to _swiftEmptyArrayStorage // Since count is always 0 there, this code does nothing anyway newResult.firstElementAddress.moveInitialize( from: result.firstElementAddress, count: result.capacity) result.count = 0 } (result, newResult) = (newResult, result) } addWithExistingCapacity(element) } /// Add an element to the buffer, which must have remaining capacity. @inlinable @inline(__always) // For performance reasons. internal mutating func addWithExistingCapacity(_ element: Element) { _internalInvariant(remainingCapacity > 0, "_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity") remainingCapacity -= 1 p.initialize(to: element) p += 1 } /// Finish initializing the buffer, adjusting its count to the final /// number of elements. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inlinable @inline(__always) // For performance reasons. internal mutating func finish() -> ContiguousArray<Element> { // Adjust the initialized count of the buffer. result.count = result.capacity - remainingCapacity return finishWithOriginalCount() } /// Finish initializing the buffer, assuming that the number of elements /// exactly matches the `initialCount` for which the initialization was /// started. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inlinable @inline(__always) // For performance reasons. internal mutating func finishWithOriginalCount() -> ContiguousArray<Element> { _internalInvariant(remainingCapacity == result.capacity - result.count, "_UnsafePartiallyInitializedContiguousArrayBuffer has incorrect count") var finalResult = _ContiguousArrayBuffer<Element>() (finalResult, result) = (result, finalResult) remainingCapacity = 0 return ContiguousArray(_buffer: finalResult) } }
apache-2.0
a97ffd647de348528a7bbbf4f4aadc36
30.757373
110
0.699168
4.801581
false
false
false
false
steelwheels/KiwiScript
KiwiShell/Source/KHShellConverter.swift
1
3030
/** * @file KHShellConverter.swift * @brief Define KHShellConverter class * @par Copyright * Copyright (C) 2020 Steel Wheels Project */ import KiwiLibrary import CoconutShell import CoconutData import Foundation public func KHCompileShellStatement(statements stmts: Array<KHStatement>) -> Array<KHStatement> { var newstmts: Array<KHStatement> = [] var hasnewstmts: Bool = false for stmt in stmts { var curstmt: KHStatement = stmt let builtinconv = KHBuiltinCommandConverter() if let newstmt = builtinconv.accept(statement: curstmt) { hasnewstmts = true curstmt = newstmt } newstmts.append(curstmt) } return hasnewstmts ? newstmts : stmts } private class KHBuiltinCommandConverter: KHShellStatementConverter { open override func visit(shellCommandStatement stmt: KHShellCommandStatement) -> KHSingleStatement? { if let newcmd = convertToNativeBuiltinCommand(statement: stmt) { return newcmd } else if let (url, args) = convertToBuiltinScriptCommand(command: stmt.shellCommand) { let newstmt = KHBuiltinCommandStatement(scriptURL: url, arguments: args) newstmt.importProperties(source: stmt) return newstmt } else { return nil } } private func convertToNativeBuiltinCommand(statement stmt: KHShellCommandStatement) -> KHSingleStatement? { let (cmdnamep, restp) = CNStringUtil.cutFirstWord(string: stmt.shellCommand) if let cmdname = cmdnamep { switch cmdname { case "cd": var path: String? = nil if let rest = restp { (path, _) = CNStringUtil.cutFirstWord(string: rest) } let newstmt = KHCdCommandStatement(path: path) newstmt.importProperties(source: stmt) return newstmt case "history": let newstmt = KHHistoryCommandStatement() newstmt.importProperties(source: stmt) return newstmt case "run": var path: String? = nil var arg: String? = nil if let rest = restp { (path, arg) = CNStringUtil.cutFirstWord(string: rest) } let newstmt = KHRunCommandStatement(scriptPath: path, argument: arg) newstmt.importProperties(source: stmt) return newstmt case "install": var path: String? = nil var arg: String? = nil if let rest = restp { (path, arg) = CNStringUtil.cutFirstWord(string: rest) } let newstmt = KHInstallCommandStatement(scriptPath: path, argument: arg) newstmt.importProperties(source: stmt) return newstmt case "clean": var file: String? = nil if let rest = restp { (file, _) = CNStringUtil.cutFirstWord(string: rest) } let newstmt = KHCleanCommandStatement(scriptFile: file) newstmt.importProperties(source: stmt) return newstmt default: break } } return nil } private func convertToBuiltinScriptCommand(command cmd: String) -> (URL, Array<String>)? { var words = CNStringUtil.divideBySpaces(string: cmd) if words.count > 0 { if let url = KLBuiltinScripts.shared.search(scriptName: words[0]) { words.removeFirst() return (url, words) } } return nil } }
lgpl-2.1
551b0a56fa1e8f8864731db52adddc9c
27.317757
108
0.708251
3.304253
false
false
false
false
mightydeveloper/swift
test/1_stdlib/RangeTraps.swift
9
2182
//===--- RangeTraps.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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: rm -rf %t // RUN: mkdir -p %t // RUN: %target-build-swift %s -o %t/a.out_Debug // RUN: %target-build-swift %s -o %t/a.out_Release -O // // RUN: %target-run %t/a.out_Debug // RUN: %target-run %t/a.out_Release // REQUIRES: executable_test import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif var RangeTraps = TestSuite("RangeTraps") RangeTraps.test("HalfOpen") .skip(.Custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { var range = 1..<1 expectType(Range<Int>.self, &range) expectCrashLater() 1..<0 } RangeTraps.test("Closed") .skip(.Custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { var range = 1...1 expectType(Range<Int>.self, &range) expectCrashLater() 1...0 } RangeTraps.test("OutOfRange") .skip(.Custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { 0..<Int.max // This is a Range // This works for Intervals, but... expectTrue(ClosedInterval(0...Int.max).contains(Int.max)) // ...no support yet for Ranges containing the maximum representable value expectCrashLater() #if arch(i386) || arch(arm) // FIXME <rdar://17670791> Range<Int> bounds checking not enforced in optimized 32-bit 1...0 // crash some other way #else 0...Int.max #endif } runAllTests()
apache-2.0
a075bed309bdb60ef3d7a39f4b3f15e9
26.974359
88
0.649404
3.821366
false
true
false
false
jyxia/nostalgic-pluto-ios
nostalgic-pluto-ios/AppDelegate.swift
1
6163
// // AppDelegate.swift // nostalgic-pluto-ios // // Created by Jinyue Xia on 7/18/15. // Copyright (c) 2015 Jinyue Xia. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "org.ios.jx.nostalgic_pluto_ios" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() 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 modelURL = NSBundle.mainBundle().URLForResource("nostalgic_pluto_ios", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy 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) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("nostalgic_pluto_ios.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = 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 \(error), \(error!.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 if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation 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 \(error), \(error!.userInfo)") abort() } } } }
mit
5d5a981a3cc341ea9fda25a49d03d988
54.522523
290
0.715723
5.643773
false
false
false
false
PairOfNewbie/BeautifulDay
BeautifulDay/Controller/Album/AlbumDetailController.swift
1
8869
// // AlbumDetailController.swift // BeautifulDay // // Created by DaiFengyi on 16/5/4. // Copyright © 2016年 PairOfNewbie. All rights reserved. // import UIKit private let albumZanCellIdentifier = "AlbumZanCell" private let albumCommentCellIdentifier = "AlbumCommentCell" class AlbumDetailController: UITableViewController { @IBOutlet weak var webHeader: UIWebView! var albumId = 0 { didSet { fetchAlbumDetailInfo(albumId, failure: { (error) in print(error.description) }, success: { [unowned self](albumDetail) in self.albumDetail = albumDetail // webHeader let request = NSURLRequest(URL: NSURL(string: (albumDetail.albuminfo?.pageUrl)!)!, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 10) self.webHeader.loadRequest(request) self.webHeader.scrollView.scrollEnabled = false self.tableView.reloadData() }) } } var albumDetail: AlbumDetail? override func viewDidLoad() { super.viewDidLoad() // 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() self.automaticallyAdjustsScrollViewInsets = true tableView.estimatedRowHeight = 44 tableView.rowHeight = UITableViewAutomaticDimension tableView.registerNib(UINib(nibName: albumZanCellIdentifier, bundle: nil), forCellReuseIdentifier: albumZanCellIdentifier) tableView.registerNib(UINib(nibName: albumCommentCellIdentifier, bundle: nil), forCellReuseIdentifier: albumCommentCellIdentifier) } override func viewWillAppear(animated: Bool) { self.navigationController?.hidesBarsOnSwipe = true super.viewWillAppear(animated) } override func viewWillDisappear(animated: Bool) { self.navigationController?.hidesBarsOnSwipe = false self.navigationController?.setNavigationBarHidden(false, animated: true) super.viewWillDisappear(animated) } // MARK: - Action @objc func zan(sender: UIButton) { guard currentUser.isLogin else { return } sender.selected = !sender.selected let keyframeAni = CAKeyframeAnimation(keyPath: "transform.scale") keyframeAni.duration = 0.5; keyframeAni.values = [0.1, 1.5, 1.0]; keyframeAni.keyTimes = [0, 0.8, 1]; keyframeAni.calculationMode = kCAAnimationLinear; sender.layer.addAnimation(keyframeAni, forKey: "zan") zanAction(sender.selected) } private func zanAction(status: Bool) { postZan(albumId, zanStatus: status, failure: { (error) in print("zan failure") SAIUtil.showMsg("点赞失败") }, success:{ (z) in print("zan success") }) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: if let list = albumDetail?.commentList { return list.count }else { return 0 } default: return 0 } } override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if section == 0 { return nil } let inputBar = NSBundle.mainBundle().loadNibNamed("InputBar", owner: self, options: nil).last as? InputBar inputBar?.clickAction = { if currentUser.isLogin { self.performSegueWithIdentifier("showComment", sender: nil) } } return inputBar } override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == 0 { return 0 } return 44 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch indexPath.section { case 0: let cell = tableView.dequeueReusableCellWithIdentifier(albumZanCellIdentifier, forIndexPath: indexPath) if let button = cell.accessoryView as? UIButton { button.addTarget(self, action: #selector(AlbumDetailController.zan(_:)), forControlEvents: .TouchUpInside) } return cell case 1: let cell = tableView.dequeueReusableCellWithIdentifier(albumCommentCellIdentifier, forIndexPath: indexPath) return cell default: return UITableViewCell() } } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.section { case 0: let c = cell as! AlbumZanCell var zlist = String() if let zanlist = albumDetail?.zanList { for z in zanlist { if let userName = z.userName { if zlist.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0 { zlist = userName }else { zlist = zlist + (",\(userName)") } } } } if zlist.isEmpty { zlist = "还没人点赞,赶紧点赞吧!" } c.zanList.text = zlist break; case 1: let c = cell as! AlbumCommentCell if let comment = albumDetail?.commentList![indexPath.row] { // todo // c.name.text = comment.userId c.content.text = comment.content } default: break; } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if currentUser.isLogin { self.performSegueWithIdentifier("showComment", sender: nil) } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> 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, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .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, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // 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?) { let vc = segue.destinationViewController as! AlbumCommentController vc.albumDetail = albumDetail // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } } extension AlbumDetailController: UIWebViewDelegate { func webViewDidFinishLoad(webView: UIWebView) { // webHeader.frame.size = webHeader.scrollView.contentSize webHeader.frame.size = webHeader.sizeThatFits(CGSizeZero) tableView.reloadData() } func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { } }
mit
6773f05bdfabfc94a71dce564b8bfbfb
35.504132
161
0.616935
5.429625
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/Views/LoginEntryView.swift
1
3878
// // LoginEntryView.swift // Habitica // // Created by Phillip on 27.07.17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import Foundation @IBDesignable class LoginEntryView: UIView, UITextFieldDelegate { @IBInspectable var placeholderText: String? { didSet { if let text = placeholderText { let color = UIColor.white.withAlphaComponent(0.5) entryView.attributedPlaceholder = NSAttributedString(string: text, attributes: [NSAttributedString.Key.foregroundColor: color]) } else { entryView.placeholder = "" } } } weak public var delegate: UITextFieldDelegate? @IBInspectable var icon: UIImage? { didSet { iconView.image = icon } } @IBInspectable var keyboard: Int { get { return entryView.keyboardType.rawValue } set(keyboardIndex) { if let type = UIKeyboardType.init(rawValue: keyboardIndex) { entryView.keyboardType = type } } } @IBInspectable var isSecureTextEntry: Bool = false { didSet { entryView.isSecureTextEntry = isSecureTextEntry } } @IBOutlet weak var entryView: UITextField! @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var bottomBorder: UIView! var gestureRecognizer: UIGestureRecognizer? var hasError: Bool = false { didSet { setBarColor() } } private var wasEdited = false override init(frame: CGRect) { super.init(frame: frame) xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() } func xibSetup() { if let view = loadViewFromNib() { view.frame = bounds view.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight] addSubview(view) gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tappedView)) if let gestureRecognizer = self.gestureRecognizer { addGestureRecognizer(gestureRecognizer) } isUserInteractionEnabled = true } } func loadViewFromNib() -> UIView? { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil)[0] as? UIView return view } func textFieldDidBeginEditing(_ textField: UITextField) { wasEdited = true UIView.animate(withDuration: 0.3) {[weak self] in self?.bottomBorder.alpha = 1.0 } if let gestureRecognizer = self.gestureRecognizer { removeGestureRecognizer(gestureRecognizer) } } func textFieldDidEndEditing(_ textField: UITextField) { UIView.animate(withDuration: 0.3) {[weak self] in self?.bottomBorder.alpha = 0.15 } if let gestureRecognizer = gestureRecognizer { addGestureRecognizer(gestureRecognizer) } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if let function = delegate?.textFieldShouldReturn { return function(textField) } return false } @objc func tappedView() { entryView.becomeFirstResponder() } private func setBarColor() { if !wasEdited { return } if hasError { bottomBorder.backgroundColor = UIColor.red50 } else { bottomBorder.backgroundColor = .white } } }
gpl-3.0
84fe9f857f136253e726daac3f2de6de
26.496454
143
0.579056
5.422378
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureDashboard/Sources/FeatureDashboardUI/Components/WalletActionCell/WalletActionTableViewCell.swift
1
1790
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformUIKit import UIKit final class WalletActionTableViewCell: UITableViewCell { // MARK: - Properties var presenter: WalletActionCellPresenter! { didSet { badgeImageView.viewModel = presenter.badgeImageViewModel titleLabel.content = presenter.titleLabelContent descriptionLabel.content = presenter.descriptionLabelContent } } // MARK: - Private Properties private let badgeImageView = BadgeImageView() private let stackView = UIStackView() private let titleLabel = UILabel() private let descriptionLabel = UILabel() // MARK: - Setup override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { contentView.addSubview(badgeImageView) contentView.addSubview(stackView) stackView.axis = .vertical stackView.addArrangedSubview(titleLabel) stackView.addArrangedSubview(descriptionLabel) badgeImageView.layoutToSuperview(.leading, offset: Spacing.outer) badgeImageView.layout(size: .init(edge: Sizing.badge)) badgeImageView.layout(edges: .centerY, to: stackView) stackView.layout(to: .top, of: contentView, offset: Spacing.inner) stackView.layout(edges: .trailing, to: contentView, offset: -Spacing.inner) stackView.layout(edge: .leading, to: .trailing, of: badgeImageView, offset: Spacing.inner) stackView.layout(edges: .centerY, to: contentView) } }
lgpl-3.0
eecd77e2b764804154a61e4bf63e4123
32.754717
98
0.690889
4.969444
false
false
false
false
pvbaleeiro/movie-aholic
movieaholic/movieaholic/recursos/view/ExploreHeaderView.swift
1
14967
// // ExploreHeaderView.swift // movieaholic // // Created by Victor Baleeiro on 24/09/17. // Copyright © 2017 Victor Baleeiro. All rights reserved. // import UIKit //------------------------------------------------------------------------------------------------------------- // MARK: Delegate //------------------------------------------------------------------------------------------------------------- protocol ExploreHeaderViewDelegate { func didSelect(viewController: UIViewController, completion: (() -> Void)?) func didCollapseHeader(completion: (() -> Void)?) func didExpandHeader(completion: (() -> Void)?) } class ExploreHeaderView: UIView { //------------------------------------------------------------------------------------------------------------- // MARK: Propriedades //------------------------------------------------------------------------------------------------------------- override var bounds: CGRect { didSet { backgroundGradientLayer.frame = bounds } } var delegate: UIViewController? { didSet { } } lazy var backgroundGradientLayer: CAGradientLayer = { let layer = CAGradientLayer() layer.startPoint = CGPoint(x: 0, y: 0.5) layer.endPoint = CGPoint(x: 1, y: 0.5) layer.colors = self.backgroundGradient return layer }() var whiteOverlayView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor.white view.alpha = 0 return view }() var backgroundGradient: [CGColor] = [UIColor.primaryColor().cgColor, UIColor.primaryColorDark().cgColor] var pageTabDelegate: ExploreHeaderViewDelegate? var pageTabControllers = [UIViewController]() { didSet { setupPagers() } } let pageTabHeight: CGFloat = 50 let headerInputHeight: CGFloat = 50 var minHeaderHeight: CGFloat { return 20 // status bar + pageTabHeight } var midHeaderHeight: CGFloat { return 20 + 10 // status bar + spacing + headerInputHeight // input 1 + pageTabHeight } var maxHeaderHeight: CGFloat { return 20 + 10 // status bar + spacing + 50 // collapse button + 50 + 10 // input 1 + spacing + 50 + 10 // input 2 + spacing + 50 // input 3 + 50 // page tabs } let collapseButtonHeight: CGFloat = 40 let collapseButtonMaxTopSpacing: CGFloat = 20 + 10 let collapseButtonMinTopSpacing: CGFloat = 0 var collapseButtonTopConstraint: NSLayoutConstraint? lazy var collapseButton: UIButton = { let button = UIButton() button.setImage(UIImage(named: "collapse"), for: .normal) button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) button.translatesAutoresizingMaskIntoConstraints = false button.contentHorizontalAlignment = .center button.addTarget(self, action: #selector(ExploreHeaderView.handleCollapse), for: .touchUpInside) return button }() var destinationFilterTopConstraint: NSLayoutConstraint? lazy var summaryFilter: UIButton = { let btn = UIButton() btn.translatesAutoresizingMaskIntoConstraints = false btn.backgroundColor = UIColor.primaryColor() btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left btn.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) btn.adjustsImageWhenHighlighted = false btn.addTarget(self, action: #selector(ExploreHeaderView.handleExpand), for: .touchUpInside) let img = UIImage(named: "Search") btn.setImage(img, for: .normal) btn.imageView?.contentMode = .scaleAspectFit btn.setTitle("Search • Places • News", for: .normal) btn.setTitleColor(UIColor.white, for: .normal) btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15) btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) btn.titleLabel?.lineBreakMode = .byTruncatingTail return btn }() lazy var searchBarFilter: UISearchBar = { let searchBar = UISearchBar() searchBar.translatesAutoresizingMaskIntoConstraints = false searchBar.backgroundColor = UIColor.primaryColor() searchBar.showsCancelButton = true return searchBar }() lazy var btnNews: UIButton = { let btn = UIButton() btn.translatesAutoresizingMaskIntoConstraints = false btn.backgroundColor = UIColor.primaryColor() btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left btn.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) btn.adjustsImageWhenHighlighted = false btn.addTarget(self, action: #selector(ExploreHeaderView.funcNotImplemented), for: .touchUpInside) btn.imageView?.contentMode = .scaleAspectFit btn.setTitle("News", for: .normal) btn.setTitleColor(UIColor.white, for: .normal) btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15) btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) btn.titleLabel?.lineBreakMode = .byTruncatingTail return btn }() lazy var btnPrincipal: UIButton = { let btn = UIButton() btn.translatesAutoresizingMaskIntoConstraints = false btn.backgroundColor = UIColor.primaryColor() btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left btn.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) btn.adjustsImageWhenHighlighted = false btn.imageView?.contentMode = .scaleAspectFit btn.setTitle("Principal", for: .normal) btn.setTitleColor(UIColor.white, for: .normal) btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15) btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) btn.titleLabel?.lineBreakMode = .byTruncatingTail return btn }() var pagerView: PageTabNavigationView = { let view = PageTabNavigationView() view.translatesAutoresizingMaskIntoConstraints = false return view }() init() { super.init(frame: CGRect.zero) backgroundColor = UIColor.primaryColorDark() setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupViews() { addSubview(collapseButton) collapseButton.heightAnchor.constraint(equalToConstant: collapseButtonHeight).isActive = true collapseButtonTopConstraint = collapseButton.topAnchor.constraint(equalTo: topAnchor, constant: collapseButtonMaxTopSpacing) collapseButtonTopConstraint?.isActive = true collapseButton.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true collapseButton.widthAnchor.constraint(equalToConstant: collapseButtonHeight).isActive = true addSubview(searchBarFilter) searchBarFilter.heightAnchor.constraint(equalToConstant: 50).isActive = true destinationFilterTopConstraint = searchBarFilter.topAnchor.constraint(equalTo: topAnchor, constant: collapseButtonHeight + collapseButtonMaxTopSpacing + 10) destinationFilterTopConstraint?.isActive = true searchBarFilter.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true searchBarFilter.widthAnchor.constraint(equalTo: widthAnchor, constant: -20).isActive = true addSubview(summaryFilter) summaryFilter.heightAnchor.constraint(equalToConstant: 50).isActive = true summaryFilter.topAnchor.constraint(equalTo: searchBarFilter.topAnchor).isActive = true summaryFilter.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true summaryFilter.widthAnchor.constraint(equalTo: widthAnchor, constant: -20).isActive = true summaryFilter.alpha = 0 addSubview(btnNews) btnNews.heightAnchor.constraint(equalToConstant: 50).isActive = true btnNews.topAnchor.constraint(equalTo: searchBarFilter.bottomAnchor, constant: 10).isActive = true btnNews.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true btnNews.widthAnchor.constraint(equalTo: widthAnchor, constant: -20).isActive = true addSubview(btnPrincipal) btnPrincipal.heightAnchor.constraint(equalToConstant: 50).isActive = true btnPrincipal.topAnchor.constraint(equalTo: btnNews.bottomAnchor, constant: 10).isActive = true btnPrincipal.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true btnPrincipal.widthAnchor.constraint(equalTo: widthAnchor, constant: -20).isActive = true addSubview(whiteOverlayView) whiteOverlayView.topAnchor.constraint(equalTo: topAnchor).isActive = true whiteOverlayView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true whiteOverlayView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true whiteOverlayView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true } func setupPagers() { // TODO: remove all subviews addSubview(pagerView) pagerView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true pagerView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true pagerView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true pagerView.heightAnchor.constraint(equalToConstant: pageTabHeight).isActive = true for vc in pageTabControllers { pagerView.appendPageTabItem(withTitle: vc.title ?? "") pagerView.navigationDelegate = self if (searchBarFilter.delegate == nil) { searchBarFilter.delegate = vc as? UISearchBarDelegate } } } override func layoutSubviews() { } public func updateHeader(newHeight: CGFloat, offset: CGFloat) { let headerBottom = newHeight - pageTabHeight let midMaxPercentage = (newHeight - midHeaderHeight) / (maxHeaderHeight - midHeaderHeight) btnNews.alpha = midMaxPercentage var datePickerPercentage3 = (headerBottom - btnPrincipal.frame.origin.y) / btnPrincipal.frame.height datePickerPercentage3 = max(0, min(1, datePickerPercentage3)) // capped between 0 and 1 btnPrincipal.alpha = datePickerPercentage3 collapseButton.alpha = datePickerPercentage3 var collapseButtonTopSpacingPercentage = (headerBottom - searchBarFilter.frame.origin.y) / (btnPrincipal.frame.origin.y + btnPrincipal.frame.height - searchBarFilter.frame.origin.y) collapseButtonTopSpacingPercentage = max(0, min(1, collapseButtonTopSpacingPercentage)) collapseButtonTopConstraint?.constant = collapseButtonTopSpacingPercentage * collapseButtonMaxTopSpacing summaryFilter.setTitle("\("Search") • \(btnNews.titleLabel!.text!) • \(btnPrincipal.titleLabel!.text!)", for: .normal) if newHeight > midHeaderHeight { searchBarFilter.alpha = collapseButtonTopSpacingPercentage destinationFilterTopConstraint?.constant = max(UIApplication.shared.statusBarFrame.height + 10,collapseButtonTopSpacingPercentage * (collapseButtonHeight + collapseButtonMaxTopSpacing + 10)) summaryFilter.alpha = 1 - collapseButtonTopSpacingPercentage whiteOverlayView.alpha = 0 pagerView.backgroundColor = UIColor.primaryColorDark() pagerView.titleColor = UIColor.white pagerView.selectedTitleColor = UIColor.white } else if newHeight == midHeaderHeight { destinationFilterTopConstraint?.constant = UIApplication.shared.statusBarFrame.height + 10 searchBarFilter.alpha = 0 summaryFilter.alpha = 1 whiteOverlayView.alpha = 0 pagerView.backgroundColor = UIColor.primaryColorDark() pagerView.titleColor = UIColor.white pagerView.selectedTitleColor = UIColor.white } else { destinationFilterTopConstraint?.constant = destinationFilterTopConstraint!.constant - offset let minMidPercentage = (newHeight - minHeaderHeight) / (midHeaderHeight - minHeaderHeight) searchBarFilter.alpha = 0 summaryFilter.alpha = minMidPercentage whiteOverlayView.alpha = 1 - minMidPercentage pagerView.backgroundColor = UIColor.fade(fromColor: UIColor.primaryColorDark(), toColor: UIColor.white, withPercentage: 1 - minMidPercentage) pagerView.titleColor = UIColor.fade(fromColor: UIColor.white, toColor: UIColor.darkGray, withPercentage: 1 - minMidPercentage) pagerView.selectedTitleColor = UIColor.fade(fromColor: UIColor.white, toColor: UIColor.primaryColor(), withPercentage: 1 - minMidPercentage) } } @objc func handleCollapse() { pageTabDelegate?.didCollapseHeader(completion: nil) } @objc func handleExpand() { pageTabDelegate?.didExpandHeader(completion: nil) } @objc func funcNotImplemented() { let alertView = UIAlertController(title: "Aviso", message: "Essa funcionalidade ainda não foi implementada", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: { (alert) in NSLog("OK clicado") }) alertView.addAction(action) //Exibe alerta let controller = delegate controller?.present(alertView, animated: true, completion: nil) } } //------------------------------------------------------------------------------------------------------------- // MARK: PageTabNavigationViewDelegate //------------------------------------------------------------------------------------------------------------- extension ExploreHeaderView: PageTabNavigationViewDelegate { func didSelect(tabItem: PageTabItem, atIndex index: Int, completion: (() -> Void)?) { if index >= 0, index < pageTabControllers.count { pageTabDelegate?.didSelect(viewController: pageTabControllers[index]) { if let handler = completion { handler() } } } } func animatePageTabSelection(toIndex index: Int) { pagerView.animatePageTabSelection(toIndex: index) } }
mit
4aca001d17246327b7baea6f77917e8e
42.606414
202
0.638898
5.490822
false
false
false
false
JarlRyan/IOSNote
Swift/City/City/ViewController.swift
1
2863
// // ViewController.swift // City // // Created by bingoogol on 14-6-15. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource { var _province:NSArray! var _city:NSMutableDictionary! override func viewDidLoad() { super.viewDidLoad() // 初始化选择器控件 let picker = UIPickerView() // 1.设置选择器数据源 picker.dataSource = self // 2.设置选择器代理 picker.delegate = self picker.showsSelectionIndicator = true self.view.addSubview(picker) // 3.指定选择器的内容 loadPickerData() } func loadPickerData() { // 1.省份 _province = ["北京","河北","湖南"] // 2.城市 // 2.1初始化城市字典 _city = NSMutableDictionary() // 2.2实例化城市中的数据 let city1 = ["东城","西城"] _city["北京"] = city1 let city2 = ["石家庄","唐山","保定"] _city["河北"] = city2 let city3 = ["长沙","郴州","衡阳"] _city["湖南"] = city3 } // 选择器数据源方法 // 设置数据列数 func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int { return 2 } // 设置数据行数 func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int { if component == 0 { return _province.count } else { let rowProvince = pickerView.selectedRowInComponent(0) let provinceName = _province[rowProvince] as String let citys = _city[provinceName] as NSArray return citys.count } } // 设置选择器行的内容 func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! { if component == 0 { return _province[row] as String } else { let rowProvince = pickerView.selectedRowInComponent(0) let provinceName = _province[rowProvince] as String let citys = _city[provinceName] as NSArray return citys[row] as String } } // 用户选择行的时候刷新数据 func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { if component == 0 { pickerView.reloadComponent(1) } else { let rowProvince = pickerView.selectedRowInComponent(0) let provinceName = _province[rowProvince] as String let citys = _city[provinceName] as NSArray let cityName = citys[row] as String println("\(provinceName):\(cityName)") } } }
apache-2.0
7e2a3b41f46b92c3eac7d155c6498e66
28.761364
110
0.57121
4.469283
false
false
false
false