repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
A-Kod/vkrypt | Pods/SwiftyVK/Library/Sources/Networking/Attempt/AttemptSheduler.swift | 4 | 1018 | import Foundation
protocol AttemptSheduler: class {
func setLimit(to: AttemptLimit)
func shedule(attempt: Attempt, concurrent: Bool)
}
final class AttemptShedulerImpl: AttemptSheduler {
private lazy var concurrentQueue: OperationQueue = {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = .max
return queue
}()
private let serialQueue: AttemptApiQueue
private var limit: AttemptLimit {
get { return serialQueue.limit }
set { serialQueue.limit = newValue }
}
init(limit: AttemptLimit) {
serialQueue = AttemptApiQueue(limit: limit)
}
func setLimit(to newLimit: AttemptLimit) {
limit = newLimit
}
func shedule(attempt: Attempt, concurrent: Bool) {
let operation = attempt.toOperation()
if concurrent {
concurrentQueue.addOperation(operation)
}
else {
self.serialQueue.addOperation(operation)
}
}
}
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/26531-swift-modulefile-maybereadgenericparams.swift | 1 | 437 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
{{({{class B{
let a{
let c{class
case,
| apache-2.0 |
wilzh40/SwiftSkeleton | SwiftSkeleton/MenuViewController.swift | 1 | 2807 | //
// MenuViewController.swift
// SwiftSkeleton
//
// Created by Wilson Zhao on 1/28/15.
// Copyright (c) 2015 Innogen. All rights reserved.
//
import Foundation
import UIKit
class MenuViewController: UITableViewController {
let singleton:Singleton = Singleton.sharedInstance
var tableData:NSMutableArray = ["Error"]
func setupData() {
self.tableData = singleton.centerViewControllers
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupData()
ConnectionManager.testNetworking()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "protoCell")
let VC:UIViewController = tableData[indexPath.row] as UIViewController
cell.textLabel?.text = VC.title
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Change the center view controller
let newCenterVC = singleton.centerViewControllers[indexPath.row] as UIViewController
if indexPath.row != singleton.currentCenterViewController {
// Do not allow selection of the current VC
self.evo_drawerController?.setCenterViewController(newCenterVC, withCloseAnimation: true, completion: nil)
self.evo_drawerController?.closeDrawerAnimated(true, completion: nil)
singleton.currentCenterViewController = indexPath.row
}
self.tableView.reloadData()
}
// Visually disable selection of the current VC
override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if indexPath.row == singleton.currentCenterViewController {
return false
}
return true
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if indexPath.row == singleton.currentCenterViewController {
return nil
}
return indexPath
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == singleton.currentCenterViewController {
cell.alpha = 0.4
cell.backgroundColor = UIColor.grayColor()
}
}
} | mit |
julienbodet/wikipedia-ios | Wikipedia/Code/StorageAndSyncingSettingsViewController.swift | 1 | 17594 | private struct Section {
let type: ItemType
let footerText: String?
let items: [Item]
init(for type: ItemType, with items: [Item]) {
var footerText: String? = nil
switch type {
case .syncSavedArticlesAndLists:
footerText = WMFLocalizedString("settings-storage-and-syncing-enable-sync-footer-text", value: "Allow Wikimedia to save your saved articles and reading lists to your user preferences when you login and sync.", comment: "Footer text of the settings option that enables saved articles and reading lists syncing")
case .showSavedReadingList:
footerText = WMFLocalizedString("settings-storage-and-syncing-show-default-reading-list-footer-text", value: "Show the Saved (eg. default) reading list as a separate list in your reading lists view. This list appears on Android devices.", comment: "Footer text of the settings option that enables showing the default reading list")
case .syncWithTheServer:
footerText = WMFLocalizedString("settings-storage-and-syncing-server-sync-footer-text", value: "Request an update to your synced articles and reading lists.", comment: "Footer text of the settings button that initiates saved articles and reading lists server sync")
default:
break
}
self.type = type
self.footerText = footerText
self.items = items
}
}
private struct Item {
let disclosureType: WMFSettingsMenuItemDisclosureType?
let type: ItemType
let title: String
let isSwitchOn: Bool
init(for type: ItemType, isSwitchOn: Bool = false) {
self.type = type
self.isSwitchOn = isSwitchOn
var disclosureType: WMFSettingsMenuItemDisclosureType? = nil
let title: String
switch type {
case .syncSavedArticlesAndLists:
disclosureType = .switch
title = WMFLocalizedString("settings-storage-and-syncing-enable-sync-title", value: "Sync saved articles and lists", comment: "Title of the settings option that enables saved articles and reading lists syncing")
case .showSavedReadingList:
disclosureType = .switch
title = WMFLocalizedString("settings-storage-and-syncing-show-default-reading-list-title", value: "Show Saved reading list", comment: "Title of the settings option that enables showing the default reading list")
case .syncWithTheServer:
disclosureType = .titleButton
title = WMFLocalizedString("settings-storage-and-syncing-server-sync-title", value: "Update synced reading lists", comment: "Title of the settings button that initiates saved articles and reading lists server sync")
default:
title = ""
break
}
self.title = title
self.disclosureType = disclosureType
}
}
private enum ItemType: Int {
case syncSavedArticlesAndLists, showSavedReadingList, eraseSavedArticles, syncWithTheServer
}
@objc(WMFStorageAndSyncingSettingsViewController)
class StorageAndSyncingSettingsViewController: UIViewController {
private var theme: Theme = Theme.standard
@IBOutlet weak var tableView: UITableView!
@objc public var dataStore: MWKDataStore?
private var indexPathForCellWithSyncSwitch: IndexPath?
private var shouldShowReadingListsSyncAlertWhenViewAppears = false
private var shouldShowReadingListsSyncAlertWhenSyncEnabled = false
private var sections: [Section] {
let syncSavedArticlesAndLists = Item(for: .syncSavedArticlesAndLists, isSwitchOn: isSyncEnabled)
let showSavedReadingList = Item(for: .showSavedReadingList, isSwitchOn: dataStore?.readingListsController.isDefaultListEnabled ?? false)
let eraseSavedArticles = Item(for: .eraseSavedArticles)
let syncWithTheServer = Item(for: .syncWithTheServer)
let syncSavedArticlesAndListsSection = Section(for: .syncSavedArticlesAndLists, with: [syncSavedArticlesAndLists])
let showSavedReadingListSection = Section(for: .showSavedReadingList, with: [showSavedReadingList])
let eraseSavedArticlesSection = Section(for: .eraseSavedArticles, with: [eraseSavedArticles])
let syncWithTheServerSection = Section(for: .syncWithTheServer, with: [syncWithTheServer])
return [syncSavedArticlesAndListsSection, showSavedReadingListSection, eraseSavedArticlesSection, syncWithTheServerSection]
}
override func viewDidLoad() {
super.viewDidLoad()
title = CommonStrings.settingsStorageAndSyncing
tableView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
tableView.register(WMFSettingsTableViewCell.wmf_classNib(), forCellReuseIdentifier: WMFSettingsTableViewCell.identifier)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.identifier)
tableView.register(WMFTableHeaderFooterLabelView.wmf_classNib(), forHeaderFooterViewReuseIdentifier: WMFTableHeaderFooterLabelView.identifier)
tableView.sectionFooterHeight = UITableViewAutomaticDimension
tableView.estimatedSectionFooterHeight = 44
apply(theme: self.theme)
NotificationCenter.default.addObserver(self, selector: #selector(readingListsServerDidConfirmSyncWasEnabledForAccount(notification:)), name: ReadingListsController.readingListsServerDidConfirmSyncWasEnabledForAccountNotification, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard shouldShowReadingListsSyncAlertWhenViewAppears else {
return
}
if isSyncEnabled {
showReadingListsSyncAlert()
} else { // user logged in to an account that has sync disabled, prompt them to enable sync
wmf_showEnableReadingListSyncPanel(theme: theme, oncePerLogin: false, didNotPresentPanelCompletion: nil) {
self.shouldShowReadingListsSyncAlertWhenSyncEnabled = true
}
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
tableView.reloadData()
}
private func showReadingListsSyncAlert() {
wmf_showAlertWithMessage(WMFLocalizedString("settings-storage-and-syncing-full-sync", value: "Your reading lists will be synced in the background", comment: "Message confirming to the user that their reading lists will be synced in the background"))
}
@objc private func readingListsServerDidConfirmSyncWasEnabledForAccount(notification: Notification) {
if let indexPathForCellWithSyncSwitch = indexPathForCellWithSyncSwitch {
tableView.reloadRows(at: [indexPathForCellWithSyncSwitch], with: .none)
}
guard shouldShowReadingListsSyncAlertWhenSyncEnabled else {
return
}
if isSyncEnabled {
showReadingListsSyncAlert()
}
}
private var isSyncEnabled: Bool {
guard let dataStore = dataStore else {
assertionFailure("dataStore is nil")
return false
}
return dataStore.readingListsController.isSyncEnabled
}
@objc private func eraseSavedArticles() {
let alert = UIAlertController(title: WMFLocalizedString("settings-storage-and-syncing-erase-saved-articles-alert-title", value: "Erase all saved articles?", comment: "Title of the alert shown before erasing all saved article."), message: WMFLocalizedString("settings-storage-and-syncing-erase-saved-articles-alert-message", value: "Erasing your saved articles will remove them from your user account if you have syncing turned on as well as from this device. You cannot undo this action.", comment: "Message for the alert shown before erasing all saved articles."), preferredStyle: .alert)
let cancel = UIAlertAction(title: CommonStrings.cancelActionTitle, style: .cancel)
let erase = UIAlertAction(title: CommonStrings.eraseAllSavedArticles, style: .destructive) { (_) in
guard let isSyncEnabled = self.dataStore?.readingListsController.isSyncEnabled else {
assertionFailure("dataStore is nil")
return
}
self.dataStore?.clearCachesForUnsavedArticles()
if isSyncEnabled {
self.dataStore?.readingListsController.setSyncEnabled(true, shouldDeleteLocalLists: true, shouldDeleteRemoteLists: true)
} else {
self.dataStore?.readingListsController.setSyncEnabled(true, shouldDeleteLocalLists: true, shouldDeleteRemoteLists: true)
self.dataStore?.readingListsController.setSyncEnabled(false, shouldDeleteLocalLists: false, shouldDeleteRemoteLists: false)
}
self.tableView.reloadData()
}
alert.addAction(cancel)
alert.addAction(erase)
present(alert, animated: true)
}
private lazy var eraseSavedArticlesView: EraseSavedArticlesView? = {
let eraseSavedArticlesView = EraseSavedArticlesView.wmf_viewFromClassNib()
eraseSavedArticlesView?.titleLabel.text = CommonStrings.eraseAllSavedArticles
eraseSavedArticlesView?.button.setTitle(WMFLocalizedString("settings-storage-and-syncing-erase-saved-articles-button-title", value: "Erase", comment: "Title of the settings button that enables erasing saved articles"), for: .normal)
eraseSavedArticlesView?.button.addTarget(self, action: #selector(eraseSavedArticles), for: .touchUpInside)
return eraseSavedArticlesView
}()
}
// MARK: UITableViewDataSource
extension StorageAndSyncingSettingsViewController: UITableViewDataSource {
private func getItem(at indexPath: IndexPath) -> Item {
return sections[indexPath.section].items[indexPath.row]
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let settingsItem = getItem(at: indexPath)
guard let disclosureType = settingsItem.disclosureType else {
let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.identifier, for: indexPath)
cell.selectionStyle = .none
cell.backgroundColor = theme.colors.paperBackground
if let eraseSavedArticlesView = eraseSavedArticlesView {
let temporaryCacheSize = ImageController.shared.temporaryCacheSize
let sitesDirectorySize = Int64(dataStore?.sitesDirectorySize() ?? 0)
let dataSizeString = ByteCountFormatter.string(fromByteCount: temporaryCacheSize + sitesDirectorySize, countStyle: .file)
let format = WMFLocalizedString("settings-storage-and-syncing-erase-saved-articles-footer-text", value: "Erasing your saved articles will remove them from your user account if you have syncing turned on as well as from this device.\n\nErasing your saved articles will free up about %1$@ of space.", comment: "Footer text of the settings option that enables erasing saved articles. %1$@ will be replaced with a number and a system provided localized unit indicator for MB or KB.")
eraseSavedArticlesView.footerLabel.text = String.localizedStringWithFormat(format, dataSizeString)
eraseSavedArticlesView.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.wmf_addSubviewWithConstraintsToEdges(eraseSavedArticlesView)
} else {
assertionFailure("Couldn't load EraseSavedArticlesView from nib")
}
return cell
}
guard let cell = tableView.dequeueReusableCell(withIdentifier: WMFSettingsTableViewCell.identifier, for: indexPath) as? WMFSettingsTableViewCell else {
return UITableViewCell()
}
cell.delegate = self
cell.configure(disclosureType, disclosureText: nil, title: settingsItem.title, subtitle: nil, iconName: nil, isSwitchOn: settingsItem.isSwitchOn, iconColor: nil, iconBackgroundColor: nil, controlTag: settingsItem.type.rawValue, theme: theme)
if settingsItem.type == .syncSavedArticlesAndLists {
indexPathForCellWithSyncSwitch = indexPath
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let item = getItem(at: indexPath)
switch item.type {
case .syncWithTheServer:
let loginSuccessCompletion = {
self.dataStore?.readingListsController.fullSync({})
self.shouldShowReadingListsSyncAlertWhenViewAppears = true
}
if WMFAuthenticationManager.sharedInstance.isLoggedIn && isSyncEnabled {
dataStore?.readingListsController.fullSync({})
showReadingListsSyncAlert()
} else if !WMFAuthenticationManager.sharedInstance.isLoggedIn {
wmf_showLoginOrCreateAccountToSyncSavedArticlesToReadingListPanel(theme: theme, dismissHandler: nil, loginSuccessCompletion: loginSuccessCompletion, loginDismissedCompletion: nil)
} else {
wmf_showEnableReadingListSyncPanel(theme: theme, oncePerLogin: false, didNotPresentPanelCompletion: nil) {
self.shouldShowReadingListsSyncAlertWhenSyncEnabled = true
}
}
default:
break
}
}
}
// MARK: UITableViewDelegate
extension StorageAndSyncingSettingsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: WMFTableHeaderFooterLabelView.identifier) as? WMFTableHeaderFooterLabelView else {
return nil
}
footer.setShortTextAsProse(sections[section].footerText)
footer.type = .footer
if let footer = footer as Themeable? {
footer.apply(theme: theme)
}
return footer
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard let _ = self.tableView(tableView, viewForFooterInSection: section) as? WMFTableHeaderFooterLabelView else {
return 0
}
return UITableViewAutomaticDimension
}
}
// MARK: - WMFSettingsTableViewCellDelegate
extension StorageAndSyncingSettingsViewController: WMFSettingsTableViewCellDelegate {
func settingsTableViewCell(_ settingsTableViewCell: WMFSettingsTableViewCell!, didToggleDisclosureSwitch sender: UISwitch!) {
guard let settingsItemType = ItemType(rawValue: sender.tag) else {
assertionFailure("Toggled discloure switch of WMFSettingsTableViewCell for undefined StorageAndSyncingSettingsItemType")
return
}
guard let dataStore = self.dataStore else {
return
}
let isSwitchOn = sender.isOn
switch settingsItemType {
case .syncSavedArticlesAndLists where !WMFAuthenticationManager.sharedInstance.isLoggedIn:
assert(!isSyncEnabled, "Sync cannot be enabled if user is not logged in")
let dismissHandler = {
sender.setOn(false, animated: true)
}
let loginSuccessCompletion: () -> Void = {
dataStore.readingListsController.setSyncEnabled(true, shouldDeleteLocalLists: false, shouldDeleteRemoteLists: false)
SettingsFunnel.shared.logSyncEnabledInSettings()
}
wmf_showLoginOrCreateAccountToSyncSavedArticlesToReadingListPanel(theme: theme, dismissHandler: dismissHandler, loginSuccessCompletion: loginSuccessCompletion, loginDismissedCompletion: dismissHandler)
case .syncSavedArticlesAndLists where WMFAuthenticationManager.sharedInstance.isLoggedIn:
let setSyncEnabled = {
dataStore.readingListsController.setSyncEnabled(isSwitchOn, shouldDeleteLocalLists: false, shouldDeleteRemoteLists: !isSwitchOn)
if isSwitchOn {
SettingsFunnel.shared.logSyncEnabledInSettings()
} else {
SettingsFunnel.shared.logSyncDisabledInSettings()
}
}
if !isSwitchOn {
self.wmf_showKeepSavedArticlesOnDevicePanelIfNecessary(triggeredBy: .syncDisabled, theme: self.theme) {
setSyncEnabled()
}
} else {
setSyncEnabled()
}
case .showSavedReadingList:
dataStore.readingListsController.isDefaultListEnabled = isSwitchOn
default:
return
}
}
}
// MARK: Themeable
extension StorageAndSyncingSettingsViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
tableView.backgroundColor = theme.colors.baseBackground
eraseSavedArticlesView?.apply(theme: theme)
}
}
| mit |
iluuu1994/Conway-s-Game-of-Life | Conway's Game of Life/Conway's Game of Life/CGOLView.swift | 1 | 4069 | //
// CGOLView.swift
// Conway's Game of Life
//
// Created by Ilija Tovilo on 26/08/14.
// Copyright (c) 2014 Ilija Tovilo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class CGOLView: UIView {
// --------------------
// MARK: - Properties -
// --------------------
private var _gridWidth = 10
private var _gridHeight = 10
private var _gameModel: CGOLModel!
private var _tileViews: Matrix<TileView!>!
// --------------
// MARK: - Init -
// --------------
public init(gridWidth: Int, gridHeight: Int) {
super.init(frame: CGRect(x: 0, y: 0, width:500 , height: 500))
_init(gridWidth: gridWidth, gridHeight: gridHeight)
}
required public init(coder: NSCoder) {
super.init(coder: coder)
_init(gridWidth: _gridWidth, gridHeight: _gridHeight)
}
private func _init(#gridWidth: Int, gridHeight: Int) {
// Init values
_gridWidth = gridWidth
_gridHeight = gridHeight
_gameModel = CGOLModel(gridWidth: _gridWidth, gridHeight: _gridHeight)
_tileViews = Matrix<TileView!>(width: _gridWidth, height: _gridHeight, repeatedValue: nil)
// Fill the matrix with views
for (x, y, _) in _tileViews {
let tileView = TileView(frame: CGRectZero)
tileView.coordinates = (x: x, y: y)
let tileModel = _gameModel.getTile(x: x, y: y)
// Two way binding
tileView.twoWayBinding = TwoWayBinding(
leadingElement: tileModel,
leadingKeyPath: "alive",
followingElement: tileView,
followingKeyPath: "alive"
)
addSubview(tileView)
_tileViews[x, y] = tileView
}
}
// -----------------
// MARK: - Methods -
// -----------------
public func step() {
_gameModel.step()
}
public func clear() {
_gameModel.clear()
}
// ----------------
// MARK: - Layout -
// ----------------
override public func layoutSubviews() {
super.layoutSubviews()
_layoutTiles()
}
private func _layoutTiles() {
for (x, y, tileView) in _tileViews {
tileView.frame = tileFrame(x: x, y: y)
}
}
private var tileSize: CGSize {
return CGSize(
width: bounds.width / CGFloat(_gridWidth),
height: bounds.height / CGFloat(_gridHeight)
)
}
private func tileOrigin(coordinates: TileCoordinates) -> CGPoint {
return CGPoint(
x: CGFloat(coordinates.x) * tileSize.width,
y: CGFloat(coordinates.y) * tileSize.height
)
}
private func tileFrame(coordinates: TileCoordinates) -> CGRect {
return CGRect(
origin: tileOrigin(coordinates),
size: tileSize
)
}
}
| bsd-2-clause |
lnds/9d9l | desafio1/swift/Sources/toque-y-fama/main.swift | 1 | 1980 |
func validar(tam:Int, acc:String!) -> [Int]? {
var num = [Int]()
let chars = Array(acc)
for (i,c) in chars.enumerated() {
if i >= tam {
return nil
} else if c < "0" || c > "9" {
return nil
} else {
let digito = Int(String(c))!
if num.contains(digito) {
return nil
}
num.append(Int(String(c))!)
}
}
if num.count != tam { return nil }
return num
}
func comparar(num:[Int], sec:[Int]) -> (toques:Int, famas:Int) {
var toques = 0
var famas = 0
for (i, n) in num.enumerated() {
for (j, m) in sec.enumerated() {
if n == m {
if i == j { famas += 1 }
else { toques += 1 }
}
}
}
return (toques, famas)
}
let tam = 5
let numbers = 0...9
var sec = Array(numbers.shuffled().prefix(tam))
print (" Bienvenido a Toque y Fama.\n",
"==========================\n\n",
"En este juego debes tratar de adivinar una secuencia de \(tam) dígitos generadas por el programa.\n",
"Para esto ingresas \(tam) dígitos distintos con el fin de adivinar la secuencia.\n",
"Si has adivinado correctamente la posición de un dígito se produce una Fama.\n",
"Si has adivinado uno de los dígitos de la secuencia, pero en una posición distinta se trata de un Toque.\n\n",
"Ejemplo: Si la secuencia es secuencia: [8, 0, 6, 1, 3] e ingresas 40863, entonces en pantalla aparecerá:\n",
"tu ingresaste [4, 0, 8, 6, 3]\n",
"resultado: 2 Toques 2 Famas\n\n")
var intentos = 0
while true {
intentos += 1
print("Ingresa una secuencia de \(tam) dígitos distintos (o escribe salir):")
let accion = readLine(strippingNewline:true)
if accion == "salir" {
break
} else {
let num = validar(tam:tam, acc:accion!)
if num == nil {
print("error!\n")
} else {
print("ingresaste: ", num!)
let (toques, famas) = comparar(num: num!, sec:sec)
print("resultado: \(toques) Toques, \(famas) Famas\n")
if famas == tam {
print("Ganaste! Acertaste al intento \(intentos)! La secuencia era \(sec).")
break
}
}
}
} | mit |
SixFiveSoftware/Swift_Pair_Programming_Resources | FizzBuzz/FizzBuzz/FizzBuzz.swift | 1 | 900 | //
// FizzBuzz.swift
// FizzBuzz
//
// Created by BJ Miller on 9/27/14.
// Copyright (c) 2014 Six Five Software, LLC. All rights reserved.
//
import Foundation
struct FizzBuzz {
static func check(value: Int) -> String {
var returnValue = "\(value)"
if value % 3 == 0 {
returnValue = "Fizz"
}
if value % 5 == 0 {
returnValue = (returnValue == "Fizz" )
? "FizzBuzz"
: "Buzz"
}
return returnValue
}
}
extension Int {
var FizzBuzz: String {
var returnValue = "\(self)"
if self % 3 == 0 {
returnValue = "Fizz"
}
if self % 5 == 0 {
returnValue = (returnValue == "Fizz" )
? "FizzBuzz"
: "Buzz"
}
return returnValue
}
} | mit |
kaushaldeo/Olympics | Olympics/Views/KDStoryboardSegue.swift | 1 | 1148 | //
// KDStoryboardSegue.swift
// Olympics
//
// Created by Kaushal Deo on 6/27/16.
// Copyright © 2016 Scorpion Inc. All rights reserved.
//
import UIKit
class KDStoryboardSegue: UIStoryboardSegue {
override func perform() {
if let window = self.sourceViewController.view.window {
let snapShot = window.snapshotViewAfterScreenUpdates(true)
self.destinationViewController.view.addSubview(snapShot)
window.rootViewController = self.destinationViewController
UIView.animateWithDuration(0.5, animations: {
snapShot.layer.opacity = 0
snapShot.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5)
}, completion: { (finished) in
snapShot.removeFromSuperview()
})
}
}
}
class KDReplaceSegue: UIStoryboardSegue {
override func perform() {
if let window = self.sourceViewController.view.window {
window.rootViewController = self.destinationViewController
}
}
}
| apache-2.0 |
parkera/swift-corelibs-foundation | Foundation/Host.swift | 1 | 10095 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
open class Host: NSObject {
enum ResolveType {
case name
case address
case current
}
internal var _info: String?
internal var _type: ResolveType
internal var _resolved = false
internal var _names = [String]()
internal var _addresses = [String]()
#if os(Android)
static internal let NI_MAXHOST = 1025
#endif
static internal let _current = Host(currentHostName(), .current)
internal init(_ info: String?, _ type: ResolveType) {
_info = info
_type = type
}
static internal func currentHostName() -> String {
#if os(Windows)
var dwLength: DWORD = 0
GetComputerNameExA(ComputerNameDnsHostname, nil, &dwLength)
guard dwLength > 0 else { return "localhost" }
guard let hostname: UnsafeMutablePointer<Int8> =
UnsafeMutableBufferPointer<Int8>
.allocate(capacity: Int(dwLength + 1))
.baseAddress else {
return "localhost"
}
defer { hostname.deallocate() }
guard GetComputerNameExA(ComputerNameDnsHostname, hostname, &dwLength) != FALSE else {
return "localhost"
}
return String(cString: hostname)
#else
let hname = UnsafeMutablePointer<Int8>.allocate(capacity: Int(NI_MAXHOST))
defer {
hname.deallocate()
}
let r = gethostname(hname, Int(NI_MAXHOST))
if r < 0 || hname[0] == 0 {
return "localhost"
}
return String(cString: hname)
#endif
}
open class func current() -> Host {
return _current
}
public convenience init(name: String?) {
self.init(name, .name)
}
public convenience init(address: String) {
self.init(address, .address)
}
open func isEqual(to aHost: Host) -> Bool {
if self === aHost { return true }
return addresses.firstIndex { aHost.addresses.contains($0) } != nil
}
internal func _resolveCurrent() {
#if os(Android)
return
#elseif os(Windows)
var ulSize: ULONG = 0
var ulResult: ULONG =
GetAdaptersAddresses(ULONG(AF_UNSPEC), 0, nil, nil, &ulSize)
let arAdapterInfo: UnsafeMutablePointer<IP_ADAPTER_ADDRESSES> =
UnsafeMutablePointer<IP_ADAPTER_ADDRESSES_LH>
.allocate(capacity: Int(ulSize) / MemoryLayout<IP_ADAPTER_ADDRESSES>.size)
defer { arAdapterInfo.deallocate() }
ulResult = GetAdaptersAddresses(ULONG(AF_UNSPEC), 0, nil, arAdapterInfo, &ulSize)
var buffer: UnsafeMutablePointer<WCHAR> =
UnsafeMutablePointer<WCHAR>.allocate(capacity: Int(NI_MAXHOST))
defer { buffer.deallocate() }
var arCurrentAdapterInfo: UnsafeMutablePointer<IP_ADAPTER_ADDRESSES>? =
arAdapterInfo
while arCurrentAdapterInfo != nil {
var arAddress: UnsafeMutablePointer<IP_ADAPTER_UNICAST_ADDRESS>? =
arCurrentAdapterInfo!.pointee.FirstUnicastAddress
while arAddress != nil {
let arCurrentAddress: IP_ADAPTER_UNICAST_ADDRESS = arAddress!.pointee
switch arCurrentAddress.Address.lpSockaddr.pointee.sa_family {
case ADDRESS_FAMILY(AF_INET), ADDRESS_FAMILY(AF_INET6):
if GetNameInfoW(arCurrentAddress.Address.lpSockaddr,
arCurrentAddress.Address.iSockaddrLength,
buffer, DWORD(NI_MAXHOST),
nil, 0, NI_NUMERICHOST) == 0 {
_addresses.append(String(decodingCString: buffer,
as: UTF16.self))
}
default: break
}
arAddress = arCurrentAddress.Next
}
arCurrentAdapterInfo = arCurrentAdapterInfo!.pointee.Next
}
_resolved = true
#else
var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
if getifaddrs(&ifaddr) != 0 {
return
}
var ifa: UnsafeMutablePointer<ifaddrs>? = ifaddr
let address = UnsafeMutablePointer<Int8>.allocate(capacity: Int(NI_MAXHOST))
defer {
freeifaddrs(ifaddr)
address.deallocate()
}
while let ifaValue = ifa?.pointee {
if let ifa_addr = ifaValue.ifa_addr, ifaValue.ifa_flags & UInt32(IFF_LOOPBACK) == 0 {
let family = ifa_addr.pointee.sa_family
if family == sa_family_t(AF_INET) || family == sa_family_t(AF_INET6) {
let sa_len: socklen_t = socklen_t((family == sa_family_t(AF_INET6)) ? MemoryLayout<sockaddr_in6>.size : MemoryLayout<sockaddr_in>.size)
if getnameinfo(ifa_addr, sa_len, address, socklen_t(NI_MAXHOST), nil, 0, NI_NUMERICHOST) == 0 {
_addresses.append(String(cString: address))
}
}
}
ifa = ifaValue.ifa_next
}
_resolved = true
#endif
}
internal func _resolve() {
guard _resolved == false else { return }
#if os(Android)
return
#elseif os(Windows)
if let info = _info {
if _type == .current { return _resolveCurrent() }
var hints: ADDRINFOW = ADDRINFOW()
memset(&hints, 0, MemoryLayout<ADDRINFOW>.size)
switch (_type) {
case .name:
hints.ai_flags = AI_PASSIVE | AI_CANONNAME
case .address:
hints.ai_flags = AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST
case .current:
break
}
hints.ai_family = AF_UNSPEC
hints.ai_socktype = SOCK_STREAM
hints.ai_protocol = IPPROTO_TCP.rawValue
var aiResult: UnsafeMutablePointer<ADDRINFOW>?
var bSucceeded: Bool = false
info.withCString(encodedAs: UTF16.self) {
if GetAddrInfoW($0, nil, &hints, &aiResult) == 0 {
bSucceeded = true
}
}
guard bSucceeded == true else { return }
defer { FreeAddrInfoW(aiResult) }
let wszHostName =
UnsafeMutablePointer<WCHAR>.allocate(capacity: Int(NI_MAXHOST))
defer { wszHostName.deallocate() }
while aiResult != nil {
let aiInfo: ADDRINFOW = aiResult!.pointee
var sa_len: socklen_t = 0
switch aiInfo.ai_family {
case AF_INET:
sa_len = socklen_t(MemoryLayout<sockaddr_in>.size)
case AF_INET6:
sa_len = socklen_t(MemoryLayout<sockaddr_in6>.size)
default:
aiResult = aiInfo.ai_next
continue
}
let lookup = { (content: inout [String], flags: Int32) in
if GetNameInfoW(aiInfo.ai_addr, sa_len, wszHostName,
DWORD(NI_MAXHOST), nil, 0, flags) == 0 {
content.append(String(decodingCString: wszHostName,
as: UTF16.self))
}
}
lookup(&_addresses, NI_NUMERICHOST)
lookup(&_names, NI_NAMEREQD)
lookup(&_names, NI_NOFQDN | NI_NAMEREQD)
aiResult = aiInfo.ai_next
}
_resolved = true
}
#else
if let info = _info {
var flags: Int32 = 0
switch (_type) {
case .name:
flags = AI_PASSIVE | AI_CANONNAME
case .address:
flags = AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST
case .current:
_resolveCurrent()
return
}
var hints = addrinfo()
hints.ai_family = PF_UNSPEC
#if os(macOS) || os(iOS) || os(Android)
hints.ai_socktype = SOCK_STREAM
#else
hints.ai_socktype = Int32(SOCK_STREAM.rawValue)
#endif
hints.ai_flags = flags
var res0: UnsafeMutablePointer<addrinfo>? = nil
let r = getaddrinfo(info, nil, &hints, &res0)
defer {
freeaddrinfo(res0)
}
if r != 0 {
return
}
var res: UnsafeMutablePointer<addrinfo>? = res0
let host = UnsafeMutablePointer<Int8>.allocate(capacity: Int(NI_MAXHOST))
defer {
host.deallocate()
}
while res != nil {
let info = res!.pointee
let family = info.ai_family
if family != AF_INET && family != AF_INET6 {
res = info.ai_next
continue
}
let sa_len: socklen_t = socklen_t((family == AF_INET6) ? MemoryLayout<sockaddr_in6>.size : MemoryLayout<sockaddr_in>.size)
let lookupInfo = { (content: inout [String], flags: Int32) in
if getnameinfo(info.ai_addr, sa_len, host, socklen_t(NI_MAXHOST), nil, 0, flags) == 0 {
content.append(String(cString: host))
}
}
lookupInfo(&_addresses, NI_NUMERICHOST)
lookupInfo(&_names, NI_NAMEREQD)
lookupInfo(&_names, NI_NOFQDN|NI_NAMEREQD)
res = info.ai_next
}
_resolved = true
}
#endif
}
open var name: String? {
return names.first
}
open var names: [String] {
_resolve()
return _names
}
open var address: String? {
return addresses.first
}
open var addresses: [String] {
_resolve()
return _addresses
}
open var localizedName: String? {
return nil
}
}
| apache-2.0 |
mohsinalimat/SpringIndicator | SpringIndicatorExample/SpringIndicatorExample/WebViewController.swift | 4 | 1291 | //
// WebViewController.swift
// SpringIndicatorExample
//
// Created by Kyohei Ito on 2015/04/20.
// Copyright (c) 2015年 kyohei_ito. All rights reserved.
//
import UIKit
import SpringIndicator
class WebViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
let refreshControl = SpringIndicator.Refresher()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let url = NSURL(string: "https://www.apple.com")
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
refreshControl.indicator.lineColor = UIColor.redColor()
refreshControl.addTarget(self, action: "onRefresh", forControlEvents: .ValueChanged)
webView.scrollView.addSubview(refreshControl)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func onRefresh() {
webView.reload()
}
func webViewDidFinishLoad(webView: UIWebView) {
refreshControl.endRefreshing()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
refreshControl.endRefreshing()
}
}
| mit |
auth0/Lock.iOS-OSX | Lock/OnePassword.swift | 1 | 2532 | // OnePassword.swift
//
// Copyright (c) 2017 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
protocol PasswordManager {
var enabled: Bool { get set }
var available: Bool { get }
var onUpdate: (String, String) -> Void { get set }
func login(callback: @escaping (Error?) -> Void)
func store(withPolicy policy: [String: Any]?, identifier: String?, callback: @escaping (Error?) -> Void)
}
public class OnePassword: PasswordManager {
/// A Boolean value indicating whether the password manager is enabled.
public var enabled: Bool = true
/// The text identifier to use with the password manager to identify which credentials to use.
public var appIdentifier: String
/// The title to be displayed when creating a new password manager entry.
public var displayName: String
weak var controller: UIViewController?
public init() {
self.appIdentifier = Bundle.main.bundleIdentifier.verbatim()
self.displayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName").verbatim()
}
var available: Bool {
return false
}
var onUpdate: (String, String) -> Void = { _, _ in }
func login(callback: @escaping (Error?) -> Void) {
return
}
func store(withPolicy policy: [String: Any]?, identifier: String?, callback: @escaping (Error?) -> Void) {
return
}
private func handleResut(_ dict: [AnyHashable: Any]?) {
return
}
}
| mit |
rizumita/TransitionOperator | TransitionOperator/CompositeTransitionOperator.swift | 1 | 1261 | //
// CompositeTransitionOperator.swift
// TransitionOperator
//
// Created by 和泉田 領一 on 2016/02/28.
// Copyright © 2016年 CAPH TECH. All rights reserved.
//
import Foundation
public class CompositeTransitionOperator: TransitionOperatorType, ArrayLiteralConvertible {
public typealias Element = TransitionOperatorType
public required init(arrayLiteral elements: Element...) {
operators = elements
}
public var forced: Bool = false
private var operators: [Element] = []
init(operators: [Element], forced: Bool = false) {
self.operators = operators
}
public func add(nextOperator nextOperator: Element) {
operators.append(nextOperator)
}
public func operate(executor executor: TransitionExecutorType, source: Any, destination: Any) -> Bool {
for op in operators {
if op.operate(executor: executor, source: source, destination: destination) == false && !forced {
return false
}
}
return true
}
}
infix operator += {}
public func +=(compositeOperator: CompositeTransitionOperator, nextOperator: TransitionOperatorType) {
compositeOperator.add(nextOperator: nextOperator)
}
| mit |
Baichenghui/TestCode | 16-计步器OneHourWalker-master/OneHourWalkerTests/OneHourWalkerTests.swift | 1 | 999 | //
// OneHourWalkerTests.swift
// OneHourWalkerTests
//
// Created by Matthew Maher on 2/18/16.
// Copyright © 2016 Matt Maher. All rights reserved.
//
import XCTest
@testable import OneHourWalker
class OneHourWalkerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit |
tomtclai/swift-algorithm-club | Monty Hall Problem/MontyHall.playground/Contents.swift | 8 | 1332 | //: Playground - noun: a place where people can play
import Foundation
func random(_ n: Int) -> Int {
return Int(arc4random_uniform(UInt32(n)))
}
let numberOfDoors = 3
var rounds = 0
var winOriginalChoice = 0
var winChangedMind = 0
func playRound() {
// The door with the prize.
let prizeDoor = random(numberOfDoors)
// The door the player chooses.
let chooseDoor = random(numberOfDoors)
// The door that Monty opens. This must be empty and not the one the player chose.
var openDoor = -1
repeat {
openDoor = random(numberOfDoors)
} while openDoor == prizeDoor || openDoor == chooseDoor
// What happens when the player changes his mind and picks the other door.
var changeMind = -1
repeat {
changeMind = random(numberOfDoors)
} while changeMind == openDoor || changeMind == chooseDoor
// Figure out which choice was the winner.
if chooseDoor == prizeDoor {
winOriginalChoice += 1
}
if changeMind == prizeDoor {
winChangedMind += 1
}
rounds += 1
}
// Run the simulation a large number of times.
for i in 1...5000 {
playRound()
}
let stubbornPct = Double(winOriginalChoice)/Double(rounds)
let changedMindPct = Double(winChangedMind)/Double(rounds)
print(String(format: "Played %d rounds, stubborn: %g%% vs changed mind: %g%%", rounds, stubbornPct, changedMindPct))
| mit |
MrSuperJJ/JJMediatorDemo | JJMediatorDemo/JJMediator/JJMediator.swift | 1 | 4920 | //
// JJMediator.swift
// JJMediator
//
// Created by yejiajun on 2017/4/27.
// Copyright © 2017年 yejiajun. All rights reserved.
//
import UIKit
public class JJMediator: NSObject {
// 单例
private static let singleInstance = JJMediator()
public class func sharedInstance() -> JJMediator {
return singleInstance
}
/// 远程APP调用入口
/// 格式 - scheme://[target]/[action]?[params],例子 - scheme://target/action?key=value
/// 上述URL为固定格式,有定制化需求的话,请修改具体的处理逻辑
///
/// - Parameters:
/// - URL: URL
/// - completion: block回调
public func performAction(URL url: URL, completion: (_ result: AnyObject) -> Void) -> AnyObject? {
// 判断URLScheme和命名空间(项目名称)是否一致
let scheme = url.scheme!
guard scheme == fetchNameSpace() else {
return NSNumber(value: false)
}
var parameters = Dictionary<String, Any>()
let targetName = url.host
let actionName = url.lastPathComponent
let parameterString = url.query
if let targetName = targetName, let parameterString = parameterString {
let keyEqualValueArray = parameterString.components(separatedBy: "&")
for keyEqualValueString in keyEqualValueArray {
let keyAndValueArray = keyEqualValueString.components(separatedBy: "=")
if keyAndValueArray.count != 2 {
continue
}
parameters[keyAndValueArray[0]] = keyAndValueArray[1]
}
// 远程调用的Action方法,为保证结构统一,parameters参数建议使用字典类型封装
let result = perform(targetName: targetName, actionName: actionName, parameters: parameters)
if let result = result{
completion(result)
}
}
return NSNumber(value: true)
}
/// 本地组件调用入口
///
/// - Parameters:
/// - targetName: target名称
/// - actionName: action名称
/// - parameters: 参数
/// - isSwiftClass: target是否是Swift类
/// - Returns: Optional<AnyObject>对象
public func perform(targetName: String, actionName: String, parameters: Dictionary<String, Any>?, moduleName: String? = nil) -> AnyObject? {
// Target名称(类名),Swift类需加上命名空间
let targetClassString: String
if let moduleName = moduleName {
targetClassString = moduleName + "." + "Target_" + targetName
} else {
targetClassString = "Target_" + targetName
}
// Action名称(方法名)
let actionString = "Action_" + actionName + (parameters != nil ? ":" : "" )
// // 根据Target获取Class,返回Optional<NSObject.Type>类型的值
// let targetClass = NSClassFromString(targetClassString) as? NSObject.Type
// // Class实例化,返回Optional<NSObject>类型的值
// let target = targetClass?.init()
// 根据Target获取Class,返回Optional<AnyClass>类型的值
let targetClass: AnyClass? = NSClassFromString(targetClassString)
// Class实例化,返回Optional<AnyObject>类型的值
let target = targetClass?.alloc()
// 根据Action获取Selector
let action = NSSelectorFromString(actionString)
if let target = target {
// 检查Class实例能否响应Action方法,并执行Selector
if target.responds(to: action) {
let object = target.perform(action, with: parameters)
// 返回Optional<Unmanaged<AnyObject>>对象
if let object = object {
return object.takeUnretainedValue()
} else {
return nil
}
} else {
// 无响应请求时,调用默认notFound方法
let action = NSSelectorFromString("notFound:")
if target.responds(to: action) {
let object = target.perform(action, with: parameters)
if let object = object {
return object.takeUnretainedValue()
} else {
return nil
}
} else {
// notFound方法也无响应时,返回nil
return nil
}
}
} else {
// target不存在,返回nil
return nil
}
}
// 获取命名空间
private func fetchNameSpace() -> String {
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
return namespace
}
}
| mit |
Rag0n/QuNotes | Core/Utility/Extensions/Array+Extensions.swift | 1 | 921 | //
// Array+Extensions.swift
// QuNotes
//
// Created by Alexander Guschin on 12.07.17.
// Copyright © 2017 Alexander Guschin. All rights reserved.
//
extension Array where Element: Equatable {
func appending(_ newElement: Element) -> [Element] {
var updatedArray = self
updatedArray.append(newElement)
return updatedArray
}
func removing(_ element: Element) -> [Element] {
guard let index = index(of: element) else { return self }
var updatedArray = self
updatedArray.remove(at: index)
return updatedArray
}
func removing(at index: Int) -> [Element] {
var updatedArray = self
updatedArray.remove(at: index)
return updatedArray
}
func replacing(at index: Int, with element: Element) -> [Element] {
var updatedArray = self
updatedArray[index] = element
return updatedArray
}
}
| gpl-3.0 |
shohei/firefox-ios | Storage/DatabaseError.swift | 4 | 547 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
/**
* Used to bridge the NSErrors we get here into something that Result is happy with.
*/
public class DatabaseError: ErrorType {
let err: NSError?
public var description: String {
return err?.localizedDescription ?? "Unknown database error."
}
init(err: NSError?) {
self.err = err
}
} | mpl-2.0 |
Bouke/HAP | Sources/HAP/Base/Predefined/Services/Service.LeakSensor.swift | 1 | 1380 | import Foundation
extension Service {
open class LeakSensor: Service {
public init(characteristics: [AnyCharacteristic] = []) {
var unwrapped = characteristics.map { $0.wrapped }
leakDetected = getOrCreateAppend(
type: .leakDetected,
characteristics: &unwrapped,
generator: { PredefinedCharacteristic.leakDetected() })
name = get(type: .name, characteristics: unwrapped)
statusActive = get(type: .statusActive, characteristics: unwrapped)
statusFault = get(type: .statusFault, characteristics: unwrapped)
statusLowBattery = get(type: .statusLowBattery, characteristics: unwrapped)
statusTampered = get(type: .statusTampered, characteristics: unwrapped)
super.init(type: .leakSensor, characteristics: unwrapped)
}
// MARK: - Required Characteristics
public let leakDetected: GenericCharacteristic<Enums.LeakDetected>
// MARK: - Optional Characteristics
public let name: GenericCharacteristic<String>?
public let statusActive: GenericCharacteristic<Bool>?
public let statusFault: GenericCharacteristic<UInt8>?
public let statusLowBattery: GenericCharacteristic<Enums.StatusLowBattery>?
public let statusTampered: GenericCharacteristic<UInt8>?
}
}
| mit |
openhab/openhab.ios | openHAB/DynamicButtonStyleBell.swift | 1 | 2084 | // Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import DynamicButton
import UIKit
/// Bell symbol style: 🔔
struct DynamicButtonStyleBell: DynamicButtonBuildableStyle {
/// "Bell" style.
static var styleName: String {
"Bell"
}
let pathVector: DynamicButtonPathVector
init(center: CGPoint, size: CGFloat, offset: CGPoint, lineWidth: CGFloat) {
let gongRadius = size / 7
let gongCenter = CGPoint(x: center.x, y: size - gongRadius - lineWidth)
let startAngle = CGFloat.pi
let endAngle = startAngle + CGFloat.pi
let gongPath = UIBezierPath(arcCenter: gongCenter, radius: gongRadius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
let bellHeight = gongCenter.y - (lineWidth / 2.0)
let bellTop = UIBezierPath()
bellTop.move(to: CGPoint(x: 0, y: 26))
bellTop.addCurve(to: CGPoint(x: 6, y: 12), controlPoint1: CGPoint(x: 0, y: 26), controlPoint2: CGPoint(x: 4.5, y: 22))
bellTop.addCurve(to: CGPoint(x: 16, y: 2), controlPoint1: CGPoint(x: 6, y: 6), controlPoint2: CGPoint(x: 10.5, y: 2))
bellTop.addCurve(to: CGPoint(x: 26, y: 12), controlPoint1: CGPoint(x: 21.5, y: 2), controlPoint2: CGPoint(x: 26, y: 6))
bellTop.addCurve(to: CGPoint(x: 32, y: 26), controlPoint1: CGPoint(x: 27.5, y: 22), controlPoint2: CGPoint(x: 32, y: 26))
bellTop.apply(CGAffineTransform(scaleX: size / 32.0, y: bellHeight / 26.0))
let bellBottom = UIBezierPath()
bellBottom.move(to: CGPoint(x: 0, y: bellHeight))
bellBottom.addLine(to: CGPoint(x: size, y: bellHeight))
pathVector = DynamicButtonPathVector(p1: bellTop.cgPath, p2: bellBottom.cgPath, p3: bellBottom.cgPath, p4: gongPath.cgPath)
}
}
| epl-1.0 |
e155707/remote | AfuRo/AfuRo/Main/DataController.swift | 1 | 889 | //
// DataController.swift
// AfuRo
//
// Created by 赤堀 貴一 on 2017/11/27.
// Copyright © 2017年 Ryukyu. All rights reserved.
//
import Foundation
class DataController{
let defaults = UserDefaults.standard
func getTotalStepsData() -> Int{
let steps = defaults.integer(forKey: "totalSteps")
return steps
}
func setTotalStepsData(_ steps:Int){
defaults.set(steps, forKey: "totalSteps")
}
func getLastDateData() -> Date{
guard
let lastDate = defaults.object(forKey: "lastDate") as? Date
else {
print("ラストデータを取得できません.")
return Date()
}
return lastDate
}
func setLastDateData(_ lastDate:Date){
defaults.set(lastDate, forKey: "lastDate")
}
}
| mit |
lfkdsk/JustUiKit | JustUiKit/utils/ColorExtension.swift | 1 | 1555 | /// MIT License
///
/// Copyright (c) 2017 JustWe
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
import UIKit
extension UIColor {
public convenience init(rgb: UInt, alphaVal: CGFloat? = 1.0) {
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000FF) / 255.0,
alpha: CGFloat(alphaVal!)
)
}
}
| mit |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/DiscountCodeApplication.swift | 1 | 7206 | //
// DiscountCodeApplication.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// Discount code applications capture the intentions of a discount code at the
/// time that it is applied.
open class DiscountCodeApplicationQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = DiscountCodeApplication
/// The method by which the discount's value is allocated to its entitled
/// items.
@discardableResult
open func allocationMethod(alias: String? = nil) -> DiscountCodeApplicationQuery {
addField(field: "allocationMethod", aliasSuffix: alias)
return self
}
/// Specifies whether the discount code was applied successfully.
@discardableResult
open func applicable(alias: String? = nil) -> DiscountCodeApplicationQuery {
addField(field: "applicable", aliasSuffix: alias)
return self
}
/// The string identifying the discount code that was used at the time of
/// application.
@discardableResult
open func code(alias: String? = nil) -> DiscountCodeApplicationQuery {
addField(field: "code", aliasSuffix: alias)
return self
}
/// Which lines of targetType that the discount is allocated over.
@discardableResult
open func targetSelection(alias: String? = nil) -> DiscountCodeApplicationQuery {
addField(field: "targetSelection", aliasSuffix: alias)
return self
}
/// The type of line that the discount is applicable towards.
@discardableResult
open func targetType(alias: String? = nil) -> DiscountCodeApplicationQuery {
addField(field: "targetType", aliasSuffix: alias)
return self
}
/// The value of the discount application.
@discardableResult
open func value(alias: String? = nil, _ subfields: (PricingValueQuery) -> Void) -> DiscountCodeApplicationQuery {
let subquery = PricingValueQuery()
subfields(subquery)
addField(field: "value", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// Discount code applications capture the intentions of a discount code at the
/// time that it is applied.
open class DiscountCodeApplication: GraphQL.AbstractResponse, GraphQLObject, DiscountApplication {
public typealias Query = DiscountCodeApplicationQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "allocationMethod":
guard let value = value as? String else {
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
return DiscountApplicationAllocationMethod(rawValue: value) ?? .unknownValue
case "applicable":
guard let value = value as? Bool else {
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
return value
case "code":
guard let value = value as? String else {
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
return value
case "targetSelection":
guard let value = value as? String else {
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
return DiscountApplicationTargetSelection(rawValue: value) ?? .unknownValue
case "targetType":
guard let value = value as? String else {
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
return DiscountApplicationTargetType(rawValue: value) ?? .unknownValue
case "value":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
return try UnknownPricingValue.create(fields: value)
default:
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
}
/// The method by which the discount's value is allocated to its entitled
/// items.
open var allocationMethod: Storefront.DiscountApplicationAllocationMethod {
return internalGetAllocationMethod()
}
func internalGetAllocationMethod(alias: String? = nil) -> Storefront.DiscountApplicationAllocationMethod {
return field(field: "allocationMethod", aliasSuffix: alias) as! Storefront.DiscountApplicationAllocationMethod
}
/// Specifies whether the discount code was applied successfully.
open var applicable: Bool {
return internalGetApplicable()
}
func internalGetApplicable(alias: String? = nil) -> Bool {
return field(field: "applicable", aliasSuffix: alias) as! Bool
}
/// The string identifying the discount code that was used at the time of
/// application.
open var code: String {
return internalGetCode()
}
func internalGetCode(alias: String? = nil) -> String {
return field(field: "code", aliasSuffix: alias) as! String
}
/// Which lines of targetType that the discount is allocated over.
open var targetSelection: Storefront.DiscountApplicationTargetSelection {
return internalGetTargetSelection()
}
func internalGetTargetSelection(alias: String? = nil) -> Storefront.DiscountApplicationTargetSelection {
return field(field: "targetSelection", aliasSuffix: alias) as! Storefront.DiscountApplicationTargetSelection
}
/// The type of line that the discount is applicable towards.
open var targetType: Storefront.DiscountApplicationTargetType {
return internalGetTargetType()
}
func internalGetTargetType(alias: String? = nil) -> Storefront.DiscountApplicationTargetType {
return field(field: "targetType", aliasSuffix: alias) as! Storefront.DiscountApplicationTargetType
}
/// The value of the discount application.
open var value: PricingValue {
return internalGetValue()
}
func internalGetValue(alias: String? = nil) -> PricingValue {
return field(field: "value", aliasSuffix: alias) as! PricingValue
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
return []
}
}
}
| mit |
hnag409/HIITTimer | HIITimer/ViewController.swift | 1 | 371 | //
// ViewController.swift
// HIITimer
//
// Created by hannah gaskins on 6/30/16.
// Copyright © 2016 hannah gaskins. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
lacklock/ClosuresKit | ClosuresKit/SequenceTypeExtension.swift | 1 | 1727 | //
// SequenceTypeExtension.swift
// ClosuresKit
//
// Created by 卓同学 on 16/4/22.
// Copyright © 2016年 zhuo. All rights reserved.
//
import Foundation
extension SequenceType{
/**
loops through the sequeence to find the match element
it's will stop and return on the first match
if thers isn't any element match, return nil
*/
public func cs_match(@noescape condition:(Self.Generator.Element) throws -> Bool) rethrows -> Self.Generator.Element?{
for element in self {
if try condition(element) {
return element
}
}
return nil
}
/**
Loops through the sequeence to find whether any object matches the closure.
*/
public func cs_any(@noescape condition:(Self.Generator.Element) throws -> Bool) rethrows -> Bool{
for element in self {
if try condition(element) {
return true
}
}
return false
}
/**
Loops through an sequeence to find whether all element match the closure
*/
public func cs_all(@noescape condition:(Self.Generator.Element) throws -> Bool) rethrows -> Bool{
for element in self {
if try !condition(element) {
return false
}
}
return true
}
/**
Loops through an sequeence to find whether no element match the closure
*/
public func cs_none(@noescape condition:(Self.Generator.Element) throws -> Bool) rethrows -> Bool{
for element in self {
if try condition(element) {
return false
}
}
return true
}
} | mit |
NobodyNada/SwiftStack | Sources/SwiftStack/RequestsPrivileges.swift | 1 | 1998 | //
// RequestsPrivileges.swift
// SwiftStack
//
// Created by FelixSFD on 14.02.17.
//
//
import Foundation
/**
This extension contains all requests in the PRIVILEGES section of the StackExchange API Documentation.
- authors: NobodyNada, FelixSFD
*/
public extension APIClient {
// - MARK: /privileges
/**
Fetches all `Privileges`s synchronously.
- parameter parameters: The dictionary of parameters used in the request
- parameter backoffBehavior: The behavior when an `APIRequest` has a backoff
- returns: The list of sites as `APIResponse<Privilege>`
- authors: NobodyNada, FelixSFD
*/
func fetchPrivileges(
parameters: [String:String] = [:],
backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Privilege> {
return try performAPIRequest(
"privileges",
parameters: parameters,
backoffBehavior: backoffBehavior
)
}
/**
Fetches all `Privileges`s asynchronously.
- parameter parameters: The dictionary of parameters used in the request
- parameter backoffBehavior: The behavior when an `APIRequest` has a backoff
- parameter completionHandler: Passes either an `APIResponse<Privilege>?` or an `Error?`
- authors: NobodyNada, FelixSFD
*/
func fetchPrivileges(
parameters: [String: String] = [:],
backoffBehavior: BackoffBehavior = .wait,
completionHandler: @escaping (APIResponse<Privilege>?, Error?) -> ()) {
queue.async {
do {
let response: APIResponse<Privilege> = try self.fetchPrivileges(
parameters: parameters,
backoffBehavior: backoffBehavior
)
completionHandler(response, nil)
} catch {
completionHandler(nil, error)
}
}
}
}
| mit |
sschiau/swift-package-manager | Tests/POSIXTests/ReaddirTests.swift | 2 | 1786 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import POSIX
extension MemoryLayout {
fileprivate static func ofInstance(_: @autoclosure () -> T) -> MemoryLayout<T>.Type {
return MemoryLayout<T>.self
}
}
class ReaddirTests: XCTestCase {
func testName() {
do {
var s = dirent()
withUnsafeMutablePointer(to: &s.d_name) { ptr in
let ptr = UnsafeMutableRawPointer(ptr).assumingMemoryBound(to: UInt8.self)
ptr[0] = UInt8(ascii: "A")
ptr[1] = UInt8(ascii: "B")
ptr[2] = 0
}
XCTAssertEqual(s.name, "AB")
}
do {
var s = dirent()
withUnsafeMutablePointer(to: &s.d_name) { ptr in
let ptr = UnsafeMutableRawPointer(ptr).assumingMemoryBound(to: UInt8.self)
ptr[0] = 0xFF
ptr[1] = 0xFF
ptr[2] = 0
}
XCTAssertEqual(s.name, nil)
}
do {
var s = dirent()
let n = MemoryLayout.ofInstance(s.d_name).size - 1
withUnsafeMutablePointer(to: &s.d_name) { ptr in
let ptr = UnsafeMutableRawPointer(ptr).assumingMemoryBound(to: UInt8.self)
for i in 0 ..< n {
ptr[i] = UInt8(ascii: "A")
}
ptr[n] = 0
}
XCTAssertEqual(s.name, String(repeating: "A", count: n))
}
}
}
| apache-2.0 |
lemberg/connfa-ios | Pods/SwiftDate/Sources/SwiftDate/Formatters/RelativeFormatter/languages/lang_ps.swift | 1 | 3948 | import Foundation
// swiftlint:disable type_name
public class lang_ps: RelativeFormatterLang {
/// Pashto
public static let identifier: String = "ps"
public required init() {}
public func quantifyKey(forValue value: Double) -> RelativeFormatter.PluralForm? {
return (value == 1 ? .one : .other)
}
public var flavours: [String: Any] {
return [
RelativeFormatter.Flavour.long.rawValue: self._long,
RelativeFormatter.Flavour.narrow.rawValue: self._narrow,
RelativeFormatter.Flavour.short.rawValue: self._short
]
}
private var _short: [String: Any] {
return [
"year": [
"previous": "پروسږکال",
"current": "سږکال",
"next": "بل کال",
"past": [
"one": "{0} کال مخکې",
"other": "{0} کاله مخکې"
],
"future": [
"one": "په {0} کال کې",
"other": "په {0} کالونو کې"
]
],
"quarter": [
"previous": "last quarter",
"current": "this quarter",
"next": "next quarter",
"past": "-{0} Q",
"future": "+{0} Q"
],
"month": [
"previous": "last month",
"current": "this month",
"next": "next month",
"past": "-{0} m",
"future": "+{0} m"
],
"week": [
"previous": "last week",
"current": "this week",
"next": "next week",
"past": "-{0} w",
"future": "+{0} w"
],
"day": [
"previous": "yesterday",
"current": "today",
"next": "tomorrow",
"past": "-{0} d",
"future": "+{0} d"
],
"hour": [
"current": "this hour",
"past": "-{0} h",
"future": "+{0} h"
],
"minute": [
"current": "this minute",
"past": "-{0} min",
"future": "+{0} min"
],
"second": [
"current": "now",
"past": "-{0} s",
"future": "+{0} s"
],
"now": "now"
]
}
private var _narrow: [String: Any] {
return [
"year": [
"previous": "پروسږکال",
"current": "سږکال",
"next": "بل کال",
"past": [
"one": "{0} کال مخکې",
"other": "{0} کاله مخکې"
],
"future": [
"one": "په {0} کال کې",
"other": "په {0} کالونو کې"
]
],
"quarter": [
"previous": "last quarter",
"current": "this quarter",
"next": "next quarter",
"past": "-{0} Q",
"future": "+{0} Q"
],
"month": [
"previous": "last month",
"current": "this month",
"next": "next month",
"past": "-{0} m",
"future": "+{0} m"
],
"week": [
"previous": "last week",
"current": "this week",
"next": "next week",
"past": "-{0} w",
"future": "+{0} w"
],
"day": [
"previous": "yesterday",
"current": "today",
"next": "tomorrow",
"past": "-{0} d",
"future": "+{0} d"
],
"hour": [
"current": "this hour",
"past": "-{0} h",
"future": "+{0} h"
],
"minute": [
"current": "this minute",
"past": "-{0} min",
"future": "+{0} min"
],
"second": [
"current": "now",
"past": "-{0} s",
"future": "+{0} s"
],
"now": "now"
]
}
private var _long: [String: Any] {
return [
"year": [
"previous": "پروسږکال",
"current": "سږکال",
"next": "بل کال",
"past": [
"one": "{0} کال مخکې",
"other": "{0} کاله مخکې"
],
"future": [
"one": "په {0} کال کې",
"other": "په {0} کالونو کې"
]
],
"quarter": [
"previous": "last quarter",
"current": "this quarter",
"next": "next quarter",
"past": "-{0} Q",
"future": "+{0} Q"
],
"month": [
"previous": "last month",
"current": "this month",
"next": "next month",
"past": "-{0} m",
"future": "+{0} m"
],
"week": [
"previous": "last week",
"current": "this week",
"next": "next week",
"past": "-{0} w",
"future": "+{0} w"
],
"day": [
"previous": "yesterday",
"current": "today",
"next": "tomorrow",
"past": "-{0} d",
"future": "+{0} d"
],
"hour": [
"current": "this hour",
"past": "-{0} h",
"future": "+{0} h"
],
"minute": [
"current": "this minute",
"past": "-{0} min",
"future": "+{0} min"
],
"second": [
"current": "now",
"past": "-{0} s",
"future": "+{0} s"
],
"now": "now"
]
}
}
| apache-2.0 |
DianQK/Flix | Example/Providers/UniqueButtonTableViewProvider.swift | 1 | 1421 | //
// UniqueButtonTableViewProvider.swift
// Example
//
// Created by DianQK on 04/10/2017.
// Copyright © 2017 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Flix
open class UniqueButtonTableViewProvider: SingleUITableViewCellProvider {
let textLabel = UILabel()
let activityIndicatorView = UIActivityIndicatorView()
public override init() {
super.init()
textLabel.textAlignment = .center
backgroundView = UIView()
selectedBackgroundView = UIView()
contentView.addSubview(textLabel)
textLabel.translatesAutoresizingMaskIntoConstraints = false
textLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
textLabel.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
textLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
textLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
contentView.addSubview(activityIndicatorView)
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
activityIndicatorView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15).isActive = true
activityIndicatorView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
}
}
| mit |
22377832/ccyswift | Attachment/Attachment/AppDelegate.swift | 1 | 2162 | //
// AppDelegate.swift
// Attachment
//
// Created by sks on 17/1/25.
// Copyright © 2017年 chen. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
Sadmansamee/quran-ios | Quran/Bookmark.swift | 1 | 265 | //
// Bookmark.swift
// Quran
//
// Created by Mohamed Afifi on 10/29/16.
// Copyright © 2016 Quran.com. All rights reserved.
//
import Foundation
protocol Bookmark {
var page: Int { get }
var creationDate: Date { get }
var tags: [Tag] { get }
}
| mit |
milseman/swift | test/SILGen/load_from_lvalue_in_plus_zero_context.swift | 4 | 770 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
class A {
lazy var b: B = B()
}
final class B {
var c: C? {
get { return nil }
set {}
}
}
struct C {
let d: String
}
// CHECK-LABEL: sil hidden @{{.*}}test
func test(a: A) {
let s: String?
// CHECK: [[C_TEMP:%.*]] = alloc_stack $Optional<C>
// CHECK: [[TAG:%.*]] = select_enum_addr [[C_TEMP]]
// CHECK: cond_br [[TAG]], [[SOME:bb[0-9]+]], [[NONE:bb[0-9]+]]
// CHECK: [[SOME]]:
// CHECK: [[C_PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[C_TEMP]]
// -- This must be a copy, since we'll immediately destroy the value in the
// temp buffer
// CHECK: [[LOAD:%.*]] = load [copy] [[C_PAYLOAD]]
// CHECK: destroy_addr [[C_TEMP]]
s = a.b.c?.d
print(s)
}
| apache-2.0 |
nodes-vapor/admin-panel | Sources/AdminPanel/Models/AdminPanelUser/Extensions/AdminPanelUser+AdminPanelUserType.swift | 1 | 797 | import Reset
import Vapor
extension AdminPanelUser: AdminPanelUserType {
public typealias Role = AdminPanelUserRole
public static let usernameKey: WritableKeyPath<AdminPanelUser, String> = \.email
public static let passwordKey: WritableKeyPath<AdminPanelUser, String> = \.password
public func didCreate(on req: Request) throws -> Future<Void> {
struct ShouldSpecifyPassword: Decodable {
let shouldSpecifyPassword: Bool?
}
guard
try req.content.syncDecode(ShouldSpecifyPassword.self).shouldSpecifyPassword == true
else {
let config: ResetConfig<AdminPanelUser> = try req.make()
return try config.reset(self, context: .newUserWithoutPassword, on: req)
}
return req.future()
}
}
| mit |
ryanglobus/Augustus | Augustus/Augustus/AUDateLabel.swift | 1 | 2806 | //
// AUDateViewLabel.swift
// Augustus
//
// Created by Ryan Globus on 7/19/15.
// Copyright (c) 2015 Ryan Globus. All rights reserved.
//
import Cocoa
import AppKit
class AUDateLabel: NSView {
var date: Date
var auDelegate: AUDateLabelDelegate?
override var intrinsicContentSize: NSSize {
return CGSize(width: 0, height: 50)
}
convenience init(date: Date) {
self.init(date: date, frame: NSRect())
}
init(date: Date, frame frameRect: NSRect) {
self.date = date
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
NSGraphicsContext.current()?.saveGraphicsState()
// Drawing code here.
self.drawBorders()
self.drawDayOfMonth()
self.drawDayOfWeek()
NSGraphicsContext.current()?.restoreGraphicsState()
}
override func mouseDown(with theEvent: NSEvent) {
if theEvent.clickCount == 2 {
self.auDelegate?.requestNewEventForDateLabel?(self)
} else {
self.auDelegate?.selectDateLabel?(self)
}
}
// TODO fonts and placement are not robust
fileprivate func drawBorders() {
let path = NSBezierPath()
// border below
path.move(to: NSPoint(x: 0, y: 0))
path.line(to: NSPoint(x: self.frame.width, y: 0))
path.lineWidth = 2
path.stroke()
}
fileprivate func drawDayOfMonth() {
let dayOfMonth = (AUModel.calendar as NSCalendar).component(NSCalendar.Unit.day, from: self.date).description
let dayOfMonthAttributes = [NSFontAttributeName: NSFont.boldSystemFont(ofSize: 20)]
let dayOfMonthLabel = NSAttributedString(string: dayOfMonth, attributes: dayOfMonthAttributes)
let x = (self.frame.width - dayOfMonthLabel.size().width) / 2.0
dayOfMonthLabel.draw(at: CGPoint(x: x, y: 0))
}
fileprivate func drawDayOfWeek() {
let dayOfWeekNumber = (AUModel.calendar as NSCalendar).component(NSCalendar.Unit.weekday, from: self.date)
let dayOfWeek = AUModel.calendar.weekdaySymbols[dayOfWeekNumber - 1]
let dayOfWeekAttributes = [NSFontAttributeName: NSFont.systemFont(ofSize: 18)]
let dayOfWeekLabel = NSAttributedString(string: dayOfWeek, attributes: dayOfWeekAttributes)
let x = (self.frame.width - dayOfWeekLabel.size().width) / 2.0
dayOfWeekLabel.draw(at: CGPoint(x: x, y: 25))
}
}
@objc protocol AUDateLabelDelegate {
@objc optional func selectDateLabel(_ dateLabel: AUDateLabel)
@objc optional func requestNewEventForDateLabel(_ dateLabel: AUDateLabel)
}
| gpl-2.0 |
pkx0128/UIKit | MUIPinchGestureRecognizer/MUIPinchGestureRecognizer/ViewController.swift | 1 | 1302 | //
// ViewController.swift
// MUIPinchGestureRecognizer
//
// Created by pankx on 2017/10/11.
// Copyright © 2017年 pankx. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var pinchView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
pinchView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
pinchView.center = view.center
pinchView.backgroundColor = UIColor.blue
view.addSubview(pinchView)
let pinchG = UIPinchGestureRecognizer(target: self, action: #selector(pinchEvent))
pinchView.addGestureRecognizer(pinchG)
}
@objc func pinchEvent(e: UIPinchGestureRecognizer) {
let pf = pinchView.frame
if e.state == .began {
print("pinch Began!")
}else if e.state == .changed {
if pf.width * e.scale > 100 && pf.height * e.scale < 400 {
pinchView.frame = CGRect(x: pf.origin.x, y: pf.origin.y, width: pf.width * e.scale, height: pf.height * e.scale)
}
}else if e.state == .ended {
print("Pinch End")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
iwheelbuy/VK | VK/Object/VK+Object+MarketItem.swift | 1 | 4855 | import Foundation
public extension Object {
/// Объект, описывающий товар
public struct MarketItem: Decodable {
/// Статус доступности товара
public enum Availability: Decodable {
/// Товар доступен
case available
/// Товар удален
case deleted
/// Товар недоступен
case unavailable
/// Неизвестное значение
case unexpected(Int)
init(rawValue: Int) {
switch rawValue {
case 0:
self = .available
case 1:
self = .deleted
case 2:
self = .unavailable
default:
self = .unexpected(rawValue)
}
}
public var rawValue: Int {
switch self {
case .available:
return 0
case .deleted:
return 1
case .unavailable:
return 2
case .unexpected(let value):
return value
}
}
public init(from decoder: Decoder) throws {
var container = try decoder.singleValueContainer()
let rawValue: Int = try container.decode()
self = Object.MarketItem.Availability(rawValue: rawValue)
}
}
/// Категория товара
public struct Category: Decodable {
/// Секция
public struct Section: Decodable {
/// Идентификатор секции
public let id: Int?
/// Название секции
public let name: String?
}
/// Идентификатор категории
public let id: Int?
/// Название категории
public let name: String?
/// Секция
public let section: Object.MarketItem.Category.Section?
}
/// Информация об отметках «Мне нравится»
public struct Likes: Decodable {
/// Число отметок «Мне нравится»
let count: Int?
/// Есть ли отметка «Мне нравится» от текущего пользователя
let user_likes: Object.Boolean?
}
/// Объект, описывающий цену
public struct Price: Decodable {
/// Объект, описывающий информацию о валюте
public struct Currency: Decodable {
/// Идентификатор валюты
public let id: Int?
/// Буквенное обозначение валюты
public let name: String?
}
/// Цена товара в сотых долях единицы валюты
public let amount: String?
/// Объект currency
public let currency: Object.MarketItem.Price.Currency?
/// Строка с локализованной ценой и валютой
public let text: String?
}
/// Статус доступности товара
public let availability: Object.MarketItem.Availability?
/// Возможность комментировать товар для текущего пользователя
public let can_comment: Object.Boolean?
/// Возможность сделать репост товара для текущего пользователя
public let can_repost: Object.Boolean?
/// Категория товара
public let category: Object.MarketItem.Category?
/// Creation date in Unixtime
public let date: Int?
/// Текст описания товара
public let description: String?
/// Идентификатор товара
public let id: Int?
/// Информация об отметках «Мне нравится»
public let likes: Object.MarketItem.Likes?
/// Идентификатор владельца товара
public let owner_id: Int?
/// Изображения товара
public let photos: [Object.Photo]?
/// Цена
public let price: Object.MarketItem.Price?
/// URL of the item photo
public let thumb_photo: String?
/// Название товара
public let title: String?
}
}
| mit |
gerlandiolucena/iosvisits | iOSVisits/Pods/RealmSwift/RealmSwift/Realm.swift | 16 | 29241 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
A `Realm` instance (also referred to as "a Realm") represents a Realm database.
Realms can either be stored on disk (see `init(path:)`) or in memory (see `Configuration`).
`Realm` instances are cached internally, and constructing equivalent `Realm` objects (for example, by using the same
path or identifier) produces limited overhead.
If you specifically want to ensure a `Realm` instance is destroyed (for example, if you wish to open a Realm, check
some property, and then possibly delete the Realm file and re-open it), place the code which uses the Realm within an
`autoreleasepool {}` and ensure you have no other strong references to it.
- warning: `Realm` instances are not thread safe and cannot be shared across threads or dispatch queues. You must
construct a new instance for each thread in which a Realm will be accessed. For dispatch queues, this means
that you must construct a new instance in each block which is dispatched, as a queue is not guaranteed to
run all of its blocks on the same thread.
*/
public final class Realm {
// MARK: Properties
/// The `Schema` used by the Realm.
public var schema: Schema { return Schema(rlmRealm.schema) }
/// The `Configuration` value that was used to create the `Realm` instance.
public var configuration: Configuration { return Configuration.fromRLMRealmConfiguration(rlmRealm.configuration) }
/// Indicates if the Realm contains any objects.
public var isEmpty: Bool { return rlmRealm.isEmpty }
// MARK: Initializers
/**
Obtains an instance of the default Realm.
The default Realm is persisted as *default.realm* under the *Documents* directory of your Application on iOS, and
in your application's *Application Support* directory on OS X.
The default Realm is created using the default `Configuration`, which can be changed by setting the
`Realm.Configuration.defaultConfiguration` property to a new value.
- throws: An `NSError` if the Realm could not be initialized.
*/
public convenience init() throws {
let rlmRealm = try RLMRealm(configuration: RLMRealmConfiguration.default())
self.init(rlmRealm)
}
/**
Obtains a `Realm` instance with the given configuration.
- parameter configuration: A configuration value to use when creating the Realm.
- throws: An `NSError` if the Realm could not be initialized.
*/
public convenience init(configuration: Configuration) throws {
let rlmRealm = try RLMRealm(configuration: configuration.rlmConfiguration)
self.init(rlmRealm)
}
/**
Obtains a `Realm` instance persisted at a specified file URL.
- parameter fileURL: The local URL of the file the Realm should be saved at.
- throws: An `NSError` if the Realm could not be initialized.
*/
public convenience init(fileURL: URL) throws {
var configuration = Configuration.defaultConfiguration
configuration.fileURL = fileURL
try self.init(configuration: configuration)
}
// MARK: Transactions
/**
Performs actions contained within the given block inside a write transaction.
If the block throws an error, the transaction will be canceled and any
changes made before the error will be rolled back.
Only one write transaction can be open at a time for each Realm file. Write
transactions cannot be nested, and trying to begin a write transaction on a
Realm which is already in a write transaction will throw an exception.
Calls to `write` from `Realm` instances for the same Realm file in other
threads or other processes will block until the current write transaction
completes or is cancelled.
Before beginning the write transaction, `write` updates the `Realm`
instance to the latest Realm version, as if `refresh()` had been called,
and generates notifications if applicable. This has no effect if the Realm
was already up to date.
- parameter block: The block containing actions to perform.
- throws: An `NSError` if the transaction could not be completed successfully.
If `block` throws, the function throws the propagated `ErrorType` instead.
*/
public func write(_ block: (() throws -> Void)) throws {
beginWrite()
do {
try block()
} catch let error {
if isInWriteTransaction { cancelWrite() }
throw error
}
if isInWriteTransaction { try commitWrite() }
}
/**
Begins a write transaction on the Realm.
Only one write transaction can be open at a time for each Realm file. Write
transactions cannot be nested, and trying to begin a write transaction on a
Realm which is already in a write transaction will throw an exception.
Calls to `beginWrite` from `Realm` instances for the same Realm file in
other threads or other processes will block until the current write
transaction completes or is cancelled.
Before beginning the write transaction, `beginWrite` updates the `Realm`
instance to the latest Realm version, as if `refresh()` had been called,
and generates notifications if applicable. This has no effect if the Realm
was already up to date.
It is rarely a good idea to have write transactions span multiple cycles of
the run loop, but if you do wish to do so you will need to ensure that the
Realm participating in the write transaction is kept alive until the write
transaction is committed.
*/
public func beginWrite() {
rlmRealm.beginWriteTransaction()
}
/**
Commits all write operations in the current write transaction, and ends
the transaction.
After saving the changes and completing the write transaction, all
notification blocks registered on this specific `Realm` instance are called
synchronously. Notification blocks for `Realm` instances on other threads
and blocks registered for any Realm collection (including those on the
current thread) are scheduled to be called synchronously.
You can skip notifiying specific notification blocks about the changes made
in this write transaction by passing in their associated notification
tokens. This is primarily useful when the write transaction is saving
changes already made in the UI and you do not want to have the notification
block attempt to re-apply the same changes.
The tokens passed to this function must be for notifications for this Realm
which were added on the same thread as the write transaction is being
performed on. Notifications for different threads cannot be skipped using
this method.
- warning: This method may only be called during a write transaction.
- throws: An `NSError` if the transaction could not be written due to
running out of disk space or other i/o errors.
*/
public func commitWrite(withoutNotifying tokens: [NotificationToken] = []) throws {
try rlmRealm.commitWriteTransactionWithoutNotifying(tokens)
}
/**
Reverts all writes made in the current write transaction and ends the transaction.
This rolls back all objects in the Realm to the state they were in at the
beginning of the write transaction, and then ends the transaction.
This restores the data for deleted objects, but does not revive invalidated
object instances. Any `Object`s which were added to the Realm will be
invalidated rather than becoming unmanaged.
Given the following code:
```swift
let oldObject = objects(ObjectType).first!
let newObject = ObjectType()
realm.beginWrite()
realm.add(newObject)
realm.delete(oldObject)
realm.cancelWrite()
```
Both `oldObject` and `newObject` will return `true` for `isInvalidated`,
but re-running the query which provided `oldObject` will once again return
the valid object.
KVO observers on any objects which were modified during the transaction
will be notified about the change back to their initial values, but no
other notifcations are produced by a cancelled write transaction.
- warning: This method may only be called during a write transaction.
*/
public func cancelWrite() {
rlmRealm.cancelWriteTransaction()
}
/**
Indicates whether the Realm is currently in a write transaction.
- warning: Do not simply check this property and then start a write transaction whenever an object needs to be
created, updated, or removed. Doing so might cause a large number of write transactions to be created,
degrading performance. Instead, always prefer performing multiple updates during a single transaction.
*/
public var isInWriteTransaction: Bool {
return rlmRealm.inWriteTransaction
}
// MARK: Adding and Creating objects
/**
Adds or updates an existing object into the Realm.
Only pass `true` to `update` if the object has a primary key. If no objects exist in the Realm with the same
primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values.
When added, all child relationships referenced by this object will also be added to the Realm if they are not
already in it. If the object or any related objects are already being managed by a different Realm an error will be
thrown. Instead, use one of the `create` functions to insert a copy of a managed object into a different Realm.
The object to be added must be valid and cannot have been previously deleted from a Realm (i.e. `isInvalidated`
must be `false`).
- parameter object: The object to be added to this Realm.
- parameter update: If `true`, the Realm will try to find an existing copy of the object (with the same primary
key), and update it. Otherwise, the object will be added.
*/
public func add(_ object: Object, update: Bool = false) {
if update && object.objectSchema.primaryKeyProperty == nil {
throwRealmException("'\(object.objectSchema.className)' does not have a primary key and can not be updated")
}
RLMAddObjectToRealm(object, rlmRealm, update)
}
/**
Adds or updates all the objects in a collection into the Realm.
- see: `add(_:update:)`
- warning: This method may only be called during a write transaction.
- parameter objects: A sequence which contains objects to be added to the Realm.
- parameter update: If `true`, objects that are already in the Realm will be updated instead of added anew.
*/
public func add<S: Sequence>(_ objects: S, update: Bool = false) where S.Iterator.Element: Object {
for obj in objects {
add(obj, update: update)
}
}
/**
Creates or updates a Realm object with a given value, adding it to the Realm and returning it.
Only pass `true` to `update` if the object has a primary key. If no objects exist in
the Realm with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
The `value` argument can be a key-value coding compliant object, an array or dictionary returned from the methods
in `NSJSONSerialization`, or an `Array` containing one element for each managed property. An exception will be
thrown if any required properties are not present and those properties were not defined with default values. Do not
pass in a `LinkingObjects` instance, either by itself or as a member of a collection.
When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as
the properties defined in the model.
- warning: This method may only be called during a write transaction.
- parameter type: The type of the object to create.
- parameter value: The value used to populate the object.
- parameter update: If `true`, the Realm will try to find an existing copy of the object (with the same primary
key), and update it. Otherwise, the object will be added.
- returns: The newly created object.
*/
@discardableResult
public func create<T: Object>(_ type: T.Type, value: Any = [:], update: Bool = false) -> T {
let typeName = (type as Object.Type).className()
if update && schema[typeName]?.primaryKeyProperty == nil {
throwRealmException("'\(typeName)' does not have a primary key and can not be updated")
}
return unsafeDowncast(RLMCreateObjectInRealmWithValue(rlmRealm, typeName, value, update), to: T.self)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `create(_:value:update:)`.
Creates or updates an object with the given class name and adds it to the `Realm`, populating
the object with the given value.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or
dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing one element for each
managed property. An exception will be thrown if any required properties are not present and those properties were
not defined with default values.
When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as
the properties defined in the model.
- warning: This method can only be called during a write transaction.
- parameter className: The class name of the object to create.
- parameter value: The value used to populate the object.
- parameter update: If true will try to update existing objects with the same primary key.
- returns: The created object.
:nodoc:
*/
@discardableResult
public func dynamicCreate(_ typeName: String, value: Any = [:], update: Bool = false) -> DynamicObject {
if update && schema[typeName]?.primaryKeyProperty == nil {
throwRealmException("'\(typeName)' does not have a primary key and can not be updated")
}
return noWarnUnsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, typeName, value, update),
to: DynamicObject.self)
}
// MARK: Deleting objects
/**
Deletes an object from the Realm. Once the object is deleted it is considered invalidated.
- warning: This method may only be called during a write transaction.
- parameter object: The object to be deleted.
*/
public func delete(_ object: Object) {
RLMDeleteObjectFromRealm(object, rlmRealm)
}
/**
Deletes zero or more objects from the Realm.
Do not pass in a slice to a `Results` or any other auto-updating Realm collection
type (for example, the type returned by the Swift `suffix(_:)` standard library
method). Instead, make a copy of the objects to delete using `Array()`, and pass
that instead. Directly passing in a view into an auto-updating collection may
result in 'index out of bounds' exceptions being thrown.
- warning: This method may only be called during a write transaction.
- parameter objects: The objects to be deleted. This can be a `List<Object>`,
`Results<Object>`, or any other Swift `Sequence` whose
elements are `Object`s (subject to the caveats above).
*/
public func delete<S: Sequence>(_ objects: S) where S.Iterator.Element: Object {
for obj in objects {
delete(obj)
}
}
/**
Deletes zero or more objects from the Realm.
- warning: This method may only be called during a write transaction.
- parameter objects: A list of objects to delete.
:nodoc:
*/
public func delete<T: Object>(_ objects: List<T>) {
rlmRealm.deleteObjects(objects._rlmArray)
}
/**
Deletes zero or more objects from the Realm.
- warning: This method may only be called during a write transaction.
- parameter objects: A `Results` containing the objects to be deleted.
:nodoc:
*/
public func delete<T: Object>(_ objects: Results<T>) {
rlmRealm.deleteObjects(objects.rlmResults)
}
/**
Deletes all objects from the Realm.
- warning: This method may only be called during a write transaction.
*/
public func deleteAll() {
RLMDeleteAllObjectsFromRealm(rlmRealm)
}
// MARK: Object Retrieval
/**
Returns all objects of the given type stored in the Realm.
- parameter type: The type of the objects to be returned.
- returns: A `Results` containing the objects.
*/
public func objects<T: Object>(_ type: T.Type) -> Results<T> {
return Results<T>(RLMGetObjects(rlmRealm, (type as Object.Type).className(), nil))
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objects(type:)`.
Returns all objects for a given class name in the Realm.
- parameter typeName: The class name of the objects to be returned.
- returns: All objects for the given class name as dynamic objects
:nodoc:
*/
public func dynamicObjects(_ typeName: String) -> Results<DynamicObject> {
return Results<DynamicObject>(RLMGetObjects(rlmRealm, typeName, nil))
}
/**
Retrieves the single instance of a given object type with the given primary key from the Realm.
This method requires that `primaryKey()` be overridden on the given object class.
- see: `Object.primaryKey()`
- parameter type: The type of the object to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `type`, or `nil` if no instance with the given primary key exists.
*/
public func object<T: Object, K>(ofType type: T.Type, forPrimaryKey key: K) -> T? {
return unsafeBitCast(RLMGetObject(rlmRealm, (type as Object.Type).className(),
dynamicBridgeCast(fromSwift: key)) as! RLMObjectBase?,
to: Optional<T>.self)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objectForPrimaryKey(_:key:)`.
Get a dynamic object with the given class name and primary key.
Returns `nil` if no object exists with the given class name and primary key.
This method requires that `primaryKey()` be overridden on the given subclass.
- see: Object.primaryKey()
- warning: This method is useful only in specialized circumstances.
- parameter className: The class name of the object to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `DynamicObject` or `nil` if an object with the given primary key does not exist.
:nodoc:
*/
public func dynamicObject(ofType typeName: String, forPrimaryKey key: Any) -> DynamicObject? {
return unsafeBitCast(RLMGetObject(rlmRealm, typeName, key) as! RLMObjectBase?, to: Optional<DynamicObject>.self)
}
// MARK: Notifications
/**
Adds a notification handler for changes made to this Realm, and returns a notification token.
Notification handlers are called after each write transaction is committed, independent of the thread or process.
Handler blocks are called on the same thread that they were added on, and may only be added on threads which are
currently within a run loop. Unless you are specifically creating and running a run loop on a background thread,
this will normally only be the main thread.
Notifications can't be delivered as long as the run loop is blocked by other activity. When notifications can't be
delivered instantly, multiple notifications may be coalesced.
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `stop()` on the token.
- parameter block: A block which is called to process Realm notifications. It receives the following parameters:
`notification`: the incoming notification; `realm`: the Realm for which the notification
occurred.
- returns: A token which must be held for as long as you wish to continue receiving change notifications.
*/
public func addNotificationBlock(_ block: @escaping NotificationBlock) -> NotificationToken {
return rlmRealm.addNotificationBlock { rlmNotification, _ in
switch rlmNotification {
case RLMNotification.DidChange:
block(.didChange, self)
case RLMNotification.RefreshRequired:
block(.refreshRequired, self)
default:
fatalError("Unhandled notification type: \(rlmNotification)")
}
}
}
// MARK: Autorefresh and Refresh
/**
Set this property to `true` to automatically update this Realm when changes happen in other threads.
If set to `true` (the default), changes made on other threads will be reflected in this Realm on the next cycle of
the run loop after the changes are committed. If set to `false`, you must manually call `refresh()` on the Realm
to update it to get the latest data.
Note that by default, background threads do not have an active run loop and you will need to manually call
`refresh()` in order to update to the latest version, even if `autorefresh` is set to `true`.
Even with this property enabled, you can still call `refresh()` at any time to update the Realm before the
automatic refresh would occur.
Notifications are sent when a write transaction is committed whether or not automatic refreshing is enabled.
Disabling `autorefresh` on a `Realm` without any strong references to it will not have any effect, and
`autorefresh` will revert back to `true` the next time the Realm is created. This is normally irrelevant as it
means that there is nothing to refresh (as managed `Object`s, `List`s, and `Results` have strong references to the
`Realm` that manages them), but it means that setting `autorefresh = false` in
`application(_:didFinishLaunchingWithOptions:)` and only later storing Realm objects will not work.
Defaults to `true`.
*/
public var autorefresh: Bool {
get {
return rlmRealm.autorefresh
}
set {
rlmRealm.autorefresh = newValue
}
}
/**
Updates the Realm and outstanding objects managed by the Realm to point to the most recent data.
- returns: Whether there were any updates for the Realm. Note that `true` may be returned even if no data actually
changed.
*/
@discardableResult
public func refresh() -> Bool {
return rlmRealm.refresh()
}
// MARK: Invalidation
/**
Invalidates all `Object`s, `Results`, `LinkingObjects`, and `List`s managed by the Realm.
A Realm holds a read lock on the version of the data accessed by it, so
that changes made to the Realm on different threads do not modify or delete the
data seen by this Realm. Calling this method releases the read lock,
allowing the space used on disk to be reused by later write transactions rather
than growing the file. This method should be called before performing long
blocking operations on a background thread on which you previously read data
from the Realm which you no longer need.
All `Object`, `Results` and `List` instances obtained from this `Realm` instance on the current thread are
invalidated. `Object`s and `Array`s cannot be used. `Results` will become empty. The Realm itself remains valid,
and a new read transaction is implicitly begun the next time data is read from the Realm.
Calling this method multiple times in a row without reading any data from the
Realm, or before ever reading any data from the Realm, is a no-op. This method
may not be called on a read-only Realm.
*/
public func invalidate() {
rlmRealm.invalidate()
}
// MARK: Writing a Copy
/**
Writes a compacted and optionally encrypted copy of the Realm to the given local URL.
The destination file cannot already exist.
Note that if this method is called from within a write transaction, the *current* data is written, not the data
from the point when the previous write transaction was committed.
- parameter fileURL: Local URL to save the Realm to.
- parameter encryptionKey: Optional 64-byte encryption key to encrypt the new file with.
- throws: An `NSError` if the copy could not be written.
*/
public func writeCopy(toFile fileURL: URL, encryptionKey: Data? = nil) throws {
try rlmRealm.writeCopy(to: fileURL, encryptionKey: encryptionKey)
}
// MARK: Internal
internal var rlmRealm: RLMRealm
internal init(_ rlmRealm: RLMRealm) {
self.rlmRealm = rlmRealm
}
}
// MARK: Equatable
extension Realm: Equatable {
/// Returns whether two `Realm` isntances are equal.
public static func == (lhs: Realm, rhs: Realm) -> Bool {
return lhs.rlmRealm == rhs.rlmRealm
}
}
// MARK: Notifications
extension Realm {
/// A notification indicating that changes were made to a Realm.
public enum Notification: String {
/**
This notification is posted when the data in a Realm has changed.
`didChange` is posted after a Realm has been refreshed to reflect a write transaction, This can happen when an
autorefresh occurs, `refresh()` is called, after an implicit refresh from `write(_:)`/`beginWrite()`, or after
a local write transaction is committed.
*/
case didChange = "RLMRealmDidChangeNotification"
/**
This notification is posted when a write transaction has been committed to a Realm on a different thread for
the same file.
It is not posted if `autorefresh` is enabled, or if the Realm is refreshed before the notification has a chance
to run.
Realms with autorefresh disabled should normally install a handler for this notification which calls
`refresh()` after doing some work. Refreshing the Realm is optional, but not refreshing the Realm may lead to
large Realm files. This is because an extra copy of the data must be kept for the stale Realm.
*/
case refreshRequired = "RLMRealmRefreshRequiredNotification"
}
}
/// The type of a block to run for notification purposes when the data in a Realm is modified.
public typealias NotificationBlock = (_ notification: Realm.Notification, _ realm: Realm) -> Void
// MARK: Unavailable
extension Realm {
@available(*, unavailable, renamed: "isInWriteTransaction")
public var inWriteTransaction: Bool { fatalError() }
@available(*, unavailable, renamed: "object(ofType:forPrimaryKey:)")
public func objectForPrimaryKey<T: Object>(_ type: T.Type, key: AnyObject) -> T? { fatalError() }
@available(*, unavailable, renamed: "dynamicObject(ofType:forPrimaryKey:)")
public func dynamicObjectForPrimaryKey(_ className: String, key: AnyObject) -> DynamicObject? { fatalError() }
@available(*, unavailable, renamed: "writeCopy(toFile:encryptionKey:)")
public func writeCopyToURL(_ fileURL: NSURL, encryptionKey: Data? = nil) throws { fatalError() }
}
| gpl-3.0 |
renrawnalon/R.swift | Sources/RswiftCore/SwiftTypes/Typealias.swift | 4 | 591 | //
// Typealias.swift
// R.swift
//
// Created by Mathijs Kadijk on 10-12-15.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
struct Typealias: UsedTypesProvider, CustomStringConvertible {
let accessModifier: AccessLevel
let alias: String
let type: Type?
var usedTypes: [UsedType] {
return type?.usedTypes ?? []
}
var description: String {
let accessModifierString = accessModifier.swiftCode
let typeString = type.map { " = \($0)" } ?? ""
return "\(accessModifierString)typealias \(alias)\(typeString)"
}
}
| mit |
coderMONSTER/ioscelebrity | YStar/YStar/Scenes/Controller/TimeAndPlaceVC.swift | 1 | 5409 | //
// TimeAndPlaceVC.swift
// YStar
//
// Created by MONSTER on 2017/7/28.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
import SVProgressHUD
private let KoneCellID = "oneCell"
private let KtwoCellID = "twoCell"
private let KthreeCellID = "threeCell"
class TimeAndPlaceVC: BaseTableViewController,DateSelectorViewDelegate {
var placeString : String = "上海市"
var beginDateString : String = ""
var endDatrString : String = ""
// 点击时间标识
var startOrEnd : Bool = true
// MARK: - 初始化
override func viewDidLoad() {
super.viewDidLoad()
self.title = "时间地址管理"
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0)
}
// MARK: - UITableViewDataSource,UITableViewDelegate
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: KoneCellID, for: indexPath)
cell.detailTextLabel?.text = placeString
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: KtwoCellID, for: indexPath)
cell.detailTextLabel?.text = beginDateString
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: KthreeCellID, for: indexPath)
cell.detailTextLabel?.text = endDatrString
return cell
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 0 {
let choosePlaceVC = ChoosePlaceVC.init(style: .plain)
choosePlaceVC.placeBlock = { (placeCityStr) in
self.placeString = placeCityStr
self.tableView.reloadData()
}
self.navigationController?.pushViewController(choosePlaceVC, animated: true)
}
if indexPath.row == 1 {
let datePickerView = DateSelectorView(delegate: self)
datePickerView.datePicker.minimumDate = NSDate() as Date
startOrEnd = true
datePickerView.showPicker()
}
if indexPath.row == 2 {
let datePickerView = DateSelectorView(delegate: self)
datePickerView.datePicker.minimumDate = NSDate() as Date
startOrEnd = false
datePickerView.showPicker()
}
}
// MARK: - DateSelectorViewDelegate
func chooseDate(datePickerView: DateSelectorView, date: Date) {
if startOrEnd == true {
let dateString = date.string_from(formatter: "yyyy-MM-dd")
self.beginDateString = dateString
self.tableView.reloadData()
} else {
let dateString = date.string_from(formatter: "yyyy-MM-dd")
self.endDatrString = dateString
self.tableView.reloadData()
}
}
// MARK: - 确定修改按钮Action
@IBAction func sureToModifyAction(_ sender: UIButton) {
if self.placeString == "" {
SVProgressHUD.showErrorMessage(ErrorMessage: "约见城市不允许为空", ForDuration: 2.0, completion: nil)
return
}
if self.beginDateString == "" {
SVProgressHUD.showErrorMessage(ErrorMessage: "约见起始日期不允许为空", ForDuration: 2.0, completion: nil)
return
}
if self.endDatrString == "" {
SVProgressHUD.showErrorMessage(ErrorMessage: "约见结束日期不允许为空", ForDuration: 2.0, completion: nil)
return
}
// 比较 约见起始日期 - 约见结束日期
let beginDate = Date.yt_convertDateStrToDate(self.beginDateString, format: "yyyy-MM-dd")
let endDate = Date.yt_convertDateStrToDate(self.endDatrString, format: "yyyy-MM-dd")
let result:ComparisonResult = beginDate.compare(endDate)
if result == ComparisonResult.orderedDescending {
SVProgressHUD.showErrorMessage(ErrorMessage: "约见结束日期不允许小于约见开始日期", ForDuration: 2.0, completion: nil)
return
}
let model = placeAndDateRequestModel()
model.meet_city = self.placeString
model.startdate = self.beginDateString
model.enddate = self.endDatrString
AppAPIHelper.commen().requestPlaceAndDate(model: model, complete: { (response) -> ()? in
if let objects = response as? ResultModel {
if objects.result == 1 {
SVProgressHUD.showSuccessMessage(SuccessMessage: "修改成功", ForDuration: 2.0, completion: {
self.navigationController?.popViewController(animated: true)
})
}
}
return nil
}, error: errorBlockFunc())
}
}
| mit |
erikmartens/NearbyWeather | NearbyWeather/Commons/Factory/Factory+UINavigationController.swift | 1 | 2217 | //
// Factory+NavigationController.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 19.04.20.
// Copyright © 2020 Erik Maximilian Martens. All rights reserved.
//
import UIKit.UINavigationController
extension Factory {
struct NavigationController: FactoryFunction {
enum NavigationControllerType {
case standard
case standardTabbed(tabTitle: String? = nil, systemImageName: String? = nil)
}
typealias InputType = NavigationControllerType
typealias ResultType = UINavigationController
static func make(fromType type: InputType) -> ResultType {
let navigationController = UINavigationController()
let appearance = UINavigationBarAppearance()
appearance.configureWithDefaultBackground()
appearance.titleTextAttributes = [.foregroundColor: Constants.Theme.Color.ViewElement.Label.titleDark]
appearance.buttonAppearance = UIBarButtonItemAppearance(style: .plain)
navigationController.navigationBar.standardAppearance = appearance
navigationController.navigationBar.barTintColor = Constants.Theme.Color.MarqueColors.standardMarque
navigationController.navigationBar.tintColor = Constants.Theme.Color.MarqueColors.standardMarque
navigationController.navigationBar.isTranslucent = true
navigationController.navigationBar.barStyle = .default
navigationController.navigationBar.scrollEdgeAppearance = .none
switch type {
case .standard:
break
case let .standardTabbed(tabTitle, systemImageName):
navigationController.tabBarItem.title = tabTitle
let tabImage: UIImage
if let systemImageName = systemImageName {
tabImage = UIImage(
systemName: systemImageName,
withConfiguration: UIImage.SymbolConfiguration(weight: .semibold).applying(UIImage.SymbolConfiguration(scale: .large))
)?
.trimmingTransparentPixels()?
.withRenderingMode(.alwaysTemplate) ?? UIImage()
} else {
tabImage = UIImage()
}
navigationController.tabBarItem.image = tabImage
}
return navigationController
}
}
}
| mit |
fr500/RetroArch | pkg/apple/OnScreenKeyboard/EmulatorKeyboardViewModel.swift | 6 | 1957 | //
// EmulatorKeyboardViewModel.swift
// RetroArchiOS
//
// Created by Yoshi Sugawara on 3/3/22.
// Copyright © 2022 RetroArch. All rights reserved.
//
struct KeyPosition {
let row: Int
let column: Int
}
@objc class EmulatorKeyboardViewModel: NSObject, KeyRowsDataSource {
var keys = [[KeyCoded]]()
var alternateKeys: [[KeyCoded]]?
var modifiers: [Int16: KeyCoded]?
var isDraggable = true
@objc weak var delegate: EmulatorKeyboardKeyPressedDelegate?
@objc weak var modifierDelegate: EmulatorKeyboardModifierPressedDelegate?
init(keys: [[KeyCoded]], alternateKeys: [[KeyCoded]]? = nil) {
self.keys = keys
self.alternateKeys = alternateKeys
}
func createView() -> EmulatorKeyboardView {
let view = EmulatorKeyboardView()
view.viewModel = self
return view
}
func keyForPositionAt(_ position: KeyPosition) -> KeyCoded? {
guard position.row < keys.count else {
return nil
}
let row = keys[position.row]
guard position.column < row.count else {
return nil
}
return row[position.column]
}
func modifierKeyToggleStateForKey(_ key: KeyCoded) -> Bool {
return key.isModifier && (modifierDelegate?.isModifierEnabled(key: key) ?? false)
}
func keyPressed(_ key: KeyCoded) {
if key.isModifier {
let isPressed = modifierDelegate?.isModifierEnabled(key: key) ?? false
modifierDelegate?.modifierPressedWithKey(key, enable: !isPressed)
return
}
delegate?.keyDown(key)
}
func keyReleased(_ key: KeyCoded) {
if key.isModifier {
return
}
delegate?.keyUp(key)
}
// KeyCoded can support a shifted key label
// view can update with shifted key labels?
// cluster can support alternate keys and view can swap them out?
}
| gpl-3.0 |
TeachersPayTeachers/PerspectivePhotoBrowser | Pod/Classes/Extensions/UICollectionView.swift | 1 | 892 |
extension UICollectionView {
func widthForCell(withNumberOfColumns numberOfColumns: Int) -> CGFloat {
let collectionViewFlowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
let leftInset = collectionViewFlowLayout.sectionInset.left
let rightInset = collectionViewFlowLayout.sectionInset.right
let lineSpacing = collectionViewFlowLayout.minimumLineSpacing
let contentWidth = (bounds.width - leftInset - rightInset - lineSpacing * CGFloat(numberOfColumns - 1)) / CGFloat(numberOfColumns)
return contentWidth
}
func minimumHeight() -> CGFloat {
let collectionViewFlowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
let totalHeight = bounds.height - collectionViewFlowLayout.sectionInset.top - collectionViewFlowLayout.sectionInset.bottom - self.contentInset.bottom - self.contentInset.top
return totalHeight
}
}
| mit |
silt-lang/silt | Sources/Mantle/Invert.swift | 1 | 8024 | /// Invert.swift
///
/// Copyright 2017-2018, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
import Lithosphere
import Moho
import Basic
extension TypeChecker {
/// An inversion is a substitution mapping the free variables in the spine of
/// an applied metavariable to TT terms.
///
/// An inversion may fail to create a non-trivial substitution map. Thus,
/// we also tag the inversion with the arity of the type so we don't lie
/// to the signature while solving.
struct Inversion: CustomStringConvertible {
let substitution: [(Var, Term<TT>)]
let arity: Int
var description: String {
let invBody = self.substitution.map({ (variable, term) in
return "\(variable) |-> \(term)"
}).joined(separator: ", ")
return "Inversion[\(invBody)]"
}
}
/// Attempts to generate an inversion from a sequence of eliminators.
///
/// Given a metavariable `($0: T)` with spine `[e1, e2, ..., en]` and a
/// target term `t`, inversion attempts to find a value for `$0` that solves
/// the equation `$0[e1, e2, ..., en] ≡ t`.
func invert(_ elims: [Elim<Term<TT>>]) -> Validation<Set<Meta>, Inversion> {
guard let args = elims.mapM({ $0.applyTerm }) else {
return .failure([])
}
let mvArgs = args.mapM(self.checkSpineArgument)
switch mvArgs {
case .failure(.fail(_)):
return .failure([])
case let .failure(.collect(mvs)):
return .failure(mvs)
case let .success(mvArgs):
guard let inv = self.tryGenerateInversion(mvArgs) else {
return .failure([])
}
return .success(inv)
}
}
/// Checks that the pattern condition holds before generating an inversion.
///
/// The list of variables must be linear.
func tryGenerateInversion(_ vars: [Var]) -> Inversion? {
guard vars.count == Set(vars).count else {
return nil
}
guard !vars.isEmpty else {
return Inversion(substitution: [], arity: vars.count)
}
let zips = zip((0..<vars.count).reversed(), vars)
let subs = zips.map({ (idx, v) -> (Var, Term<TT>) in
return (v, TT.apply(.variable(Var(wildcardName, UInt(idx))), []))
})
return Inversion(substitution: subs, arity: subs.count)
}
typealias SpineCheck = Validation<Collect<(), Set<Meta>>, Var>
func checkSpineArgument(_ arg: Term<TT>) -> SpineCheck {
switch self.toWeakHeadNormalForm(arg) {
case let .notBlocked(t):
switch self.toWeakHeadNormalForm(self.etaContract(t)).ignoreBlocking {
case let .apply(.variable(v), vArgs):
guard vArgs.mapM({ $0.projectTerm }) != nil else {
return .failure(.fail(()))
}
return .success(v)
case let .constructor(dataCon, dataArgs):
print(dataCon, dataArgs)
fatalError("Support inversion of constructor spines")
default:
return .failure(.fail(()))
}
case let .onHead(mv, _):
return .failure(.collect([mv]))
case let .onMetas(mvs, _, _):
return .failure(.collect(mvs))
}
}
}
extension TypeChecker where PhaseState == SolvePhaseState {
// typealias InversionResult<T> = Validation<Collect<Var, Set<Meta>>, T>
private func isIdentity(_ ts: [(Var, Term<TT>)]) -> Bool {
for (v, u) in ts {
switch self.toWeakHeadNormalForm(u).ignoreBlocking {
case let .apply(.variable(v2), xs) where xs.isEmpty:
if v == v2 {
continue
}
return false
default:
return false
}
}
return true
}
// Takes a meta inversion and applies it to a term. If substitution encounters
// a free variable, this function will fail and return that variable. If
// inversion fails because of unsolved metas, the substitution will
// also fail and return the set of blocking metas.
func applyInversion(
_ inversion: Inversion, to term: Term<TT>, in ctx: Context
) -> Validation<Collect<Var, Set<Meta>>, Meta.Binding> {
guard isIdentity(inversion.substitution) else {
return self.applyInversionSubstitution(inversion.substitution, term).map {
return Meta.Binding(arity: inversion.arity, body: $0)
}
}
// Optimization: The identity substitution requires no work.
guard ctx.count != inversion.substitution.count else {
return .success(Meta.Binding(arity: inversion.arity, body: term))
}
let fvs = freeVars(term)
let invVars = inversion.substitution.map { $0.0 }
guard fvs.all.isSubset(of: invVars) else {
return self.applyInversionSubstitution(inversion.substitution, term).map {
return Meta.Binding(arity: inversion.arity, body: $0)
}
}
return .success(Meta.Binding(arity: inversion.arity, body: term))
}
private func applyInversionSubstitution(
_ subst: [(Var, Term<TT>)], _ term: Term<TT>
) -> Validation<Collect<Var, Set<Meta>>, Term<TT>> {
func invert(_ str: UInt, _ v0: Var) -> Either<Var, Term<TT>> {
guard let v = v0.strengthen(0, by: str) else {
return .right(TT.apply(.variable(v0), []))
}
guard let (_, substVar) = subst.first(where: { $0.0 == v }) else {
return .left(v)
}
return .right(substVar.forceApplySubstitution(.weaken(Int(str)),
self.eliminate))
}
func applyInversion(
after idx: UInt, _ t: Term<TT>
) -> Validation<Collect<Var, Set<Meta>>, Term<TT>> {
switch self.toWeakHeadNormalForm(t).ignoreBlocking {
case .refl:
return .success(.refl)
case .type:
return .success(.type)
case let .lambda(body):
switch applyInversion(after: idx + 1, body) {
case let .failure(f):
return .failure(f)
case let .success(bdy):
return .success(TT.lambda(bdy))
}
case let .pi(domain, codomain):
let invDomain = applyInversion(after: idx, domain)
let invCodomain = applyInversion(after: idx + 1, codomain)
switch invDomain.merge2(invCodomain) {
case let .success((dom, cod)):
return .success(TT.pi(dom, cod))
case let .failure(e):
return .failure(e)
}
case let .equal(type, lhs, rhs):
let invType = applyInversion(after: idx, type)
let invLHS = applyInversion(after: idx, lhs)
let invRHS = applyInversion(after: idx, rhs)
switch invType.merge2(invLHS).merge2(invRHS) {
case let .success(((type2, x2), y2)):
return .success(TT.equal(type2, x2, y2))
case let .failure(e):
return .failure(e)
}
case let .constructor(dataCon, args):
switch args.mapM({ arg in applyInversion(after: idx, arg) }) {
case let .success(args2):
return .success(TT.constructor(dataCon, args2))
case let .failure(e):
return .failure(e)
}
case let .apply(h, elims):
typealias InvElim = Validation<Collect<Var, Set<Meta>>, Elim<TT>>
let invElims = elims.mapM({ (e) -> InvElim in
switch e {
case let .apply(t2):
return applyInversion(after: idx, t2).map(Elim<TT>.apply)
case .project(_):
return .success(e)
}
})
switch h {
case let .meta(mv):
switch invElims {
case let .failure(.collect(mvs)):
return .failure(.collect(mvs.union([mv])))
case .failure(.fail(_)):
return .failure(.collect(Set([mv])))
default:
return invElims.map { TT.apply(h, $0) }
}
case .definition(_):
return invElims.map { TT.apply(h, $0) }
case let .variable(v):
switch invert(idx, v) {
case let .right(inv):
return invElims.map { self.eliminate(inv, $0) }
case let .left(e):
return .failure(.fail(e))
}
}
}
}
return applyInversion(after: 0, term)
}
}
| mit |
stephencelis/SQLite.swift | Tests/SQLiteTests/Typed/QueryIntegrationTests.swift | 1 | 11138 | import XCTest
#if SQLITE_SWIFT_STANDALONE
import sqlite3
#elseif SQLITE_SWIFT_SQLCIPHER
import SQLCipher
#elseif os(Linux)
import CSQLite
#else
import SQLite3
#endif
@testable import SQLite
class QueryIntegrationTests: SQLiteTestCase {
let id = Expression<Int64>("id")
let email = Expression<String>("email")
let age = Expression<Int>("age")
override func setUpWithError() throws {
try super.setUpWithError()
try createUsersTable()
}
// MARK: -
func test_select() throws {
let managerId = Expression<Int64>("manager_id")
let managers = users.alias("managers")
let alice = try db.run(users.insert(email <- "alice@example.com"))
_ = try db.run(users.insert(email <- "betsy@example.com", managerId <- alice))
for user in try db.prepare(users.join(managers, on: managers[id] == users[managerId])) {
_ = user[users[managerId]]
}
}
func test_prepareRowIterator() throws {
let names = ["a", "b", "c"]
try insertUsers(names)
let emailColumn = Expression<String>("email")
let emails = try db.prepareRowIterator(users).map { $0[emailColumn] }
XCTAssertEqual(names.map({ "\($0)@example.com" }), emails.sorted())
}
func test_ambiguousMap() throws {
let names = ["a", "b", "c"]
try insertUsers(names)
let emails = try db.prepare("select email from users", []).map { $0[0] as! String }
XCTAssertEqual(names.map({ "\($0)@example.com" }), emails.sorted())
}
func test_select_optional() throws {
let managerId = Expression<Int64?>("manager_id")
let managers = users.alias("managers")
let alice = try db.run(users.insert(email <- "alice@example.com"))
_ = try db.run(users.insert(email <- "betsy@example.com", managerId <- alice))
for user in try db.prepare(users.join(managers, on: managers[id] == users[managerId])) {
_ = user[users[managerId]]
}
}
func test_select_codable() throws {
let table = Table("codable")
try db.run(table.create { builder in
builder.column(Expression<Int>("int"))
builder.column(Expression<String>("string"))
builder.column(Expression<Bool>("bool"))
builder.column(Expression<Double>("float"))
builder.column(Expression<Double>("double"))
builder.column(Expression<Date>("date"))
builder.column(Expression<UUID>("uuid"))
builder.column(Expression<String?>("optional"))
builder.column(Expression<Data>("sub"))
})
let value1 = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4,
date: Date(timeIntervalSince1970: 0), uuid: testUUIDValue, optional: nil, sub: nil)
let value = TestCodable(int: 5, string: "6", bool: true, float: 7, double: 8,
date: Date(timeIntervalSince1970: 5000), uuid: testUUIDValue, optional: "optional", sub: value1)
try db.run(table.insert(value))
let rows = try db.prepare(table)
let values: [TestCodable] = try rows.map({ try $0.decode() })
XCTAssertEqual(values.count, 1)
XCTAssertEqual(values[0].int, 5)
XCTAssertEqual(values[0].string, "6")
XCTAssertEqual(values[0].bool, true)
XCTAssertEqual(values[0].float, 7)
XCTAssertEqual(values[0].double, 8)
XCTAssertEqual(values[0].date, Date(timeIntervalSince1970: 5000))
XCTAssertEqual(values[0].uuid, testUUIDValue)
XCTAssertEqual(values[0].optional, "optional")
XCTAssertEqual(values[0].sub?.int, 1)
XCTAssertEqual(values[0].sub?.string, "2")
XCTAssertEqual(values[0].sub?.bool, true)
XCTAssertEqual(values[0].sub?.float, 3)
XCTAssertEqual(values[0].sub?.double, 4)
XCTAssertEqual(values[0].sub?.date, Date(timeIntervalSince1970: 0))
XCTAssertNil(values[0].sub?.optional)
XCTAssertNil(values[0].sub?.sub)
}
func test_scalar() throws {
XCTAssertEqual(0, try db.scalar(users.count))
XCTAssertEqual(false, try db.scalar(users.exists))
try insertUsers("alice")
XCTAssertEqual(1, try db.scalar(users.select(id.average)))
}
func test_pluck() throws {
let rowid = try db.run(users.insert(email <- "alice@example.com"))
XCTAssertEqual(rowid, try db.pluck(users)![id])
}
func test_insert() throws {
let id = try db.run(users.insert(email <- "alice@example.com"))
XCTAssertEqual(1, id)
}
func test_insert_many() throws {
let id = try db.run(users.insertMany([[email <- "alice@example.com"], [email <- "geoff@example.com"]]))
XCTAssertEqual(2, id)
}
func test_insert_many_encodables() throws {
let table = Table("codable")
try db.run(table.create { builder in
builder.column(Expression<Int?>("int"))
builder.column(Expression<String?>("string"))
builder.column(Expression<Bool?>("bool"))
builder.column(Expression<Double?>("float"))
builder.column(Expression<Double?>("double"))
builder.column(Expression<Date?>("date"))
builder.column(Expression<UUID?>("uuid"))
})
let value1 = TestOptionalCodable(int: 5, string: "6", bool: true, float: 7, double: 8,
date: Date(timeIntervalSince1970: 5000), uuid: testUUIDValue)
let valueWithNils = TestOptionalCodable(int: nil, string: nil, bool: nil, float: nil, double: nil, date: nil, uuid: nil)
try db.run(table.insertMany([value1, valueWithNils]))
let rows = try db.prepare(table)
let values: [TestOptionalCodable] = try rows.map({ try $0.decode() })
XCTAssertEqual(values.count, 2)
}
func test_upsert() throws {
try XCTSkipUnless(db.satisfiesMinimumVersion(minor: 24))
let fetchAge = { () throws -> Int? in
try self.db.pluck(self.users.filter(self.email == "alice@example.com")).flatMap { $0[self.age] }
}
let id = try db.run(users.upsert(email <- "alice@example.com", age <- 30, onConflictOf: email))
XCTAssertEqual(1, id)
XCTAssertEqual(30, try fetchAge())
let nextId = try db.run(users.upsert(email <- "alice@example.com", age <- 42, onConflictOf: email))
XCTAssertEqual(1, nextId)
XCTAssertEqual(42, try fetchAge())
}
func test_update() throws {
let changes = try db.run(users.update(email <- "alice@example.com"))
XCTAssertEqual(0, changes)
}
func test_delete() throws {
let changes = try db.run(users.delete())
XCTAssertEqual(0, changes)
}
func test_union() throws {
let expectedIDs = [
try db.run(users.insert(email <- "alice@example.com")),
try db.run(users.insert(email <- "sally@example.com"))
]
let query1 = users.filter(email == "alice@example.com")
let query2 = users.filter(email == "sally@example.com")
let actualIDs = try db.prepare(query1.union(query2)).map { $0[id] }
XCTAssertEqual(expectedIDs, actualIDs)
let query3 = users.select(users[*], Expression<Int>(literal: "1 AS weight")).filter(email == "sally@example.com")
let query4 = users.select(users[*], Expression<Int>(literal: "2 AS weight")).filter(email == "alice@example.com")
let sql = query3.union(query4).order(Expression<Int>(literal: "weight")).asSQL()
XCTAssertEqual(sql,
"""
SELECT "users".*, 1 AS weight FROM "users" WHERE ("email" = 'sally@example.com') UNION \
SELECT "users".*, 2 AS weight FROM "users" WHERE ("email" = 'alice@example.com') ORDER BY weight
""")
let orderedIDs = try db.prepare(query3.union(query4).order(Expression<Int>(literal: "weight"), email)).map { $0[id] }
XCTAssertEqual(Array(expectedIDs.reversed()), orderedIDs)
}
func test_no_such_column() throws {
let doesNotExist = Expression<String>("doesNotExist")
try insertUser("alice")
let row = try db.pluck(users.filter(email == "alice@example.com"))!
XCTAssertThrowsError(try row.get(doesNotExist)) { error in
if case QueryError.noSuchColumn(let name, _) = error {
XCTAssertEqual("\"doesNotExist\"", name)
} else {
XCTFail("unexpected error: \(error)")
}
}
}
func test_catchConstraintError() throws {
try db.run(users.insert(email <- "alice@example.com"))
do {
try db.run(users.insert(email <- "alice@example.com"))
XCTFail("expected error")
} catch let Result.error(_, code, _) where code == SQLITE_CONSTRAINT {
// expected
} catch let error {
XCTFail("unexpected error: \(error)")
}
}
// https://github.com/stephencelis/SQLite.swift/issues/285
func test_order_by_random() throws {
try insertUsers(["a", "b", "c'"])
let result = Array(try db.prepare(users.select(email).order(Expression<Int>.random()).limit(1)))
XCTAssertEqual(1, result.count)
}
func test_with_recursive() throws {
let nodes = Table("nodes")
let id = Expression<Int64>("id")
let parent = Expression<Int64?>("parent")
let value = Expression<Int64>("value")
try db.run(nodes.create { builder in
builder.column(id)
builder.column(parent)
builder.column(value)
})
try db.run(nodes.insertMany([
[id <- 0, parent <- nil, value <- 2],
[id <- 1, parent <- 0, value <- 4],
[id <- 2, parent <- 0, value <- 9],
[id <- 3, parent <- 2, value <- 8],
[id <- 4, parent <- 2, value <- 7],
[id <- 5, parent <- 4, value <- 3]
]))
// Compute the sum of the values of node 5 and its ancestors
let ancestors = Table("ancestors")
let sum = try db.scalar(
ancestors
.select(value.sum)
.with(ancestors,
columns: [id, parent, value],
recursive: true,
as: nodes
.where(id == 5)
.union(all: true,
nodes.join(ancestors, on: nodes[id] == ancestors[parent])
.select(nodes[id], nodes[parent], nodes[value])
)
)
)
XCTAssertEqual(21, sum)
}
}
extension Connection {
func satisfiesMinimumVersion(minor: Int, patch: Int = 0) -> Bool {
guard let version = try? scalar("SELECT sqlite_version()") as? String else { return false }
let components = version.split(separator: ".", maxSplits: 3).compactMap { Int($0) }
guard components.count == 3 else { return false }
return components[1] >= minor && components[2] >= patch
}
}
| mit |
jjatie/Charts | ChartsDemo-iOS/Swift/Demos/AnotherBarChartViewController.swift | 1 | 2848 | //
// AnotherBarChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
#if canImport(UIKit)
import UIKit
#endif
import Charts
class AnotherBarChartViewController: DemoBaseViewController {
@IBOutlet var chartView: BarChartView!
@IBOutlet var sliderX: UISlider!
@IBOutlet var sliderY: UISlider!
@IBOutlet var sliderTextX: UITextField!
@IBOutlet var sliderTextY: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "Another Bar Chart"
options = [.toggleValues,
.toggleHighlight,
.animateX,
.animateY,
.animateXY,
.saveToGallery,
.togglePinchZoom,
.toggleData,
.toggleBarBorders]
chartView.delegate = self
chartView.chartDescription.isEnabled = false
chartView.maxVisibleCount = 60
chartView.isPinchZoomEnabled = false
chartView.isDrawBarShadowEnabled = false
let xAxis = chartView.xAxis
xAxis.labelPosition = .bottom
chartView.legend.isEnabled = false
sliderX.value = 10
sliderY.value = 100
slidersValueChanged(nil)
}
override func updateChartData() {
if shouldHideData {
chartView.data = nil
return
}
setDataCount(Int(sliderX.value) + 1, range: Double(sliderY.value))
}
func setDataCount(_ count: Int, range: Double) {
let yVals = (0 ..< count).map { (i) -> BarChartDataEntry in
let mult = range + 1
let val = Double(arc4random_uniform(UInt32(mult))) + mult / 3
return BarChartDataEntry(x: Double(i), y: val)
}
var set1: BarChartDataSet!
if let set = chartView.data?.first as? BarChartDataSet {
set1 = set
set1?.replaceEntries(yVals)
chartView.data?.notifyDataChanged()
chartView.notifyDataSetChanged()
} else {
set1 = BarChartDataSet(entries: yVals, label: "Data Set")
set1.colors = ChartColorTemplates.vordiplom
set1.isDrawValuesEnabled = false
let data = BarChartData(dataSet: set1)
chartView.data = data
chartView.fitBars = true
}
chartView.setNeedsDisplay()
}
override func optionTapped(_ option: Option) {
super.handleOption(option, forChartView: chartView)
}
// MARK: - Actions
@IBAction func slidersValueChanged(_: Any?) {
sliderTextX.text = "\(Int(sliderX.value))"
sliderTextY.text = "\(Int(sliderY.value))"
updateChartData()
}
}
| apache-2.0 |
JakubTudruj/SweetCherry | SweetCherry/Protocols/SweetCherryConfigurable.swift | 1 | 770 | //
// SweetCherryConfigurableProtocol.swift
// SweetCherry
//
// Created by Jakub Tudruj on 25/02/2017.
// Copyright © 2017 Jakub Tudruj. All rights reserved.
//
import Foundation
import Alamofire
import ObjectMapper
public protocol SweetCherryConfigurable {
var url: String? {get set}
var standardHeaders: HTTPHeaders? {get set}
var authHeaders: HTTPHeaders? {get set}
var logger: SweetCherryLoggable? {get set}
func register(logger: SweetCherryLoggable)
var validResponse: SweetCherryValidResponseConfigurable {get set}
var mainSuccess: ((DataResponse<Any>) -> ())? {get set}
var mainFailure: SweetCherry.FailureHandler? {get set}
var mainCompletion: SweetCherry.CompletionHandler<Mappable>? {get set}
}
| mit |
strangeliu/firefox-ios | Client/Frontend/Browser/TabTrayController.swift | 2 | 31298 | /* 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 SnapKit
struct TabTrayControllerUX {
static let CornerRadius = CGFloat(4.0)
static let BackgroundColor = UIConstants.AppBackgroundColor
static let CellBackgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1)
static let TextBoxHeight = CGFloat(32.0)
static let FaviconSize = CGFloat(18.0)
static let Margin = CGFloat(15)
static let ToolbarBarTintColor = UIConstants.AppBackgroundColor
static let ToolbarButtonOffset = CGFloat(10.0)
static let TabTitleTextFont = UIConstants.DefaultSmallFontBold
static let CloseButtonSize = CGFloat(18.0)
static let CloseButtonMargin = CGFloat(6.0)
static let CloseButtonEdgeInset = CGFloat(10)
static let NumberOfColumnsThin = 1
static let NumberOfColumnsWide = 3
static let CompactNumberOfColumnsThin = 2
// Moved from UIConstants temporarily until animation code is merged
static var StatusBarHeight: CGFloat {
if UIScreen.mainScreen().traitCollection.verticalSizeClass == .Compact {
return 0
}
return 20
}
}
struct LightTabCellUX {
static let TabTitleTextColor = UIColor.blackColor()
}
struct DarkTabCellUX {
static let TabTitleTextColor = UIColor.whiteColor()
}
protocol TabCellDelegate: class {
func tabCellDidClose(cell: TabCell)
}
class TabCell: UICollectionViewCell {
enum Style {
case Light
case Dark
}
static let Identifier = "TabCellIdentifier"
var style: Style = .Light {
didSet {
applyStyle(style)
}
}
let backgroundHolder = UIView()
let background = UIImageViewAligned()
let titleText: UILabel
let innerStroke: InnerStrokedView
let favicon: UIImageView = UIImageView()
let closeButton: UIButton
var title: UIVisualEffectView!
var animator: SwipeAnimator!
weak var delegate: TabCellDelegate?
// Changes depending on whether we're full-screen or not.
var margin = CGFloat(0)
override init(frame: CGRect) {
self.backgroundHolder.backgroundColor = UIColor.whiteColor()
self.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
self.backgroundHolder.clipsToBounds = true
self.backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor
self.background.contentMode = UIViewContentMode.ScaleAspectFill
self.background.clipsToBounds = true
self.background.userInteractionEnabled = false
self.background.alignLeft = true
self.background.alignTop = true
self.favicon.backgroundColor = UIColor.clearColor()
self.favicon.layer.cornerRadius = 2.0
self.favicon.layer.masksToBounds = true
self.titleText = UILabel()
self.titleText.textAlignment = NSTextAlignment.Left
self.titleText.userInteractionEnabled = false
self.titleText.numberOfLines = 1
self.titleText.font = TabTrayControllerUX.TabTitleTextFont
self.closeButton = UIButton()
self.closeButton.setImage(UIImage(named: "stop"), forState: UIControlState.Normal)
self.closeButton.imageEdgeInsets = UIEdgeInsetsMake(TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset)
self.innerStroke = InnerStrokedView(frame: self.backgroundHolder.frame)
self.innerStroke.layer.backgroundColor = UIColor.clearColor().CGColor
super.init(frame: frame)
self.opaque = true
self.animator = SwipeAnimator(animatingView: self.backgroundHolder, container: self)
self.closeButton.addTarget(self.animator, action: "SELcloseWithoutGesture", forControlEvents: UIControlEvents.TouchUpInside)
contentView.addSubview(backgroundHolder)
backgroundHolder.addSubview(self.background)
backgroundHolder.addSubview(innerStroke)
// Default style is light
applyStyle(style)
self.accessibilityCustomActions = [
UIAccessibilityCustomAction(name: NSLocalizedString("Close", comment: "Accessibility label for action denoting closing a tab in tab list (tray)"), target: self.animator, selector: "SELcloseWithoutGesture")
]
}
private func applyStyle(style: Style) {
self.title?.removeFromSuperview()
let title: UIVisualEffectView
switch style {
case .Light:
title = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight))
self.titleText.textColor = LightTabCellUX.TabTitleTextColor
case .Dark:
title = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
self.titleText.textColor = DarkTabCellUX.TabTitleTextColor
}
titleText.backgroundColor = UIColor.clearColor()
title.layer.shadowColor = UIColor.blackColor().CGColor
title.layer.shadowOpacity = 0.2
title.layer.shadowOffset = CGSize(width: 0, height: 0.5)
title.layer.shadowRadius = 0
title.addSubview(self.closeButton)
title.addSubview(self.titleText)
title.addSubview(self.favicon)
backgroundHolder.addSubview(title)
self.title = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let w = frame.width
let h = frame.height
backgroundHolder.frame = CGRect(x: margin,
y: margin,
width: w,
height: h)
background.frame = CGRect(origin: CGPointMake(0, 0), size: backgroundHolder.frame.size)
title.frame = CGRect(x: 0,
y: 0,
width: backgroundHolder.frame.width,
height: TabTrayControllerUX.TextBoxHeight)
favicon.frame = CGRect(x: 6,
y: (TabTrayControllerUX.TextBoxHeight - TabTrayControllerUX.FaviconSize)/2,
width: TabTrayControllerUX.FaviconSize,
height: TabTrayControllerUX.FaviconSize)
let titleTextLeft = favicon.frame.origin.x + favicon.frame.width + 6
titleText.frame = CGRect(x: titleTextLeft,
y: 0,
width: title.frame.width - titleTextLeft - margin - TabTrayControllerUX.CloseButtonSize - TabTrayControllerUX.CloseButtonMargin * 2,
height: title.frame.height)
innerStroke.frame = background.frame
closeButton.snp_makeConstraints { make in
make.size.equalTo(title.snp_height)
make.trailing.centerY.equalTo(title)
}
let top = (TabTrayControllerUX.TextBoxHeight - titleText.bounds.height) / 2.0
titleText.frame.origin = CGPoint(x: titleText.frame.origin.x, y: max(0, top))
}
override func prepareForReuse() {
// Reset any close animations.
backgroundHolder.transform = CGAffineTransformIdentity
backgroundHolder.alpha = 1
}
override func accessibilityScroll(direction: UIAccessibilityScrollDirection) -> Bool {
var right: Bool
switch direction {
case .Left:
right = false
case .Right:
right = true
default:
return false
}
animator.close(right: right)
return true
}
}
@available(iOS 9, *)
struct PrivateModeStrings {
static let toggleAccessibilityLabel = NSLocalizedString("Private Mode", tableName: "PrivateBrowsing", comment: "Accessibility label for toggling on/off private mode")
static let toggleAccessibilityHint = NSLocalizedString("Turns private mode on or off", tableName: "PrivateBrowsing", comment: "Accessiblity hint for toggling on/off private mode")
static let toggleAccessibilityValueOn = NSLocalizedString("On", tableName: "PrivateBrowsing", comment: "Toggled ON accessibility value")
static let toggleAccessibilityValueOff = NSLocalizedString("Off", tableName: "PrivateBrowsing", comment: "Toggled OFF accessibility value")
}
class TabTrayController: UIViewController {
let tabManager: TabManager
let profile: Profile
var collectionView: UICollectionView!
var navBar: UIView!
var addTabButton: UIButton!
var settingsButton: UIButton!
var collectionViewTransitionSnapshot: UIView?
private var privateMode: Bool = false {
didSet {
if #available(iOS 9, *) {
togglePrivateMode.selected = privateMode
togglePrivateMode.accessibilityValue = privateMode ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff
emptyPrivateTabsView.hidden = !(privateMode && tabManager.privateTabs.count == 0)
tabDataSource.tabs = tabsToDisplay
collectionView.reloadData()
}
}
}
private var tabsToDisplay: [Browser] {
return self.privateMode ? tabManager.privateTabs : tabManager.normalTabs
}
@available(iOS 9, *)
lazy var togglePrivateMode: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "smallPrivateMask"), forState: UIControlState.Normal)
button.setImage(UIImage(named: "smallPrivateMaskSelected"), forState: UIControlState.Selected)
button.addTarget(self, action: "SELdidTogglePrivateMode", forControlEvents: .TouchUpInside)
button.accessibilityLabel = PrivateModeStrings.toggleAccessibilityLabel
button.accessibilityHint = PrivateModeStrings.toggleAccessibilityHint
button.accessibilityValue = self.privateMode ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff
return button
}()
@available(iOS 9, *)
private lazy var emptyPrivateTabsView: EmptyPrivateTabsView = {
return EmptyPrivateTabsView()
}()
private lazy var tabDataSource: TabManagerDataSource = {
return TabManagerDataSource(tabs: self.tabsToDisplay, cellDelegate: self)
}()
private lazy var tabLayoutDelegate: TabLayoutDelegate = {
let delegate = TabLayoutDelegate(profile: self.profile, traitCollection: self.traitCollection)
delegate.tabSelectionDelegate = self
return delegate
}()
private var removedTabIndexPath: NSIndexPath?
init(tabManager: TabManager, profile: Profile) {
self.tabManager = tabManager
self.profile = profile
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View Controller Callbacks
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.")
tabManager.addDelegate(self)
navBar = UIView()
navBar.backgroundColor = TabTrayControllerUX.BackgroundColor
addTabButton = UIButton()
addTabButton.setImage(UIImage(named: "add"), forState: .Normal)
addTabButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: .TouchUpInside)
addTabButton.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.")
settingsButton = UIButton()
settingsButton.setImage(UIImage(named: "settings"), forState: .Normal)
settingsButton.addTarget(self, action: "SELdidClickSettingsItem", forControlEvents: .TouchUpInside)
settingsButton.accessibilityLabel = NSLocalizedString("Settings", comment: "Accessibility label for the Settings button in the Tab Tray.")
let flowLayout = TabTrayCollectionViewLayout()
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: flowLayout)
collectionView.dataSource = tabDataSource
collectionView.delegate = tabLayoutDelegate
collectionView.registerClass(TabCell.self, forCellWithReuseIdentifier: TabCell.Identifier)
collectionView.backgroundColor = TabTrayControllerUX.BackgroundColor
view.addSubview(collectionView)
view.addSubview(navBar)
view.addSubview(addTabButton)
view.addSubview(settingsButton)
makeConstraints()
if #available(iOS 9, *) {
view.addSubview(togglePrivateMode)
togglePrivateMode.snp_makeConstraints { make in
make.right.equalTo(addTabButton.snp_left).offset(-10)
make.size.equalTo(UIConstants.ToolbarHeight)
make.centerY.equalTo(self.navBar)
}
view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView)
emptyPrivateTabsView.hidden = !(privateMode && tabManager.privateTabs.count == 0)
emptyPrivateTabsView.snp_makeConstraints { make in
make.edges.equalTo(self.view)
}
if let tab = tabManager.selectedTab where tab.isPrivate {
privateMode = true
}
}
}
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Update the trait collection we reference in our layout delegate
tabLayoutDelegate.traitCollection = traitCollection
collectionView.collectionViewLayout.invalidateLayout()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
private func makeConstraints() {
let viewBindings: [String: AnyObject] = [
"topLayoutGuide" : topLayoutGuide,
"navBar" : navBar
]
let topConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[topLayoutGuide][navBar]", options: [], metrics: nil, views: viewBindings)
view.addConstraints(topConstraints)
navBar.snp_makeConstraints { make in
make.height.equalTo(UIConstants.ToolbarHeight)
make.left.right.equalTo(self.view)
}
addTabButton.snp_makeConstraints { make in
make.trailing.bottom.equalTo(self.navBar)
make.size.equalTo(UIConstants.ToolbarHeight)
}
settingsButton.snp_makeConstraints { make in
make.leading.bottom.equalTo(self.navBar)
make.size.equalTo(UIConstants.ToolbarHeight)
}
collectionView.snp_makeConstraints { make in
make.top.equalTo(navBar.snp_bottom)
make.left.right.bottom.equalTo(self.view)
}
}
// MARK: Selectors
func SELdidClickDone() {
presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
}
func SELdidClickSettingsItem() {
let settingsTableViewController = SettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
let controller = SettingsNavigationController(rootViewController: settingsTableViewController)
controller.popoverDelegate = self
controller.modalPresentationStyle = UIModalPresentationStyle.FormSheet
presentViewController(controller, animated: true, completion: nil)
}
func SELdidClickAddTab() {
if #available(iOS 9, *) {
if privateMode {
emptyPrivateTabsView.hidden = true
}
}
// We're only doing one update here, but using a batch update lets us delay selecting the tab
// until after its insert animation finishes.
self.collectionView.performBatchUpdates({ _ in
var tab: Browser
if #available(iOS 9, *) {
tab = self.tabManager.addTab(isPrivate: self.privateMode)
} else {
tab = self.tabManager.addTab()
}
self.tabManager.selectTab(tab)
}, completion: { finished in
if finished {
self.navigationController?.popViewControllerAnimated(true)
}
})
}
@available(iOS 9, *)
func SELdidTogglePrivateMode() {
privateMode = !privateMode
}
}
extension TabTrayController: TabSelectionDelegate {
func didSelectTabAtIndex(index: Int) {
let tab = tabsToDisplay[index]
tabManager.selectTab(tab)
self.navigationController?.popViewControllerAnimated(true)
}
}
extension TabTrayController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(modalViewController: UIViewController, animated: Bool) {
dismissViewControllerAnimated(animated, completion: { self.collectionView.reloadData() })
}
}
extension TabTrayController: TabManagerDelegate {
func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) {
}
func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool) {
}
func tabManager(tabManager: TabManager, didAddTab tab: Browser, restoring: Bool) {
// Get the index of the added tab from it's set (private or normal)
guard let index = tabsToDisplay.indexOf(tab) else { return }
tabDataSource.tabs.append(tab)
self.collectionView.performBatchUpdates({ _ in
self.collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)])
}, completion: { finished in
if finished {
tabManager.selectTab(tab)
// don't pop the tab tray view controller if it is not in the foreground
if self.presentedViewController == nil {
self.navigationController?.popViewControllerAnimated(true)
}
}
})
}
func tabManager(tabManager: TabManager, didRemoveTab tab: Browser) {
if let removedIndex = removedTabIndexPath {
tabDataSource.tabs.removeAtIndex(removedIndex.item)
self.collectionView.deleteItemsAtIndexPaths([removedIndex])
self.collectionView.reloadItemsAtIndexPaths(self.collectionView.indexPathsForVisibleItems())
removedTabIndexPath = nil
if #available(iOS 9, *) {
if privateMode && tabsToDisplay.count == 0 {
emptyPrivateTabsView.hidden = false
}
}
}
}
func tabManagerDidAddTabs(tabManager: TabManager) {
}
func tabManagerDidRestoreTabs(tabManager: TabManager) {
}
}
extension TabTrayController: UIScrollViewAccessibilityDelegate {
func accessibilityScrollStatusForScrollView(scrollView: UIScrollView) -> String? {
var visibleCells = collectionView.visibleCells() as! [TabCell]
var bounds = collectionView.bounds
bounds = CGRectOffset(bounds, collectionView.contentInset.left, collectionView.contentInset.top)
bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right
bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom
// visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...)
visibleCells = visibleCells.filter { !CGRectIsEmpty(CGRectIntersection($0.frame, bounds)) }
var indexPaths = visibleCells.map { self.collectionView.indexPathForCell($0)! }
indexPaths.sortInPlace { $0.section < $1.section || ($0.section == $1.section && $0.row < $1.row) }
if indexPaths.count == 0 {
return NSLocalizedString("No tabs", comment: "Message spoken by VoiceOver to indicate that there are no tabs in the Tabs Tray")
}
let firstTab = indexPaths.first!.row + 1
let lastTab = indexPaths.last!.row + 1
let tabCount = collectionView.numberOfItemsInSection(0)
if (firstTab == lastTab) {
let format = NSLocalizedString("Tab %@ of %@", comment: "Message spoken by VoiceOver saying the position of the single currently visible tab in Tabs Tray, along with the total number of tabs. E.g. \"Tab 2 of 5\" says that tab 2 is visible (and is the only visible tab), out of 5 tabs total.")
return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: tabCount))
} else {
let format = NSLocalizedString("Tabs %@ to %@ of %@", comment: "Message spoken by VoiceOver saying the range of tabs that are currently visible in Tabs Tray, along with the total number of tabs. E.g. \"Tabs 8 to 10 of 15\" says tabs 8, 9 and 10 are visible, out of 15 tabs total.")
return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: lastTab), NSNumber(integer: tabCount))
}
}
}
extension TabTrayController: SwipeAnimatorDelegate {
func swipeAnimator(animator: SwipeAnimator, viewDidExitContainerBounds: UIView) {
let tabCell = animator.container as! TabCell
if let indexPath = collectionView.indexPathForCell(tabCell) {
let tab = tabsToDisplay[indexPath.item]
removedTabIndexPath = indexPath
tabManager.removeTab(tab)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Closing tab", comment: ""))
}
}
}
extension TabTrayController: TabCellDelegate {
func tabCellDidClose(cell: TabCell) {
let indexPath = collectionView.indexPathForCell(cell)!
let tab = tabsToDisplay[indexPath.item]
removedTabIndexPath = indexPath
tabManager.removeTab(tab)
}
}
private class TabManagerDataSource: NSObject, UICollectionViewDataSource {
unowned var cellDelegate: protocol<TabCellDelegate, SwipeAnimatorDelegate>
var tabs: [Browser]
init(tabs: [Browser], cellDelegate: protocol<TabCellDelegate, SwipeAnimatorDelegate>) {
self.cellDelegate = cellDelegate
self.tabs = tabs
super.init()
}
@objc func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let tabCell = collectionView.dequeueReusableCellWithReuseIdentifier(TabCell.Identifier, forIndexPath: indexPath) as! TabCell
tabCell.animator.delegate = cellDelegate
tabCell.delegate = cellDelegate
let tab = tabs[indexPath.item]
tabCell.style = tab.isPrivate ? .Dark : .Light
tabCell.titleText.text = tab.displayTitle
if !tab.displayTitle.isEmpty {
tabCell.accessibilityLabel = tab.displayTitle
} else {
tabCell.accessibilityLabel = AboutUtils.getAboutComponent(tab.url)
}
tabCell.isAccessibilityElement = true
tabCell.accessibilityHint = NSLocalizedString("Swipe right or left with three fingers to close the tab.", comment: "Accessibility hint for tab tray's displayed tab.")
if let favIcon = tab.displayFavicon {
tabCell.favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!)
} else {
tabCell.favicon.image = UIImage(named: "defaultFavicon")
}
tabCell.background.image = tab.screenshot
return tabCell
}
@objc func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabs.count
}
}
@objc protocol TabSelectionDelegate: class {
func didSelectTabAtIndex(index :Int)
}
private class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout {
weak var tabSelectionDelegate: TabSelectionDelegate?
private var traitCollection: UITraitCollection
private var profile: Profile
private var numberOfColumns: Int {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
// iPhone 4-6+ portrait
if traitCollection.horizontalSizeClass == .Compact && traitCollection.verticalSizeClass == .Regular {
return compactLayout ? TabTrayControllerUX.CompactNumberOfColumnsThin : TabTrayControllerUX.NumberOfColumnsThin
} else {
return TabTrayControllerUX.NumberOfColumnsWide
}
}
init(profile: Profile, traitCollection: UITraitCollection) {
self.profile = profile
self.traitCollection = traitCollection
super.init()
}
private func cellHeightForCurrentDevice() -> CGFloat {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
let shortHeight = (compactLayout ? TabTrayControllerUX.TextBoxHeight * 6 : TabTrayControllerUX.TextBoxHeight * 5)
if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.Compact {
return shortHeight
} else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Compact {
return shortHeight
} else {
return TabTrayControllerUX.TextBoxHeight * 8
}
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let cellWidth = (collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns)
return CGSizeMake(cellWidth, self.cellHeightForCurrentDevice())
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin)
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row)
}
}
// There seems to be a bug with UIKit where when the UICollectionView changes its contentSize
// from > frame.size to <= frame.size: the contentSet animation doesn't properly happen and 'jumps' to the
// final state.
// This workaround forces the contentSize to always be larger than the frame size so the animation happens more
// smoothly. This also makes the tabs be able to 'bounce' when there are not enough to fill the screen, which I
// think is fine, but if needed we can disable user scrolling in this case.
private class TabTrayCollectionViewLayout: UICollectionViewFlowLayout {
private override func collectionViewContentSize() -> CGSize {
var calculatedSize = super.collectionViewContentSize()
let collectionViewHeight = collectionView?.bounds.size.height ?? 0
if calculatedSize.height < collectionViewHeight && collectionViewHeight > 0 {
calculatedSize.height = collectionViewHeight + 1
}
return calculatedSize
}
}
// A transparent view with a rectangular border with rounded corners, stroked
// with a semi-transparent white border.
class InnerStrokedView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let strokeWidth = 1.0 as CGFloat
let halfWidth = strokeWidth/2 as CGFloat
let path = UIBezierPath(roundedRect: CGRect(x: halfWidth,
y: halfWidth,
width: rect.width - strokeWidth,
height: rect.height - strokeWidth),
cornerRadius: TabTrayControllerUX.CornerRadius)
path.lineWidth = strokeWidth
UIColor.whiteColor().colorWithAlphaComponent(0.2).setStroke()
path.stroke()
}
}
struct EmptyPrivateTabsViewUX {
static let TitleColor = UIColor.whiteColor()
static let TitleFont = UIFont.systemFontOfSize(22, weight: UIFontWeightMedium)
static let DescriptionColor = UIColor.whiteColor()
static let DescriptionFont = UIFont.systemFontOfSize(17)
static let TextMargin: CGFloat = 18
static let MaxDescriptionWidth: CGFloat = 250
}
// View we display when there are no private tabs created
private class EmptyPrivateTabsView: UIView {
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.TitleColor
label.font = EmptyPrivateTabsViewUX.TitleFont
label.textAlignment = NSTextAlignment.Center
return label
}()
private var descriptionLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.DescriptionColor
label.font = EmptyPrivateTabsViewUX.DescriptionFont
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 3
label.preferredMaxLayoutWidth = EmptyPrivateTabsViewUX.MaxDescriptionWidth
return label
}()
private var iconImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "largePrivateMask"))
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.text = NSLocalizedString("Private Browsing",
tableName: "PrivateBrowsing", comment: "Title displayed for when there are no open tabs while in private mode")
descriptionLabel.text = NSLocalizedString("Firefox won't remember any of your history or cookies, but new bookmarks will be saved.",
tableName: "PrivateBrowsing", comment: "Description text displayed when there are no open tabs while in private mode")
// This landed last-minute as a new string that is needed in the EmptyPrivateTabsView
let learnMoreLabelText = NSLocalizedString("Learn More", tableName: "PrivateBrowsing", comment: "Text button displayed when there are no tabs open while in private mode")
addSubview(titleLabel)
addSubview(descriptionLabel)
addSubview(iconImageView)
titleLabel.snp_makeConstraints { make in
make.center.equalTo(self)
}
iconImageView.snp_makeConstraints { make in
make.bottom.equalTo(titleLabel.snp_top).offset(-EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
descriptionLabel.snp_makeConstraints { make in
make.top.equalTo(titleLabel.snp_bottom).offset(EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 |
andrebocchini/SwiftChatty | SwiftChatty/Requests/Notifications/DetachAccountRequest.swift | 1 | 626 | //
// DetachAccountRequest.swift
// SwiftChatty
//
// Created by Andre Bocchini on 1/28/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.
import Alamofire
/// -SeeAlso: http://winchatty.com/v2/readme#_Toc421451708
public struct DetachAccountRequest: Request {
public let endpoint: ApiEndpoint = .DetachAccount
public let httpMethod: HTTPMethod = .post
public let account: Account
public var customParameters: [String : Any] = [:]
public init(withClientId clientId: String, account: Account) {
self.account = account
self.customParameters["clientId"] = clientId
}
}
| mit |
onevcat/Kingfisher | Sources/Extensions/NSButton+Kingfisher.swift | 2 | 15146 | //
// NSButton+Kingfisher.swift
// Kingfisher
//
// Created by Jie Zhang on 14/04/2016.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.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.
#if canImport(AppKit) && !targetEnvironment(macCatalyst)
import AppKit
extension KingfisherWrapper where Base: NSButton {
// MARK: Setting Image
/// Sets an image to the button with a source.
///
/// - Parameters:
/// - source: The `Source` object contains information about how to get the image.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// Internally, this method will use `KingfisherManager` to get the requested source.
/// Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
return setImage(
with: source,
placeholder: placeholder,
parsedOptions: options,
progressBlock: progressBlock,
completionHandler: completionHandler
)
}
/// Sets an image to the button with a requested resource.
///
/// - Parameters:
/// - resource: The `Resource` object contains information about the resource.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
/// or network. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with resource: Resource?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setImage(
with: resource?.convertToSource(),
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
func setImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
parsedOptions: KingfisherParsedOptionsInfo,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
var mutatingSelf = self
guard let source = source else {
base.image = placeholder
mutatingSelf.taskIdentifier = nil
completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
return nil
}
var options = parsedOptions
if !options.keepCurrentImageWhileLoading {
base.image = placeholder
}
let issuedIdentifier = Source.Identifier.next()
mutatingSelf.taskIdentifier = issuedIdentifier
if let block = progressBlock {
options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
}
let task = KingfisherManager.shared.retrieveImage(
with: source,
options: options,
downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
progressiveImageSetter: { self.base.image = $0 },
referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
completionHandler: { result in
CallbackQueue.mainCurrentOrAsync.execute {
guard issuedIdentifier == self.taskIdentifier else {
let reason: KingfisherError.ImageSettingErrorReason
do {
let value = try result.get()
reason = .notCurrentSourceTask(result: value, error: nil, source: source)
} catch {
reason = .notCurrentSourceTask(result: nil, error: error, source: source)
}
let error = KingfisherError.imageSettingError(reason: reason)
completionHandler?(.failure(error))
return
}
mutatingSelf.imageTask = nil
mutatingSelf.taskIdentifier = nil
switch result {
case .success(let value):
self.base.image = value.image
completionHandler?(result)
case .failure:
if let image = options.onFailureImage {
self.base.image = image
}
completionHandler?(result)
}
}
}
)
mutatingSelf.imageTask = task
return task
}
// MARK: Cancelling Downloading Task
/// Cancels the image download task of the button if it is running.
/// Nothing will happen if the downloading has already finished.
public func cancelImageDownloadTask() {
imageTask?.cancel()
}
// MARK: Setting Alternate Image
@discardableResult
public func setAlternateImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
return setAlternateImage(
with: source,
placeholder: placeholder,
parsedOptions: options,
progressBlock: progressBlock,
completionHandler: completionHandler
)
}
/// Sets an alternate image to the button with a requested resource.
///
/// - Parameters:
/// - resource: The `Resource` object contains information about the resource.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
/// or network. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setAlternateImage(
with resource: Resource?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setAlternateImage(
with: resource?.convertToSource(),
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
func setAlternateImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
parsedOptions: KingfisherParsedOptionsInfo,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
var mutatingSelf = self
guard let source = source else {
base.alternateImage = placeholder
mutatingSelf.alternateTaskIdentifier = nil
completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
return nil
}
var options = parsedOptions
if !options.keepCurrentImageWhileLoading {
base.alternateImage = placeholder
}
let issuedIdentifier = Source.Identifier.next()
mutatingSelf.alternateTaskIdentifier = issuedIdentifier
if let block = progressBlock {
options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
}
if let provider = ImageProgressiveProvider(options, refresh: { image in
self.base.alternateImage = image
}) {
options.onDataReceived = (options.onDataReceived ?? []) + [provider]
}
options.onDataReceived?.forEach {
$0.onShouldApply = { issuedIdentifier == self.alternateTaskIdentifier }
}
let task = KingfisherManager.shared.retrieveImage(
with: source,
options: options,
downloadTaskUpdated: { mutatingSelf.alternateImageTask = $0 },
completionHandler: { result in
CallbackQueue.mainCurrentOrAsync.execute {
guard issuedIdentifier == self.alternateTaskIdentifier else {
let reason: KingfisherError.ImageSettingErrorReason
do {
let value = try result.get()
reason = .notCurrentSourceTask(result: value, error: nil, source: source)
} catch {
reason = .notCurrentSourceTask(result: nil, error: error, source: source)
}
let error = KingfisherError.imageSettingError(reason: reason)
completionHandler?(.failure(error))
return
}
mutatingSelf.alternateImageTask = nil
mutatingSelf.alternateTaskIdentifier = nil
switch result {
case .success(let value):
self.base.alternateImage = value.image
completionHandler?(result)
case .failure:
if let image = options.onFailureImage {
self.base.alternateImage = image
}
completionHandler?(result)
}
}
}
)
mutatingSelf.alternateImageTask = task
return task
}
// MARK: Cancelling Alternate Image Downloading Task
/// Cancels the alternate image download task of the button if it is running.
/// Nothing will happen if the downloading has already finished.
public func cancelAlternateImageDownloadTask() {
alternateImageTask?.cancel()
}
}
// MARK: - Associated Object
private var taskIdentifierKey: Void?
private var imageTaskKey: Void?
private var alternateTaskIdentifierKey: Void?
private var alternateImageTaskKey: Void?
extension KingfisherWrapper where Base: NSButton {
// MARK: Properties
public private(set) var taskIdentifier: Source.Identifier.Value? {
get {
let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
return box?.value
}
set {
let box = newValue.map { Box($0) }
setRetainedAssociatedObject(base, &taskIdentifierKey, box)
}
}
private var imageTask: DownloadTask? {
get { return getAssociatedObject(base, &imageTaskKey) }
set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
}
public private(set) var alternateTaskIdentifier: Source.Identifier.Value? {
get {
let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &alternateTaskIdentifierKey)
return box?.value
}
set {
let box = newValue.map { Box($0) }
setRetainedAssociatedObject(base, &alternateTaskIdentifierKey, box)
}
}
private var alternateImageTask: DownloadTask? {
get { return getAssociatedObject(base, &alternateImageTaskKey) }
set { setRetainedAssociatedObject(base, &alternateImageTaskKey, newValue)}
}
}
#endif
| mit |
roecrew/AudioKit | AudioKit/Common/Operations/Math/min.swift | 2 | 960 | //
// min.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
/// Minimum of two operations
///
/// - Parameters:
/// - x: 1st operation
/// - y: 2nd operation
///
public func min(x: AKComputedParameter, _ y: AKComputedParameter) -> AKOperation {
return AKOperation(module: "min", inputs: x.toMono(), y.toMono())
}
/// Minimum of an operation and a parameter
///
/// - Parameters:
/// - x: parameter
/// - y: operation
///
public func min(operation: AKComputedParameter, _ parameter: AKParameter) -> AKOperation {
return AKOperation(module: "min", inputs: operation.toMono(), parameter)
}
/// Minimum of an operation and a parameter
///
/// - Parameters:
/// - x: parameter
/// - y: operation
///
public func min(parameter: AKParameter, _ operation: AKComputedParameter) -> AKOperation {
return min(operation, parameter)
}
| mit |
natmark/ProcessingKit | ProcessingKitExample/ProcessingKitExample/BasicFunctions/RectSampleView.swift | 1 | 495 | //
// RectSampleView.swift
// ProcessingKitExample
//
// Created by AtsuyaSato on 2017/08/16.
// Copyright © 2017年 Atsuya Sato. All rights reserved.
//
import UIKit
import ProcessingKit
class RectSampleView : ProcessingView {
func setup() {
background(UIColor.white)
fill(UIColor.red)
rect(200, 100, 100, 100)
fill(UIColor.blue)
rect(250, 150, 100, 100)
noFill()
stroke(UIColor.black)
rect(150, 200, 100, 100)
}
}
| mit |
pgorzelany/experimental-swift-ios | ExperimentalSwift/ActivityHandler.swift | 1 | 1086 | //
// NetworkActivityHandler.swift
// ExperimentalSwift
//
// Created by PiotrGorzelanyMac on 10/04/2017.
// Copyright © 2017 rst-it. All rights reserved.
//
import Foundation
import UIKit
protocol ActivityHandler {
func showActivityIndicator()
func hideActivityIndicator()
}
extension UIViewController: ActivityHandler {
@nonobjc static var activityIndicator: UIActivityIndicatorView?
func showActivityIndicator() {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
UIViewController.activityIndicator = activityIndicator
view.addSubview(activityIndicator)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
func hideActivityIndicator() {
UIViewController.activityIndicator?.removeFromSuperview()
UIViewController.activityIndicator = nil
}
}
| mit |
morizotter/SwiftFontName | Example/ExampleTests/FontsTests.swift | 1 | 1459 | //
// ExampleTests.swift
// ExampleTests
//
// Created by MORITANAOKI on 2015/07/18.
// Copyright (c) 2015年 molabo. All rights reserved.
//
import UIKit
import XCTest
@testable import Example
class FontsTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testExistsFontNames() {
for systemFamilyName in UIFont.familyNames {
for systemFontName in UIFont.fontNames(forFamilyName: systemFamilyName) {
let index = FontName.fontNames().firstIndex(of: systemFontName)
print(systemFontName)
XCTAssertTrue(index != nil, "\(systemFontName) doesn't exist.")
}
}
}
func testLocalizations() {
let preferredLanguage = Locale.preferredLanguages.first!
let fontName = LocalizedFontName(FontName.Copperplate, localizedFontNames: ["ja": FontName.HiraKakuProNW6, "en": FontName.HelveticaNeueLight])
if preferredLanguage == "ja" {
XCTAssertEqual(fontName, FontName.HiraKakuProNW6, "Localization failed: \(preferredLanguage)")
} else if preferredLanguage == "en" {
XCTAssertEqual(fontName, FontName.HelveticaNeueLight, "Localization failed: \(preferredLanguage)")
} else {
XCTAssertEqual(fontName, FontName.Copperplate, "Localization failed: \(preferredLanguage)")
}
}
}
| mit |
GrandCentralBoard/GrandCentralBoard | GrandCentralBoard/Widgets/GitHub/GitHubTableDataSource.swift | 2 | 945 | //
// GitHubTableDataSource.swift
// GrandCentralBoard
//
// Created by Michał Laskowski on 21/05/16.
//
import UIKit
class GitHubTableDataSource: NSObject, UITableViewDataSource {
private let maxRowsToShow = 3
private let cellID = "cell"
var items: [GitHubCellViewModel] = []
func setUpTableView(tableView: UITableView) {
tableView.registerNib(UINib(nibName: "GitHubCell", bundle: nil), forCellReuseIdentifier: cellID)
tableView.dataSource = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return min(maxRowsToShow, items.count)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! GitHubCell
cell.configureWithViewModel(items[indexPath.row])
return cell
}
}
| gpl-3.0 |
alexbredy/ABBadgeButton | ABBadgeButton/Classes/ABBadgeButton.swift | 1 | 2926 | //
// ABBadgeButton.swift
// ABBadgeButton
//
// Created by Alexander Bredy on 11/08/2016.
// Copyright (c) 2016 Alexander Bredy. All rights reserved.
//
import UIKit
open class ABBadgeButton: UIButton {
fileprivate var badge: UILabel
open var badgeValue: String = ""{
didSet{
setBadgeText(badgeValue)
}
}
open var badgeInsets: CGFloat = 6{
didSet{
setBadgeText(badgeValue)
}
}
open var badgeOriginOffset: CGPoint = CGPoint(x: 0, y: 0){
didSet{
setBadgeText(badgeValue)
}
}
open var badgeBorderColor: CGColor?{
didSet{
updateBadgeStyle()
}
}
open var badgeBorderWidth: CGFloat = 0{
didSet{
updateBadgeStyle()
}
}
open var badgeBackgroundColor: UIColor = UIColor.red{
didSet{
updateBadgeStyle()
}
}
open var badgeTextColor: UIColor = UIColor.white{
didSet{
updateBadgeStyle()
}
}
open var badgeFont: UIFont = UIFont.systemFont(ofSize: 12){
didSet{
setBadgeText(badgeValue)
}
}
override public init(frame: CGRect) {
badge = UILabel()
super.init(frame: frame)
setBadgeText("")
}
required public init?(coder aDecoder: NSCoder) {
badge = UILabel()
super.init(coder: aDecoder)
setBadgeText("")
}
/*
* Update the UI style of the badge (colors, borders, alignment and font)
*/
fileprivate func updateBadgeStyle(){
badge.textAlignment = NSTextAlignment.center
badge.backgroundColor = badgeBackgroundColor
badge.textColor = badgeTextColor
badge.layer.borderWidth = badgeBorderWidth
badge.layer.borderColor = badgeBorderColor
}
/*
* Calculates the badge frame based on the badgeValue and badgeInsets properties
*/
fileprivate func setBadgeText(_ text: String) {
badge.text = text
badge.font = badgeFont
badge.clipsToBounds = true
badge.sizeToFit()
let badgeHeight = badge.frame.height + badgeInsets
let minBadgeWidth = badge.bounds.size.width + badgeInsets
var frame = badge.frame
frame.size.height = badgeHeight
frame.size.width = minBadgeWidth < badgeHeight ? badgeHeight : minBadgeWidth
let origin: CGPoint = CGPoint(x: (self.frame.width - frame.width/2) + badgeOriginOffset.x, y: (-frame.size.height/2) + badgeOriginOffset.y)
badge.frame = CGRect(origin: origin, size: frame.size)
badge.layer.cornerRadius = badgeHeight / 2
updateBadgeStyle()
addSubview(badge)
badge.layer.zPosition = 9999
badge.isHidden = (text.characters.count == 0)
}
}
| mit |
MingLoan/PageTabBarController | sources/PageTabBarBackdropView.swift | 1 | 1757 | //
// PageTabBarBackdropView.swift
// PageTabBarController
//
// Created by Keith Chan on 7/3/2018.
// Copyright © 2018 com.mingloan. All rights reserved.
//
import UIKit
final class PageTabBarBackdropView: UIView {
var translucentFactor: CGFloat = 0.6
var isTranslucent: Bool = true {
didSet {
backgroundColor = isTranslucent ? barTintColor.withAlphaComponent(translucentFactor) : barTintColor
}
}
var barBlurStyle: UIBlurEffect.Style = .light {
didSet {
backDropBlurView.effect = UIBlurEffect(style: barBlurStyle)
}
}
var barTintColor: UIColor = .white {
didSet {
backgroundColor = isTranslucent ? barTintColor.withAlphaComponent(translucentFactor) : barTintColor
}
}
private let backDropBlurView: UIVisualEffectView = {
let backDropBlurView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffect.Style.light))
backDropBlurView.translatesAutoresizingMaskIntoConstraints = false
return backDropBlurView
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
addSubview(backDropBlurView)
NSLayoutConstraint.activate([backDropBlurView.topAnchor.constraint(equalTo: topAnchor),
backDropBlurView.leftAnchor.constraint(equalTo: leftAnchor),
backDropBlurView.rightAnchor.constraint(equalTo: rightAnchor),
backDropBlurView.bottomAnchor.constraint(equalTo: bottomAnchor)])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit |
michaello/AEConsole | Sources/Brain.swift | 1 | 8641 | //
// Brain.swift
//
// Copyright (c) 2016 Marko Tadić <tadija@me.com> http://tadija.net
//
// 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 AELog
class Brain: NSObject {
// MARK: - Outlets
var console: View!
// MARK: - Properties
fileprivate let config = Config.shared
var lines = [Line]()
var filteredLines = [Line]()
var contentWidth: CGFloat = 0.0
var filterText: String? {
didSet {
isFilterActive = !isEmpty(filterText)
}
}
var isFilterActive = false {
didSet {
updateFilter()
updateInterfaceIfNeeded()
}
}
// MARK: - API
func configureConsole(with appDelegate: UIApplicationDelegate) {
guard let _window = appDelegate.window, let window = _window else { return }
console = createConsoleView(in: window)
console.tableView.dataSource = self
console.tableView.delegate = self
console.textField.delegate = self
}
public func configureConsoleUI(with delegate: UIApplicationDelegate, injectedConsoleView: View) {
guard let _window = delegate.window, let window = _window else { return }
let aConsole = injectedConsoleView
aConsole.frame = window.bounds
aConsole.autoresizingMask = [.flexibleWidth, .flexibleHeight]
aConsole.isOnScreen = Config.shared.isAutoStartEnabled
window.addSubview(aConsole)
console = aConsole
console.tableView.dataSource = self
console.tableView.delegate = self
console.tableView.rowHeight = UITableViewAutomaticDimension
console.textField.delegate = self
}
func addLogLine(_ line: Line) {
calculateContentWidth(for: line)
updateFilteredLines(with: line)
if let lastLine = lines.last, lastLine.message != line.message {
lines.append(line)
} else if lines.last == nil {
lines.append(line)
}
updateInterfaceIfNeeded()
}
func isEmpty(_ text: String?) -> Bool {
guard let text = text else { return true }
let characterSet = CharacterSet.whitespacesAndNewlines
let isTextEmpty = text.trimmingCharacters(in: characterSet).isEmpty
return isTextEmpty
}
// MARK: - Actions
func clearLog() {
lines.removeAll()
filteredLines.removeAll()
updateInterfaceIfNeeded()
}
func exportAllLogLines() {
let stringLines = lines.map({ $0.description })
let log = stringLines.joined(separator: "\n")
if isEmpty(log) {
aelog("Log is empty, nothing to export here.")
} else {
writeLog(log)
}
}
}
extension Brain {
// MARK: - Helpers
fileprivate func updateFilter() {
if isFilterActive {
applyFilter()
} else {
clearFilter()
}
}
private func applyFilter() {
guard let filter = filterText else { return }
aelog("Filter Lines [\(isFilterActive)] - <\(filter)>")
let filtered = lines.filter({ $0.description.localizedCaseInsensitiveContains(filter) })
filteredLines = filtered
}
private func clearFilter() {
aelog("Filter Lines [\(isFilterActive)]")
filteredLines.removeAll()
}
fileprivate func updateInterfaceIfNeeded() {
if console.isOnScreen {
console.updateUI()
}
}
fileprivate func createConsoleView(in window: UIWindow) -> View {
let view = View()
view.frame = window.bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.isOnScreen = config.isAutoStartEnabled
window.addSubview(view)
return view
}
fileprivate func calculateContentWidth(for line: Line) {
contentWidth = UIScreen.main.bounds.width
}
fileprivate func updateFilteredLines(with line: Line) {
if isFilterActive {
guard let filter = filterText else { return }
if line.description.contains(filter) {
filteredLines.append(line)
}
}
}
private func getWidth(for line: Line) -> CGFloat {
let text = line.description
let maxSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: config.rowHeight)
let options = NSStringDrawingOptions.usesLineFragmentOrigin
let attributes = [NSFontAttributeName : config.consoleFont]
let nsText = text as NSString
let size = nsText.boundingRect(with: maxSize, options: options, attributes: attributes, context: nil)
let width = size.width
return width
}
fileprivate func writeLog(_ log: String) {
let filename = "\(Date().timeIntervalSince1970).aelog"
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let documentsURL = URL(fileURLWithPath: documentsPath)
let fileURL = documentsURL.appendingPathComponent(filename)
do {
try log.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
aelog("Log is exported to path: \(fileURL)")
} catch {
aelog(error)
}
}
}
extension Brain: UITableViewDataSource, UITableViewDelegate {
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let rows = isFilterActive ? filteredLines : lines
return rows.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Cell.identifier) as! Cell
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let rows = isFilterActive ? filteredLines : lines
let logLine = rows[indexPath.row]
cell.textLabel?.text = logLine.description
}
func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
let pasteboard = UIPasteboard.general
pasteboard.string = lines.reduce("\n ") { $0 + $1.message + "\n" }
}
func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
if action == "copy:" {
return true
}
return false
}
func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
return true
}
// MARK: - UIScrollViewDelegate
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
console.currentOffsetX = scrollView.contentOffset.x
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
console.currentOffsetX = scrollView.contentOffset.x
}
}
extension Brain: UITextFieldDelegate {
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if !isEmpty(textField.text) {
filterText = textField.text
}
return true
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Blockchain/Wallet/Ethereum/LegacyEthereumWalletAPI.swift | 1 | 1075 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
import RxSwift
protocol LegacyEthereumWalletAPI: AnyObject {
func checkIfEthereumAccountExists() -> Bool
func ethereumAccounts(
with secondPassword: String?,
success: @escaping ([[String: Any]]) -> Void,
error: @escaping (String) -> Void
)
func getLabelForEthereumAccount(
with secondPassword: String?,
success: @escaping (String) -> Void,
error: @escaping (String) -> Void
)
func getEthereumAddress(
with secondPassword: String?,
success: @escaping (String) -> Void,
error: @escaping (String) -> Void
)
func getEthereumNote(
for transaction: String,
success: @escaping (String?) -> Void,
error: @escaping (String) -> Void
)
func setEthereumNote(for transaction: String, note: String?)
func recordLastEthereumTransaction(
transactionHash: String,
success: @escaping () -> Void,
error: @escaping (String) -> Void
)
}
| lgpl-3.0 |
PJayRushton/stats | Stats/CreateGame.swift | 1 | 825 | //
// CreateGame.swift
// Stats
//
// Created by Parker Rushton on 4/18/17.
// Copyright © 2017 AppsByPJ. All rights reserved.
//
import Foundation
struct NewGameReadyToShow: Event {
var ready = true
}
struct CreateGame: Command {
var game: Game
func execute(state: AppState, core: Core<AppState>) {
networkAccess.addObject(at: game.ref, parameters: game.jsonObject()) { result in
switch result {
case .success:
core.fire(event: NewGameReadyToShow(ready: true))
core.fire(event: Selected<Game>(self.game))
core.fire(event: Updated<Game>(self.game))
case let .failure(error):
core.fire(event: ErrorEvent(error: error, message: "Error creating game"))
}
}
}
}
| mit |
EZ-NET/ESSwim | Sources/Calculation/Zeroable.swift | 1 | 1688 | //
// Zeroable.swift
// ESSwim
//
// Created by Tomohiro Kumagai on H27/07/30.
//
//
public protocol Zeroable {
static var zero:Self { get }
var isZero:Bool { get }
}
extension Zeroable {
public func nonZeroMap<Result:Zeroable>(predicate:(Self) throws -> Result) rethrows -> Result {
if self.isZero {
return Result.zero
}
else {
return try predicate(self)
}
}
}
extension Zeroable where Self : Equatable {
public var isZero:Bool {
return self == Self.zero
}
public var isNonZero:Bool {
return !self.isZero
}
}
// MARK: - Extension
extension Float : Zeroable {
public static let zero:Float = 0
}
extension Double : Zeroable {
public static let zero:Double = 0
}
extension Int : Zeroable {
public static let zero:Int = 0
}
extension Int8 : Zeroable {
public static let zero:Int8 = 0
}
extension Int16 : Zeroable {
public static let zero:Int16 = 0
}
extension Int32 : Zeroable {
public static let zero:Int32 = 0
}
extension Int64 : Zeroable {
public static let zero:Int64 = 0
}
extension UInt : Zeroable {
public static let zero:UInt = 0
}
extension UInt8 : Zeroable {
public static let zero:UInt8 = 0
}
extension UInt16 : Zeroable {
public static let zero:UInt16 = 0
}
extension UInt32 : Zeroable {
public static let zero:UInt32 = 0
}
extension UInt64 : Zeroable {
public static let zero:UInt64 = 0
}
extension String : Zeroable {
public static let zero:String = ""
public var isZero:Bool {
return self.isEmpty
}
}
extension Set : Zeroable {
public static var zero:Set<Element> {
return Set<Element>()
}
public var isZero:Bool {
return self.isEmpty
}
}
| mit |
billdonner/sheetcheats9 | sc9/SubEditorViewController.swift | 1 | 1169 | //
// SubEditorViewController.swift
//
// Created by william donner on 9/24/15.
//
//
// SubEditorViewController
//
// Created by william donner on 9/23/15.
//
import UIKit
protocol SubEditorDelegate {
func returningResults(_ data:String)
}
class SubEditorViewController: UIViewController {
var delegate:SubEditorDelegate?
// unwind to here from subordinate editors, passing back values via custom protocols for each
deinit {
self.cleanupFontSizeAware(self)
}
// @IBAction func unwindToVC(segue: UIStoryboardSegue) {
// }
// MARK: - when the goback button is pressed, send some data and take us home
@IBAction func gobackPressed(_ sender: AnyObject) {
delegate?.returningResults("123456")
self.unwindToMainMenu(self)
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.setupFontSizeAware(self)
}
}
extension SubEditorViewController:SegueHelpers {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
self.prepForSegue(segue , sender: sender)
}
}
extension SubEditorViewController : FontSizeAware {
func refreshFontSizeAware(_ vc:SubEditorViewController) {
vc.view.setNeedsDisplay()
}
}
| apache-2.0 |
JaSpa/swift | test/IRGen/playground.swift | 3 | 735 | // RUN: rm -rf %t
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -assume-parsing-unqualified-ownership-sil -use-jit -playground -parse-stdlib %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: OS=macosx
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Swift
@objc class C { }
public func anchor() {}
anchor()
// CHECK-LABEL: define{{( protected)?}} i32 @main
// CHECK: call void @runtime_registration
// CHECK: call void @_T010playground6anchoryyF
// CHECK: ret void
// CHECK: }
// CHECK-LABEL: define{{( protected)?}} private void @runtime_registration
// CHECK: call void @swift_instantiateObjCClass({{.*}} @_T010playground1CCN
| apache-2.0 |
konanxu/WeiBoWithSwift | WeiBo/WeiBo/Classes/Common/UIBarButtonItem+Category.swift | 1 | 671 | //
// UIBarButtonItem+Category.swift
// WeiBo
//
// Created by Konan on 16/3/13.
// Copyright © 2016年 Konan. All rights reserved.
//
import UIKit
extension UIBarButtonItem{
class func createBarButton(imageName:String,target:AnyObject?,action:Selector) ->UIBarButtonItem{
let btn = UIButton()
btn.setImage(UIImage(named: imageName), forState: UIControlState.Normal)
btn.setImage(UIImage(named: imageName + "_highlighted"), forState: UIControlState.Highlighted)
btn.addTarget(target, action: action, forControlEvents: UIControlEvents.TouchUpInside)
btn.sizeToFit()
return UIBarButtonItem(customView: btn)
}
} | mit |
dlilly/Charting | Charting/ChartUtils.swift | 1 | 1049 | //
// ChartUtils.swift
// Charting
//
// Created by Dave Lilly on 5/26/15.
// Copyright (c) 2015 Dave Lilly. All rights reserved.
//
import UIKit
class ChartUtils: NSObject {
}
func findMax(data: [DataPoint]!) -> CGFloat {
var maxValue: CGFloat = 0
for datum in data {
if datum.value > maxValue {
maxValue = datum.value
}
}
return maxValue
}
extension CGRect {
func horizontalCenteredRect(size: CGSize) -> CGRect {
return CGRectMake((self.size.width - size.width) / 2, 0, size.width, size.height)
}
func verticalCenteredRect(size: CGSize) -> CGRect {
return CGRectMake(0, (self.size.height - size.height) / 2, size.width, size.height)
}
func centeredRect(size: CGSize) -> CGRect {
return CGRectMake((self.size.width - size.width) / 2, (self.size.height - size.height) / 2, size.width, size.height)
}
}
extension UIView {
func showBorders() {
layer.borderWidth = 1.0
layer.borderColor = UIColor.blackColor().CGColor
}
} | mit |
sebastiancrossa/smack | Smack/Controller/LoginVC.swift | 1 | 1739 | //
// LoginVC.swift
// Smack
//
// Created by Sebastian Crossa on 7/29/17.
// Copyright © 2017 Sebastian Crossa. All rights reserved.
//
import UIKit
class LoginVC: UIViewController {
// Outlets
@IBOutlet weak var usernameText: UITextField!
@IBOutlet weak var passwordText: UITextField!
@IBOutlet weak var spinner: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
@IBAction func loginPressed(_ sender: Any) {
spinner.isHidden = false
spinner.startAnimating()
guard let email = usernameText.text , usernameText.text != "" else { return }
guard let pass = passwordText.text , passwordText.text != "" else { return }
AuthService.instance.loginUser(email: email, password: pass) { (success) in
if success {
AuthService.instance.findUserByEmail(completion: { (success) in
if success {
NotificationCenter.default.post(name: NOTIF_USER_DATA_DID_CHANGE, object: nil)
self.spinner.isHidden = true
self.spinner.stopAnimating()
self.dismiss(animated: true, completion: nil)
}
})
}
}
}
// Will segue to CreateAccountVC
@IBAction func createAccountButtonPressed(_ sender: Any) {
performSegue(withIdentifier: TO_CREATE_ACCOUNT, sender: nil)
}
@IBAction func closePressed (_ sender: Any) {
dismiss(animated: true, completion: nil)
}
func setupView() {
spinner.isHidden = true
}
}
| apache-2.0 |
machelix/SwiftLocation | SwiftLocationExample/SwiftLocationExample/ViewController.swift | 1 | 2402 | //
// ViewController.swift
// SwiftLocationExample
//
// Created by daniele on 31/07/15.
// Copyright (c) 2015 danielemargutti. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
SwiftLocation.shared.currentLocation(Accuracy.Neighborhood, timeout: 20, onSuccess: { (location) -> Void in
// location is a CLPlacemark
println("Location found \(location?.description)")
}) { (error) -> Void in
// something went wrong
println("Something went wrong -> \(error?.localizedDescription)")
}
return
SwiftLocation.shared.reverseAddress(Service.Apple, address: "1 Infinite Loop, Cupertino (USA)", region: nil, onSuccess: { (place) -> Void in
// our CLPlacemark is here
}) { (error) -> Void in
// something went wrong
}
let coordinates = CLLocationCoordinate2DMake(41.890198, 12.492204)
SwiftLocation.shared.reverseCoordinates(Service.Apple, coordinates: coordinates, onSuccess: { (place) -> Void in
// our placemark is here
}) { (error) -> Void in
// something went wrong
}
let requestID = SwiftLocation.shared.continuousLocation(Accuracy.Room, onSuccess: { (location) -> Void in
// a new location has arrived
}) { (error) -> Void in
// something went wrong. request will be cancelled automatically
}
// Sometime in the future... you may want to interrupt it
SwiftLocation.shared.cancelRequest(requestID)
SwiftLocation.shared.significantLocation({ (location) -> Void in
// a new significant location has arrived
}, onFail: { (error) -> Void in
// something went wrong. request will be cancelled automatically
})
let regionCoordinates = CLLocationCoordinate2DMake(41.890198, 12.492204)
var region = CLCircularRegion(center: regionCoordinates, radius: CLLocationDistance(50), identifier: "identifier_region")
SwiftLocation.shared.monitorRegion(region, onEnter: { (region) -> Void in
// events called on enter
}) { (region) -> Void in
// event called on exit
}
let bRegion = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "ciao"), identifier: "myIdentifier")
SwiftLocation.shared.monitorBeaconsInRegion(bRegion, onRanging: { (regions) -> Void in
// events called on ranging
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/InsertMediaSettingsViewController.swift | 1 | 14734 | import UIKit
import SafariServices
typealias InsertMediaSettings = InsertMediaSettingsViewController.Settings
final class InsertMediaSettingsViewController: ViewController {
private let tableView = UITableView(frame: .zero, style: .grouped)
private let image: UIImage
let searchResult: InsertMediaSearchResult
private var textViewHeightDelta: (value: CGFloat, row: Int)?
private var textViewsGroupedByType = [TextViewType: UITextView]()
struct Settings {
let caption: String?
let alternativeText: String?
let advanced: Advanced
struct Advanced {
let wrapTextAroundImage: Bool
let imagePosition: ImagePosition
let imageType: ImageType
let imageSize: ImageSize
enum ImagePosition: String {
case right
case left
case center
case none
var displayTitle: String {
switch self {
case .right:
return WMFLocalizedString("insert-media-image-position-setting-right", value: "Right", comment: "Title for image position setting that positions image on the right")
case .left:
return WMFLocalizedString("insert-media-image-position-setting-left", value: "Left", comment: "Title for image position setting that positions image on the left")
case .center:
return WMFLocalizedString("insert-media-image-position-setting-center", value: "Center", comment: "Title for image position setting that positions image in the center")
case .none:
return WMFLocalizedString("insert-media-image-position-setting-none", value: "None", comment: "Title for image position setting that doesn't set image's position")
}
}
static var displayTitle: String {
return WMFLocalizedString("insert-media-image-position-settings-title", value: "Image position", comment: "Display ritle for image position setting")
}
}
enum ImageType: String {
case thumbnail = "thumb"
case frameless
case frame
case basic
var displayTitle: String {
switch self {
case .thumbnail:
return WMFLocalizedString("insert-media-image-type-setting-thumbnail", value: "Thumbnail", comment: "Title for image type setting that formats image as thumbnail")
case .frameless:
return WMFLocalizedString("insert-media-image-type-setting-frameless", value: "Frameless", comment: "Title for image type setting that formats image as frameless")
case .frame:
return WMFLocalizedString("insert-media-image-type-setting-frame", value: "Frame", comment: "Title for image type setting that formats image as framed")
case .basic:
return WMFLocalizedString("insert-media-image-type-setting-basic", value: "Basic", comment: "Title for image type setting that formats image as basic")
}
}
static var displayTitle: String {
return WMFLocalizedString("insert-media-image-type-settings-title", value: "Image type", comment: "Display ritle for image type setting")
}
}
enum ImageSize {
case `default`
case custom(width: Int, height: Int)
var displayTitle: String {
switch self {
case .default:
return WMFLocalizedString("insert-media-image-size-setting-default", value: "Default", comment: "Title for image size setting that sizes image using default size")
case .custom:
return WMFLocalizedString("insert-media-image-size-setting-custom", value: "Custom", comment: "Title for image size setting that sizes image using custom size")
}
}
static var displayTitle: String {
return WMFLocalizedString("insert-media-image-size-settings-title", value: "Image size", comment: "Display ritle for image size setting")
}
var rawValue: String {
switch self {
case .default:
return "\(ImageSize.defaultWidth)x\(ImageSize.defaultHeight)px"
case .custom(let width, let height):
return "\(width)x\(height)px"
}
}
static var unitName = WMFLocalizedString("insert-media-image-size-settings-px-unit-name", value: "px", comment: "Image size unit name, abbreviation for 'pixels'")
static var defaultWidth = 220
static var defaultHeight = 124
}
init(wrapTextAroundImage: Bool = false, imagePosition: ImagePosition = .right, imageType: ImageType = .thumbnail, imageSize: ImageSize = .default) {
self.wrapTextAroundImage = wrapTextAroundImage
self.imagePosition = imagePosition
self.imageType = imageType
self.imageSize = imageSize
}
}
init(caption: String?, alternativeText: String?, advanced: Advanced = Advanced()) {
self.caption = caption
self.alternativeText = alternativeText
self.advanced = advanced
}
}
var settings: Settings? {
let captionTextView = textViewsGroupedByType[.caption]
let alternativeTextTextView = textViewsGroupedByType[.alternativeText]
let caption = captionTextView?.text.wmf_hasNonWhitespaceText ?? false ? captionTextView?.text : nil
let alternativeText = alternativeTextTextView?.text.wmf_hasNonWhitespaceText ?? false ? alternativeTextTextView?.text : nil
return Settings(caption: caption, alternativeText: alternativeText, advanced: insertMediaAdvancedSettingsViewController.advancedSettings)
}
private lazy var imageView: InsertMediaSettingsImageView = {
let imageView = InsertMediaSettingsImageView.wmf_viewFromClassNib()!
imageView.image = image
imageView.heading = WMFLocalizedString("insert-media-uploaded-image-title", value: "Uploaded image", comment: "Title that appears next to an image in media settings")
imageView.title = searchResult.displayTitle
imageView.titleURL = searchResult.imageInfo?.filePageURL
imageView.titleAction = { [weak self] url in
self?.present(SFSafariViewController(url: url), animated: true)
}
imageView.autoresizingMask = []
return imageView
}()
private lazy var insertMediaAdvancedSettingsViewController = InsertMediaAdvancedSettingsViewController()
private lazy var buttonView: InsertMediaSettingsButtonView = {
let buttonView = InsertMediaSettingsButtonView.wmf_viewFromClassNib()!
let isRTL = UIApplication.shared.wmf_isRTL
let buttonTitleWithoutChevron = InsertMediaAdvancedSettingsViewController.title
let buttonTitleWithChevron = isRTL ? "< \(buttonTitleWithoutChevron)" : "\(buttonTitleWithoutChevron) >"
buttonView.buttonTitle = buttonTitleWithChevron
buttonView.buttonAction = { [weak self] _ in
guard let self = self else {
return
}
self.insertMediaAdvancedSettingsViewController.apply(theme: self.theme)
self.navigationController?.pushViewController(self.insertMediaAdvancedSettingsViewController, animated: true)
}
buttonView.autoresizingMask = []
return buttonView
}()
private struct TextViewModel {
let type: TextViewType
let headerText: String
let placeholder: String
let footerText: String
init(type: TextViewType) {
self.type = type
switch type {
case .caption:
headerText = WMFLocalizedString("insert-media-caption-title", value: "Caption", comment: "Title for setting that allows users to add image captions")
placeholder = WMFLocalizedString("insert-media-caption-caption-placeholder", value: "How does this image relate to the article?", comment: "Placeholder text for setting that allows users to add image captions")
footerText = WMFLocalizedString("insert-media-caption-description", value: "Label that shows next to the item for all readers", comment: "Description for setting that allows users to add image captions")
case .alternativeText:
headerText = WMFLocalizedString("insert-media-alternative-text-title", value: "Alternative text", comment: "Title for setting that allows users to add image alternative text")
placeholder = WMFLocalizedString("insert-media-alternative-text-placeholder", value: "Describe this image", comment: "Placeholder text for setting that allows users to add image alternative text")
footerText = WMFLocalizedString("insert-media-alternative-text-description", value: "Text description for readers who cannot see the image", comment: "Description for setting that allows users to add image alternative text")
}
}
}
private enum TextViewType: Int, Hashable {
case caption
case alternativeText
}
private lazy var viewModels: [TextViewModel] = {
let captionViewModel = TextViewModel(type: .caption)
let alternativeTextViewModel = TextViewModel(type: .alternativeText)
return [captionViewModel, alternativeTextViewModel]
}()
init(image: UIImage, searchResult: InsertMediaSearchResult) {
self.image = image
self.searchResult = searchResult
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
scrollView = tableView
super.viewDidLoad()
navigationBar.isBarHidingEnabled = false
tableView.dataSource = self
view.wmf_addSubviewWithConstraintsToEdges(tableView)
tableView.register(InsertMediaSettingsTextTableViewCell.wmf_classNib(), forCellReuseIdentifier: InsertMediaSettingsTextTableViewCell.identifier)
tableView.separatorStyle = .none
tableView.tableHeaderView = imageView
tableView.tableFooterView = buttonView
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard let headerView = tableView.tableHeaderView else {
return
}
let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
guard headerView.frame.size.height != height else {
return
}
headerView.frame.size.height = height
tableView.tableHeaderView = headerView
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
guard textViewHeightDelta != nil else {
return
}
UIView.performWithoutAnimation {
self.textViewHeightDelta = nil
self.tableView.beginUpdates()
self.tableView.endUpdates()
}
}
// MARK: - Themeable
override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
tableView.backgroundColor = view.backgroundColor
imageView.apply(theme: theme)
buttonView.apply(theme: theme)
}
}
// MARK: - Table view data source
extension InsertMediaSettingsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: InsertMediaSettingsTextTableViewCell.identifier, for: indexPath) as? InsertMediaSettingsTextTableViewCell else {
return UITableViewCell()
}
let viewModel = viewModels[indexPath.row]
cell.headerText = viewModel.headerText
textViewsGroupedByType[viewModel.type] = cell.textViewConfigured(with: self, placeholder: viewModel.placeholder, placeholderDelegate: self, clearDelegate: self, tag: indexPath.row)
cell.footerText = viewModel.footerText
cell.selectionStyle = .none
cell.apply(theme: theme)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard
let cell = tableView.visibleCells[safeIndex: indexPath.row] as? InsertMediaSettingsTextTableViewCell,
let textViewHeightDelta = textViewHeightDelta,
textViewHeightDelta.row == indexPath.row
else {
return UITableView.automaticDimension
}
return cell.frame.size.height + textViewHeightDelta.value
}
}
extension InsertMediaSettingsViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
updateTextViewHeight(textView)
}
private func updateTextViewHeight(_ textView: UITextView) {
let oldHeight = textView.frame.size.height
let newHeight = textView.systemLayoutSizeFitting(textView.frame.size).height
guard oldHeight != newHeight else {
return
}
textViewHeightDelta = (newHeight - oldHeight, textView.tag)
UIView.performWithoutAnimation {
textView.frame.size.height = newHeight
tableView.beginUpdates()
tableView.endUpdates()
}
}
}
extension InsertMediaSettingsViewController: ThemeableTextViewPlaceholderDelegate {
func themeableTextViewPlaceholderDidHide(_ themeableTextView: UITextView, isPlaceholderHidden: Bool) {
updateTextViewHeight(themeableTextView)
}
}
extension InsertMediaSettingsViewController: ThemeableTextViewClearDelegate {
func themeableTextViewDidClear(_ themeableTextView: UITextView) {
updateTextViewHeight(themeableTextView)
}
}
| mit |
chrisjmendez/swift-exercises | Menus/Pinterest/PinterestSwift/AppDelegate.swift | 2 | 2369 | //
// AppDelegate.swift
// PinterestSwift
//
// Created by Nicholas Tau on 6/30/14.
// Copyright (c) 2014 Nicholas Tau. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
// Override point for customization after application launch.
// var navigationContorller = self.window?.rootViewController as UINavigationController
// navigationContorller.setNavigationBarHidden(true, animated: false)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
square/wire | wire-library/wire-tests-swift/src/main/swift/NestedVersionTwo.swift | 1 | 2987 | // Code generated by Wire protocol buffer compiler, do not edit.
// Source: squareup.protos.kotlin.unknownfields.NestedVersionTwo in unknown_fields.proto
import Foundation
import Wire
public struct NestedVersionTwo {
public var i: Int32?
public var v2_i: Int32?
public var v2_s: String?
public var v2_f32: UInt32?
@JSONString
public var v2_f64: UInt64?
public var v2_rs: [String]
public var unknownFields: Data = .init()
public init(
i: Int32? = nil,
v2_i: Int32? = nil,
v2_s: String? = nil,
v2_f32: UInt32? = nil,
v2_f64: UInt64? = nil,
v2_rs: [String] = []
) {
self.i = i
self.v2_i = v2_i
self.v2_s = v2_s
self.v2_f32 = v2_f32
self.v2_f64 = v2_f64
self.v2_rs = v2_rs
}
}
#if !WIRE_REMOVE_EQUATABLE
extension NestedVersionTwo : Equatable {
}
#endif
#if !WIRE_REMOVE_HASHABLE
extension NestedVersionTwo : Hashable {
}
#endif
extension NestedVersionTwo : ProtoMessage {
public static func protoMessageTypeURL() -> String {
return "type.googleapis.com/squareup.protos.kotlin.unknownfields.NestedVersionTwo"
}
}
extension NestedVersionTwo : Proto2Codable {
public init(from reader: ProtoReader) throws {
var i: Int32? = nil
var v2_i: Int32? = nil
var v2_s: String? = nil
var v2_f32: UInt32? = nil
var v2_f64: UInt64? = nil
var v2_rs: [String] = []
let token = try reader.beginMessage()
while let tag = try reader.nextTag(token: token) {
switch tag {
case 1: i = try reader.decode(Int32.self)
case 2: v2_i = try reader.decode(Int32.self)
case 3: v2_s = try reader.decode(String.self)
case 4: v2_f32 = try reader.decode(UInt32.self, encoding: .fixed)
case 5: v2_f64 = try reader.decode(UInt64.self, encoding: .fixed)
case 6: try reader.decode(into: &v2_rs)
default: try reader.readUnknownField(tag: tag)
}
}
self.unknownFields = try reader.endMessage(token: token)
self.i = i
self.v2_i = v2_i
self.v2_s = v2_s
self.v2_f32 = v2_f32
self.v2_f64 = v2_f64
self.v2_rs = v2_rs
}
public func encode(to writer: ProtoWriter) throws {
try writer.encode(tag: 1, value: self.i)
try writer.encode(tag: 2, value: self.v2_i)
try writer.encode(tag: 3, value: self.v2_s)
try writer.encode(tag: 4, value: self.v2_f32, encoding: .fixed)
try writer.encode(tag: 5, value: self.v2_f64, encoding: .fixed)
try writer.encode(tag: 6, value: self.v2_rs)
try writer.writeUnknownFields(unknownFields)
}
}
#if !WIRE_REMOVE_CODABLE
extension NestedVersionTwo : Codable {
public enum CodingKeys : String, CodingKey {
case i
case v2_i
case v2_s
case v2_f32
case v2_f64
case v2_rs
}
}
#endif
| apache-2.0 |
robbdimitrov/pixelgram-ios | PixelGram/Classes/Shared/ViewControllers/ViewController.swift | 1 | 3062 | //
// ViewController.swift
// PixelGram
//
// Created by Robert Dimitrov on 10/31/17.
// Copyright © 2017 Robert Dimitrov. All rights reserved.
//
import UIKit
import RxSwift
class ViewController: UIViewController {
let disposeBag = DisposeBag()
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationItem()
}
// MARK: - Config
func setupNavigationItem() {
navigationItem.leftBarButtonItems = leftButtonItems()
navigationItem.rightBarButtonItems = rightButtonItems()
}
func leftButtonItems() -> [UIBarButtonItem]? {
// Implemented by subclasses
return nil
}
func rightButtonItems() -> [UIBarButtonItem]? {
// Implemented by subclasses
return nil
}
func setupTitleView(with image: UIImage) {
let logoView = UIImageView()
let image = UIImage(named: "logo")
let ratio: CGFloat = (image?.size.width ?? 0) / (image?.size.height ?? 1)
let height: CGFloat = 30.0;
let size = CGSize(width: height * ratio, height: height)
logoView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
logoView.image = image
let titleView = UIView()
titleView.addSubview(logoView)
logoView.center = titleView.center
self.navigationItem.titleView = titleView
}
func setupTitleView(with title: String, font: UIFont = UIFont.systemFont(ofSize: 17.0)) {
let label = UILabel()
label.font = font
label.text = title
navigationItem.titleView = label
}
// MARK: - State
func showMessage(title: String, content: String) {
let alert = UIAlertController(title: title, message: content, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
func showError(error: String) {
showMessage(title: "Error", content: error)
}
// MARK: - Components
func buttonItem(with title: String) -> UIBarButtonItem {
return UIBarButtonItem(title: title, style: .plain,
target: nil, action: nil)
}
func cancelButtonItem() -> UIBarButtonItem {
return buttonItem(with: "Cancel")
}
func doneButtonItem() -> UIBarButtonItem {
return buttonItem(with: "Done")
}
func closeButtonItem() -> UIBarButtonItem {
return buttonItem(with: "Close")
}
// MARK: - Storyboard
func instantiateViewController(withIdentifier identifier: String) -> UIViewController {
guard let storyboard = storyboard else {
print("Storyboard is nil")
return UIViewController()
}
return storyboard.instantiateViewController(withIdentifier: identifier)
}
}
| mit |
remirobert/LoginProvider | LoginProvider/GoogleProvider.swift | 1 | 1721 | //
// GoogleProvider.swift
// BookMe5iOS
//
// Created by Remi Robert on 06/12/15.
// Copyright © 2015 Remi Robert. All rights reserved.
//
import UIKit
import Alamofire
class GoogleProvider: NSObject, Provider, GIDSignInDelegate, GIDSignInUIDelegate {
let providerType = LoginProviderType.Google
var delegate: LoginProviderDelegate?
var parentController: UIViewController!
@objc func signIn(signIn: GIDSignIn!,
presentViewController viewController: UIViewController!) {
self.parentController.presentViewController(viewController, animated: true, completion: nil)
}
@objc func signIn(signIn: GIDSignIn!,
dismissViewController viewController: UIViewController!) {
self.parentController.dismissViewControllerAnimated(true, completion: nil)
}
@objc func signIn(signIn: GIDSignIn!, didDisconnectWithUser user: GIDGoogleUser!, withError error: NSError!) {
GIDSignIn.sharedInstance().signIn()
}
@objc func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
if (error == nil) {
let idToken = user.authentication.idToken
self.delegate?.loginProvider(self, didSucceed: APIAuth.Google(token: idToken))
}
else {
self.delegate?.loginProvider(self, didError: error)
}
}
func login() {
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().signOut()
GIDSignIn.sharedInstance().signIn()
}
init(parentController: UIViewController) {
self.parentController = parentController
}
}
| mit |
kevinmbeaulieu/Signal-iOS | Signal/test/Models/AccountManagerTest.swift | 2 | 3852 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import XCTest
import PromiseKit
struct VerificationFailedError: Error { }
struct FailedToGetRPRegistrationTokenError: Error { }
enum PushNotificationRequestResult: String {
case FailTSOnly = "FailTSOnly",
FailRPOnly = "FailRPOnly",
FailBoth = "FailBoth",
Succeed = "Succeed"
}
class FailingTSAccountManager: TSAccountManager {
let phoneNumberAwaitingVerification = "+13235555555"
override func verifyAccount(withCode: String, success: @escaping () -> Void, failure: @escaping (Error) -> Void) {
failure(VerificationFailedError())
}
override func registerForPushNotifications(pushToken: String, voipToken: String, success successHandler: @escaping () -> Void, failure failureHandler: @escaping (Error) -> Void) {
if pushToken == PushNotificationRequestResult.FailTSOnly.rawValue || pushToken == PushNotificationRequestResult.FailBoth.rawValue {
failureHandler(OWSErrorMakeUnableToProcessServerResponseError())
} else {
successHandler()
}
}
}
class VerifyingTSAccountManager: FailingTSAccountManager {
override func verifyAccount(withCode: String, success: @escaping () -> Void, failure: @escaping (Error) -> Void) {
success()
}
}
class TokenObtainingTSAccountManager: VerifyingTSAccountManager {
}
class AccountManagerTest: XCTestCase {
let tsAccountManager = FailingTSAccountManager()
func testRegisterWhenEmptyCode() {
let accountManager = AccountManager(textSecureAccountManager: tsAccountManager)
let expectation = self.expectation(description: "should fail")
firstly {
accountManager.register(verificationCode: "")
}.then {
XCTFail("Should fail")
}.catch { error in
let nserror = error as NSError
if OWSErrorCode(rawValue: nserror.code) == OWSErrorCode.userError {
expectation.fulfill()
} else {
XCTFail("Unexpected error: \(error)")
}
}
self.waitForExpectations(timeout: 1.0, handler: nil)
}
func testRegisterWhenVerificationFails() {
let accountManager = AccountManager(textSecureAccountManager: tsAccountManager)
let expectation = self.expectation(description: "should fail")
firstly {
accountManager.register(verificationCode: "123456")
}.then {
XCTFail("Should fail")
}.catch { error in
if error is VerificationFailedError {
expectation.fulfill()
} else {
XCTFail("Unexpected error: \(error)")
}
}
self.waitForExpectations(timeout: 1.0, handler: nil)
}
func testSuccessfulRegistration() {
let tsAccountManager = TokenObtainingTSAccountManager()
let accountManager = AccountManager(textSecureAccountManager: tsAccountManager)
let expectation = self.expectation(description: "should succeed")
firstly {
accountManager.register(verificationCode: "123456")
}.then {
expectation.fulfill()
}.catch { error in
XCTFail("Unexpected error: \(error)")
}
self.waitForExpectations(timeout: 1.0, handler: nil)
}
func testUpdatePushTokens() {
let accountManager = AccountManager(textSecureAccountManager: tsAccountManager)
let expectation = self.expectation(description: "should fail")
accountManager.updatePushTokens(pushToken: PushNotificationRequestResult.FailTSOnly.rawValue, voipToken: "whatever").then {
XCTFail("Expected to fail.")
}.catch { _ in
expectation.fulfill()
}
self.waitForExpectations(timeout: 1.0, handler: nil)
}
}
| gpl-3.0 |
ello/ello-ios | Sources/Controllers/Stream/StreamResponders.swift | 1 | 3919 | ////
/// StreamResponders.swift
//
import PromiseKit
import PINRemoteImage
@objc
protocol StreamCellResponder: class {
func streamCellTapped(cell: UICollectionViewCell)
func artistInviteSubmissionTapped(cell: UICollectionViewCell)
}
@objc
protocol SimpleStreamResponder: class {
func showSimpleStream(boxedEndpoint: BoxedElloAPI, title: String)
}
@objc
protocol StreamImageCellResponder: class {
func imageTapped(cell: StreamImageCell)
}
@objc
protocol StreamPostTappedResponder: class {
func postTappedInStream(_ cell: UICollectionViewCell)
}
@objc
protocol StreamEditingResponder: class {
func cellDoubleTapped(cell: UICollectionViewCell, location: CGPoint)
func cellDoubleTapped(cell: UICollectionViewCell, post: Post, location: CGPoint)
func cellLongPressed(cell: UICollectionViewCell)
}
typealias StreamCellItemGenerator = () -> [StreamCellItem]
protocol StreamViewDelegate: class {
func streamViewStreamCellItems(jsonables: [Model], defaultGenerator: StreamCellItemGenerator)
-> [StreamCellItem]?
func streamWillPullToRefresh()
func streamViewDidScroll(scrollView: UIScrollView)
func streamViewWillBeginDragging(scrollView: UIScrollView)
func streamViewDidEndDragging(scrollView: UIScrollView, willDecelerate: Bool)
func streamViewInfiniteScroll() -> Promise<[Model]>?
}
@objc
protocol CategoryResponder: class {
func categoryTapped(_ category: Category)
}
@objc
protocol CategoryCellResponder: class {
func categoryCellTapped(cell: UICollectionViewCell)
}
@objc
protocol SelectedCategoryResponder: class {
func categoriesSelectionChanged(selection: [Category])
}
@objc
protocol SubscribedCategoryResponder: class {
func categorySubscribeTapped(cell: UICollectionViewCell)
}
@objc
protocol ChooseCategoryResponder: class {
func categoryChosen(_ category: Category)
}
@objc
protocol PromotionalHeaderResponder: class {
func categorySubscribed(categoryId: String)
}
@objc
protocol CategoryHeaderResponder: class {
func categoryHeaderTapped(cell: UICollectionViewCell, header: PageHeader)
}
@objc
protocol UserResponder: class {
func userTappedAuthor(cell: UICollectionViewCell)
func userTappedReposter(cell: UICollectionViewCell)
func userTapped(user: User)
}
@objc
protocol WebLinkResponder: class {
func webLinkTapped(path: String, type: ElloURIWrapper, data: String?)
}
@objc
protocol StreamSelectionCellResponder: class {
func streamTapped(_ type: String)
}
@objc
protocol SearchStreamResponder: class {
func searchFieldChanged(text: String)
}
@objc
protocol AnnouncementCellResponder: class {
func markAnnouncementAsRead(cell: UICollectionViewCell)
}
@objc
protocol AnnouncementResponder: class {
func markAnnouncementAsRead(announcement: Announcement)
}
@objc
protocol PostCommentsResponder: class {
func loadCommentsTapped()
}
@objc
protocol PostTappedResponder: class {
func postTapped(_ post: Post)
func postTapped(_ post: Post, scrollToComment: ElloComment?)
func postTapped(_ post: Post, scrollToComments: Bool)
func postTapped(postId: String)
}
@objc
protocol UserTappedResponder: class {
func userTapped(_ user: User)
func userParamTapped(_ param: String, username: String?)
}
@objc
protocol CreatePostResponder: class {
func createPost(text: String?, fromController: UIViewController)
func createComment(_ postId: String, text: String?, fromController: UIViewController)
func editComment(_ comment: ElloComment, fromController: UIViewController)
func editPost(_ post: Post, fromController: UIViewController)
}
@objc
protocol InviteResponder: class {
func onInviteFriends()
func sendInvite(person: LocalPerson, isOnboarding: Bool, completion: @escaping Block)
}
@objc
protocol PostFeaturedResponder: class {
func categoryPostTapped(streamCellItem: StreamCellItem, categoryPost: CategoryPost)
}
| mit |
zach-freeman/swift-localview | localviewTests/MockNetwork.swift | 1 | 903 | //
// MockNetwork.swift
// localview
//
// Created by Zach Freeman on 3/6/16.
// Copyright © 2016 sparkwing. All rights reserved.
//
import Foundation
@testable import localview
class MockNetwork: Networking {
var requestCount: Int = 0
init() { }
func request(_ latitude: String, longitude: String, completion: @escaping (Any?) -> Void) {
requestCount = 1
do {
let flickrResponse: Data = LocalViewTestsHelpers
.bundleFileContentsAsData("good-flickr-response", filetype: "json")
let flickrResponseJsonObject = try JSONSerialization
.jsonObject(with: flickrResponse,
options: JSONSerialization.ReadingOptions.mutableContainers)
completion(flickrResponseJsonObject as AnyObject?)
} catch _ {
print("could not open flickr response file")
}
}
}
| mit |
dmitriy-shmilo/portfolio-app | ios/Portfolio App/Portfolio App/Data/Repository.swift | 1 | 593 | //
// Repository.swift
// Portfolio App
//
// Created by Dmitriy Shmilo on 10/27/17.
// Copyright © 2017 Dmitriy Shmilo. All rights reserved.
//
import Foundation
class Repository<TItem:RepositoryItem<TId>, TId> {
func addOrUpdate(item:TItem) -> TItem {
preconditionFailure("Unimplemented");
}
func removeItem(id:TId) {
preconditionFailure("Unimplemented");
}
func getItem(id:TId) -> TItem? {
preconditionFailure("Unimplemented");
}
func getAll() -> [TItem] {
preconditionFailure("Unimplemented");
}
}
| mit |
daggmano/photo-management-studio | src/Client/OSX/Photo Management Studio/Photo Management Studio/ResponseObject.swift | 1 | 2150 | //
// ResponseObject.swift
// Photo Management Studio
//
// Created by Darren Oster on 12/02/2016.
// Copyright © 2016 Darren Oster. All rights reserved.
//
import Foundation
class ResponseObject<T : JsonProtocol> : NSObject, JsonProtocol {
internal private(set) var links: LinksObject?
internal private(set) var data: T?
init(links: LinksObject, data: T) {
self.links = links
self.data = data
}
required init(json: [String: AnyObject]) {
if let links = json["links"] as? [String: AnyObject] {
self.links = LinksObject(json: links)
}
if let data = json["data"] as? [String: AnyObject] {
self.data = T(json: data)
}
}
func toJSON() -> [String: AnyObject] {
var result = [String: AnyObject]()
if let links = self.links {
result["links"] = links.toJSON()
}
if let data = self.data {
result["data"] = data.toJSON()
}
return result
}
}
class ResponseListObject<T : JsonProtocol> : NSObject, JsonProtocol {
internal private(set) var links: LinksObject?
internal private(set) var data: Array<T>?
init(links: LinksObject, data: Array<T>) {
self.links = links
self.data = data
}
required init(json: [String: AnyObject]) {
if let links = json["links"] as? [String: AnyObject] {
self.links = LinksObject(json: links)
}
if let dataArray = json["data"] as? [[String: AnyObject]] {
self.data = [T]()
for data in dataArray {
self.data!.append(T(json: data))
}
}
}
func toJSON() -> [String: AnyObject] {
var result = [String: AnyObject]()
if let links = self.links {
result["links"] = links.toJSON()
}
if let data = self.data {
var array = [[String: AnyObject]]()
for dataItem in data {
array.append(dataItem.toJSON())
}
result["data"] = array
}
return result
}
}
| mit |
jsslai/Action | Carthage/Checkouts/RxSwift/RxCocoa/Common/CocoaUnits/Driver/Driver+Subscription.swift | 1 | 5132 | //
// Driver+Subscription.swift
// Rx
//
// Created by Krunoslav Zaher on 9/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
private let driverErrorMessage = "`drive*` family of methods can be only called from `MainThread`.\n" +
"This is required to ensure that the last replayed `Driver` element is delivered on `MainThread`.\n"
// This would ideally be Driver, but unfortunatelly Driver can't be extended in Swift 3.0
extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy {
/**
Creates new subscription and sends elements to observer.
This method can be only called from `MainThread`.
In this form it's equivalent to `subscribe` method, but it communicates intent better.
- parameter observer: Observer that receives events.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return self.asSharedSequence().asObservable().subscribe(observer)
}
/**
Creates new subscription and sends elements to variable.
This method can be only called from `MainThread`.
- parameter variable: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the variable.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive(_ variable: Variable<E>) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return drive(onNext: { e in
variable.value = e
})
}
/**
Subscribes to observable sequence using custom binder function.
This method can be only called from `MainThread`.
- parameter with: Function used to bind elements from `self`.
- returns: Object representing subscription.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive<R>(_ transformation: (Observable<E>) -> R) -> R {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return transformation(self.asObservable())
}
/**
Subscribes to observable sequence using custom binder function and final parameter passed to binder function
after `self` is passed.
public func drive<R1, R2>(with: Self -> R1 -> R2, curriedArgument: R1) -> R2 {
return with(self)(curriedArgument)
}
This method can be only called from `MainThread`.
- parameter with: Function used to bind elements from `self`.
- parameter curriedArgument: Final argument passed to `binder` to finish binding process.
- returns: Object representing subscription.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive<R1, R2>(_ with: (Observable<E>) -> (R1) -> R2, curriedArgument: R1) -> R2 {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return with(self.asObservable())(curriedArgument)
}
/**
Subscribes an element handler, a completion handler and disposed handler to an observable sequence.
This method can be only called from `MainThread`.
Error callback is not exposed because `Driver` can't error out.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
gracefully completed, errored, or if the generation is cancelled by disposing subscription)
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is cancelled by disposing subscription)
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive(onNext: ((E) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed)
}
/**
Subscribes an element handler to an observable sequence.
This method can be only called from `MainThread`.
- parameter onNext: Action to invoke for each element in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
@available(*, deprecated, renamed: "drive(onNext:)")
public func driveNext(_ onNext: @escaping (E) -> Void) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return self.asObservable().subscribe(onNext: onNext)
}
}
| mit |
everald/JetPack | Sources/Extensions/Swift/Array.swift | 1 | 743 | public extension Array {
public func getOrNil(_ index: Index) -> Iterator.Element? {
guard indices.contains(index) else {
return nil
}
return self[index]
}
public func toArray() -> [Iterator.Element] {
return self
}
}
public extension Array where Iterator.Element: _Optional, Iterator.Element.Wrapped: Equatable {
public func index(of element: Iterator.Element.Wrapped?) -> Int? {
return index { $0.value == element }
}
}
public func === <T: AnyObject> (a: [T], b: [T]) -> Bool {
guard a.count == b.count else {
return false
}
for index in a.indices {
guard a[index] === b[index] else {
return false
}
}
return true
}
public func !== <T: AnyObject> (a: [T], b: [T]) -> Bool {
return !(a === b)
}
| mit |
genedelisa/AVAudioUnitSamplerFrobs | AVAudioUnitSamplerFrobs/ViewController.swift | 1 | 1525 | //
// ViewController.swift
// AVAudioUnitSamplerFrobs
//
// Created by Gene De Lisa on 1/13/16.
// Copyright © 2016 Gene De Lisa. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var sampler1: Sampler1!
var samplerSequence: SamplerSequence!
var samplerSequenceOTF: SamplerSequenceOTF!
var drumMachine: DrumMachine!
var duet: Duet!
override func viewDidLoad() {
super.viewDidLoad()
sampler1 = Sampler1()
samplerSequence = SamplerSequence()
samplerSequenceOTF = SamplerSequenceOTF()
drumMachine = DrumMachine()
duet = Duet()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sampler1Down(_ sender: UIButton) {
sampler1.play()
}
@IBAction func sampler1Up(_ sender: UIButton) {
sampler1.stop()
}
@IBAction func samplerSequence(_ sender: UIButton) {
samplerSequence.play()
}
@IBAction func samplerSequenceOTF(_ sender: UIButton) {
samplerSequenceOTF.play()
}
@IBAction func drumMachinePlay(_ sender: UIButton) {
drumMachine.play()
}
@IBAction func duetDown(_ sender: UIButton) {
duet.play()
}
@IBAction func duetUp(_ sender: UIButton) {
duet.stop()
}
}
| mit |
apple/swift | validation-test/compiler_crashers_fixed/01335-swift-astvisitor.swift | 65 | 443 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
let b = {
(v: T? = i: A, AnyObject) in x = b
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/09757-swift-sourcemanager-getmessage.swift | 11 | 242 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A {
struct d {
let start = {
return m( {
protocol P {
class
case ,
| mit |
hilenium/HISwiftExtensions | Example/Tests/NSURLTests.swift | 1 | 1282 | ////
//// NSURLTests.swift
//// HISwiftExtensions
////
//// Created by Matthew on 29/12/2015.
//// Copyright © 2015 CocoaPods. All rights reserved.
////
//
import Quick
import Nimble
import HISwiftExtensions
//
//class NSURLSpec: QuickSpec {
//
// override func spec() {
// describe("nsurl extensions") {
//
// it("query parameters") {
//
// let url = NSURL(string: "http://foo.com?foo=bar&bar=foo")
// let dict = url?.queryParameters
//
// expect(dict?["foo"]!).to(equal("bar"))
// expect(dict?["bar"]!).to(equal("foo"))
// }
//
// it("failable convenience initializer - successful") {
//
// let string: String? = "http://foo.com"
// let url = NSURL(optionalString: string)
//
// expect(url).toNot(equal(.none))
// }
//
// it("failable convenience initializer - failure") {
//
// let string: String? = "foo"
// let url = NSURL(optionalString: string)
//
// expect(url).to(equal(.none))
// }
// }
// }
//}
//
| mit |
Tsiems/STRiNg | CarFile/CarFile/NewCarViewController.swift | 1 | 18907 | //
// NewCarViewController.swift
// CarFile
//
// Created by Travis Siems on 11/1/15.
// Copyright © 2015 STRiNg, int. All rights reserved.
//
import UIKit
import Foundation
import SwiftHTTP
import CoreData
class NewCarViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var deleteButton: UIButton!
@IBOutlet weak var populateVinButton: UIButton!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var populateVinTextField: UITextField!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var makeTextField: UITextField!
@IBOutlet weak var modelTextField: UITextField!
@IBOutlet weak var yearTextField: UITextField!
@IBOutlet weak var colorTextField: UITextField!
@IBOutlet weak var priceTextField: UITextField!
@IBOutlet weak var vinNumTextField: UITextField!
@IBOutlet weak var licNumTextField: UITextField!
@IBOutlet weak var notesTextField: UITextField!
var styleID: String?
var newCar: Bool?
var carIndex: Int?
var leftBarItem: UIBarButtonItem?
var rightBarItem: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
setTextFieldDelegates()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name:UIKeyboardWillHideNotification, object: nil)
self.styleID = ""
// let backItem = UIBarButtonItem(title: "cancel", style: .Plain, target: nil, action: nil)
// navigationItem.backBarButtonItem = backItem
if newCar == true
{
prepareNewCar()
}
else
{
prepareExistingCar()
}
navigationController!.navigationBar.barTintColor = UIColor(red:0.09,green:0.55,blue:1.00,alpha: 1.00)
let attributes = [
NSForegroundColorAttributeName: UIColor.whiteColor(),
NSFontAttributeName: UIFont(name: "HelveticaNeue-Bold", size: 28)!
]
navigationController!.navigationBar.titleTextAttributes = attributes
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
let width = UIScreen.mainScreen().bounds.size.width
let height = UIScreen.mainScreen().bounds.size.height
scrollView.contentSize = CGSizeMake(width, height)
scrollView.scrollEnabled = true
//scroll to top
self.scrollView.setContentOffset(CGPoint(x:0,y:0), animated: false)
}
func prepareNewCar() {
title = "New Car"
enableTextEditting()
//set the bar items
let leftButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancelToCarMenu:")
let rightButton = UIBarButtonItem(title: "Save", style: .Done, target: self, action: "saveToCarMenu:")
leftButton.tintColor = UIColor.whiteColor()
rightButton.tintColor = UIColor.whiteColor()
self.navigationItem.leftBarButtonItem = leftButton
self.navigationItem.rightBarButtonItem = rightButton
//save these in case they change
leftBarItem = self.navigationItem.leftBarButtonItem
rightBarItem = self.navigationItem.rightBarButtonItem
}
func prepareExistingCar() {
enableTextEditting()
populateFields()
disableTextEditting()
//set the right button time
let rightButton = UIBarButtonItem(title: "Edit", style: .Done, target: self, action: "editButtonPressed:")
rightButton.tintColor = UIColor.whiteColor()
self.navigationItem.rightBarButtonItem = rightButton
//save these in case they change
leftBarItem = self.navigationItem.leftBarButtonItem
rightBarItem = self.navigationItem.rightBarButtonItem
}
func populateFields() {
title = cars[carIndex!].valueForKey("name") as? String
nameTextField.text = title
makeTextField.text = cars[carIndex!].valueForKey("make") as? String
modelTextField.text = cars[carIndex!].valueForKey("model") as? String
yearTextField.text = cars[carIndex!].valueForKey("year") as? String
colorTextField.text = cars[carIndex!].valueForKey("color") as? String
priceTextField.text = cars[carIndex!].valueForKey("price") as? String
vinNumTextField.text = cars[carIndex!].valueForKey("vinNum") as? String
licNumTextField.text = cars[carIndex!].valueForKey("licNum") as? String
notesTextField.text = cars[carIndex!].valueForKey("notes") as? String
}
func updateData() {
cars[carIndex!].setValue(nameTextField.text, forKey: "name")
cars[carIndex!].setValue(makeTextField.text, forKey: "make")
cars[carIndex!].setValue(modelTextField.text, forKey: "model")
cars[carIndex!].setValue(yearTextField.text, forKey: "year")
cars[carIndex!].setValue(colorTextField.text, forKey: "color")
cars[carIndex!].setValue(priceTextField.text, forKey: "price")
cars[carIndex!].setValue(vinNumTextField.text, forKey: "vinNum")
cars[carIndex!].setValue(licNumTextField.text, forKey: "licNum")
cars[carIndex!].setValue(notesTextField.text, forKey: "notes")
//save in persistent store
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.saveContext()
//populateFields() //not really needed, just the title
title = nameTextField.text
}
func cancelToCarMenu(sender: UIBarButtonItem) {
self.performSegueWithIdentifier("cancelToMenuSegue", sender: sender)
}
func saveToCarMenu(sender: UIBarButtonItem) {
self.nameTextField.text = self.nameTextField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if self.nameTextField.text != "" {
self.performSegueWithIdentifier("saveToMenuSegue", sender: sender)
}
else {
let invalidFieldsAlert = UIAlertController(title: "Save Car", message: "The car must have a name.", preferredStyle: UIAlertControllerStyle.Alert)
invalidFieldsAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
//do nothing
}))
presentViewController(invalidFieldsAlert, animated: true, completion: nil)
}
}
func editButtonPressed(sender: UIBarButtonItem) {
enableTextEditting()
//set the bar items
let leftButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancelButtonPressed")
let rightButton = UIBarButtonItem(title: "Save", style: .Done, target: self, action: "saveButtonPressedForUpdate")
leftButton.tintColor = UIColor.whiteColor()
rightButton.tintColor = UIColor.whiteColor()
self.navigationItem.leftBarButtonItem = leftButton
self.navigationItem.rightBarButtonItem = rightButton
}
func cancelButtonPressed() {
disableTextEditting()
resetBarItems()
}
func saveButtonPressedForUpdate() {
self.nameTextField.text = self.nameTextField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if self.nameTextField.text != "" {
updateData()
disableTextEditting()
resetBarItems()
}
else {
let invalidFieldsAlert = UIAlertController(title: "Save Car", message: "The car must have a name.", preferredStyle: UIAlertControllerStyle.Alert)
invalidFieldsAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
//do nothing
}))
presentViewController(invalidFieldsAlert, animated: true, completion: nil)
}
}
@IBAction func deleteButtonPressed(sender: AnyObject) {
let deleteAlert = UIAlertController(title: "Delete Car", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)
deleteAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
//do nothing
}))
deleteAlert.addAction(UIAlertAction(title: "Ok", style: .Destructive, handler: { (action: UIAlertAction!) in
self.deleteThisCar(sender)
//exit this view (the car is gone)
self.performSegueWithIdentifier("cancelToMenuSegue", sender: sender)
}))
presentViewController(deleteAlert, animated: true, completion: nil)
}
func deleteThisCar(sender: AnyObject) {
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let thisCarID = cars[carIndex!].valueForKey("id") as? Int
for i in 0...maintenanceItems.count-1
{
if maintenanceItems[i].valueForKey("carID") as? Int == thisCarID
{
managedContext.deleteObject(maintenanceItems[i] as NSManagedObject)
}
}
//delete the car
managedContext.deleteObject(cars[carIndex!] as NSManagedObject)
cars.removeAtIndex(carIndex!)
appDelegate.saveContext()
}
func resetBarItems() {
self.navigationItem.leftBarButtonItem = self.leftBarItem
self.navigationItem.rightBarButtonItem = self.rightBarItem
}
func disableTextEditting() {
populateVinTextField.hidden = true
populateVinButton.hidden = true
nameTextField.hidden = true
nameLabel.hidden = true
populateVinTextField.userInteractionEnabled = false
nameTextField.userInteractionEnabled = false
makeTextField.userInteractionEnabled = false
makeTextField.borderStyle = UITextBorderStyle.None
modelTextField.userInteractionEnabled = false
modelTextField.borderStyle = UITextBorderStyle.None
yearTextField.userInteractionEnabled = false
yearTextField.borderStyle = UITextBorderStyle.None
colorTextField.userInteractionEnabled = false
colorTextField.borderStyle = UITextBorderStyle.None
priceTextField.userInteractionEnabled = false
priceTextField.borderStyle = UITextBorderStyle.None
vinNumTextField.userInteractionEnabled = false
vinNumTextField.borderStyle = UITextBorderStyle.None
licNumTextField.userInteractionEnabled = false
licNumTextField.borderStyle = UITextBorderStyle.None
notesTextField.userInteractionEnabled = false
notesTextField.borderStyle = UITextBorderStyle.None
deleteButton.hidden = true
}
func enableTextEditting() {
populateVinTextField.hidden = false
populateVinButton.hidden = false
nameTextField.hidden = false
nameLabel.hidden = false
populateVinTextField.userInteractionEnabled = true
nameTextField.userInteractionEnabled = true
makeTextField.userInteractionEnabled = true
makeTextField.borderStyle = UITextBorderStyle.RoundedRect
modelTextField.userInteractionEnabled = true
modelTextField.borderStyle = UITextBorderStyle.RoundedRect
yearTextField.userInteractionEnabled = true
yearTextField.borderStyle = UITextBorderStyle.RoundedRect
colorTextField.userInteractionEnabled = true
colorTextField.borderStyle = UITextBorderStyle.RoundedRect
priceTextField.userInteractionEnabled = true
priceTextField.borderStyle = UITextBorderStyle.RoundedRect
vinNumTextField.userInteractionEnabled = true
vinNumTextField.borderStyle = UITextBorderStyle.RoundedRect
licNumTextField.userInteractionEnabled = true
licNumTextField.borderStyle = UITextBorderStyle.RoundedRect
notesTextField.userInteractionEnabled = true
notesTextField.borderStyle = UITextBorderStyle.RoundedRect
if newCar == false {
deleteButton.hidden = false
}
else {
deleteButton.hidden = true
}
}
@IBAction func populateVin(sender: AnyObject) {
//Steven's Car VIN (Not Case Sensitive): 1FADP3L9XFL256135
var vin = ""
vin = populateVinTextField.text!
self.view.window?.endEditing(true)
if vin.characters.count == 17
{
let urlString = "https://api.edmunds.com/api/vehicle/v2/vins/" + vin + "?fmt=json&api_key=5zyd8sa5k3yxgpcg7t49agav"
if let url = NSURL(string: urlString)
{
if let data = try? NSData(contentsOfURL: url, options: [])
{
let json = JSON(data: data)
if json["make"]["id"].intValue > 0
{
//let id = json["make"]["id"].intValue
let makeName = json["make"]["name"].stringValue
let modelName = json["model"]["name"].stringValue
let yearName = json["years"][0]["year"].stringValue
let colorName = json["colors"][1]["options"][0]["name"].stringValue
let priceName = json["price"]["baseMSRP"].stringValue
let vinName = json["vin"].stringValue
let styleID = json["years"][0]["styles"][0]["id"].stringValue
let obj = ["makeName": makeName, "modelName": modelName, "yearName": yearName, "colorName": colorName, "priceName": priceName, "vinName": vinName, "styleID": styleID]
setObject(obj)
populateVinTextField.text="";
}
else
{
let invalidFieldsAlert = UIAlertController(title: "Populate Failed", message: "Invalid Vin Number.", preferredStyle: UIAlertControllerStyle.Alert)
invalidFieldsAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
//do nothing
}))
presentViewController(invalidFieldsAlert, animated: true, completion: nil)
}
}
}
}
else
{
let invalidFieldsAlert = UIAlertController(title: "Populate Information", message: "Invalid Vin Number.", preferredStyle: UIAlertControllerStyle.Alert)
invalidFieldsAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
//do nothing
}))
presentViewController(invalidFieldsAlert, animated: true, completion: nil)
}
} // END of Populate Button Function
func setObject(obj:[String:String])
{
self.makeTextField.text = obj["makeName"]
self.modelTextField.text = obj["modelName"]
self.yearTextField.text = obj["yearName"]
self.colorTextField.text = obj["colorName"]
self.priceTextField.text = obj["priceName"]
self.vinNumTextField.text = obj["vinName"]
self.styleID = obj["styleID"]
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
let nextTage=textField.tag+1;
// Try to find next responder
let nextResponder=textField.superview?.viewWithTag(nextTage) as UIResponder!
if (nextResponder != nil){
// Found next responder, so set it.
nextResponder?.becomeFirstResponder()
}
else
{
// Not found, so remove keyboard
textField.resignFirstResponder()
}
return false // We do not want UITextField to insert line-breaks.
}
func setTextFieldDelegates() {
self.populateVinTextField.delegate = self
self.nameTextField.delegate = self
self.makeTextField.delegate = self
self.modelTextField.delegate = self
self.yearTextField.delegate = self
self.colorTextField.delegate = self
self.priceTextField.delegate = self
self.vinNumTextField.delegate = self
self.licNumTextField.delegate = self
self.notesTextField.delegate = self
}
func keyboardWillShow(notification:NSNotification){
var userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
keyboardFrame = self.view.convertRect(keyboardFrame, fromView: nil)
scrollView.scrollEnabled = true
var contentInset:UIEdgeInsets = self.scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height
self.scrollView.contentInset = contentInset
//scrollView.scrollEnabled = false
}
func keyboardWillHide(notification:NSNotification){
scrollView.scrollEnabled = true
self.scrollView.setContentOffset(CGPoint(x:0,y:0), animated: true)
scrollView.scrollEnabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
//put stuff to save textfield's text
}
}
| gpl-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/14575-swift-sourcemanager-getmessage.swift | 11 | 250 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A {
class c {
{
{
}
}
{
}
func a
{
enum A {
deinit {
( [ {
class
case ,
| mit |
stefanoa/Spectrogram | Spectogram/play.playground/Contents.swift | 1 | 421 | //: Playground - noun: a place where people can play
import UIKit
let delta:CGFloat = 10
func yAtIndex(index:Int)->CGFloat{
let indexF = CGFloat(index)
return round((log(indexF+1)/log(noteSeparation))*delta)
}
let noteSeparation:CGFloat = 1.059463
let size:Int = 16
let y0 = yAtIndex(index: 0)
for i in 0...size-1{
let y = yAtIndex(index: i)
print("y:\(y)")
}
print ("size:\(yAtIndex(index:size-1))")
| mit |
spotify/SPTDataLoader | Sources/SPTDataLoaderSwift/Request+Concurrency.swift | 1 | 4004 | // Copyright 2015-2022 Spotify AB
//
// 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.
#if compiler(>=5.5.2) && canImport(_Concurrency)
import Foundation
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
public extension Request {
func task() -> ResponseTask<Void> {
return ResponseTask(request: self)
}
func dataTask() -> ResponseTask<Data> {
return ResponseTask(request: self)
}
func decodableTask<Value: Decodable>(
type: Value.Type = Value.self,
decoder: ResponseDecoder = JSONDecoder()
) -> ResponseTask<Value> {
return ResponseTask(request: self, decodableType: type, decoder: decoder)
}
func jsonTask(options: JSONSerialization.ReadingOptions = []) -> ResponseTask<Any> {
return ResponseTask(request: self, options: options)
}
func serializableTask<Serializer: ResponseSerializer>(serializer: Serializer) -> ResponseTask<Serializer.Output> {
return ResponseTask(request: self, serializer: serializer)
}
}
// MARK: -
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
public struct ResponseTask<Value> {
private let task: Task<Response<Value, Error>, Never>
fileprivate init(
request: Request,
continuation: @escaping (CheckedContinuation<Response<Value, Error>, Never>) -> Void
) {
self.task = Task {
await withTaskCancellationHandler(
operation: { await withCheckedContinuation(continuation) },
onCancel: {
request.cancel()
}
)
}
}
public func cancel() {
task.cancel()
}
public var response: Response<Value, Error> {
get async { await task.value }
}
public var result: Result<Value, Error> {
get async { await response.result }
}
public var value: Value {
get async throws { try await result.get() }
}
}
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
private extension ResponseTask {
init(request: Request) where Value == Void {
self.init(request: request) { continuation in
request.response { response in
continuation.resume(returning: response)
}
}
}
init(request: Request) where Value == Data {
self.init(request: request) { continuation in
request.responseData { response in
continuation.resume(returning: response)
}
}
}
init(request: Request, decodableType: Value.Type, decoder: ResponseDecoder) where Value: Decodable {
self.init(request: request) { continuation in
request.responseDecodable(type: decodableType, decoder: decoder) { response in
continuation.resume(returning: response)
}
}
}
init(request: Request, options: JSONSerialization.ReadingOptions) where Value == Any {
self.init(request: request) { continuation in
request.responseJSON(options: options) { response in
continuation.resume(returning: response)
}
}
}
init<Serializer: ResponseSerializer>(request: Request, serializer: Serializer) where Value == Serializer.Output {
self.init(request: request) { continuation in
request.responseSerializable(serializer: serializer) { response in
continuation.resume(returning: response)
}
}
}
}
#endif
| apache-2.0 |
brentdax/swift | test/Driver/force-response-files.swift | 6 | 195 | // Ensure that -driver-force-response-files works.
// RUN: %swiftc_driver -driver-force-response-files -typecheck %S/../Inputs/empty.swift -### 2>&1 | %FileCheck %s
// CHECK: @
// CHECK: .resp
| apache-2.0 |
tardieu/swift | test/IDE/infer_import_as_member.swift | 7 | 4876 | // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/custom-modules/CollisionImportAsMember.h -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=InferImportAsMember -always-argument-labels -enable-infer-import-as-member > %t.printed.A.txt
// RUN: %target-swift-frontend -typecheck -import-objc-header %S/Inputs/custom-modules/CollisionImportAsMember.h -I %t -I %S/Inputs/custom-modules %s -enable-infer-import-as-member -verify
// RUN: %FileCheck %s -check-prefix=PRINT -strict-whitespace < %t.printed.A.txt
// REQUIRES: objc_interop
import InferImportAsMember
let mine = IAMStruct1()
let _ = mine.getCollisionNonProperty(1)
// TODO: more cases, eventually exhaustive, as we start inferring the result we
// want
// PRINT-LABEL: struct IAMStruct1 {
// PRINT-NEXT: var x: Double
// PRINT-NEXT: var y: Double
// PRINT-NEXT: var z: Double
// PRINT-NEXT: init()
// PRINT-NEXT: init(x x: Double, y y: Double, z z: Double)
// PRINT-NEXT: }
// PRINT-LABEL: extension IAMStruct1 {
// PRINT-NEXT: static var globalVar: Double
//
// PRINT-LABEL: /// Init
// PRINT-NEXT: init(copyIn in: IAMStruct1)
// PRINT-NEXT: init(simpleValue value: Double)
// PRINT-NEXT: init(redundant redundant: Double)
// PRINT-NEXT: init(specialLabel specialLabel: ())
//
// PRINT-LABEL: /// Methods
// PRINT-NEXT: func invert() -> IAMStruct1
// PRINT-NEXT: mutating func invertInPlace()
// PRINT-NEXT: func rotate(radians radians: Double) -> IAMStruct1
// PRINT-NEXT: func selfComesLast(x x: Double)
// PRINT-NEXT: func selfComesThird(a a: Double, b b: Float, x x: Double)
//
// PRINT-LABEL: /// Properties
// PRINT-NEXT: var radius: Double { get nonmutating set }
// PRINT-NEXT: var altitude: Double
// PRINT-NEXT: var magnitude: Double { get }
// PRINT-NEXT: var length: Double
//
// PRINT-LABEL: /// Various instance functions that can't quite be imported as properties.
// PRINT-NEXT: func getNonPropertyNumParams() -> Float
// PRINT-NEXT: func setNonPropertyNumParams(a a: Float, b b: Float)
// PRINT-NEXT: func getNonPropertyType() -> Float
// PRINT-NEXT: func setNonPropertyType(x x: Double)
// PRINT-NEXT: func getNonPropertyNoSelf() -> Float
// PRINT-NEXT: static func setNonPropertyNoSelf(x x: Double, y y: Double)
// PRINT-NEXT: func setNonPropertyNoGet(x x: Double)
// PRINT-NEXT: func setNonPropertyExternalCollision(x x: Double)
//
// PRINT-LABEL: /// Various static functions that can't quite be imported as properties.
// PRINT-NEXT: static func staticGetNonPropertyNumParams() -> Float
// PRINT-NEXT: static func staticSetNonPropertyNumParams(a a: Float, b b: Float)
// PRINT-NEXT: static func staticGetNonPropertyNumParamsGetter(d d: Double)
// PRINT-NEXT: static func staticGetNonPropertyType() -> Float
// PRINT-NEXT: static func staticSetNonPropertyType(x x: Double)
// PRINT-NEXT: static func staticGetNonPropertyNoSelf() -> Float
// PRINT-NEXT: static func staticSetNonPropertyNoSelf(x x: Double, y y: Double)
// PRINT-NEXT: static func staticSetNonPropertyNoGet(x x: Double)
//
// PRINT-LABEL: /// Static method
// PRINT-NEXT: static func staticMethod() -> Double
// PRINT-NEXT: static func tlaThreeLetterAcronym() -> Double
//
// PRINT-LABEL: /// Static computed properties
// PRINT-NEXT: static var staticProperty: Double
// PRINT-NEXT: static var staticOnlyProperty: Double { get }
//
// PRINT-LABEL: /// Omit needless words
// PRINT-NEXT: static func onwNeedlessTypeArgLabel(_ Double: Double) -> Double
//
// PRINT-LABEL: /// Fuzzy
// PRINT-NEXT: init(fuzzy fuzzy: ())
// PRINT-NEXT: init(fuzzyWithFuzzyName fuzzyWithFuzzyName: ())
// PRINT-NEXT: init(fuzzyName fuzzyName: ())
//
// PRINT-NEXT: func getCollisionNonProperty(_ _: Int32) -> Float
//
// PRINT-NEXT: }
//
// PRINT-NEXT: func __IAMStruct1IgnoreMe(_ s: IAMStruct1) -> Double
//
// PRINT-LABEL: /// Mutable
// PRINT-NEXT: struct IAMMutableStruct1 {
// PRINT-NEXT: init()
// PRINT-NEXT: }
// PRINT-NEXT: extension IAMMutableStruct1 {
// PRINT-NEXT: init(with withIAMStruct1: IAMStruct1)
// PRINT-NEXT: init(url url: UnsafePointer<Int8>!)
// PRINT-NEXT: func doSomething()
// PRINT-NEXT: }
//
// PRINT-LABEL: struct TDStruct {
// PRINT-NEXT: var x: Double
// PRINT-NEXT: init()
// PRINT-NEXT: init(x x: Double)
// PRINT-NEXT: }
// PRINT-NEXT: extension TDStruct {
// PRINT-NEXT: init(float Float: Float)
// PRINT-NEXT: }
//
// PRINT-LABEL: /// Class
// PRINT-NEXT: class IAMClass {
// PRINT-NEXT: }
// PRINT-NEXT: typealias IAMOtherName = IAMClass
// PRINT-NEXT: extension IAMClass {
// PRINT-NEXT: class var typeID: UInt32 { get }
// PRINT-NEXT: init!(i i: Double)
// PRINT-NEXT: class func invert(_ iamOtherName: IAMOtherName!)
// PRINT-NEXT: }
| apache-2.0 |
brentdax/swift | test/Interpreter/generic_ref_counts.swift | 38 | 1107 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
import Swift
// Regression test for <rdar://problem/16119895>.
struct Generic<T> {
typealias Storage = ManagedBuffer<Int,T>
init() {
buffer = ManagedBufferPointer(
bufferClass: Storage.self, minimumCapacity: 0) { _,_ in 0 }
}
mutating func isUniqueReference() -> Bool {
return buffer.isUniqueReference()
}
var buffer: ManagedBufferPointer<Int, T>
}
func g0() {
var x = Generic<Int>()
// CHECK: true
print(x.isUniqueReference())
// CHECK-NEXT: true
print(x.buffer.isUniqueReference())
}
g0()
struct NonGeneric {
typealias T = Int
typealias Storage = ManagedBuffer<Int,T>
init() {
buffer = ManagedBufferPointer(
bufferClass: Storage.self, minimumCapacity: 0) { _,_ in 0 }
}
mutating func isUniqueReference() -> Bool {
return buffer.isUniqueReference()
}
var buffer: ManagedBufferPointer<Int, T>
}
func g1() {
var x = NonGeneric()
// CHECK-NEXT: true
print(x.isUniqueReference())
// CHECK-NEXT: true
print(x.buffer.isUniqueReference())
}
g1()
| apache-2.0 |
bjvanlinschoten/Pala | Pala/Pala/LoginViewController.swift | 1 | 5797 | //
// ViewController.swift
// EventDateApp
//
// Created by Boris van Linschoten on 02-06-15.
// Copyright (c) 2015 bjvanlinschoten. All rights reserved.
//
import UIKit
import Parse
protocol LoginViewControllerDelegate {
func prepareForLogout()
}
class LoginViewController: UIViewController {
// Properties
var currentUser: User?
@IBOutlet weak var loginButton: UIButton?
override func viewDidLoad() {
super.viewDidLoad()
// Set appearance
self.navigationController?.navigationBarHidden = true
self.view.backgroundColor = UIColor(hexString: "FF7400")
// If user is already logged in
if let user = PFUser.currentUser() {
self.loginButton?.hidden = true
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
// Set currentUser
self.currentUser = User(parseUser: user)
// Set-up and load chat
self.setUpPNChannel(user.objectId!)
self.setUpUserForPushMessages()
self.loadUnseenMessages()
self.currentUser?.getUserEvents() { () -> Void in
self.nextView()
}
} else {
self.loginButton?.hidden = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func fbLoginClick(sender: AnyObject) {
// Start login
self.loginButton?.hidden = true
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
// Login with FB
PFFacebookUtils.logInInBackgroundWithReadPermissions(["public_profile", "user_events", "user_birthday"]) {
(user: PFUser?, error: NSError?) -> Void in
// If successful
if let user = user {
self.currentUser = User(parseUser: user)
// Set-up channel for chat
self.setUpPNChannel(user.objectId!)
self.setUpUserForPushMessages()
self.loadUnseenMessages()
if user.isNew {
self.setUpUserForPushMessages()
self.currentUser?.populateNewUserWithFBData() {(completion:Void) in
self.nextView()
}
} else {
self.currentUser?.parseUser.fetchInBackground()
self.nextView()
}
}
else {
// User cancelled login
self.loginButton?.hidden = false
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
}
func setUpUserForPushMessages(){
// Set up installation with pointer to User, to send push to user
let installation: PFInstallation = PFInstallation.currentInstallation()
installation["user"] = self.currentUser?.parseUser
installation.saveEventually { (success: Bool, error: NSError?) -> Void in
if success == true {
} else {
println(error)
}
}
}
// Load messages that were received while app was inactive
func loadUnseenMessages() {
let chat = Chat()
chat.currentUser = self.currentUser
chat.loadUnseenMessagesFromServer()
}
// Connect to PubNub and subscribe to own channel
func setUpPNChannel(userId: String) {
let userChannel: PNChannel = PNChannel.channelWithName(userId) as! PNChannel
PubNub.connect()
PubNub.subscribeOn([userChannel])
}
func nextView() {
MBProgressHUD.hideHUDForView(self.view, animated: true)
// Instantiate all views that are in the slide menu
var storyboard = UIStoryboard(name: "Main", bundle: nil)
let wvc = storyboard.instantiateViewControllerWithIdentifier("WallViewController") as! WallCollectionViewController
wvc.currentUser = self.currentUser
let wnvc: UINavigationController = UINavigationController(rootViewController: wvc)
let evc = storyboard.instantiateViewControllerWithIdentifier("EventsViewController") as! EventsViewController
let envc: UINavigationController = UINavigationController(rootViewController: evc)
evc.currentUser = self.currentUser
evc.wallViewController = wvc
let cvc = storyboard.instantiateViewControllerWithIdentifier("ChatsViewController") as! ChatsTableViewController
let cnvc: UINavigationController = UINavigationController(rootViewController: cvc)
cvc.currentUser = self.currentUser
cvc.wallViewController = wvc
// instantiate slide menu
let slideMenuController = SlideMenuController(mainViewController: wnvc, leftMenuViewController: envc, rightMenuViewController: cnvc)
let slideNvc: UINavigationController = UINavigationController(rootViewController: slideMenuController)
slideNvc.navigationBarHidden = true
slideNvc.automaticallyAdjustsScrollViewInsets = false
// Present the slide menu
self.presentViewController(slideNvc, animated: false, completion: nil)
}
// Log out user
@IBAction func logOut(segue:UIStoryboardSegue) {
prepareForLogout()
self.currentUser?.logout()
}
// Prepare view for logout
func prepareForLogout() {
MBProgressHUD.hideHUDForView(self.view, animated: true)
self.navigationController?.navigationBarHidden = true
self.loginButton?.hidden = false
}
}
| mit |
tkremenek/swift | test/Constraints/openExistential.swift | 34 | 355 | // RUN: %target-typecheck-verify-swift
protocol P { }
func foo<T: P>(_: T) {}
func bar<T: P>(_: T.Type) {}
func open(existential: P, mutExistential: inout P) {
_openExistential(existential, do: foo)
_openExistential(type(of: existential), do: bar)
_openExistential(mutExistential, do: foo)
_openExistential(type(of: mutExistential), do: bar)
}
| apache-2.0 |
Mazy-ma/DemoBySwift | FireworksByCAEmitterLayer/FireworksByCAEmitterLayer/ViewController.swift | 1 | 4922 | //
// ViewController.swift
// FireworksByCAEmitterLayer
//
// Created by Mazy on 2017/7/17.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var emitterLayer: CAEmitterLayer = CAEmitterLayer()
lazy var fireworksView: FireworksView = {
let fv = FireworksView()
return fv
}()
override func viewDidLoad() {
super.viewDidLoad()
let backImage = UIImage(named: "backImage")
let backImageView = UIImageView(image: backImage)
backImageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
backImageView.contentMode = .scaleAspectFill
view.addSubview(backImageView)
backImageView.isUserInteractionEnabled = true
let gesture = UITapGestureRecognizer(target: self, action: #selector(startAnimation))
backImageView.addGestureRecognizer(gesture)
}
func startAnimation() {
view.addSubview(fireworksView)
fireworksView.giftImage = UIImage(named: "flower")
fireworksView.startFireworks()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2) {
self.fireworksView.stopFireworks()
self.fireworksView.removeFromSuperview()
}
}
func setupFireworks() {
// 发射源
emitterLayer.emitterPosition = CGPoint(x: view.bounds.width/2, y: view.bounds.height-50)
// 发射源尺寸大小
emitterLayer.emitterSize = CGSize(width: 50, height: 0)
// 发射源模式
emitterLayer.emitterMode = kCAEmitterLayerOutline
// 发射源的形状
emitterLayer.emitterShape = kCAEmitterLayerLine
// 渲染模式
emitterLayer.renderMode = kCAEmitterLayerAdditive
// 发射方向
emitterLayer.velocity = 1
// 随机产生粒子
emitterLayer.seed = (arc4random()%100) + 1
// cell
let cell: CAEmitterCell = CAEmitterCell()
// 速率
cell.birthRate = 1.0
// 发射的角度
cell.emissionRange = 0.11 * CGFloat(M_PI)
// 速度
cell.velocity = 300
// 范围
cell.velocityRange = 150
// Y轴,加速度分量
cell.yAcceleration = 75
// 声明周期
cell.lifetime = 2.04
// 内容:是个CGImageRef的对象,既粒子要展现的图片
cell.contents = UIImage(named: "ring")?.cgImage
// 缩放比例
cell.scale = 0.2
// 粒子的颜色
cell.color = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1.0).cgColor
// 一个粒子的颜色green 能改变的范围
cell.greenRange = 1.0
// 一个粒子的颜色red 能改变的范围
cell.redRange = 1.0
// 一个粒子的颜色blue 能改变的范围
cell.blueRange = 1.0
// 子旋转角度范围
cell.spinRange = CGFloat(M_PI)
// 爆炸💥
let burst: CAEmitterCell = CAEmitterCell()
// 粒子产生系数
burst.birthRate = 1.0
// 速度
burst.velocity = 0
// 缩放比例
burst.scale = 2.5
// shifting粒子red在生命周期内的改变速度
burst.redSpeed = -1.5
// shifting粒子blue在生命周期内的改变速度
burst.blueSpeed += 1.5
// shifting粒子green在生命周期内的改变速度
burst.greenSpeed = +1.0
// 生命周期
burst.lifetime = 0.35
// 火花 and finally, the sparks
let spark: CAEmitterCell = CAEmitterCell()
// 粒子产生系数,默认为1.0
spark.birthRate = 400
// 速度
spark.velocity = 125
// 360 deg //周围发射角度
spark.emissionRange = 2 * CGFloat(M_PI)
// gravity //y方向上的加速度分量
spark.yAcceleration = 75
// 粒子生命周期
spark.lifetime = 3
// 是个CGImageRef的对象,既粒子要展现的图片
spark.contents = UIImage(named: "fireworks")?.cgImage
// 缩放比例速度
spark.scaleSpeed = -0.2
// 粒子green在生命周期内的改变速度
spark.greenSpeed = -0.1
// 粒子red在生命周期内的改变速度
spark.redSpeed = 0.4
// 粒子blue在生命周期内的改变速度
spark.blueSpeed = -0.1
// 粒子透明度在生命周期内的改变速度
spark.alphaSpeed = -0.25
// 子旋转角度
spark.spin = 2 * CGFloat(M_PI)
// 子旋转角度范围
spark.spinRange = 2 * CGFloat(M_PI)
emitterLayer.emitterCells = [cell]
cell.emitterCells = [burst]
burst.emitterCells = [spark]
self.view.layer.addSublayer(emitterLayer)
}
}
| apache-2.0 |
joalbright/Playgrounds | TernarySwitch.playground/Contents.swift | 1 | 2246 | //: Playground - noun: a place where people can play
import UIKit
enum LifeStatus: Int { case Alive, Dead, Zombie }
enum AgeGroup: Int { case Baby, Toddler, Kid, Preteen, Teen, Adult }
////////////////////
let life: LifeStatus = .Dead
// embedded ternary operators … how I have built a ternary switch in past
let old = life == .Alive ? UIColor.greenColor()
: life == .Dead ? UIColor.redColor()
: life == .Zombie ? UIColor.grayColor()
: UIColor.whiteColor()
// using custom operators
let v2 = life ??? .Alive --> UIColor.greenColor()
||| .Dead --> UIColor.redColor()
||| .Zombie --> UIColor.grayColor()
*** UIColor.whiteColor()
let v3 = 100 ??? 10 --> UIColor.greenColor()
||| 20 --> UIColor.redColor()
||| 30 --> UIColor.grayColor()
*** UIColor.magentaColor()
// works with ranges
let r1 = 21 ??? (0...3) --> AgeGroup.Baby
||| (4...12) --> AgeGroup.Kid
||| (13...19) --> AgeGroup.Teen
*** AgeGroup.Adult
// works with closures
let c1 = life ??? {
switch $0 {
case .Alive: return UIColor.greenColor()
case .Dead: return UIColor.redColor()
case .Zombie: return UIColor.grayColor()
}
}
let c2 = 12 ??? {
switch $0 {
case 0..<10: return UIColor.clearColor()
case let x where x < 20: return UIColor.yellowColor()
case let x where x < 30: return UIColor.orangeColor()
case let x where x < 40: return UIColor.redColor()
default: return UIColor.whiteColor()
}
}
extension UIView: SwitchInit { }
let button1 = life ??? UIButton.self ||| {
switch $0 {
case .Alive : $1.setTitle("Eat Lunch", forState: .Normal)
case .Dead : $1.setTitle("Eat Dirt", forState: .Normal)
case .Zombie : $1.setTitle("Eat Brains", forState: .Normal)
}
}
let button2 = UIButton (life) {
switch $0 {
case .Alive : $1.setTitle("Eat Lunch", forState: .Normal)
case .Dead : $1.setTitle("Eat Dirt", forState: .Normal)
case .Zombie : $1.setTitle("Eat Brains", forState: .Normal)
}
}
button1.titleLabel?.text
button2.titleLabel?.text
| apache-2.0 |
borut-t/Kingfisher | KingfisherTests/ImageDownloaderTests.swift | 7 | 8804 | //
// ImageDownloaderTests.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/10.
//
// Copyright (c) 2015 Wei Wang <onevcat@gmail.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 XCTest
import Kingfisher
class ImageDownloaderTests: XCTestCase {
var downloader: ImageDownloader!
override class func setUp() {
super.setUp()
LSNocilla.sharedInstance().start()
}
override class func tearDown() {
super.tearDown()
LSNocilla.sharedInstance().stop()
}
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
downloader = ImageDownloader(name: "test")
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
LSNocilla.sharedInstance().clearStubs()
downloader = nil
super.tearDown()
}
func testDownloadAnImage() {
let expectation = expectationWithDescription("wait for downloading image")
let URLString = testKeys[0]
stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
let URL = NSURL(string: URLString)!
downloader.downloadImageWithURL(URL, options: KingfisherManager.OptionsNone, progressBlock: { (receivedSize, totalSize) -> () in
return
}) { (image, error, imageURL) -> () in
expectation.fulfill()
XCTAssert(image != nil, "Download should be able to finished for URL: \(imageURL)")
}
waitForExpectationsWithTimeout(5, handler: nil)
}
func testDownloadMultipleImages() {
let expectation = expectationWithDescription("wait for all downloading finish")
let group = dispatch_group_create()
for URLString in testKeys {
if let URL = NSURL(string: URLString) {
dispatch_group_enter(group)
stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
downloader.downloadImageWithURL(URL, options: KingfisherManager.OptionsNone, progressBlock: { (receivedSize, totalSize) -> () in
}, completionHandler: { (image, error, imageURL) -> () in
XCTAssert(image != nil, "Download should be able to finished for URL: \(imageURL).")
dispatch_group_leave(group)
})
}
}
dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
expectation.fulfill()
}
waitForExpectationsWithTimeout(5, handler: nil)
}
func testDownloadAnImageWithMultipleCallback() {
let expectation = expectationWithDescription("wait for downloading image")
let group = dispatch_group_create()
let URLString = testKeys[0]
stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
for _ in 0...5 {
dispatch_group_enter(group)
downloader.downloadImageWithURL(NSURL(string: URLString)!, options: KingfisherManager.OptionsNone, progressBlock: { (receivedSize, totalSize) -> () in
}) { (image, error, imageURL) -> () in
XCTAssert(image != nil, "Download should be able to finished for URL: \(imageURL).")
dispatch_group_leave(group)
}
}
dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
expectation.fulfill()
}
waitForExpectationsWithTimeout(5, handler: nil)
}
func testDownloadWithModifyingRequest() {
let expectation = expectationWithDescription("wait for downloading image")
let URLString = testKeys[0]
stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
downloader.requestModifier = {
(request: NSMutableURLRequest) in
request.URL = NSURL(string: URLString)
}
let someURL = NSURL(string: "some_strange_url")!
downloader.downloadImageWithURL(someURL, options: KingfisherManager.OptionsNone, progressBlock: { (receivedSize, totalSize) -> () in
}) { (image, error, imageURL) -> () in
XCTAssert(image != nil, "Download should be able to finished for URL: \(imageURL).")
XCTAssertEqual(imageURL!, NSURL(string: URLString)!, "The returned imageURL should be the replaced one")
expectation.fulfill()
}
waitForExpectationsWithTimeout(5, handler: nil)
}
func testServerNotModifiedResponse() {
let expectation = expectationWithDescription("wait for server response 304")
let URLString = testKeys[0]
stubRequest("GET", URLString).andReturn(304)
downloader.downloadImageWithURL(NSURL(string: URLString)!, options: KingfisherManager.OptionsNone, progressBlock: { (receivedSize, totalSize) -> () in
}) { (image, error, imageURL) -> () in
XCTAssertNotNil(error, "There should be an error since server returning 304 and no image downloaded.")
XCTAssertEqual(error!.code, KingfisherError.NotModified.rawValue, "The error should be NotModified.")
expectation.fulfill()
}
waitForExpectationsWithTimeout(5, handler: nil)
}
// Since we could not receive one challage, no test for trusted hosts currently.
// See http://stackoverflow.com/questions/27065372/why-is-a-https-nsurlsession-connection-only-challenged-once-per-domain for more.
func testSSLCertificateValidation() {
LSNocilla.sharedInstance().stop()
let URL = NSURL(string: "https://testssl-expire.disig.sk/Expired.png")!
let expectation = expectationWithDescription("wait for download from an invalid ssl site.")
downloader.downloadImageWithURL(URL, progressBlock: nil, completionHandler: { (image, error, imageURL) -> () in
XCTAssertNotNil(error, "Error should not be nil")
XCTAssert(error?.code == NSURLErrorServerCertificateUntrusted || error?.code == NSURLErrorSecureConnectionFailed, "Error should be NSURLErrorServerCertificateUntrusted, but \(error)")
expectation.fulfill()
LSNocilla.sharedInstance().start()
})
waitForExpectationsWithTimeout(20) { (error) in
XCTAssertNil(error, "\(error)")
LSNocilla.sharedInstance().start()
}
}
func testDownloadResultErrorAndRetry() {
let expectation = expectationWithDescription("wait for downloading error")
let URLString = testKeys[0]
stubRequest("GET", URLString).andFailWithError(NSError(domain: "stubError", code: -1, userInfo: nil))
let URL = NSURL(string: URLString)!
downloader.downloadImageWithURL(URL, progressBlock: nil) { (image, error, imageURL) -> () in
XCTAssertNotNil(error, "Should return with an error")
LSNocilla.sharedInstance().clearStubs()
stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
// Retry the download
self.downloader.downloadImageWithURL(URL, progressBlock: nil, completionHandler: { (image, error, imageURL) -> () in
XCTAssertNil(error, "Download should be finished without error")
expectation.fulfill()
})
}
waitForExpectationsWithTimeout(5, handler: nil)
}
}
| mit |
Serheo/PhoneNumberFormatter | PhoneNumberFormatterTests/FormatterTests.swift | 1 | 6769 | //
// FormatterTests.swift
// PhoneNumberFormatterTests
//
// Created by Sergey Shatunov on 9/3/17.
// Copyright © 2017 SHS. All rights reserved.
//
import XCTest
@testable import PhoneNumberFormatter
class FormatterTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testShouldFormatByDefault() {
let defaultFormat = PhoneFormat(defaultPhoneFormat: "+# (###) ###-##-##")
let config = ConfigurationRepo(defaultFormat: defaultFormat)
let inputNumber = "12345678901"
let formatter = PhoneFormatter(config: config)
var result = formatter.formatText(text: inputNumber, prefix: nil)
XCTAssert(result.text == "+1 (234) 567-89-01", "Should format correctly")
formatter.config.defaultConfiguration = PhoneFormat(defaultPhoneFormat: "+# (###) ###-####")
result = formatter.formatText(text: inputNumber, prefix: nil)
XCTAssert(result.text == "+1 (234) 567-8901", "Should format correctly")
}
func testShouldDetectSpecificFormats() {
let config = ConfigurationRepo(defaultFormat: PhoneFormat(defaultPhoneFormat: "+# (###) ###-##-##"))
config.add(format: PhoneFormat(phoneFormat: "+### (##) ###-##-##", regexp: "^380\\d*$"))
let formatter = PhoneFormatter(config: config)
let inputNumber = "12345678901"
let specififcInputNumber = "38012345678901"
var result = formatter.formatText(text: inputNumber, prefix: nil)
XCTAssert(result.text == "+1 (234) 567-89-01", "Should format number by default")
result = formatter.formatText(text: specififcInputNumber, prefix: nil)
XCTAssert(result.text == "+380 (12) 345-67-89", "specififcInputNumber")
}
func testShouldHandleSpecialSymbols() {
let config = ConfigurationRepo(defaultFormat: PhoneFormat(defaultPhoneFormat: "+# (###) ###-##-##"))
let formatter = PhoneFormatter(config: config)
var inputNumber = "!#dsti*&"
var result = formatter.formatText(text: inputNumber, prefix: nil)
XCTAssert(result.text == "", "should remove non-number symbols")
inputNumber = "+12345678901"
result = formatter.formatText(text: inputNumber, prefix: nil)
XCTAssert(result.text == "+1 (234) 567-89-01", "should format number by default and handle + symbol")
}
func testShouldHandleFormatWithDigitsAtStart() {
let config = ConfigurationRepo(defaultFormat: PhoneFormat(defaultPhoneFormat: "+7 (###) ###-##-##"))
let formatter = PhoneFormatter(config: config)
var inputNumber = "9201234567"
var result = formatter.formatText(text: inputNumber, prefix: nil)
XCTAssert(result.text == "+7 (920) 123-45-67", "should format correctly")
inputNumber = "7777778877"
result = formatter.formatText(text: inputNumber, prefix: nil)
XCTAssert(result.text == "+7 (777) 777-88-77", "should format correctly")
}
func testShouldHandleFormatWithDigitsInTheMiddle() {
let config = ConfigurationRepo(defaultFormat: PhoneFormat(defaultPhoneFormat: "### 123 ##-##"))
let formatter = PhoneFormatter(config: config)
var inputNumber = "3211231"
var result = formatter.formatText(text: inputNumber, prefix: nil)
XCTAssert(result.text == "321 123 12-31", "should format correctly")
inputNumber = "1113333"
result = formatter.formatText(text: inputNumber, prefix: nil)
XCTAssert(result.text == "111 123 33-33", "should format correctly")
}
func testShouldCheckPrefix() {
let prefix = "pr3f1x"
let config = ConfigurationRepo(defaultFormat: PhoneFormat(defaultPhoneFormat: "(###) ###-##-##"))
let formatter = PhoneFormatter(config: config)
let inputNumber = "9201234567"
let result = formatter.formatText(text: inputNumber, prefix: prefix)
XCTAssert(result.text == prefix + "(920) 123-45-67", "should format correctly")
}
func testShouldCheckPrefixAndDifferentFormats() {
let prefix = "pr3-f1x"
let config = ConfigurationRepo(defaultFormat: PhoneFormat(defaultPhoneFormat: "##########"))
config.add(format: PhoneFormat(phoneFormat: "+### (##) ###-##-##", regexp: "^380\\d*$"))
config.add(format: PhoneFormat(phoneFormat: "+### (##) ###-##-##", regexp: "^123\\d*$"))
let formatter = PhoneFormatter(config: config)
let inputNumber = "3801234567"
let inputNumberNonImage = "1231234567"
var result = formatter.formatText(text: inputNumber, prefix: prefix)
XCTAssert(result.text == prefix + "+380 (12) 345-67", "should format correctly")
result = formatter.formatText(text: inputNumberNonImage, prefix: prefix)
XCTAssert(result.text == prefix + "+123 (12) 345-67", "should format correctly")
}
func testShouldHandleNumberFormatStyles() {
let prefix: String? = nil
let config = ConfigurationRepo(defaultFormat: PhoneFormat(defaultPhoneFormat: "+78 (###) ###-##-##"))
let formatter = PhoneFormatter(config: config)
var result = formatter.formatText(text: "+7 (123", prefix: prefix)
XCTAssert(result.text == "+78 (123", "should format correctly")
result = formatter.formatText(text: "+87 (1234", prefix: prefix)
XCTAssert(result.text == "+78 (871) 234", "should format correctly")
formatter.config.defaultConfiguration = PhoneFormat(defaultPhoneFormat: "+7 (###) 88#-##-##")
result = formatter.formatText(text: "+7 (123", prefix: prefix)
XCTAssert(result.text == "+7 (123", "should format correctly")
result = formatter.formatText(text: "1234", prefix: prefix)
XCTAssert(result.text == "+7 (123) 884", "should format correctly")
result = formatter.formatText(text: "+7 (123) 884", prefix: prefix)
XCTAssert(result.text == "+7 (123) 888-84", "should format correctly")
result = formatter.formatText(text: "+7 (123) 8887", prefix: prefix)
XCTAssert(result.text == "+7 (123) 888-88-7", "should format correctly")
}
func testShouldHandlePrefixNumberFormatStyles() {
let prefix: String = "pr3-f1x "
let config = ConfigurationRepo(defaultFormat: PhoneFormat(defaultPhoneFormat: "+7 (###) 88#-##-##"))
let formatter = PhoneFormatter(config: config)
var result = formatter.formatText(text: "+7 (123", prefix: prefix)
XCTAssert(result.text == prefix + "+7 (123", "should format correctly")
result = formatter.formatText(text: "+7 (123) 8887", prefix: prefix)
XCTAssert(result.text == prefix + "+7 (123) 888-88-7", "should format correctly")
}
}
| mit |
lorentey/swift | test/Serialization/Inputs/comments-batch/File2.swift | 26 | 51 | /// Comment in File2
public func FuncFromFile2() {} | apache-2.0 |
Candyroot/DesignPattern | observer/observer/main.swift | 1 | 470 | //
// main.swift
// observer
//
// Created by Bing Liu on 11/2/14.
// Copyright (c) 2014 UnixOSS. All rights reserved.
//
import Foundation
let weatherData = WeatherData()
let currentDisplay = CurrentConditionsDisplay(weatherData)
let statisticsDisplay = StatisticsDisplay(weatherData)
let forecastDisplay = ForecastDisplay(weatherData)
weatherData.setMeasurements(80, 65, 30.4)
weatherData.setMeasurements(82, 70, 29.2)
weatherData.setMeasurements(78, 90, 29.2)
| apache-2.0 |
inderdhir/DatWeatherDoe | DatWeatherDoe/API/Repository/Location/Coordinates/LocationParser.swift | 1 | 1196 | //
// LocationParser.swift
// DatWeatherDoe
//
// Created by Inder Dhir on 1/10/22.
// Copyright © 2022 Inder Dhir. All rights reserved.
//
import CoreLocation
final class LocationParser {
func parseCoordinates(_ latLong: String) throws -> CLLocationCoordinate2D {
let latLongCombo = latLong.split(separator: ",")
guard latLongCombo.count == 2 else {
throw WeatherError.latLongIncorrect
}
return try parseLocationDegrees(
possibleLatitude: String(latLongCombo[0]).trim(),
possibleLongitude: String(latLongCombo[1]).trim()
)
}
private func parseLocationDegrees(
possibleLatitude: String,
possibleLongitude: String
) throws -> CLLocationCoordinate2D {
let lat = CLLocationDegrees(possibleLatitude.trim())
let long = CLLocationDegrees(possibleLongitude.trim())
guard let lat = lat, let long = long else {
throw WeatherError.latLongIncorrect
}
return .init(latitude: lat, longitude: long)
}
}
private extension String {
func trim() -> String { trimmingCharacters(in: .whitespacesAndNewlines) }
}
| apache-2.0 |
narner/AudioKit | AudioKit/Common/Operations/Generators/Oscillators/sineWave.swift | 1 | 601 | //
// sineWave.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
extension AKOperation {
/// Standard Sine Wave
///
/// - Parameters:
/// - frequency: Frequency in cycles per second (Default: 440)
/// - amplitude: Amplitude of the output (Default: 1)
///
public static func sineWave(
frequency: AKParameter = 440,
amplitude: AKParameter = 1
) -> AKOperation {
return AKOperation(module: "sine", inputs: frequency, amplitude)
}
}
| mit |
sersoft-gmbh/AutoLayout_Macoun16 | AutoLayoutTricks/Empty View/AppDelegate.swift | 1 | 2181 | //
// AppDelegate.swift
// Empty View
//
// Created by Florian Friedrich on 27/06/16.
// Copyright © 2016 ser.soft GmbH. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
pkl728/ZombieInjection | Pods/ReactiveKit/Sources/Event.swift | 2 | 2100 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// 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.
//
/// An event of a sequence.
public enum Event<Element, Error: Swift.Error> {
/// An event that carries next element.
case next(Element)
/// An event that represents failure. Carries an error.
case failed(Error)
/// An event that marks the completion of a sequence.
case completed
}
extension Event {
/// Return `true` in case of `.failure` or `.completed` event.
public var isTerminal: Bool {
switch self {
case .next:
return false
default:
return true
}
}
/// Returns the next element, or nil if the event is not `.next`
public var element: Element? {
switch self {
case .next(let element):
return element
default:
return nil
}
}
/// Return the failed error, or nil if the event is not `.failed`
public var error: Error? {
switch self {
case .failed(let error):
return error
default:
return nil
}
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.