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 |