repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
whitepixelstudios/Material | Sources/iOS/Layer.swift | 1 | 5481 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@objc(Layer)
open class Layer: CAShapeLayer {
/**
A CAShapeLayer used to manage elements that would be affected by
the clipToBounds property of the backing layer. For example, this
allows the dropshadow effect on the backing layer, while clipping
the image to a desired shape within the visualLayer.
*/
open let visualLayer = CAShapeLayer()
/**
A property that manages an image for the visualLayer's contents
property. Images should not be set to the backing layer's contents
property to avoid conflicts when using clipsToBounds.
*/
@IBInspectable
open var image: UIImage? {
didSet {
visualLayer.contents = image?.cgImage
}
}
/**
Allows a relative subrectangle within the range of 0 to 1 to be
specified for the visualLayer's contents property. This allows
much greater flexibility than the contentsGravity property in
terms of how the image is cropped and stretched.
*/
open override var contentsRect: CGRect {
didSet {
visualLayer.contentsRect = contentsRect
}
}
/**
A CGRect that defines a stretchable region inside the visualLayer
with a fixed border around the edge.
*/
open override var contentsCenter: CGRect {
didSet {
visualLayer.contentsCenter = contentsCenter
}
}
/**
A floating point value that defines a ratio between the pixel
dimensions of the visualLayer's contents property and the size
of the layer. By default, this value is set to the Screen.scale.
*/
@IBInspectable
open override var contentsScale: CGFloat {
didSet {
visualLayer.contentsScale = contentsScale
}
}
/// A Preset for the contentsGravity property.
open var contentsGravityPreset: Gravity {
didSet {
contentsGravity = GravityToValue(gravity: contentsGravityPreset)
}
}
/// Determines how content should be aligned within the visualLayer's bounds.
@IBInspectable
open override var contentsGravity: String {
get {
return visualLayer.contentsGravity
}
set(value) {
visualLayer.contentsGravity = value
}
}
/**
A property that sets the cornerRadius of the backing layer. If the shape
property has a value of .circle when the cornerRadius is set, it will
become .none, as it no longer maintains its circle shape.
*/
@IBInspectable
open override var cornerRadius: CGFloat {
didSet {
layoutShadowPath()
shapePreset = .none
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
contentsGravityPreset = .resizeAspectFill
super.init(coder: aDecoder)
prepareVisualLayer()
}
/**
An initializer the same as init(). The layer parameter is ignored
to avoid crashes on certain architectures.
- Parameter layer: Any.
*/
public override init(layer: Any) {
contentsGravityPreset = .resizeAspectFill
super.init(layer: layer)
prepareVisualLayer()
}
/// A convenience initializer.
public override init() {
contentsGravityPreset = .resizeAspectFill
super.init()
prepareVisualLayer()
}
/**
An initializer that initializes the object with a CGRect object.
- Parameter frame: A CGRect instance.
*/
public convenience init(frame: CGRect) {
self.init()
self.frame = frame
}
open override func layoutSublayers() {
super.layoutSublayers()
layoutShape()
layoutVisualLayer()
layoutShadowPath()
}
}
fileprivate extension Layer {
/// Prepares the visualLayer property.
func prepareVisualLayer() {
visualLayer.zPosition = 0
visualLayer.masksToBounds = true
addSublayer(visualLayer)
}
/// Manages the layout for the visualLayer property.
func layoutVisualLayer() {
visualLayer.frame = bounds
visualLayer.cornerRadius = cornerRadius
}
}
| bsd-3-clause | 70e250e0e8108f79c35b58ee864d140a | 29.792135 | 88 | 0.729064 | 4.522277 | false | false | false | false |
lammertw/XebiaBlogRSSWidget | XebiaBlogStyleKit.swift | 1 | 2157 | //
// XebiaBlogStyleKit.swift
// XebiaBlog
//
// Created by Lammert Westerhoff on 09/09/14.
// Copyright (c) 2014 CompanyName. All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
import UIKit
public class XebiaBlogStyleKit : NSObject {
//// Drawing Methods
public class func drawArrow(frame: CGRect, arrowStroke: UIColor) {
//// Subframes
let arrowShape: CGRect = CGRectMake(frame.minX - 0.5, frame.minY + 0.5, frame.width, frame.height - 3)
//// ArrowShape
//// Bezier Drawing
var bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(arrowShape.minX + 0.30000 * arrowShape.width, arrowShape.minY + 0.00000 * arrowShape.height))
bezierPath.addLineToPoint(CGPointMake(arrowShape.minX + 0.30000 * arrowShape.width, arrowShape.minY + 0.62222 * arrowShape.height))
bezierPath.addLineToPoint(CGPointMake(arrowShape.minX + 0.00000 * arrowShape.width, arrowShape.minY + 0.44444 * arrowShape.height))
bezierPath.addLineToPoint(CGPointMake(arrowShape.minX + 0.50000 * arrowShape.width, arrowShape.minY + 1.00000 * arrowShape.height))
arrowStroke.setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()
//// Bezier 2 Drawing
var bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(arrowShape.minX + 0.70000 * arrowShape.width, arrowShape.minY + 0.00000 * arrowShape.height))
bezier2Path.addLineToPoint(CGPointMake(arrowShape.minX + 0.70000 * arrowShape.width, arrowShape.minY + 0.62222 * arrowShape.height))
bezier2Path.addLineToPoint(CGPointMake(arrowShape.minX + 1.00000 * arrowShape.width, arrowShape.minY + 0.44444 * arrowShape.height))
bezier2Path.addLineToPoint(CGPointMake(arrowShape.minX + 0.50000 * arrowShape.width, arrowShape.minY + 1.00000 * arrowShape.height))
arrowStroke.setStroke()
bezier2Path.lineWidth = 1
bezier2Path.stroke()
}
}
@objc protocol StyleKitSettableImage {
var image: UIImage! { get set }
}
@objc protocol StyleKitSettableSelectedImage {
var selectedImage: UIImage! { get set }
}
| gpl-2.0 | 7763da2c94902ac28c55d6242707a5ed | 36.842105 | 140 | 0.701437 | 4.237721 | false | false | false | false |
CallMeDaKing/DouYuAPP | DouYuProject/DouYuProject/Classes/Tools/Common.swift | 1 | 330 | //
// Common.swift
// DouYuProject
//
// Created by li king on 2017/10/27.
// Copyright © 2017年 li king. All rights reserved.
//
import UIKit
let kStateBarH : CGFloat = 20
let kNavigationBarH : CGFloat = 44
let kTabBarH :CGFloat = 44
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
| mit | 02abb3ae0b6f4d5cbf7f8095d5d9b233 | 18.235294 | 51 | 0.715596 | 3.40625 | false | false | false | false |
devpunk/cartesian | cartesian/Model/DrawProject/Menu/Zoom/MDrawProjectMenuZoom.swift | 1 | 1367 | import UIKit
class MDrawProjectMenuZoom
{
enum RuleType
{
case horizontal
case vertical
}
let items:[MDrawProjectMenuZoomItem]
private(set) var currentItem:Int
init()
{
let item10:MDrawProjectMenuZoomItem10 = MDrawProjectMenuZoomItem10()
let item50:MDrawProjectMenuZoomItem50 = MDrawProjectMenuZoomItem50()
let item100:MDrawProjectMenuZoomItem100 = MDrawProjectMenuZoomItem100()
let item200:MDrawProjectMenuZoomItem200 = MDrawProjectMenuZoomItem200()
let item300:MDrawProjectMenuZoomItem300 = MDrawProjectMenuZoomItem300()
var items:[MDrawProjectMenuZoomItem] = []
items.append(item10)
items.append(item50)
currentItem = items.count
items.append(item100)
items.append(item200)
items.append(item300)
self.items = items
}
//MARK: public
func currentZoom() -> CGFloat
{
let zoom:CGFloat = items[currentItem].scalar
return zoom
}
func currentZoomModel() -> MDrawProjectMenuZoomItem
{
let item:MDrawProjectMenuZoomItem = items[currentItem]
return item
}
func increase()
{
currentItem += 1
}
func decrease()
{
currentItem -= 1
}
}
| mit | ee17266217099deb94ad7f258546c5bb | 21.783333 | 79 | 0.609364 | 5.672199 | false | false | false | false |
darjeelingsteve/uistackview_adaptivity | CountiesUI/Sources/County Menu/CountiesCollectionViewController.swift | 1 | 14220 | //
// CountiesCollectionViewController.swift
// CountiesUI
//
// Created by Stephen Anthony on 03/02/2020.
// Copyright © 2020 Darjeeling Apps. All rights reserved.
//
import UIKit
import CountiesModel
/// The view controller responsible for displaying a collection view populated
/// by a list of counties.
final class CountiesCollectionViewController: UIViewController {
private static let countyCellIdentifier = "CountyCell"
private static let regionHeaderIdentifier = "RegionNameHeader"
/// The regions displayed by the receiver.
var regions = [Region]() {
didSet {
reloadData()
}
}
/// The delegate of the receiver.
var delegate: CountiesCollectionViewControllerDelegate?
private lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.register(CountyCell.self, forCellWithReuseIdentifier: CountiesCollectionViewController.countyCellIdentifier)
collectionView.register(SectionHeaderSupplementaryView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: CountiesCollectionViewController.regionHeaderIdentifier)
collectionView.alwaysBounceVertical = true
collectionView.preservesSuperviewLayoutMargins = true
collectionView.delegate = self
#if os(iOS)
collectionView.dragDelegate = UIApplication.shared.supportsMultipleScenes ? self : nil
collectionView.backgroundColor = .systemGroupedBackground
#elseif os(tvOS)
collectionView.remembersLastFocusedIndexPath = true
#endif
return collectionView
}()
private lazy var collectionViewLayout: CountiesCollectionViewLayout = {
let flowLayout = CountiesCollectionViewLayout()
flowLayout.minimumInteritemSpacing = layoutStyleForTraitCollection(traitCollection).collectionViewInteritemSpacing
return flowLayout
}()
private lazy var dataSource: UICollectionViewDiffableDataSource<CollectionSection, County> = {
let dataSource = UICollectionViewDiffableDataSource<CollectionSection, County>(collectionView: collectionView) { [weak self] (collectionView, indexPath, county) -> UICollectionViewCell? in
guard let self = self else { return nil }
let countyCell = collectionView.dequeueReusableCell(withReuseIdentifier: CountiesCollectionViewController.countyCellIdentifier, for: indexPath) as! CountyCell
countyCell.county = county
countyCell.displayStyle = self.traitCollection.horizontalSizeClass == .regular ? .grid : .table
return countyCell
}
dataSource.supplementaryViewProvider = { [weak self] (collectionView, kind, indexPath) in
guard let self = self, kind == UICollectionView.elementKindSectionHeader else {
return nil
}
let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CountiesCollectionViewController.regionHeaderIdentifier, for: indexPath) as! SectionHeaderSupplementaryView
switch self.dataSource.snapshot().sectionIdentifiers[indexPath.section] {
case .region(let name):
sectionHeader.title = name
}
return sectionHeader
}
return dataSource
}()
override func viewDidLoad() {
super.viewDidLoad()
#if os(iOS)
view.backgroundColor = .systemBackground
#elseif os(tvOS)
// Allow the collection view to handle focus restoration.
restoresFocusAfterTransition = false
#endif
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.topAnchor.constraint(equalTo: view.topAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
configureSectionHeaders()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reloadData() // Reload in case the trait collection changed when we were not visible.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
collectionViewLayout.invalidateLayout()
}
override func viewLayoutMarginsDidChange() {
super.viewLayoutMarginsDidChange()
collectionViewLayout.style = layoutStyleForTraitCollection(traitCollection)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
configureSectionHeaders()
collectionViewLayout.style = layoutStyleForTraitCollection(traitCollection)
guard let previousTraitCollection = previousTraitCollection else { return }
if layoutStyleForTraitCollection(traitCollection) != layoutStyleForTraitCollection(previousTraitCollection) {
collectionView.reloadData() // Reload cells to adopt the new style
}
}
private func layoutStyleForTraitCollection(_ traitCollection: UITraitCollection) -> CountiesCollectionViewLayout.Style {
if traitCollection.horizontalSizeClass == .regular {
return .grid
}
#if os(iOS)
let tableMetrics = TableStyleDisplayMetrics(traitCollection: traitCollection)
let leadingSeparatorInset = tableMetrics.leadingSeparatorInset(forLeadingLayoutMargin: view.directionalLayoutMargins.leading, cellContentInset: CountyCell.tableCellStyleNameLabelLeadingPadding)
return .table(leadingSeparatorInset: leadingSeparatorInset)
#else
fatalError("Table style only for use on iOS")
#endif
}
@objc private func reloadData() {
dataSource.apply(snapshotForCurrentState(), animatingDifferences: false)
}
private func snapshotForCurrentState() -> NSDiffableDataSourceSnapshot<CollectionSection, County> {
var snapshot = NSDiffableDataSourceSnapshot<CollectionSection, County>()
regions.forEach { (region) in
snapshot.appendSections([.region(name: region.name)])
snapshot.appendItems(region.counties)
}
return snapshot
}
private func configureSectionHeaders() {
#if os(iOS)
let isRegularWidth = traitCollection.horizontalSizeClass == .regular
collectionViewLayout.headerReferenceSize = CGSize(width: 20, height: isRegularWidth ? 40 : 32)
collectionViewLayout.sectionHeadersPinToVisibleBounds = isRegularWidth
#elseif os(tvOS)
collectionViewLayout.headerReferenceSize = CGSize(width: 20, height: 100)
collectionViewLayout.sectionHeadersPinToVisibleBounds = false
#endif
}
}
// MARK: UICollectionViewDelegateFlowLayout
extension CountiesCollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return layoutStyleForTraitCollection(traitCollection).itemSizeInCollectionView(collectionView)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
switch layoutStyleForTraitCollection(traitCollection) {
case .table:
#if os(iOS)
return CGSize(width: collectionView.bounds.width, height: TableStyleDisplayMetrics(traitCollection: collectionView.traitCollection).sectionHeaderHeight)
#else
fatalError("Table style only for use on iOS")
#endif
case .grid:
return CGSize(width: collectionView.bounds.width, height: platformValue(foriOS: 40, tvOS: 80))
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
switch layoutStyleForTraitCollection(traitCollection) {
case .table:
#if os(iOS)
let isLastSection = section == collectionView.numberOfSections - 1
let tableMetrics = TableStyleDisplayMetrics(traitCollection: collectionView.traitCollection)
return UIEdgeInsets(top: 0, left: 0, bottom: tableMetrics.sectionBottomPadding(forSectionThatIsTheLastSection: isLastSection), right: 0)
#else
fatalError("Table style only for use on iOS")
#endif
case .grid:
return UIEdgeInsets(top: 8, left: collectionView.layoutMargins.left, bottom: 24, right: collectionView.layoutMargins.right)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return layoutStyleForTraitCollection(traitCollection).collectionViewLineSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return layoutStyleForTraitCollection(traitCollection).collectionViewInteritemSpacing
}
}
// MARK: UICollectionViewDelegate
extension CountiesCollectionViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
collectionViewLayout.indexPathForHighlightedItem = indexPath
}
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
collectionViewLayout.indexPathForHighlightedItem = nil
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.countiesCollectionViewController(self, didSelect: dataSource.itemIdentifier(for: indexPath)!)
collectionView.deselectItem(at: indexPath, animated: false)
}
}
#if os(iOS)
// MARK: UICollectionViewDragDelegate
extension CountiesCollectionViewController: UICollectionViewDragDelegate {
func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
guard let county = dataSource.itemIdentifier(for: indexPath) else { return [] }
let itemProvider = NSItemProvider()
itemProvider.registerObject(county.userActivity, visibility: .all)
return [UIDragItem(itemProvider: itemProvider)]
}
func collectionView(_ collectionView: UICollectionView, dragSessionWillBegin session: UIDragSession) {
collectionView.allowsSelection = false
}
func collectionView(_ collectionView: UICollectionView, dragSessionDidEnd session: UIDragSession) {
collectionView.allowsSelection = true
}
}
#endif
/// The protocol to conform to for delegates of
/// `CountiesCollectionViewController`.
protocol CountiesCollectionViewControllerDelegate: AnyObject {
/// The message sent when the user taps on one of the sender's county cells.
/// - Parameters:
/// - countiesCollectionViewController: The controller sending the
/// message.
/// - county: The county that the user tapped on.
func countiesCollectionViewController(_ countiesCollectionViewController: CountiesCollectionViewController, didSelect county: County)
}
// MARK: - CountiesCollectionViewLayout.DisplayStyle extension to provide collection view layout information based on the layout style.
private extension CountiesCollectionViewLayout.Style {
func itemSizeInCollectionView(_ collectionView: UICollectionView) -> CGSize {
switch self {
case .table:
#if os(iOS)
return CGSize(width: collectionView.bounds.width, height: TableStyleDisplayMetrics(traitCollection: collectionView.traitCollection).cellHeight)
#else
fatalError("Table style only for use on iOS")
#endif
case .grid:
let availableWidth = collectionView.bounds.width - collectionView.layoutMargins.left - collectionView.layoutMargins.right
let interitemSpacing = (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).minimumInteritemSpacing
let numberOfItemsPerRow: Int
switch columnCountMetric {
case .fixed(let columnCount):
numberOfItemsPerRow = columnCount
case .calculated(let estimatedCellWidth):
numberOfItemsPerRow = Int(floor(availableWidth / estimatedCellWidth))
}
let totalSpacingBetweenAdjacentItems = (CGFloat(numberOfItemsPerRow - 1) * interitemSpacing)
let itemWidth = floor((availableWidth - totalSpacingBetweenAdjacentItems) / CGFloat(numberOfItemsPerRow))
return CGSize(width: itemWidth, height: floor(itemWidth / 1.3))
}
}
var collectionViewLineSpacing: CGFloat {
switch self {
case .table:
return 0
case .grid:
return platformValue(foriOS: 24, tvOS: 48)
}
}
var collectionViewInteritemSpacing: CGFloat {
#if os(tvOS)
return 80
#else
return 32
#endif
}
private var columnCountMetric: ColumnCountMetric {
#if os(tvOS)
return .fixed(columnCount: 4)
#else
return .calculated(estimatedCellWidth: 220)
#endif
}
private enum ColumnCountMetric {
case fixed(columnCount: Int)
case calculated(estimatedCellWidth: CGFloat)
}
}
private extension CountiesCollectionViewController {
/// The sections displayed in the collection view.
private enum CollectionSection: Hashable {
case region(name: String)
}
}
| mit | 0e2ff7d85260b8f9bce36112fc8e35eb | 45.165584 | 222 | 0.716365 | 6.280477 | false | false | false | false |
LoopKit/LoopKit | LoopKitUI/Views/DismissibleKeyboardTextField.swift | 1 | 5800 | //
// DismissibleKeyboardTextField.swift
// LoopKitUI
//
// Created by Michael Pangburn on 7/22/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import SwiftUI
public struct DismissibleKeyboardTextField: UIViewRepresentable {
@Binding var text: String
var placeholder: String
var font: UIFont
var textColor: UIColor
var textAlignment: NSTextAlignment
var keyboardType: UIKeyboardType
var autocapitalizationType: UITextAutocapitalizationType
var autocorrectionType: UITextAutocorrectionType
var shouldBecomeFirstResponder: Bool
var maxLength: Int?
var doneButtonColor: UIColor
var isDismissible: Bool
var textFieldDidBeginEditing: (() -> Void)?
public init(
text: Binding<String>,
placeholder: String,
font: UIFont = .preferredFont(forTextStyle: .body),
textColor: UIColor = .label,
textAlignment: NSTextAlignment = .natural,
keyboardType: UIKeyboardType = .default,
autocapitalizationType: UITextAutocapitalizationType = .sentences,
autocorrectionType: UITextAutocorrectionType = .default,
shouldBecomeFirstResponder: Bool = false,
maxLength: Int? = nil,
doneButtonColor: UIColor = .blue,
isDismissible: Bool = true,
textFieldDidBeginEditing: (() -> Void)? = nil
) {
self._text = text
self.placeholder = placeholder
self.font = font
self.textColor = textColor
self.textAlignment = textAlignment
self.keyboardType = keyboardType
self.autocapitalizationType = autocapitalizationType
self.autocorrectionType = autocorrectionType
self.shouldBecomeFirstResponder = shouldBecomeFirstResponder
self.maxLength = maxLength
self.doneButtonColor = doneButtonColor
self.isDismissible = isDismissible
self.textFieldDidBeginEditing = textFieldDidBeginEditing
}
public func makeUIView(context: Context) -> UITextField {
let textField = UITextField()
textField.inputAccessoryView = isDismissible ? makeDoneToolbar(for: textField) : nil
textField.addTarget(context.coordinator, action: #selector(Coordinator.textChanged), for: .editingChanged)
textField.addTarget(context.coordinator, action: #selector(Coordinator.editingDidBegin), for: .editingDidBegin)
textField.delegate = context.coordinator
return textField
}
private func makeDoneToolbar(for textField: UITextField) -> UIToolbar {
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: textField, action: #selector(UITextField.resignFirstResponder))
doneButton.tintColor = doneButtonColor
toolbar.items = [flexibleSpace, doneButton]
toolbar.sizeToFit()
return toolbar
}
public func updateUIView(_ textField: UITextField, context: Context) {
textField.text = text
textField.placeholder = placeholder
textField.font = font
textField.textColor = textColor
textField.textAlignment = textAlignment
textField.keyboardType = keyboardType
textField.autocapitalizationType = autocapitalizationType
textField.autocorrectionType = autocorrectionType
if shouldBecomeFirstResponder && !context.coordinator.didBecomeFirstResponder {
// See https://developer.apple.com/documentation/uikit/uiresponder/1621113-becomefirstresponder for why
// we check the window property here (otherwise it might crash)
if textField.window != nil && textField.becomeFirstResponder() {
context.coordinator.didBecomeFirstResponder = true
}
} else if !shouldBecomeFirstResponder && context.coordinator.didBecomeFirstResponder {
context.coordinator.didBecomeFirstResponder = false
}
}
public func makeCoordinator() -> Coordinator {
Coordinator(self, maxLength: maxLength)
}
public final class Coordinator: NSObject {
var parent: DismissibleKeyboardTextField
let maxLength: Int?
// Track in the coordinator to ensure the text field only becomes first responder once,
// rather than on every state change.
var didBecomeFirstResponder = false
init(_ parent: DismissibleKeyboardTextField, maxLength: Int?) {
self.parent = parent
self.maxLength = maxLength
}
@objc fileprivate func textChanged(_ textField: UITextField) {
parent.text = textField.text ?? ""
}
@objc fileprivate func editingDidBegin(_ textField: UITextField) {
// Even though we are likely already on .main, we still need to queue this cursor (selection) change in
// order for it to work
DispatchQueue.main.async {
textField.moveCursorToEnd()
}
}
}
}
extension DismissibleKeyboardTextField.Coordinator: UITextFieldDelegate {
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let maxLength = maxLength else {
return true
}
let currentString: NSString = (textField.text ?? "") as NSString
let newString: NSString =
currentString.replacingCharacters(in: range, with: string) as NSString
return newString.length <= maxLength
}
public func textFieldDidBeginEditing(_ textField: UITextField) {
parent.textFieldDidBeginEditing?()
}
}
| mit | c7d87ab746cfb92eed46bda925b67c30 | 39.838028 | 140 | 0.686325 | 5.752976 | false | false | false | false |
Yurssoft/QuickFile | QuickFile/ViewModels/YSSettingsViewModel.swift | 1 | 2962 | //
// YSSettingsViewModel.swift
// YSGGP
//
// Created by Yurii Boiko on 10/17/16.
// Copyright © 2016 Yurii Boiko. All rights reserved.
//
import Foundation
import SwiftMessages
import GoogleSignIn
class YSSettingsViewModel: YSSettingsViewModelProtocol {
var isLoggedIn: Bool {
return model!.isLoggedIn
}
var loggedString: String {
if isLoggedIn {
let loggedInMessage = "Logged in to Drive"
return loggedInMessage
}
return "Not logged in"
}
fileprivate var error: YSErrorProtocol = YSError() {
didSet {
if !error.isEmpty() {
viewDelegate?.errorDidChange(viewModel: self, error: error)
}
}
}
weak var viewDelegate: YSSettingsViewModelViewDelegate?
var model: YSSettingsModel?
weak var coordinatorDelegate: YSSettingsCoordinatorDelegate?
var isCellularAccessAllowed: Bool {
set (newValue) {
UserDefaults.standard.set(newValue, forKey: YSConstants.kCellularAccessAllowedUserDefaultKey)
}
get {
if let isCellularAllowed = UserDefaults.standard.value(forKey: YSConstants.kCellularAccessAllowedUserDefaultKey) as? Bool {
return isCellularAllowed
}
return false
}
}
func logOut() {
do {
try model?.logOut()
} catch {
guard let error = error as? YSErrorProtocol else { return }
viewDelegate?.errorDidChange(viewModel: self, error: error)
}
}
func deleteAllFiles() {
YSDatabaseManager.deleteAllDownloads { (error) in
guard let error = error else { return }
if error.messageType == Theme.success || error.title.contains("Deleted") {
self.coordinatorDelegate?.viewModelDidDeleteAllLocalFiles(viewModel: self)
}
self.viewDelegate?.errorDidChange(viewModel: self, error: error)
}
}
func deletePlayedFiles() {
YSDatabaseManager.deletePlayedDownloads { (error) in
guard let error = error else { return }
if error.messageType == Theme.success || error.title.contains("Deleted") {
self.coordinatorDelegate?.viewModelDidDeleteAllLocalFiles(viewModel: self)
}
self.viewDelegate?.errorDidChange(viewModel: self, error: error)
}
}
func deleteAllMetadata() {
YSDatabaseManager.deleteDatabase { (error) in
guard let error = error else { return }
if error.messageType == Theme.success || error.title.contains("Deleted") {
self.coordinatorDelegate?.viewModelDidDeleteAllLocalFiles(viewModel: self)
}
self.viewDelegate?.errorDidChange(viewModel: self, error: error)
}
}
func successfullyLoggedIn() {
coordinatorDelegate?.viewModelSuccessfullyLoggedIn(viewModel: self)
}
}
| mit | b02ce745eeafd34e29d83157c6987960 | 31.538462 | 135 | 0.625464 | 5.105172 | false | false | false | false |
cherrywoods/swift-meta-serialization | Examples/BasicUsage.playground/Contents.swift | 1 | 4928 | //
// BasicUsage.playground
// MetaSerialization
//
// Copyright 2018 cherrywoods
//
// 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 Cocoa
import MetaSerialization
/*
This playground contains a verry basic example
of the usage of MetaSerialization
A simple Translator will be created,
that converts (certain) swift objects
to some kind of simple json format.
For that Translator a Serialization instance will be created and used.
*/
// MARK: - encoding to a reduced JSON format
func convertToJSON(_ value: Meta) -> String {
// String and Int are the two supported types passed to PrimitivesEnumTranslator
if let string = value as? String {
return "\"\(string)\""
} else if let int = value as? Int {
return "\(int)"
}
// both Arrays and Dictionarys already contain encoded values
// Array and Dictionary always need
// to be supported when using PrimitivesEnumTranslator
if let array = value as? Array<Meta> {
var json = "[ \n"
for element in array {
json += convertToJSON(element) + "\n"
}
return json + "]"
}
if let dictionary = value as? Dictionary<String, Meta> {
var json = "{ \n"
for (key, val) in dictionary {
json += "\"\(key)\": \(convertToJSON(val))\n"
}
return json + "}"
}
return ""
}
func convertToSwift(_ json: String) -> Meta {
var json = json
switch json.first! {
case "\"":
// " at the beginning -> this is a string
// remove the two "s
// ( note that it is realy important to
// return Strings and not Substrings,
// because PrimitivesEnumTranslator can't handle Substrings )
return String(json.dropFirst().dropLast())
case "[":
// [ at the beginning -> array
// trim of [\n and \n]
json = String( json.dropFirst(2).dropLast(2) )
var array = [Meta]()
for element in json.split(separator: "\n") {
array.append( convertToSwift(String(element)) )
}
return array
case "{":
// { -> dictionary
// trim {\n and \n}
json = String( json.dropFirst(2).dropLast(2) )
var dictionary = [String: Meta]()
for line in json.split(separator: "\n") {
let keyAndValue = line.split(separator: ":")
// drop " and "
let key = String( keyAndValue[0].dropFirst().dropLast() )
// remove the blank before the values
let val = convertToSwift(String( keyAndValue[1].dropFirst() ))
dictionary[key] = val
}
return dictionary
default:
// this should be a number
return Int(json)!
}
}
func toJSON(_ value: Any?) -> Any {
return convertToJSON(value as! Meta) as Any
}
func toSwift(_ value: Any) -> Any? {
return convertToSwift(value as! String)
}
// MARK: - using MetaSerialization
// Translators are a key part of MetaSerialization.
// PrimitivesEnumTranslator is a verry simple implementation.
// Usually you will write a own implementation of the Translator protocol.
let translator = PrimitivesEnumTranslator(primitives: [.string, .int])
// and thats basically all of the code that is needed to encode
// arbitrary swift objects implementing Encodable
let serialization = SimpleSerialization<String>(translator: translator,
encodeFromMeta: convertToJSON,
decodeToMeta: convertToSwift)
// MARK: - serialization
// these are just some example instances
struct Shape: Codable {
let numberOfSides: Int
let sideLength: Int
}
let triange = Shape(numberOfSides: 3, sideLength: 4)
let array = [ "three", "four", "six" ]
let dictionary = [ "triangle" : 3, "square" : 4, "hexagon" : 6 ]
// MARK: encoding
let encodedTriagle = try! serialization.encode(triange)
let encodedArray = try! serialization.encode(array)
let encodedDictionary = try! serialization.encode(dictionary)
// MARK: decoding
try! serialization.decode(toType: Shape.self, from: encodedTriagle)
try! serialization.decode(toType: [String].self, from: encodedArray)
try! serialization.decode(toType: [String:Int].self, from: encodedDictionary)
| apache-2.0 | 4bca4ad4d824015f5445697fa33acb8d | 27.988235 | 84 | 0.622768 | 4.435644 | false | false | false | false |
r4phab/ECAB | ECAB/TestViewController.swift | 1 | 18370 | //
// ECABApplesViewController.swift
// ECAB
//
// Created by Boris Yurkevich on 18/01/2015.
// Copyright (c) 2015 Oliver Braddick and Jan Atkinson. All rights reserved.
//
import UIKit
import CoreData
class TestViewController: UIViewController, SubjectPickerDelegate, UIPopoverPresentationControllerDelegate
{
var managedContext: NSManagedObjectContext!
@IBOutlet weak var changePlayerButton: UIBarButtonItem!
@IBOutlet weak var gameIcon: UIImageView!
@IBOutlet weak var difControl: UISegmentedControl!
@IBOutlet weak var difficultyTitle: UILabel!
@IBOutlet weak var speedLabel: UILabel!
@IBOutlet weak var speedStepper: UIStepper!
@IBOutlet weak var speedLabelDescription: UILabel!
@IBOutlet weak var secondSpeedStepper: UIStepper!
@IBOutlet weak var secondSpeedLabel: UILabel!
@IBOutlet weak var secondSpeedLabelDescription: UILabel!
@IBOutlet weak var periodValue: UILabel!
@IBOutlet weak var periodControl: UIStepper!
@IBOutlet weak var periodTitle: UILabel!
@IBOutlet weak var periodHelp: UILabel!
@IBOutlet weak var thresholdLabel: UILabel!
@IBOutlet weak var thresholdStepper: UIStepper!
@IBOutlet weak var thresholdTitle: UILabel!
@IBOutlet weak var randomizeFlanker: UISwitch!
@IBOutlet weak var randomizeLabel: UILabel!
let model: Model = Model.sharedInstance
private struct Segues {
static let startApplesGame = "Start apples game"
static let openSubjectsPopover = "Open subjects popover"
}
@IBAction func adjustThreshold(sender: UIStepper) {
let formattedValue = NSString(format: "%.01f", sender.value)
let newValue = Float(formattedValue as String)!
model.data.threshold = newValue
thresholdLabel.text = "\(formattedValue)"
model.save()
}
override func viewDidLoad() {
super.viewDidLoad()
changePlayerButton.title = "Loading..."
// Subscribe from notifications from Model
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(dataLoaded),
name: "dataLoaded",
object: nil)
model.setupWithContext(managedContext)
difControl.selectedSegmentIndex = model.data.visSearchDifficulty.integerValue
randomizeFlanker.on = NSUserDefaults.standardUserDefaults().boolForKey("isFlankerRandomized")
}
func dataLoaded() {
// Select row in tableView
let navVC = splitViewController!.viewControllers.first as! UINavigationController
let testTVC = navVC.topViewController as! TestsTableViewController
testTVC.selectRow(model.data.selectedGame.integerValue)
showTheGame(model.data.selectedGame.integerValue)
// Show correct player name
changePlayerButton.title = model.data.selectedPlayer.name
}
func showTheGame(gameIndex : Int) {
// Hide all the controls
difControl.hidden = true
difficultyTitle.hidden = true
speedLabel.hidden = true
speedStepper.hidden = true
speedLabelDescription.hidden = true
secondSpeedLabel.hidden = true
secondSpeedStepper.hidden = true
secondSpeedLabelDescription.hidden = true
periodControl.hidden = true
periodTitle.hidden = true
periodHelp.hidden = true
periodValue.hidden = true
thresholdLabel.hidden = true
thresholdStepper.hidden = true
thresholdTitle.hidden = true
randomizeFlanker.hidden = true
randomizeLabel.hidden = true
// Set game title
title = model.games[model.data.selectedGame.integerValue].rawValue
switch model.games[model.data.selectedGame.integerValue].rawValue {
case Game.VisualSearch.rawValue:
gameIcon.image = UIImage(named: Picture.Icon_visualSearch.rawValue)
difControl.hidden = false
difficultyTitle.hidden = false
speedLabel.hidden = false
speedLabelDescription.hidden = false
speedStepper.hidden = false
// Set difficulty toggle
difControl.selectedSegmentIndex = model.data.visSearchDifficulty.integerValue
if model.data.visSearchDifficulty.integerValue == 0 {
speedLabel.text = "\(model.data.visSearchSpeed.doubleValue) \(MenuConstant.second)"
speedStepper.value = model.data.visSustSpeed.doubleValue
} else {
speedLabel.text = "\(model.data.visSearchSpeedHard.doubleValue) \(MenuConstant.second)"
speedStepper.value = model.data.visSearchSpeedHard.doubleValue
}
break
case Game.Flanker.rawValue, Game.FlankerRandomised.rawValue:
gameIcon.image = UIImage(named: Picture.Icon_flanker.rawValue)
randomizeFlanker.hidden = false
randomizeLabel.hidden = false
break
case Game.Counterpointing.rawValue:
gameIcon.image = UIImage(named: Picture.Icon_counterpointing.rawValue)
break
case Game.VisualSustain.rawValue:
gameIcon.image = UIImage(named: Picture.Icon_visualSustain.rawValue)
speedLabel.hidden = false
speedStepper.hidden = false
secondSpeedLabel.hidden = false
secondSpeedStepper.hidden = false
secondSpeedLabelDescription.hidden = false
speedLabelDescription.hidden = false
periodControl.hidden = false
periodTitle.hidden = false
periodHelp.hidden = false
periodValue.hidden = false
speedStepper.value = model.data.visSustSpeed.doubleValue
speedLabel.text = "\(model.data.visSustSpeed.doubleValue) \(MenuConstant.second)"
secondSpeedLabel.text = "\(model.data.visSustAcceptedDelay!.doubleValue) \(MenuConstant.second)"
secondSpeedStepper.value = model.data.visSustAcceptedDelay!.doubleValue
let exposure = model.data.visSustSpeed.doubleValue
let delay = model.data.visSustDelay.doubleValue
let totalPeriod = exposure + delay
periodControl.value = totalPeriod
periodValue.text = "\(totalPeriod) \(MenuConstant.second)"
periodHelp.text = "Blank space time: \(delay) \(MenuConstant.second)"
validateAndHighliteBlankSpaceLabel()
break
case Game.AuditorySustain.rawValue:
gameIcon.image = UIImage(named: Picture.Icon_auditory.rawValue)
break
case Game.DualSustain.rawValue:
gameIcon.image = UIImage(named: Picture.Icon_dualTask.rawValue)
speedLabel.hidden = false
speedStepper.hidden = false
secondSpeedLabel.hidden = false
secondSpeedStepper.hidden = false
secondSpeedLabelDescription.hidden = false
speedLabelDescription.hidden = false
periodControl.hidden = false
periodTitle.hidden = false
periodHelp.hidden = false
periodValue.hidden = false
speedStepper.value = model.data.dualSustSpeed.doubleValue
speedLabel.text = "\(model.data.dualSustSpeed.doubleValue) \(MenuConstant.second)"
secondSpeedLabel.text = "\(model.data.dualSustAcceptedDelay!.doubleValue) \(MenuConstant.second)"
secondSpeedStepper.value = model.data.dualSustAcceptedDelay!.doubleValue
let exposure = model.data.dualSustSpeed.doubleValue
let delay = model.data.dualSustDelay.doubleValue
let totalPeriod = exposure + delay
periodControl.value = totalPeriod
periodValue.text = "\(totalPeriod) \(MenuConstant.second)"
periodHelp.text = "Blank space time: \(delay) \(MenuConstant.second)"
break
case Game.VerbalOpposites.rawValue:
gameIcon.image = UIImage(named: Picture.Icon_verbalOpposites.rawValue)
thresholdLabel.hidden = false
thresholdStepper.hidden = false
thresholdTitle.hidden = false
let formattedValue = NSString(format: "%.01f", model.data.threshold.doubleValue)
thresholdLabel.text = "\(formattedValue)"
thresholdStepper.value = model.data.threshold.doubleValue
break
case Game.BalloonSorting.rawValue:
gameIcon.image = UIImage(named: Picture.Icon_balloonSorting.rawValue)
break
default : break
}
}
@IBAction func difficultyControlHandler(sender: UISegmentedControl) {
if sender.selectedSegmentIndex == Difficulty.Easy.rawValue {
model.data.visSearchDifficulty = Difficulty.Easy.rawValue
speedStepper.value = model.data.visSearchSpeed.doubleValue
speedLabel.text = "\(model.data.visSearchSpeed.doubleValue) \(MenuConstant.second)"
} else {
model.data.visSearchDifficulty = Difficulty.Hard.rawValue
speedStepper.value = model.data.visSearchSpeedHard.doubleValue
speedLabel.text = "\(model.data.visSearchSpeedHard.doubleValue) \(MenuConstant.second)"
}
model.save()
}
@IBAction func speedStepperHandler(sender: UIStepper) {
let formattedValue = NSString(format: "%.01f", sender.value)
let newSpeedValueDouble = Double(formattedValue as String)!
switch model.games[model.data.selectedGame.integerValue].rawValue {
case Game.VisualSearch.rawValue:
if model.data.visSearchDifficulty == Difficulty.Easy.rawValue{
model.data.visSearchSpeed = newSpeedValueDouble
} else {
model.data.visSearchSpeedHard = newSpeedValueDouble
}
break
case Game.VisualSustain.rawValue:
model.data.visSustSpeed = newSpeedValueDouble
let delay = model.data.visSustDelay.doubleValue
let newTotal = newSpeedValueDouble + delay
periodValue.text = "\(newTotal) \(MenuConstant.second)"
periodControl.value = newTotal
break
case Game.DualSustain.rawValue:
model.data.dualSustSpeed = newSpeedValueDouble
let delay = model.data.dualSustDelay.doubleValue
let newTotal = newSpeedValueDouble + delay
periodValue.text = "\(newTotal) \(MenuConstant.second)"
periodControl.value = newTotal
break
default:
break
}
speedLabel.text = "\(formattedValue) \(MenuConstant.second)"
model.save()
}
@IBAction func delayHandler(sender: UIStepper) {
let formattedValue = NSString(format: "%.01f", sender.value)
let number = Double(formattedValue as String)
secondSpeedLabel.text = "\(formattedValue) \(MenuConstant.second)"
switch model.games[model.data.selectedGame.integerValue].rawValue {
case Game.VisualSustain.rawValue:
model.data.visSustAcceptedDelay = number
break
case Game.DualSustain.rawValue:
model.data.dualSustAcceptedDelay = number
break
default:
break
}
model.save()
}
@IBAction func totalPeriodHandler(sender: UIStepper) {
let newTotalPeriod = NSString(format: "%.01f", sender.value)
let newTotalPeriodDouble = Double(newTotalPeriod as String)
let exposure = model.data.visSustSpeed.doubleValue
let newDelay = newTotalPeriodDouble! - exposure
periodValue.text = "\(newTotalPeriod) \(MenuConstant.second)"
if newDelay >= model.kMinDelay {
periodHelp.text = "Blank space time: \(newDelay) \(MenuConstant.second)"
periodHelp.textColor = UIColor.darkGrayColor()
switch model.games[model.data.selectedGame.integerValue].rawValue {
case Game.VisualSustain.rawValue:
model.data.visSustDelay = newDelay
break
case Game.DualSustain.rawValue:
model.data.dualSustDelay = newDelay
break
default:
break
}
} else {
periodHelp.text = "Blank space time: 0 \(MenuConstant.second) Ignored when less than a second"
periodHelp.textColor = UIColor.redColor()
switch model.games[model.data.selectedGame.integerValue].rawValue {
case Game.VisualSustain.rawValue:
model.data.visSustDelay = 0.0
break
case Game.DualSustain.rawValue:
model.data.dualSustDelay = 0.0
break
default:
break
}
}
model.save()
}
@IBAction func randomizedFlanker(sender: UISwitch) {
NSUserDefaults.standardUserDefaults().setBool(sender.on, forKey: "isFlankerRandmoized")
}
func validateAndHighliteBlankSpaceLabel() {
var currentDelay: Double = 0.0;
switch model.games[model.data.selectedGame.integerValue].rawValue {
case Game.VisualSustain.rawValue:
currentDelay = model.data.visSustDelay.doubleValue
break
case Game.DualSustain.rawValue:
currentDelay = model.data.dualSustDelay.doubleValue
break
default:
break
}
if currentDelay < model.kMinDelay {
periodHelp.text = "Blank space time: \(currentDelay) \(MenuConstant.second) Ignored when less than a second"
periodHelp.textColor = UIColor.redColor()
}
}
// MARK: - Navigation
@IBAction func playButtonHandler(sender: UIBarButtonItem) {
if let detailVC: UISplitViewController = splitViewController {
switch model.games[model.data.selectedGame.integerValue].rawValue {
case Game.VisualSearch.rawValue:
detailVC.presentViewController(VisualSearchViewController(), animated: true, completion: nil)
break
case Game.Flanker.rawValue, Game.FlankerRandomised.rawValue:
let gameVC = FlankerViewController()
let alert = UIAlertController(title: "Small Images.", message: "Enable small images?", preferredStyle:.Alert)
let okayAction = UIAlertAction(title: "Classic images (2x)", style: .Default, handler: { (alertAction) -> Void in
detailVC.presentViewController(gameVC, animated: true, completion: nil)
})
let smallImageAction = UIAlertAction(title: "Smaller images (1.5x)", style: .Cancel, handler: { (alertAction) -> Void in
gameVC.smallImages = true
detailVC.presentViewController(gameVC, animated: true, completion: nil)
})
alert.addAction(okayAction)
alert.addAction(smallImageAction)
self.presentViewController(alert, animated: true, completion: nil)
break
case Game.Counterpointing.rawValue:
detailVC.presentViewController(CounterpointingViewController(), animated: true, completion: nil)
break
case Game.VisualSustain.rawValue:
detailVC.presentViewController(VisualSustainViewController(), animated: true, completion: nil)
break
case Game.AuditorySustain.rawValue:
detailVC.presentViewController(AuditorySustainViewController(), animated: true, completion: nil)
break
case Game.DualSustain.rawValue:
detailVC.presentViewController(DualSustainViewController(), animated: true, completion: nil)
break
case Game.VerbalOpposites.rawValue:
detailVC.presentViewController(VerbalOppositesViewController(), animated: true, completion: nil)
break
case Game.BalloonSorting.rawValue:
detailVC.presentViewController(BalloonSortingViewController(), animated: true, completion: nil)
break
default: break
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case Segues.openSubjectsPopover:
if let tvc = segue.destinationViewController as? PlayersTableViewController {
if let ppc = tvc.popoverPresentationController {
ppc.delegate = self;
}
tvc.delegate = self
}
case Segues.startApplesGame:
if let cvc = segue.destinationViewController as? VisualSearchViewController {
cvc.presenter = self
}
default: break;
}
}
}
// MARK: <SubjectPickerDelegate>
func pickSubject() {
changePlayerButton.title = model.data.selectedPlayer.name
}
}
| mit | a03518e0c539c01fb40891d63bd8b554 | 39.731707 | 140 | 0.595373 | 5.835451 | false | false | false | false |
JudoPay/JudoKit | Source/UIColor+Judo.swift | 1 | 2122 | //
// UIColor+Judo.swift
// JudoKit
//
// Copyright (c) 2016 Alternative Payments Ltd
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public extension UIColor {
/**
Inverse color
- returns: The inverse color of the receiver
*/
func inverseColor() -> UIColor {
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 0.0
self.getRed(&r, green:&g, blue:&b, alpha:&a)
return UIColor(red: 1 - r, green: 1 - g, blue: 1 - b, alpha: a)
}
/**
Calculates a weighed greyscale representation percentage of the receiver
- returns: A greyscale representation percentage CGFloat
*/
func greyScale() -> CGFloat {
// 0.299r + 0.587g + 0.114b
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 0.0
self.getRed(&r, green:&g, blue:&b, alpha:&a)
let newValue: CGFloat = (0.299 * r + 0.587 * g + 0.114 * b)
return newValue
}
}
| mit | 39de2e3b4a37a5103028b7737531d767 | 33.786885 | 82 | 0.652215 | 4.018939 | false | false | false | false |
frodoking/GithubIOSClient | Github/Core/Common/Views/UserTableViewCell.swift | 1 | 3274 | //
// RankTableViewCell2.swift
// Github
//
// Created by frodo on 15/10/26.
// Copyright © 2015年 frodo. All rights reserved.
//
import UIKit
import Alamofire
class UserTableViewCell: UITableViewCell {
var rankLabel: UILabel!
var titleImageView: UIImageView!
var mainLabel: UILabel!
var detailLabel: UILabel!
var isInitialized = false
var user: User? {
didSet {
if !isInitialized {
loadSubview()
}
updateUi()
}
}
private func loadSubview() {
let h: CGFloat = 70.5
let orginX: CGFloat = 0
let w = UIScreen.mainScreen().bounds.width - orginX * 2
let preWidth: CGFloat = 15
let rankWidth: CGFloat = 45
let sufRankWidth: CGFloat = 10
let imageViewWidth: CGFloat = 50
let sufImageViewWidth: CGFloat = 25
let contentWidth = w - 2 * preWidth
let labelWidth = contentWidth-sufRankWidth-imageViewWidth-sufImageViewWidth
contentView.bounds = CGRectMake(0, 0, w, h)
rankLabel = UILabel.init(frame: CGRectMake(0, (h-30)/2, rankWidth+preWidth, 30))
self.contentView.addSubview(rankLabel)
titleImageView = UIImageView.init(frame: CGRectMake(preWidth+rankWidth+sufRankWidth, (h-imageViewWidth)/2, imageViewWidth, imageViewWidth))
self.contentView.addSubview(titleImageView)
mainLabel = UILabel.init(frame: CGRectMake(preWidth+rankWidth+sufRankWidth+imageViewWidth+sufImageViewWidth, (h-imageViewWidth)/2, labelWidth, imageViewWidth))
self.contentView.addSubview(mainLabel)
detailLabel=UILabel.init(frame: CGRectMake(preWidth+rankWidth+sufRankWidth+imageViewWidth+sufImageViewWidth, (h-imageViewWidth)/2+imageViewWidth/2, labelWidth, imageViewWidth/2))
detailLabel.numberOfLines = 0
self.contentView.addSubview(detailLabel)
mainLabel.numberOfLines = 0
rankLabel.textColor = Theme.Color
mainLabel.textColor = Theme.Color
detailLabel.textColor = Theme.GrayColor
rankLabel.textAlignment = NSTextAlignment.Center
mainLabel.font = UIFont.systemFontOfSize(18)
detailLabel.font = UIFont.systemFontOfSize(13)
mainLabel.textAlignment = NSTextAlignment.Left
detailLabel.textAlignment = NSTextAlignment.Left
titleImageView.layer.cornerRadius = 10
titleImageView.layer.borderColor = Theme.GrayColor.CGColor
titleImageView.layer.borderWidth = 0.3
titleImageView.layer.masksToBounds=true
isInitialized = true
}
private func updateUi() {
if let user = self.user {
if let _ = user.rank {
rankLabel.text = "\(user.rank!)"
}
mainLabel.text = user.login!
detailLabel.text = user.url!
Alamofire.request(.GET, (user.avatar_url)!)
.responseData { response in
// NSLog("Fetch: Image: \(self.user?.avatar_url)")
let imageData = UIImage(data: response.data!)
self.titleImageView?.image = imageData
}
}
}
}
| apache-2.0 | 0289387d809ac5e8144bdab0ae36f681 | 33.797872 | 186 | 0.620605 | 4.971125 | false | false | false | false |
brutella/simplediff-swift | simplediff/simplediff.swift | 1 | 3645 | //
// simplediff.swift
// simplediff
//
// Created by Matthias Hochgatterer on 31/03/15.
// Copyright (c) 2015 Matthias Hochgatterer. All rights reserved.
//
import Foundation
enum ChangeType {
case insert, delete, noop
var description: String {
get {
switch self {
case .insert: return "+"
case .delete: return "-"
case .noop: return "="
}
}
}
}
/// Operation describes an operation (insertion, deletion, or noop) of elements.
struct Change<T> {
let type: ChangeType
let elements: [T]
var elementsString: String {
return elements.map({ "\($0)" }).joined(separator: "")
}
var description: String {
get {
switch type {
case .insert:
return "[+\(elementsString)]"
case .delete:
return "[-\(elementsString)]"
default:
return "\(elementsString)"
}
}
}
}
/// diff finds the difference between two lists.
/// This algorithm a shameless copy of simplediff https://github.com/paulgb/simplediff
///
/// - parameter before: Old list of elements.
/// - parameter after: New list of elements
/// - returns: A list of operation (insert, delete, noop) to transform the list *before* to the list *after*.
func simplediff<T>(before: [T], after: [T]) -> [Change<T>] where T: Hashable {
// Create map of indices for every element
var beforeIndices = [T: [Int]]()
for (index, elem) in before.enumerated() {
var indices = beforeIndices.index(forKey: elem) != nil ? beforeIndices[elem]! : [Int]()
indices.append(index)
beforeIndices[elem] = indices
}
var beforeStart = 0
var afterStart = 0
var maxOverlayLength = 0
var overlay = [Int: Int]() // remembers *overlayLength* of previous element
for (index, elem) in after.enumerated() {
var _overlay = [Int: Int]()
// Element must be in *before* list
if let elemIndices = beforeIndices[elem] {
// Iterate over element indices in *before*
for elemIndex in elemIndices {
var overlayLength = 1
if let previousSub = overlay[elemIndex - 1] {
overlayLength += previousSub
}
_overlay[elemIndex] = overlayLength
if overlayLength > maxOverlayLength { // longest overlay?
maxOverlayLength = overlayLength
beforeStart = elemIndex - overlayLength + 1
afterStart = index - overlayLength + 1
}
}
}
overlay = _overlay
}
var operations = [Change<T>]()
if maxOverlayLength == 0 {
// No overlay; remove before and add after elements
if before.count > 0 {
operations.append(Change(type: .delete, elements: before))
}
if after.count > 0 {
operations.append(Change(type: .insert, elements: after))
}
} else {
// Recursive call with elements before overlay
operations += simplediff(before: Array(before[0..<beforeStart]), after: Array(after[0..<afterStart]))
// Noop for longest overlay
operations.append(Change(type: .noop, elements: Array(after[afterStart..<afterStart+maxOverlayLength])))
// Recursive call with elements after overlay
operations += simplediff(before: Array(before[beforeStart+maxOverlayLength..<before.count]), after: Array(after[afterStart+maxOverlayLength..<after.count]))
}
return operations
}
| mit | 85058cff45ca6e651c500b7e556cce87 | 33.386792 | 164 | 0.581619 | 4.602273 | false | false | false | false |
joelbanzatto/MVCarouselCollectionView | MVCarouselCollectionView/MVCarouselCellScrollView.swift | 1 | 4186 | // MVCarouselCellScrollView.swift
//
// Copyright (c) 2015 Andrea Bizzotto ([email protected])
//
// 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
// Image loader closure type
public typealias MVImageLoaderClosure = ((imageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) -> ())
class MVCarouselCellScrollView: UIScrollView, UIScrollViewDelegate {
let MaximumZoom = 4.0
var cellSize : CGSize = CGSizeZero
var maximumZoom = 0.0
var imagePath : String = "" {
didSet {
assert(self.imageLoader != nil, "Image loader must be specified")
self.imageLoader?(imageView : self.imageView, imagePath: imagePath, completion: {
(newImage) in
self.resetZoom()
})
}
}
var imageLoader: MVImageLoaderClosure?
@IBOutlet weak private var imageView : UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
self.delegate = self
self.imageView.contentMode = UIViewContentMode.ScaleAspectFill
}
func resetZoom() {
if self.imageView.image == nil {
return
}
let imageSize = self.imageView.image!.size
// let imageSize = self.imageView.bounds.size
// nothing to do if image is not set
if CGSizeEqualToSize(imageSize, CGSizeZero) {
return
}
// Stack overflow people suggest this, not sure if it applies to us
self.imageView.contentMode = UIViewContentMode.ScaleAspectFill
// if cellSize.width > imageSize.width && cellSize.height > imageSize.height {
// self.imageView.contentMode = UIViewContentMode.ScaleAspectFill
// }
let cellAspectRatio : CGFloat = self.cellSize.width / self.cellSize.height
let imageAspectRatio : CGFloat = imageSize.width / imageSize.height
let cellAspectRatioWiderThanImage = cellAspectRatio > imageAspectRatio
// Calculate Zoom
// If image is taller, then make edge to edge height, else make edge to edge width
let zoom = cellAspectRatioWiderThanImage ? cellSize.height / imageSize.height : cellSize.width / imageSize.width
self.maximumZoomScale = zoom * CGFloat(zoomToUse())
self.minimumZoomScale = zoom
self.zoomScale = 0.80
// Update content inset
let adjustedContentWidth = cellSize.height * imageAspectRatio
let horzContentInset = 0.0 as CGFloat // cellAspectRatioWiderThanImage ? 0.5 * (cellSize.width - adjustedContentWidth) : 0.0
let adjustedContentHeight = cellSize.width / imageAspectRatio
let vertContentInset = !cellAspectRatioWiderThanImage ? 0.5 * (cellSize.height - adjustedContentHeight) : 0.0
self.contentInset = UIEdgeInsetsMake(vertContentInset, horzContentInset, vertContentInset, horzContentInset)
}
func zoomToUse() -> Double {
return maximumZoom < 1.0 ? MaximumZoom : maximumZoom
}
func viewForZoomingInScrollView(scrollView : UIScrollView) -> UIView? {
return self.imageView
}
}
| mit | 577b895b1fae016a518dc2da7208a0ea | 40.86 | 132 | 0.683469 | 5.142506 | false | false | false | false |
mcxiaoke/learning-ios | ios_programming_4th/Homepwner-ch17/Homepwner/Item.swift | 4 | 1278 | //
// Item.swift
// Homepwner
//
// Created by Xiaoke Zhang on 2017/8/16.
// Copyright © 2017年 Xiaoke Zhang. All rights reserved.
//
import Foundation
struct Item : Equatable{
var itemName:String
var serialNumber:String
var valueInDollars:Int
let key = UUID().uuidString
let dateCreated:Date = Date()
var description:String {
return "\(itemName) (\(serialNumber)) Worth \(valueInDollars), recorded on \(dateCreated)"
}
public static func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.key == rhs.key
}
static func randomItem() -> Item {
let adjectives = ["Fluffy", "Rusty", "Shiny"]
let nouns = ["Bear", "Spork", "Mac"]
let ai = Int(arc4random()) % adjectives.count
let ni = Int(arc4random()) % nouns.count
let randomName = "\(adjectives[ai]) \(nouns[ni])"
let randomValue = Int(arc4random_uniform(100))
let s0 = "0\(arc4random_uniform(10))"
let s1 = "A\(arc4random_uniform(26))"
let s2 = "0\(arc4random_uniform(10))"
let randomSerialNumber = "\(s0)-\(s1)-\(s2)"
return Item(itemName:randomName,
serialNumber:randomSerialNumber,
valueInDollars: randomValue)
}
}
| apache-2.0 | fe0bb27c18913577ee4de60a988a552c | 29.357143 | 98 | 0.588235 | 3.947368 | false | false | false | false |
nixzhu/WorkerBee | WorkerBee/Observable.swift | 1 | 1232 | //
// Observable.swift
// WorkerBee
//
// Created by nixzhu on 2018/6/26.
// Copyright © 2018 nixWork. All rights reserved.
//
import Foundation
// ref: https://www.swiftbysundell.com/posts/handling-mutable-models-in-swift
public class Observable<Value> {
private var value: Value
private var observations = [UUID: (Value) -> Void]()
public init(value: Value) {
self.value = value
}
public func update(with value: Value) {
self.value = value
for observation in observations.values {
observation(value)
}
}
public func addObserver<O: AnyObject>(_ observer: O,
using closure: @escaping (O, Value) -> Void) {
let id = UUID()
observations[id] = { [weak self, weak observer] value in
// If the observer has been deallocated, we can safely remove
// the observation.
guard let observer = observer else {
self?.observations[id] = nil
return
}
closure(observer, value)
}
// Directly call the observation closure with the
// current value.
closure(observer, value)
}
}
| mit | 8e8674f2ebc9408d7d0e801be641c2eb | 25.191489 | 88 | 0.568643 | 4.476364 | false | false | false | false |
Constantine-Fry/wunderlist.swift | Demo/Demo-iOS/Demo-iOS/FirstViewController.swift | 1 | 1729 | //
// FirstViewController.swift
// Demo-iOS
//
// Created by Constantine Fry on 13/01/15.
// Copyright (c) 2015 Constantine Fry. All rights reserved.
//
import UIKit
import WunderlistTouch
class FirstViewController: UITableViewController {
@IBOutlet weak var loginButton: UIBarButtonItem!
var session: Session!
var lists: [List]?
override func viewDidLoad() {
super.viewDidLoad()
session = Session.sharedSession()
if session.isAuthorized() {
self.fetchLists()
}
}
@IBAction func loginButtonTapped(sender: AnyObject) {
session.authorize(self) {
(result, error) -> Void in
if result {
self.fetchLists()
}
}
}
func fetchLists() {
let listTask = self.session.lists.getLists() {
(lists, error) -> Void in
self.lists = lists
self.tableView.reloadData()
}
listTask.start()
}
//MARK: - Table View
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
let list = lists?[indexPath.row]
cell.textLabel?.text = list?.title
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if lists != nil {
return lists!.count
}
return 0
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
}
| bsd-2-clause | 36427374e50c31e326d9891671aa2e3c | 25.19697 | 118 | 0.602082 | 5.070381 | false | false | false | false |
nextcloud/ios | iOSClient/Utility/NCStoreReview.swift | 1 | 1736 | //
// NCStoreReview.swift
// Nextcloud
//
// Created by Marino Faggiana on 19/11/2018.
// Copyright © 2018 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import StoreKit
class NCStoreReview: NSObject {
let runIncrementerSetting = "numberOfRuns"
let minimumRunCount = 5
func getRunCounts () -> Int {
let uDefaults = UserDefaults()
let savedRuns = uDefaults.value(forKey: runIncrementerSetting)
var runs = 0
if savedRuns != nil {
runs = savedRuns as! Int
}
print("Nextcloud iOS run Counts are \(runs)")
return runs
}
@objc func incrementAppRuns() {
let uDefaults = UserDefaults()
let runs = getRunCounts() + 1
uDefaults.setValuesForKeys([runIncrementerSetting: runs])
uDefaults.synchronize()
}
@objc func showStoreReview() {
let runs = getRunCounts()
if runs > minimumRunCount {
SKStoreReviewController.requestReview()
}
}
}
| gpl-3.0 | 619adcb07ded820e7ac24a3642cccdab | 26.983871 | 73 | 0.667435 | 4.359296 | false | false | false | false |
TylerTheCompiler/TTPTimer | TTPTimerExample/TTPTimer/Timer.swift | 1 | 17502 | // The MIT License (MIT)
//
// Copyright (c) 2016 Tyler Prevost
//
// 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
/**
* The Timer class aims to make it easier to work with repeating NSTimers.
* Timers don't have to be invalidated, can be paused, have a running time property
* that is calculated automatically, can have a maximum running time, and can automatically
* pause themselves when the application leaves the active state.
*
* The pausing mechanism is robust in that you can pause the timer multiple times using
* different 'pause keys'. When the timer has at least one pause key set, the timer is paused,
* and when there are zero pause keys the timer resumes. This is similar to how reference
* counting works, but instead of just counting the number of pauses/resumes, keys are used
* instead. Adding a pause key that has already been added has no effect, and removing a pause
* key that was not added also has no effect.
*/
class Timer: NSObject, TimerTargetDelegate {
/**
* The object that will receive Timer delegate callbacks.
* You can only set this in the initialization of a Timer. The delegate is not retained.
* (read-only)
*/
private(set) var delegate: TimerDelegate?
/**
* True if the timer is currently running. False otherwise. (read-only)
*/
var running: Bool {
get {
return _isRunning()
}
}
/**
* True if the timer has at least one pause key set. False if there are no pause keys set. (read-only)
*/
var paused: Bool {
get {
return _isPaused()
}
}
/**
* The amount of elapsed time (in seconds) accumulated while the timer is running. (read-only)
*/
private(set) var runningTime: NSTimeInterval {
get {
return _runningTime
}
set {
_setRunningTime(newValue)
}
}
private var _runningTime: NSTimeInterval = 0.0
/**
* The number of ticks that the timer accumulates while the timer is running. (read-only)
*/
private(set) var tickCount: UInt = 0
/**
* The amount of time (in seconds) between each tick of the timer's clock.
* Setting this while the timer is running will restart the timer.
*
* (Default is 1/60.0 seconds. The minimum value is 1/200.0 seconds.)
*/
var timeInterval: NSTimeInterval {
get {
return _timeInterval
}
set {
_setTimeInterval(newValue)
}
}
private var _timeInterval: NSTimeInterval = 1 / 60.0
/**
* The maximum amount of running time (in seconds) that the timer can accrue
* before automatically pausing itself.
*
* (Default is DBL_MAX. Attempting to set this to less than or equal to zero sets it to DBL_MAX.)
*/
var maximumRunningTime: NSTimeInterval {
get {
return _maximumRunningTime
}
set {
_setMaximumRunningTime(newValue)
}
}
private var _maximumRunningTime: NSTimeInterval = DBL_MAX
/**
* Determines whether the timer automatically pauses and resumes itself when
* the application leaves/enters the UIApplicationState.Active state.
*
* (Default is true.)
*/
var pausesWhenApplicationIsNotActive: Bool {
get {
return _pausesWhenApplicationIsNotActive
}
set {
_setPausesWhenApplicationIsNotActive(newValue)
}
}
private var _pausesWhenApplicationIsNotActive: Bool = true
/**
* Initializes a new Timer object with a delegate object, a time interval, and
* a maximum running time.
* The timer is not automatically started.
*
* @param delegate The object that will receive delegate callbacks.
* @param timeInterval The amount of time (in seconds) between each tick of the timer's clock.
* @param maximumRunningTime The maximum amount of running time (in seconds) that
* the timer can accrue before automatically pausing itself.
*/
init(delegate: TimerDelegate? = nil, timeInterval: NSTimeInterval = 1 / 60.0, maximumRunningTime: NSTimeInterval? = nil) {
if let maximumRunningTime = maximumRunningTime {
_maximumRunningTime = maximumRunningTime > 0 ? maximumRunningTime : DBL_MAX
}
_timeInterval = max(timeInterval, minimumTimeInterval)
self.delegate = delegate
}
deinit {
_enableApplicationStateObserving(false)
_stopTimer()
}
/**
* Starts the timer, sets runningTime to zero and removes all pause keys.
* If the timer is already running when this is called, Timer.stop() is called first.
*/
func start() {
if _isRunning() {
_stop()
}
_resetRunningTime()
_removeAllPauseKeys()
_startTimer()
delegate?.timerDidStart(self)
}
/**
* If the timer is running OR runningTime is greater than zero,
* this stops the timer, sets runningTime to zero and removes all pause keys.
*/
func stop() {
if _canStop() {
_stopTimer()
_resetRunningTime()
_removeAllPauseKeys()
delegate?.timerDidStop(self)
}
}
/**
* Pause/unpause the timer for a given key.
*
* @param paused Whether the timer should be paused or unpaused for the given key.
* @param key The key for which to pause/unpause.
*/
func setPaused(paused: Bool, forKey key: String) {
_setPaused(paused, forKey: key)
}
/**
* Checks whether the timer is paused for a certain key.
*
* @param key
* @return True if the timer has been paused with the given key.
*/
func isPausedForKey(key: String) -> Bool {
return _isPausedForKey(key)
}
/**
* @return True if the timer is running OR runningTime is greater than zero. False otherwise.
*/
func canStop() -> Bool {
return _canStop()
}
/**
* @note Note: You may still add pause keys even if this returns false.
*
* @return True if the timer is running AND not paused already. False otherwise.
*/
func canPause() -> Bool {
return _canPause()
}
/**
* @note Note: You may still remove pause keys even if this returns NO.
*
* @return True if the timer is paused AND runningTime is less than the maximum
* running time. False otherwise.
*/
func canResume() -> Bool {
return _canResume()
}
// MARK: - Private
private class TimerTarget {
private weak var delegate: TimerTargetDelegate?
init(delegate: TimerTargetDelegate) {
self.delegate = delegate
}
@objc func handleTimer(timer: NSTimer) {
delegate?.handleTimer(timer)
}
}
private let TimerApplicationNotActivePauseKey = "__TTPTimerApplicationNotActivePauseKey"
private let TimerMaximumRunningTimeReachedPauseKey = "__TTPTimerMaximumRunningTimeReachedPauseKey"
private let minimumTimeInterval = 1 / 200.0
private var observingApplicationState = false
private var timer: NSTimer?
private var pauseKeys = Set<String>()
private func _isRunning() -> Bool {
return timer?.valid ?? false
}
private func _isPaused() -> Bool {
return pauseKeys.count > 0
}
private func _setRunningTime(runningTime: NSTimeInterval) {
if _runningTime != runningTime {
_runningTime = runningTime;
delegate?.timerDidChangeRunningTime(self)
}
}
private func _setTimeInterval(timeInterval: NSTimeInterval) {
_timeInterval = max(timeInterval, minimumTimeInterval)
if _isRunning() {
_startTimer()
}
}
private func _setMaximumRunningTime(maximumRunningTime: NSTimeInterval) {
_maximumRunningTime = maximumRunningTime > 0 ? maximumRunningTime : DBL_MAX
if _runningTime < _maximumRunningTime {
_setPaused(false, forKey: TimerMaximumRunningTimeReachedPauseKey)
}
}
private func _setPausesWhenApplicationIsNotActive(pausesWhenApplicationIsNotActive: Bool) {
_pausesWhenApplicationIsNotActive = pausesWhenApplicationIsNotActive
if UIApplication.sharedApplication().applicationState != .Active {
_setPaused(_pausesWhenApplicationIsNotActive, forKey: TimerApplicationNotActivePauseKey)
}
_enableApplicationStateObserving(_pausesWhenApplicationIsNotActive)
}
private func _start() {
}
private func _stop() {
}
private func _setPaused(paused: Bool, forKey key: String) {
if paused {
if _isRunning() || _isPaused() {
if _isPausedForKey(key) == false {
pauseKeys.insert(key)
if pauseKeys.count == 1 {
_stopTimer()
delegate?.timerDidPause(self)
}
}
}
}
else {
if _isPausedForKey(key) {
pauseKeys.remove(key)
if pauseKeys.count == 0 {
_startTimer()
delegate?.timerDidResume(self)
}
}
}
}
private func _isPausedForKey(key: String) -> Bool {
return pauseKeys.contains(key)
}
private func _canStop() -> Bool {
return _isRunning() || _runningTime > 0.0
}
private func _canPause() -> Bool {
return !_isPaused() && _isRunning()
}
private func _canResume() -> Bool {
return _isPaused() && _runningTime < _maximumRunningTime
}
private func _startTimer() {
_stopTimer()
if _runningTime < _maximumRunningTime {
_setPaused(false, forKey: TimerMaximumRunningTimeReachedPauseKey)
// timerTarget is retained by the NSTimer
let timerTarget = TimerTarget(delegate: self)
let timer = NSTimer.init(
timeInterval: _timeInterval,
target: timerTarget,
selector: #selector(TimerTarget.handleTimer(_:)),
userInfo: nil,
repeats: true
)
self.timer = timer
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}
}
private func _stopTimer() {
timer?.invalidate()
timer = nil
}
private func _resetRunningTime() {
_setRunningTime(0.0)
tickCount = 0
}
private func _removeAllPauseKeys() {
pauseKeys.removeAll()
}
private func _enableApplicationStateObserving(enabled: Bool) {
if enabled {
if observingApplicationState == false {
observingApplicationState = true
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(_appDidBecomeActive(_:)),
name: UIApplicationDidBecomeActiveNotification,
object: nil
)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(_appWillResignActive(_:)),
name: UIApplicationWillResignActiveNotification,
object: nil
)
}
}
else {
if observingApplicationState {
observingApplicationState = false
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: UIApplicationDidBecomeActiveNotification,
object: nil
)
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: UIApplicationWillResignActiveNotification,
object: nil
)
}
}
}
private func handleTimer(timer: NSTimer) {
tickCount += 1
_setRunningTime(Double(tickCount) * timer.timeInterval)
delegate?.timer(self, didFireWithTimeInterval: timer.timeInterval)
if _runningTime >= _maximumRunningTime {
delegate?.timerDidReachMaximumRunningTime(self)
}
if _runningTime >= _maximumRunningTime {
_setPaused(true, forKey: TimerMaximumRunningTimeReachedPauseKey)
}
}
@objc private func _appDidBecomeActive(notif: NSNotification) {
_setPaused(false, forKey: TimerApplicationNotActivePauseKey)
}
@objc private func _appWillResignActive(notif: NSNotification) {
if _pausesWhenApplicationIsNotActive {
_setPaused(true, forKey: TimerApplicationNotActivePauseKey)
}
}
}
private protocol TimerTargetDelegate: class {
func handleTimer(timer: NSTimer)
}
/**
* Objects conforming to this protocol can respond to Timer events.
*/
protocol TimerDelegate: NSObjectProtocol {
/**
* Called on every tick of 'timer'.
*
* @param timer The timer that fired this event.
* @param timeInterval The amount of time that should pass between ticks.
*/
func timer(timer: Timer, didFireWithTimeInterval: NSTimeInterval)
/**
* Called whenever the value of runningTime of 'timer' is changed.
*
* @param timer The timer that fired this event.
*/
func timerDidChangeRunningTime(timer: Timer)
/**
* Called when the value of runningTime of 'timer' is greater than or equal to its maximumRunningTime value.
*
* @param timer The timer that fired this event.
*/
func timerDidReachMaximumRunningTime(timer: Timer)
/**
* Called when 'timer' starts.
*
* @param timer The timer that fired this event.
*/
func timerDidStart(timer: Timer)
/**
* Called when 'timer' stops.
*
* @param timer The timer that fired this event.
*/
func timerDidStop(timer: Timer)
/**
* Called when 'timer' becomes paused.
*
* @param timer The timer that fired this event.
*/
func timerDidPause(timer: Timer)
/**
* Called when 'timer' becomes unpaused.
*
* @param timer The timer that fired this event.
*/
func timerDidResume(timer: Timer)
}
extension TimerDelegate {
func timer(timer: Timer, didFireWithTimeInterval timeInterval: NSTimeInterval) {}
func timerDidChangeRunningTime(timer: Timer) {}
func timerDidReachMaximumRunningTime(timer: Timer) {}
func timerDidStart(timer: Timer) {}
func timerDidStop(timer: Timer) {}
func timerDidPause(timer: Timer) {}
func timerDidResume(timer: Timer) {}
}
typealias TimerBlock = Timer -> Void
typealias TimerTimeIntervalBlock = (Timer, NSTimeInterval) -> Void
class TimerBlockDelegate: NSObject, TimerDelegate {
var didFireHandler: TimerTimeIntervalBlock?
var didChangeRunningTimeHandler: TimerBlock?
var didStartHandler: TimerBlock?
var didStopHandler: TimerBlock?
var didPauseHandler: TimerBlock?
var didResumeHandler: TimerBlock?
var didReachMaximumRunningTimeHandler: TimerBlock?
func timer(timer: Timer, didFireWithTimeInterval timeInterval: NSTimeInterval) {
didFireHandler?(timer, timeInterval)
}
func timerDidChangeRunningTime(timer: Timer) {
didChangeRunningTimeHandler?(timer)
}
func timerDidReachMaximumRunningTime(timer: Timer) {
didReachMaximumRunningTimeHandler?(timer)
}
func timerDidStart(timer: Timer) {
didStartHandler?(timer)
}
func timerDidStop(timer: Timer) {
didStopHandler?(timer)
}
func timerDidPause(timer: Timer) {
didPauseHandler?(timer)
}
func timerDidResume(timer: Timer) {
didResumeHandler?(timer)
}
}
| mit | ac9fd969ac0223e1c2c3a53b52c7575c | 30.253571 | 126 | 0.605931 | 5.259014 | false | false | false | false |
SwiftKit/Cuckoo | Generator/Source/CuckooGeneratorFramework/Templates/NopImplStubTemplate.swift | 1 | 1914 | //
// NopImplStubTemplate.swift
// CuckooGeneratorFramework
//
// Created by Tadeas Kriz on 11/14/17.
//
extension Templates {
static let noImplStub = """
{{container.accessibility}} class {{ container.name }}Stub{{ container.genericParameters }}: {{ container.name }}{% if container.isImplementation %}{{ container.genericArguments }}{% endif %} {
{% for property in container.properties %}
{% if debug %}
// {{property}}
{% endif %}
{% for attribute in property.attributes %}
{{ attribute.text }}
{% endfor %}
{{ property.accessibility }}{% if container.@type == "ClassDeclaration" %} override{% endif %} var {{ property.name }}: {{ property.type }} {
get {
return DefaultValueRegistry.defaultValue(for: ({{property.type|genericSafe}}).self)
}
{% ifnot property.isReadOnly %}
set { }
{% endif %}
}
{% endfor %}
{% for initializer in container.initializers %}
{{ initializer.accessibility }}{% if container.@type == "ClassDeclaration" %} override{% endif %}{% if initializer.@type == "ProtocolMethod" %} required{%endif%} init({{initializer.parameterSignature}}) {
{% if container.@type == "ClassDeclaration" %}
super.init({{initializer.call}})
{% endif %}
}
{% endfor %}
{% for method in container.methods %}
{% if debug %}
// {{method}}
{% endif %}
{% for attribute in method.attributes %}
{{ attribute.text }}
{% endfor %}
{{ method.accessibility }}{% if container.@type == "ClassDeclaration" and method.isOverriding %} override{% endif %} func {{ method.name|escapeReservedKeywords }}{{ method.genericParameters }}({{ method.parameterSignature }}) {{ method.returnSignature }} {{ method.whereClause }} {
return DefaultValueRegistry.defaultValue(for: ({{method.returnType|genericSafe}}).self)
}
{% endfor %}
}
"""
}
| mit | 0ef12af2dc9e5f30893d77d0ccae6767 | 38.061224 | 285 | 0.61651 | 4.568019 | false | false | false | false |
certificate-helper/TLS-Inspector | TLS Inspector/User Interface/UIHelper.swift | 1 | 2782 | import UIKit
class UIHelper {
private var viewController: UIViewController!
init(_ viewController: UIViewController) {
self.viewController = viewController
}
/// Present a generic alert in the given view controller. Alert has a single "Dismiss" button.
/// - Parameters:
/// - title: The title of the alert
/// - body: The body of the alert
/// - dismissed: Optional closure to call when the alert is dismissed
public func presentAlert(title: String, body: String, dismissed: (() -> Void)?) {
let alertController = UIAlertController(title: title, message: body, preferredStyle: .alert)
let dismissButton = UIAlertAction(title: "Dismiss", style: .default) { (_) in
dismissed?()
}
alertController.addAction(dismissButton)
RunOnMain {
self.viewController.present(alertController, animated: true, completion: nil)
}
}
/// Present an error alert in the given view controller. Alert has a single "Dismiss" button.
/// - Parameters:
/// - error: The error to display
/// - dismissed: Optional closure to call when the alert is dismissed
public func presentError(error: Error, dismissed: (() -> Void)?) {
self.presentAlert(title: "Error",
body: error.localizedDescription,
dismissed: dismissed)
}
/// Present an action sheet in the given view controller.
/// - Parameters:
/// - target: The target of the action sheet
/// - title: Tht optional title of the action sheet
/// - subtitle: The optional subtitle of the action sheet
/// - items: The titles for each option
/// - dismissed: Optional closure to call when an option is selected. Cancel is -1.
public func presentActionSheet(target: ActionTipTarget?,
title: String?,
subtitle: String?,
items: [String],
dismissed: ((Int) -> Void)?) {
let controller = UIAlertController(title: title, message: subtitle, preferredStyle: .actionSheet)
let cancelButton = UIAlertAction(title: lang(key: "Cancel"), style: .cancel) { (_) in
dismissed?(-1)
}
controller.addAction(cancelButton)
for (idx, title) in items.enumerated() {
let action = UIAlertAction(title: title, style: .default) { (_) in
dismissed?(idx)
}
controller.addAction(action)
}
target?.attach(to: controller.popoverPresentationController)
RunOnMain {
self.viewController.present(controller, animated: true, completion: nil)
}
}
}
| gpl-3.0 | 5ff8672886c531764d2758dafe27f113 | 42.46875 | 105 | 0.595255 | 5.076642 | false | false | false | false |
alexth/CDVDictionary | Dictionary/Dictionary/ViewControllers/MainViewController.swift | 1 | 2129 | //
// MainViewController.swift
// Dictionary
//
// Created by Alex Golub on 9/21/16.
// Copyright © 2016 Alex Golub. All rights reserved.
//
import UIKit
final class MainViewController: UIViewController {
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var rsContainerView: UIView!
@IBOutlet weak var srContainerView: UIView!
@IBOutlet weak var infoContainerView: UIView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
segmentedControl.selectedSegmentIndex = 0
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "rsSegue" {
guard let dictionaryViewController = segue.destination as? DictionaryViewController else { return }
dictionaryViewController.dictionaryName = "DICT_R-S"
} else if segue.identifier == "srSegue" {
guard let dictionaryViewController = segue.destination as? DictionaryViewController else { return }
dictionaryViewController.dictionaryName = "DICT_S-R"
}
}
// MARK: - Action
@IBAction func didChange(segmentedControl: UISegmentedControl) {
view.endEditing(true)
switch segmentedControl.selectedSegmentIndex {
case 0:
highlight(containerView: rsContainerView)
case 1:
highlight(containerView: srContainerView)
case 2:
highlight(containerView: infoContainerView)
default:
break
}
}
// MARK: - Util
private func highlight(containerView: UIView) {
let containersArray = [rsContainerView, srContainerView, infoContainerView]
for container in containersArray {
if container == containerView {
UIView.animate(withDuration: 0.3, animations: {
container?.alpha = 1.0
})
} else {
UIView.animate(withDuration: 0.3, animations: {
container?.alpha = 0.0
})
}
}
}
}
| mit | c81c7a6983eee6ee0b87fef3841ccbb4 | 28.555556 | 112 | 0.619831 | 5.165049 | false | false | false | false |
tkremenek/swift | test/Interop/Cxx/value-witness-table/custom-destructors-virtual.swift | 5 | 1633 | // With RTTI some of the objects with virtual bases / destructors in this test
// will cause linker errors because of undefined vtables.
// FIXME: Once we can link with libc++ we can start using RTTI.
//
// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-cxx-interop -Xcc -fno-rtti)
// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-cxx-interop -Xcc -fno-rtti -O)
//
// REQUIRES: executable_test
// Windows doesn't support -fno-rtti.
// UNSUPPORTED: OS=windows-msvc
import CustomDestructor
import StdlibUnittest
var CXXDestructorTestSuite = TestSuite("CXXDestructor")
func createTypeWithVirtualBaseAndDestructor(
_ ptr: UnsafeMutablePointer<Int32>
) {
_ = HasVirtualBaseAndDestructor(ptr)
}
func createTypeWithBaseWithVirtualDestructor(
_ ptr: UnsafeMutablePointer<Int32>
) {
_ = HasBaseWithVirtualDestructor(ptr)
}
func createTypeWithVirtualBaseWithVirtualDestructor(
_ ptr: UnsafeMutablePointer<Int32>
) {
_ = HasVirtualBaseWithVirtualDestructor(ptr)
}
CXXDestructorTestSuite.test("Virtual base and destructor") {
var value: Int32 = 0
createTypeWithVirtualBaseAndDestructor(&value)
expectEqual(value, 42)
}
CXXDestructorTestSuite.test("Base with virtual destructor") {
var value: Int32 = 0
createTypeWithBaseWithVirtualDestructor(&value)
expectEqual(value, 42)
}
CXXDestructorTestSuite.test("Virtual base with virtual destructor") {
var value: Int32 = 0
createTypeWithVirtualBaseWithVirtualDestructor(&value)
expectEqual(value, 42)
}
CXXDestructorTestSuite.test("Type with virtual defaulted destructor") {
_ = HasVirtualDefaultedDestructor()
}
runAllTests()
| apache-2.0 | 3b55eb08a0fca4bc482f7ca6d46d612b | 27.631579 | 95 | 0.770833 | 3.93253 | false | true | false | false |
bingFly/weibo | weibo/weibo/Classes/UI/Home/HBHomeCell.swift | 1 | 5775 | //
// HBHomeCell.swift
// weibo
//
// Created by hanbing on 15/3/9.
// Copyright (c) 2015年 fly. All rights reserved.
//
import UIKit
class HBHomeCell: UITableViewCell {
/// 头像
@IBOutlet weak var iconImage: UIImageView!
/// 姓名
@IBOutlet weak var nameLabel: UILabel!
/// 会员图标
@IBOutlet weak var memberIcon: UIImageView!
/// 认证图标
@IBOutlet weak var vipIcon: UIImageView!
/// 时间
@IBOutlet weak var timeLabel: UILabel!
/// 来源
@IBOutlet weak var sourceLabel: UILabel!
/// 微博正文
@IBOutlet weak var contextLabel: UILabel!
/// 配图
@IBOutlet weak var pictureView: UICollectionView!
/// 整体高度
@IBOutlet weak var pictureHeight: NSLayoutConstraint!
/// 整体宽度
@IBOutlet weak var pictureWidth: NSLayoutConstraint!
@IBOutlet weak var pictureLayout: UICollectionViewFlowLayout!
/// 转发微博文本
@IBOutlet weak var forwordLabel: UILabel!
/// 底部工具条
@IBOutlet weak var bottomView: UIView!
/// 定义闭包
var photoDidSelected: ((status: HBStatus, photoIndex: Int) -> ())?
var status: HBStatus? {
didSet {
nameLabel.text = status!.user!.name
timeLabel.text = status!.created_at
sourceLabel.text = status!.formatSource
contextLabel.text = status!.text
vipIcon.image = status!.user!.verifiedImage
// 等级图标
memberIcon.image = status!.user!.mkImage
if let url = status?.user?.profile_image_url {
NetworkManager.sharedManager.requestImage(url, { (result, error) -> () in
if let img = result as? UIImage {
self.iconImage.image = img
}
})
}
// 设置图片大小
let resultSize = calcPictureViewSize()
pictureHeight.constant = resultSize.viewSize.height
pictureWidth.constant = resultSize.viewSize.width
pictureLayout.itemSize = resultSize.itemSize
if status?.retweeted_status != nil {
forwordLabel.text = "@"+status!.retweeted_status!.user!.name! + ":" + status!.retweeted_status!.text!
}
// 刷新配图视图
pictureView.reloadData()
}
}
// 判断cell的类型
class func switchCellType(status: HBStatus) -> String {
if status.retweeted_status != nil {
return "forwordCell"
} else {
return "homeCell"
}
}
func calcPictureViewSize() -> (itemSize: CGSize, viewSize: CGSize){
let s: CGFloat = 90
// 图片大小
var itemSize = CGSizeMake(s, s)
// 视图大小
var viewSize = CGSizeZero
let count = status?.forword_urls?.count ?? 0
if count == 0 {
return (itemSize, viewSize)
}
if count == 1 {
let url = status!.forword_urls?[0].thumbnail_pic
let path = NetworkManager.sharedManager.fullImageCachePath(url!)
if let img = UIImage(contentsOfFile: path) {
return (img.size, img.size)
} else {
return (itemSize, viewSize)
}
}
// 间距
let m: CGFloat = 10
if count == 4 {
viewSize = CGSizeMake(s * 2 + m, s * 2 + m)
} else {
let row = (count - 1) / 3
var col = 3
if count == 2 {
col = 2
}
viewSize = CGSizeMake(CGFloat(col) * s + 2 * m, (CGFloat(row) + 1) * s + CGFloat(row) * m)
}
return (itemSize, viewSize)
}
func cellHeight(status: HBStatus) -> CGFloat {
self.status = status
layoutIfNeeded()
return CGRectGetMaxY(bottomView.frame)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func awakeFromNib() {
super.awakeFromNib()
contextLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.size.width - 20
forwordLabel?.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.size.width - 20
}
}
extension HBHomeCell: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return status?.forword_urls?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("pictureCell", forIndexPath: indexPath) as! HBPictureCell
cell.urlString = status!.forword_urls![indexPath.item].thumbnail_pic
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// 事件处理交给控制器,这里只是负责把事件传递回去 ----- 用闭包
if self.photoDidSelected != nil {
self.photoDidSelected!(status: self.status!, photoIndex: indexPath.item)
}
}
}
public class HBPictureCell: UICollectionViewCell {
@IBOutlet weak var pictureImage: UIImageView!
var urlString: String? {
didSet {
let path = NetworkManager.sharedManager.fullImageCachePath(urlString!)
pictureImage.image = UIImage(contentsOfFile: path)
}
}
}
| mit | 35b892a7e136d7947c1f085b41938f30 | 29.938889 | 130 | 0.572455 | 4.945826 | false | false | false | false |
biohazardlover/iNinja | NinjaGuide/HomeViewController.swift | 1 | 1106 |
import UIKit
class HomeViewController: UIViewController {
var weapons: [[String: AnyObject]] = {
let url = Bundle.main.url(forResource: "WeaponMoves", withExtension: "plist")
let plist = NSDictionary(contentsOf: url!)
return plist!["Weapons"] as! [[String: AnyObject]]
}()
@IBOutlet weak var separatorLineHeight: NSLayoutConstraint!
var weaponsViewController: WeaponsViewController!
var movesPageViewController: MovesPageViewController!
override func viewDidLoad() {
super.viewDidLoad()
separatorLineHeight.constant = 1 / UIScreen.main.scale
weaponsViewController = childViewControllers.first as! WeaponsViewController
movesPageViewController = childViewControllers.last as! MovesPageViewController
weaponsViewController.weapons = weapons
movesPageViewController.weapons = weapons
weaponsViewController.movesPageViewController = movesPageViewController
movesPageViewController.weaponsViewController = weaponsViewController
}
}
| mit | 94acb5a72d46b009051a6e08acec9803 | 33.5625 | 87 | 0.702532 | 6.248588 | false | false | false | false |
JohnSundell/Marathon | Sources/MarathonCore/Marathon.swift | 1 | 4354 | /**
* Marathon
* Copyright (c) John Sundell 2017
* Licensed under the MIT license. See LICENSE file.
*/
import Foundation
import Files
public final class Marathon {
public enum Error: Swift.Error {
case couldNotPerformSetup(String)
}
private struct Folders {
let module: Folder
let scripts: Folder
let packages: Folder
}
// MARK: - API
public static func run(with arguments: [String] = CommandLine.arguments,
folderPath: String = "~/.marathon",
printFunction: @escaping PrintFunction = { print($0) }) throws {
let task = try resolveTask(for: arguments, folderPath: folderPath, printFunction: printFunction)
try task.execute()
}
// MARK: - Private
private static func resolveTask(for arguments: [String],
folderPath: String,
printFunction: @escaping PrintFunction) throws -> Executable {
let command = try Command(arguments: arguments)
let printer = makePrinter(using: printFunction, command: command, arguments: arguments)
let fileSystem = FileSystem()
do {
let rootFolder = try fileSystem.createFolderIfNeeded(at: folderPath)
let packageFolder = try rootFolder.createSubfolderIfNeeded(withName: "Packages")
let scriptFolder = try rootFolder.createSubfolderIfNeeded(withName: "Scripts")
let autocompletionsFolder = try rootFolder.createSubfolderIfNeeded(withName: "ShellAutocomplete")
installShellAutocompleteIfNeeded(in: autocompletionsFolder)
let packageManager = try PackageManager(folder: packageFolder, printer: printer)
let scriptManager = try ScriptManager(folder: scriptFolder, packageManager: packageManager, printer: printer)
return command.makeTaskClosure(fileSystem.currentFolder,
Array(arguments.dropFirst(2)),
scriptManager, packageManager,
printer)
} catch {
throw Error.couldNotPerformSetup(folderPath)
}
}
private static func makePrinter(using printFunction: @escaping PrintFunction,
command: Command,
arguments: [String]) -> Printer {
let progressFunction = makeProgressPrintingFunction(using: printFunction, command: command, arguments: arguments)
let verboseFunction = makeVerbosePrintingFunction(using: progressFunction, arguments: arguments)
return Printer(
outputFunction: printFunction,
progressFunction: progressFunction,
verboseFunction: verboseFunction
)
}
private static func makeProgressPrintingFunction(using printFunction: @escaping PrintFunction,
command: Command,
arguments: [String]) -> VerbosePrintFunction {
var isFirstOutput = true
let shouldPrint = command.allowsProgressOutput || arguments.contains("--verbose")
return { (messageExpression: () -> String) in
guard shouldPrint else {
return
}
let message = messageExpression()
printFunction(message.withIndentedNewLines(prefix: isFirstOutput ? "🏃 " : " "))
isFirstOutput = false
}
}
private static func makeVerbosePrintingFunction(using progressFunction: @escaping VerbosePrintFunction,
arguments: [String]) -> VerbosePrintFunction {
let allowVerboseOutput = arguments.contains("--verbose")
return { (messageExpression: () -> String) in
guard allowVerboseOutput else {
return
}
// Make text italic
let message = "\u{001B}[0;3m\(messageExpression())\u{001B}[0;23m"
progressFunction(message)
}
}
private static func installShellAutocompleteIfNeeded(in folder: Folder) {
ZshAutocompleteInstaller.installIfNeeded(in: folder)
FishAutocompleteInstaller.installIfNeeded(in: folder)
}
}
| mit | 38a44f8acf215744dcc583c4bcf0a7c1 | 38.917431 | 121 | 0.601701 | 5.717477 | false | false | false | false |
Marguerite-iOS/Marguerite | Marguerite/ShuttleSystem+Matching.swift | 1 | 1635 | //
// ShuttleSystem+Matching.swift
// Marguerite
//
// Created by Andrew Finke on 1/26/16.
// Copyright © 2016 Andrew Finke. All rights reserved.
//
import Foundation
extension ShuttleSystem {
// MARK: - Matching items with string
/**
Gets the shuttle route with name.
- parameter name: The route name.
- returns: The route if it exists.
*/
func shuttleRouteWithName(name: String) -> ShuttleRoute? {
return routes.filter { $0.shortName == name }.first
}
/**
Gets the shuttle route with ID.
- parameter routeID: The route ID.
- returns: The route if it exists.
*/
func shuttleRouteWithID(routeID: String) -> ShuttleRoute? {
let routeIDVal = Int(routeID)
return routes.filter { $0.routeID == routeIDVal }.first
}
/**
Gets the shuttle stop with name.
- parameter name: The stop name.
- returns: The stop if it exists.
*/
func shuttleStopWithID(stopID: String) -> ShuttleStop? {
let stopIDVal = Int(stopID)
return stops.filter { $0.stopID == stopIDVal }.first
}
/**
Gets the stop at index path based on the selected segemented control index
- parameter indexPath: The index path
- returns: The stop
*/
func stopForIndexPath(indexPath: NSIndexPath, scope: Int) -> ShuttleStop {
switch scope {
case 1:
return favoriteStops[indexPath.row]
case 2:
return closestStops[indexPath.row]
default:
return stops[indexPath.row]
}
}
}
| mit | 03bdd99f4af892a826b461081be1ff52 | 23.757576 | 79 | 0.593635 | 4.392473 | false | false | false | false |
LYM-mg/MGDS_Swift | MGDS_Swift/MGDS_Swift/Class/Home/DouYu/Controller/HeaderViewDetailController.swift | 1 | 6909 | //
// HeaderViewDetailController.swift
// MGDYZB
//
// Created by i-Techsys.com on 17/4/10.
// Copyright © 2017年 ming. All rights reserved.
//
import UIKit
import SafariServices
import MJRefresh
class HeaderViewDetailController: UIViewController {
// MARK: - 懒加载属性
fileprivate lazy var headerVM: HeadViewModel = HeadViewModel()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
// 1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin/2
layout.sectionInset = UIEdgeInsets(top: 5, left: kItemMargin/2, bottom: 0, right: kItemMargin/2)
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.dataSource = self
collectionView.delegate = self
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
setUpMainView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
convenience init(model: AnchorGroup) {
self.init()
headerVM.tag_id = Int(model.tag_id)
self.title = model.anchors.count>0 ? model.icon_name :model.anchors.first?.nickname
}
}
// MARK: - 设置UI
extension HeaderViewDetailController {
func setUpMainView() {
if #available(iOS 9, *) {
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: self.view)
}
}
view.addSubview(collectionView)
setUpRefresh()
}
}
// MARK: - loadData
extension HeaderViewDetailController {
fileprivate func loadData() {
// 1.请求数据
headerVM.loadHearderData({ [weak self] (err) in
// 1.1.刷新表格
self!.collectionView.mj_header?.endRefreshing()
self!.collectionView.mj_footer?.endRefreshing()
self!.collectionView.reloadData()
})
}
fileprivate func setUpRefresh() {
// MARK: - 下拉
self.collectionView.mj_header = MJRefreshGifHeader(refreshingBlock: { [weak self]() -> Void in
self!.headerVM.anchorGroups.removeAll()
self!.headerVM.offset = 0
self!.loadData()
})
// MARK: - 上拉
self.collectionView.mj_footer = MJRefreshAutoGifFooter(refreshingBlock: {[weak self] () -> Void in
self!.headerVM.offset += 20
self!.loadData()
})
self.collectionView.mj_header?.isAutomaticallyChangeAlpha = true
self.collectionView.mj_header?.beginRefreshing()
self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
}
}
// MARK: - UICollectionViewDataSource
extension HeaderViewDetailController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return headerVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return headerVM.anchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.获取cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
if headerVM.anchorGroups.count > 0 {
cell.anchor = headerVM.anchorGroups[indexPath.section].anchors[indexPath.item]
}
return cell
}
}
// MARK: - UICollectionViewDelegate
extension HeaderViewDetailController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 1.取出对应的主播信息
let anchor = headerVM.anchorGroups[indexPath.section].anchors[indexPath.item]
// 2.判断是秀场房间&普通房间
anchor.isVertical == 0 ? pushNormalRoomVc(anchor: anchor) : presentShowRoomVc(anchor: anchor)
}
fileprivate func presentShowRoomVc(anchor: AnchorModel) {
if #available(iOS 9.0, *) {
// 1.创建SFSafariViewController
let safariVC = SFSafariViewController(url: URL(string: anchor.jumpUrl)!, entersReaderIfAvailable: true)
// 2.以Modal方式弹出
present(safariVC, animated: true, completion: nil)
} else {
let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl)
present(webVC, animated: true, completion: nil)
}
}
fileprivate func pushNormalRoomVc(anchor: AnchorModel) {
// 1.创建WebViewController
let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl)
webVC.navigationController?.setNavigationBarHidden(true, animated: true)
// 2.以Push方式弹出
navigationController?.pushViewController(webVC, animated: true)
}
}
// MARK: - UIViewControllerPreviewingDelegate
extension HeaderViewDetailController: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = collectionView.indexPathForItem(at: location) else { return nil }
guard let cell = collectionView.cellForItem(at: indexPath) else { return nil }
if #available(iOS 9.0, *) {
previewingContext.sourceRect = cell.frame
}
var vc = UIViewController()
let anchor = headerVM.anchorGroups[indexPath.section].anchors[indexPath.item]
if anchor.isVertical == 0 {
if #available(iOS 9, *) {
vc = SFSafariViewController(url: URL(string: anchor.jumpUrl)!, entersReaderIfAvailable: true)
} else {
vc = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl)
}
}else {
vc = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl)
}
return vc
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
show(viewControllerToCommit, sender: nil)
}
}
| mit | 0ec9cdb178af46d02ba2e4669642d125 | 36.071038 | 143 | 0.662883 | 5.392687 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager.swift | 1 | 110733 | //
// IQKeyboardManager.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreGraphics
import UIKit
import QuartzCore
///---------------------
/// MARK: IQToolbar tags
///---------------------
/**
Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
*/
@objc public class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate {
/**
Default tag for toolbar with Done button -1002.
*/
private static let kIQDoneButtonToolbarTag = -1002
/**
Default tag for toolbar with Previous/Next buttons -1005.
*/
private static let kIQPreviousNextButtonToolbarTag = -1005
/**
Invalid point value.
*/
private static let kIQCGPointInvalid = CGPoint.init(x: CGFloat.greatestFiniteMagnitude, y: CGFloat.greatestFiniteMagnitude)
///---------------------------
/// MARK: UIKeyboard handling
///---------------------------
/**
Registered classes list with library.
*/
private var registeredClasses = [UIView.Type]()
/**
Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method).
*/
@objc public var enable = false {
didSet {
//If not enable, enable it.
if enable == true &&
oldValue == false {
//If keyboard is currently showing. Sending a fake notification for keyboardWillHide to retain view's original position.
if let notification = _kbShowNotification {
keyboardWillShow(notification)
}
showLog("Enabled")
} else if enable == false &&
oldValue == true { //If not disable, desable it.
keyboardWillHide(nil)
showLog("Disabled")
}
}
}
private func privateIsEnabled() -> Bool {
var isEnabled = enable
// let enableMode = _textFieldView?.enableMode
//
// if enableMode == .enabled {
// isEnabled = true
// } else if enableMode == .disabled {
// isEnabled = false
// } else {
if let textFieldViewController = _textFieldView?.viewContainingController() {
if isEnabled == false {
//If viewController is kind of enable viewController class, then assuming it's enabled.
for enabledClass in enabledDistanceHandlingClasses {
if textFieldViewController.isKind(of: enabledClass) {
isEnabled = true
break
}
}
}
if isEnabled == true {
//If viewController is kind of disabled viewController class, then assuming it's disabled.
for disabledClass in disabledDistanceHandlingClasses {
if textFieldViewController.isKind(of: disabledClass) {
isEnabled = false
break
}
}
//Special Controllers
if isEnabled == true {
let classNameString = NSStringFromClass(type(of: textFieldViewController.self))
//_UIAlertControllerTextFieldViewController
if classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController") {
isEnabled = false
}
}
}
}
// }
return isEnabled
}
/**
To set keyboard distance from textField. can't be less than zero. Default is 10.0.
*/
@objc public var keyboardDistanceFromTextField: CGFloat {
set {
_privateKeyboardDistanceFromTextField = max(0, newValue)
showLog("keyboardDistanceFromTextField: \(_privateKeyboardDistanceFromTextField)")
}
get {
return _privateKeyboardDistanceFromTextField
}
}
/**
Boolean to know if keyboard is showing.
*/
@objc public var keyboardShowing: Bool {
return _privateIsKeyboardShowing
}
/**
moved distance to the top used to maintain distance between keyboard and textField. Most of the time this will be a positive value.
*/
@objc public var movedDistance: CGFloat {
return _privateMovedDistance
}
/**
Returns the default singleton instance.
*/
@objc public class var shared: IQKeyboardManager {
struct Static {
//Singleton instance. Initializing keyboard manger.
static let kbManager = IQKeyboardManager()
}
/** @return Returns the default singleton instance. */
return Static.kbManager
}
///-------------------------
/// MARK: IQToolbar handling
///-------------------------
/**
Automatic add the IQToolbar functionality. Default is YES.
*/
@objc public var enableAutoToolbar = true {
didSet {
privateIsEnableAutoToolbar() ? addToolbarIfRequired() : removeToolbarIfRequired()
let enableToolbar = enableAutoToolbar ? "Yes" : "NO"
showLog("enableAutoToolbar: \(enableToolbar)")
}
}
private func privateIsEnableAutoToolbar() -> Bool {
var enableToolbar = enableAutoToolbar
if let textFieldViewController = _textFieldView?.viewContainingController() {
if enableToolbar == false {
//If found any toolbar enabled classes then return.
for enabledClass in enabledToolbarClasses {
if textFieldViewController.isKind(of: enabledClass) {
enableToolbar = true
break
}
}
}
if enableToolbar == true {
//If found any toolbar disabled classes then return.
for disabledClass in disabledToolbarClasses {
if textFieldViewController.isKind(of: disabledClass) {
enableToolbar = false
break
}
}
//Special Controllers
if enableToolbar == true {
let classNameString = NSStringFromClass(type(of: textFieldViewController.self))
//_UIAlertControllerTextFieldViewController
if classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController") {
enableToolbar = false
}
}
}
}
return enableToolbar
}
/**
/**
IQAutoToolbarBySubviews: Creates Toolbar according to subview's hirarchy of Textfield's in view.
IQAutoToolbarByTag: Creates Toolbar according to tag property of TextField's.
IQAutoToolbarByPosition: Creates Toolbar according to the y,x position of textField in it's superview coordinate.
Default is IQAutoToolbarBySubviews.
*/
AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews.
*/
@objc public var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.bySubviews
/**
If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO.
*/
@objc public var shouldToolbarUsesTextFieldTintColor = false
/**
This is used for toolbar.tintColor when textfield.keyboardAppearance is UIKeyboardAppearanceDefault. If shouldToolbarUsesTextFieldTintColor is YES then this property is ignored. Default is nil and uses black color.
*/
@objc public var toolbarTintColor: UIColor?
/**
This is used for toolbar.barTintColor. Default is nil and uses white color.
*/
@objc public var toolbarBarTintColor: UIColor?
/**
IQPreviousNextDisplayModeDefault: Show NextPrevious when there are more than 1 textField otherwise hide.
IQPreviousNextDisplayModeAlwaysHide: Do not show NextPrevious buttons in any case.
IQPreviousNextDisplayModeAlwaysShow: Always show nextPrevious buttons, if there are more than 1 textField then both buttons will be visible but will be shown as disabled.
*/
@objc public var previousNextDisplayMode = IQPreviousNextDisplayMode.default
/**
Toolbar previous/next/done button icon, If nothing is provided then check toolbarDoneBarButtonItemText to draw done button.
*/
@objc public var toolbarPreviousBarButtonItemImage: UIImage?
@objc public var toolbarNextBarButtonItemImage: UIImage?
@objc public var toolbarDoneBarButtonItemImage: UIImage?
/**
Toolbar previous/next/done button text, If nothing is provided then system default 'UIBarButtonSystemItemDone' will be used.
*/
@objc public var toolbarPreviousBarButtonItemText: String?
@objc public var toolbarNextBarButtonItemText: String?
@objc public var toolbarDoneBarButtonItemText: String?
/**
If YES, then it add the textField's placeholder text on IQToolbar. Default is YES.
*/
@objc public var shouldShowToolbarPlaceholder = true
/**
Placeholder Font. Default is nil.
*/
@objc public var placeholderFont: UIFont?
/**
Placeholder Color. Default is nil. Which means lightGray
*/
@objc public var placeholderColor: UIColor?
/**
Placeholder Button Color when it's treated as button. Default is nil. Which means iOS Blue for light toolbar and Yellow for dark toolbar
*/
@objc public var placeholderButtonColor: UIColor?
///--------------------------
/// MARK: UITextView handling
///--------------------------
/** used to adjust contentInset of UITextView. */
private var startingTextViewContentInsets = UIEdgeInsets()
/** used to adjust scrollIndicatorInsets of UITextView. */
private var startingTextViewScrollIndicatorInsets = UIEdgeInsets()
/** used with textView to detect a textFieldView contentInset is changed or not. (Bug ID: #92)*/
private var isTextViewContentInsetChanged = false
///---------------------------------------
/// MARK: UIKeyboard appearance overriding
///---------------------------------------
/**
Override the keyboardAppearance for all textField/textView. Default is NO.
*/
@objc public var overrideKeyboardAppearance = false
/**
If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property.
*/
@objc public var keyboardAppearance = UIKeyboardAppearance.default
///-----------------------------------------------------------
/// MARK: UITextField/UITextView Next/Previous/Resign handling
///-----------------------------------------------------------
/**
Resigns Keyboard on touching outside of UITextField/View. Default is NO.
*/
@objc public var shouldResignOnTouchOutside = false {
didSet {
resignFirstResponderGesture.isEnabled = privateShouldResignOnTouchOutside()
let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO"
showLog("shouldResignOnTouchOutside: \(shouldResign)")
}
}
/** TapGesture to resign keyboard on view's touch. It's a readonly property and exposed only for adding/removing dependencies if your added gesture does have collision with this one */
@objc lazy public var resignFirstResponderGesture: UITapGestureRecognizer = {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapRecognized(_:)))
tapGesture.cancelsTouchesInView = false
tapGesture.delegate = self
return tapGesture
}()
/*******************************************/
private func privateShouldResignOnTouchOutside() -> Bool {
var shouldResign = shouldResignOnTouchOutside
let enableMode = _textFieldView?.shouldResignOnTouchOutsideMode
if enableMode == .enabled {
shouldResign = true
} else if enableMode == .disabled {
shouldResign = false
} else {
if let textFieldViewController = _textFieldView?.viewContainingController() {
if shouldResign == false {
//If viewController is kind of enable viewController class, then assuming shouldResignOnTouchOutside is enabled.
for enabledClass in enabledTouchResignedClasses {
if textFieldViewController.isKind(of: enabledClass) {
shouldResign = true
break
}
}
}
if shouldResign == true {
//If viewController is kind of disable viewController class, then assuming shouldResignOnTouchOutside is disable.
for disabledClass in disabledTouchResignedClasses {
if textFieldViewController.isKind(of: disabledClass) {
shouldResign = false
break
}
}
//Special Controllers
if shouldResign == true {
let classNameString = NSStringFromClass(type(of: textFieldViewController.self))
//_UIAlertControllerTextFieldViewController
if classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController") {
shouldResign = false
}
}
}
}
}
return shouldResign
}
/**
Resigns currently first responder field.
*/
@objc @discardableResult public func resignFirstResponder() -> Bool {
if let textFieldRetain = _textFieldView {
//Resigning first responder
let isResignFirstResponder = textFieldRetain.resignFirstResponder()
// If it refuses then becoming it as first responder again. (Bug ID: #96)
if isResignFirstResponder == false {
//If it refuses to resign then becoming it first responder again for getting notifications callback.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to resign first responder: \(textFieldRetain)")
}
return isResignFirstResponder
}
return false
}
/**
Returns YES if can navigate to previous responder textField/textView, otherwise NO.
*/
@objc public var canGoPrevious: Bool {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
//Getting index of current textField.
if let index = textFields.firstIndex(of: textFieldRetain) {
//If it is not first textField. then it's previous object canBecomeFirstResponder.
if index > 0 {
return true
}
}
}
}
return false
}
/**
Returns YES if can navigate to next responder textField/textView, otherwise NO.
*/
@objc public var canGoNext: Bool {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
//Getting index of current textField.
if let index = textFields.firstIndex(of: textFieldRetain) {
//If it is not first textField. then it's previous object canBecomeFirstResponder.
if index < textFields.count-1 {
return true
}
}
}
}
return false
}
/**
Navigate to previous responder textField/textView.
*/
@objc @discardableResult public func goPrevious() -> Bool {
//Getting all responder view's.
if let textFieldRetain = _textFieldView {
if let textFields = responderViews() {
//Getting index of current textField.
if let index = textFields.firstIndex(of: textFieldRetain) {
//If it is not first textField. then it's previous object becomeFirstResponder.
if index > 0 {
let nextTextField = textFields[index-1]
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to become first responder: \(nextTextField)")
}
return isAcceptAsFirstResponder
}
}
}
}
return false
}
/**
Navigate to next responder textField/textView.
*/
@objc @discardableResult public func goNext() -> Bool {
//Getting all responder view's.
if let textFieldRetain = _textFieldView {
if let textFields = responderViews() {
//Getting index of current textField.
if let index = textFields.firstIndex(of: textFieldRetain) {
//If it is not last textField. then it's next object becomeFirstResponder.
if index < textFields.count-1 {
let nextTextField = textFields[index+1]
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to become first responder: \(nextTextField)")
}
return isAcceptAsFirstResponder
}
}
}
}
return false
}
/** previousAction. */
@objc internal func previousAction (_ barButton: IQBarButtonItem) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if canGoPrevious == true {
if let textFieldRetain = _textFieldView {
let isAcceptAsFirstResponder = goPrevious()
var invocation = barButton.invocation
var sender = textFieldRetain
//Handling search bar special case
do {
if let searchBar = textFieldRetain.textFieldSearchBar() {
invocation = searchBar.keyboardToolbar.previousBarButton.invocation
sender = searchBar
}
}
if isAcceptAsFirstResponder {
invocation?.invoke(from: sender)
}
}
}
}
/** nextAction. */
@objc internal func nextAction (_ barButton: IQBarButtonItem) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if canGoNext == true {
if let textFieldRetain = _textFieldView {
let isAcceptAsFirstResponder = goNext()
var invocation = barButton.invocation
var sender = textFieldRetain
//Handling search bar special case
do {
if let searchBar = textFieldRetain.textFieldSearchBar() {
invocation = searchBar.keyboardToolbar.nextBarButton.invocation
sender = searchBar
}
}
if isAcceptAsFirstResponder {
invocation?.invoke(from: sender)
}
}
}
}
/** doneAction. Resigning current textField. */
@objc internal func doneAction (_ barButton: IQBarButtonItem) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if let textFieldRetain = _textFieldView {
//Resign textFieldView.
let isResignedFirstResponder = resignFirstResponder()
var invocation = barButton.invocation
var sender = textFieldRetain
//Handling search bar special case
do {
if let searchBar = textFieldRetain.textFieldSearchBar() {
invocation = searchBar.keyboardToolbar.doneBarButton.invocation
sender = searchBar
}
}
if isResignedFirstResponder {
invocation?.invoke(from: sender)
}
}
}
/** Resigning on tap gesture. (Enhancement ID: #14)*/
@objc internal func tapRecognized(_ gesture: UITapGestureRecognizer) {
if gesture.state == .ended {
//Resigning currently responder textField.
resignFirstResponder()
}
}
/** Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */
@objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
/** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */
@objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
// Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145)
for ignoreClass in touchResignedGestureIgnoreClasses {
if touch.view?.isKind(of: ignoreClass) == true {
return false
}
}
return true
}
///-----------------------
/// MARK: UISound handling
///-----------------------
/**
If YES, then it plays inputClick sound on next/previous/done click.
*/
@objc public var shouldPlayInputClicks = true
///---------------------------
/// MARK: UIAnimation handling
///---------------------------
/**
If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view.
*/
@objc public var layoutIfNeededOnUpdate = false
///------------------------------------
/// MARK: Class Level disabling methods
///------------------------------------
/**
Disable distance handling within the scope of disabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController.
*/
@objc public var disabledDistanceHandlingClasses = [UIViewController.Type]()
/**
Enable distance handling within the scope of enabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledDistanceHandlingClasses list, then enabledDistanceHandlingClasses will be ignored.
*/
@objc public var enabledDistanceHandlingClasses = [UIViewController.Type]()
/**
Disable automatic toolbar creation within the scope of disabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController.
*/
@objc public var disabledToolbarClasses = [UIViewController.Type]()
/**
Enable automatic toolbar creation within the scope of enabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledToolbarClasses list, then enabledToolbarClasses will be ignore.
*/
@objc public var enabledToolbarClasses = [UIViewController.Type]()
/**
Allowed subclasses of UIView to add all inner textField, this will allow to navigate between textField contains in different superview. Class should be kind of UIView.
*/
@objc public var toolbarPreviousNextAllowedClasses = [UIView.Type]()
/**
Disabled classes to ignore 'shouldResignOnTouchOutside' property, Class should be kind of UIViewController.
*/
@objc public var disabledTouchResignedClasses = [UIViewController.Type]()
/**
Enabled classes to forcefully enable 'shouldResignOnTouchOutsite' property. Class should be kind of UIViewController. If same Class is added in disabledTouchResignedClasses list, then enabledTouchResignedClasses will be ignored.
*/
@objc public var enabledTouchResignedClasses = [UIViewController.Type]()
/**
if shouldResignOnTouchOutside is enabled then you can customise the behaviour to not recognise gesture touches on some specific view subclasses. Class should be kind of UIView. Default is [UIControl, UINavigationBar]
*/
@objc public var touchResignedGestureIgnoreClasses = [UIView.Type]()
///----------------------------------
/// MARK: Third Party Library support
/// Add TextField/TextView Notifications customised Notifications. For example while using YYTextView https://github.com/ibireme/YYText
///----------------------------------
/**
Add/Remove customised Notification for third party customised TextField/TextView. Please be aware that the Notification object must be idential to UITextField/UITextView Notification objects and customised TextField/TextView support must be idential to UITextField/UITextView.
@param didBeginEditingNotificationName This should be identical to UITextViewTextDidBeginEditingNotification
@param didEndEditingNotificationName This should be identical to UITextViewTextDidEndEditingNotification
*/
@objc public func registerTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName: String, didEndEditingNotificationName: String) {
registeredClasses.append(aClass)
NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidBeginEditing(_:)), name: Notification.Name(rawValue: didBeginEditingNotificationName), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidEndEditing(_:)), name: Notification.Name(rawValue: didEndEditingNotificationName), object: nil)
}
@objc public func unregisterTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName: String, didEndEditingNotificationName: String) {
if let index = registeredClasses.firstIndex(where: { element in
return element == aClass.self
}) {
registeredClasses.remove(at: index)
}
NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: didBeginEditingNotificationName), object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: didEndEditingNotificationName), object: nil)
}
/**************************************************************************************/
///------------------------
/// MARK: Private variables
///------------------------
/*******************************************/
/** To save UITextField/UITextView object voa textField/textView notifications. */
private weak var _textFieldView: UIView?
/** To save rootViewController.view.frame.origin. */
private var _topViewBeginOrigin = IQKeyboardManager.kIQCGPointInvalid
/** To overcome with popGestureRecognizer issue Bug ID: #1361 */
private weak var _rootViewControllerWhilePopGestureRecognizerActive: UIViewController?
private var _topViewBeginOriginWhilePopGestureRecognizerActive = IQKeyboardManager.kIQCGPointInvalid
/** To save rootViewController */
private weak var _rootViewController: UIViewController?
/*******************************************/
/** Variable to save lastScrollView that was scrolled. */
private weak var _lastScrollView: UIScrollView?
/** LastScrollView's initial contentOffset. */
private var _startingContentOffset = CGPoint.zero
/** LastScrollView's initial scrollIndicatorInsets. */
private var _startingScrollIndicatorInsets = UIEdgeInsets()
/** LastScrollView's initial contentInsets. */
private var _startingContentInsets = UIEdgeInsets()
/*******************************************/
/** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */
private var _kbShowNotification: Notification?
/** To save keyboard rame. */
private var _kbFrame = CGRect.zero
/** To save keyboard animation duration. */
private var _animationDuration: TimeInterval = 0.25
/** To mimic the keyboard animation */
#if swift(>=4.2)
private var _animationCurve: UIView.AnimationOptions = .curveEaseOut
#else
private var _animationCurve: UIViewAnimationOptions = .curveEaseOut
#endif
/*******************************************/
/** Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */
private var _privateIsKeyboardShowing = false
private var _privateMovedDistance: CGFloat = 0.0
/** To use with keyboardDistanceFromTextField. */
private var _privateKeyboardDistanceFromTextField: CGFloat = 10.0
/** To know if we have any pending request to adjust view position. */
private var _privateHasPendingAdjustRequest = false
/**************************************************************************************/
///--------------------------------------
/// MARK: Initialization/Deinitialization
///--------------------------------------
/* Singleton Object Initialization. */
override init() {
super.init()
self.registerAllNotifications()
//Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14)
resignFirstResponderGesture.isEnabled = shouldResignOnTouchOutside
//Loading IQToolbar, IQTitleBarButtonItem, IQBarButtonItem to fix first time keyboard appearance delay (Bug ID: #550)
//If you experience exception breakpoint issue at below line then try these solutions https://stackoverflow.com/questions/27375640/all-exception-break-point-is-stopping-for-no-reason-on-simulator
let textField = UITextField()
textField.addDoneOnKeyboardWithTarget(nil, action: #selector(self.doneAction(_:)))
textField.addPreviousNextDoneOnKeyboardWithTarget(nil, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)))
disabledDistanceHandlingClasses.append(UITableViewController.self)
disabledDistanceHandlingClasses.append(UIAlertController.self)
disabledToolbarClasses.append(UIAlertController.self)
disabledTouchResignedClasses.append(UIAlertController.self)
toolbarPreviousNextAllowedClasses.append(UITableView.self)
toolbarPreviousNextAllowedClasses.append(UICollectionView.self)
toolbarPreviousNextAllowedClasses.append(IQPreviousNextView.self)
touchResignedGestureIgnoreClasses.append(UIControl.self)
touchResignedGestureIgnoreClasses.append(UINavigationBar.self)
}
/** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */
/** It doesn't work from Swift 1.2 */
// override public class func load() {
// super.load()
//
// //Enabling IQKeyboardManager.
// IQKeyboardManager.shared.enable = true
// }
deinit {
// Disable the keyboard manager.
enable = false
//Removing notification observers on dealloc.
NotificationCenter.default.removeObserver(self)
}
/** Getting keyWindow. */
private func keyWindow() -> UIWindow? {
if let keyWindow = _textFieldView?.window {
return keyWindow
} else {
struct Static {
/** @abstract Save keyWindow object for reuse.
@discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */
static weak var keyWindow: UIWindow?
}
//If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow.
if let originalKeyWindow = UIApplication.shared.keyWindow,
(Static.keyWindow == nil || Static.keyWindow != originalKeyWindow) {
Static.keyWindow = originalKeyWindow
}
//Return KeyWindow
return Static.keyWindow
}
}
///-----------------------
/// MARK: Helper Functions
///-----------------------
private func optimizedAdjustPosition() {
if _privateHasPendingAdjustRequest == false {
_privateHasPendingAdjustRequest = true
OperationQueue.main.addOperation {
self.adjustPosition()
self._privateHasPendingAdjustRequest = false
}
}
}
/* Adjusting RootViewController's frame according to interface orientation. */
private func adjustPosition() {
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
if _privateHasPendingAdjustRequest == true,
let textFieldView = _textFieldView,
let rootController = textFieldView.parentContainerViewController(),
let window = keyWindow(),
let textFieldViewRectInWindow = textFieldView.superview?.convert(textFieldView.frame, to: window),
let textFieldViewRectInRootSuperview = textFieldView.superview?.convert(textFieldView.frame, to: rootController.view?.superview) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
// Getting RootViewOrigin.
var rootViewOrigin = rootController.view.frame.origin
//Maintain keyboardDistanceFromTextField
var specialKeyboardDistanceFromTextField = textFieldView.keyboardDistanceFromTextField
if let searchBar = textFieldView.textFieldSearchBar() {
specialKeyboardDistanceFromTextField = searchBar.keyboardDistanceFromTextField
}
let newKeyboardDistanceFromTextField = (specialKeyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance) ? keyboardDistanceFromTextField : specialKeyboardDistanceFromTextField
var kbSize = _kbFrame.size
do {
var kbFrame = _kbFrame
kbFrame.origin.y -= newKeyboardDistanceFromTextField
kbFrame.size.height += newKeyboardDistanceFromTextField
//Calculating actual keyboard covered size respect to window, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381) (Bug ID: #1506)
let intersectRect = kbFrame.intersection(window.frame)
if intersectRect.isNull {
kbSize = CGSize(width: kbFrame.size.width, height: 0)
} else {
kbSize = intersectRect.size
}
}
let statusBarHeight : CGFloat
#if swift(>=5.1)
if #available(iOS 13, *) {
statusBarHeight = window.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
} else {
statusBarHeight = UIApplication.shared.statusBarFrame.height
}
#else
statusBarHeight = UIApplication.shared.statusBarFrame.height
#endif
let navigationBarAreaHeight: CGFloat = statusBarHeight + ( rootController.navigationController?.navigationBar.frame.height ?? 0)
let layoutAreaHeight: CGFloat = rootController.view.layoutMargins.bottom
let topLayoutGuide: CGFloat = max(navigationBarAreaHeight, layoutAreaHeight) + 5
let bottomLayoutGuide: CGFloat = (textFieldView is UITextView) ? 0 : rootController.view.layoutMargins.bottom //Validation of textView for case where there is a tab bar at the bottom or running on iPhone X and textView is at the bottom.
// Move positive = textField is hidden.
// Move negative = textField is showing.
// Calculating move position.
var move: CGFloat = min(textFieldViewRectInRootSuperview.minY-(topLayoutGuide), textFieldViewRectInWindow.maxY-(window.frame.height-kbSize.height)+bottomLayoutGuide)
showLog("Need to move: \(move)")
var superScrollView: UIScrollView?
var superView = textFieldView.superviewOfClassType(UIScrollView.self) as? UIScrollView
//Getting UIScrollView whose scrolling is enabled. // (Bug ID: #285)
while let view = superView {
if view.isScrollEnabled && view.shouldIgnoreScrollingAdjustment == false {
superScrollView = view
break
} else {
// Getting it's superScrollView. // (Enhancement ID: #21, #24)
superView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}
//If there was a lastScrollView. // (Bug ID: #34)
if let lastScrollView = _lastScrollView {
//If we can't find current superScrollView, then setting lastScrollView to it's original form.
if superScrollView == nil {
if lastScrollView.contentInset != self._startingContentInsets {
showLog("Restoring contentInset to: \(_startingContentInsets)")
UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
})
}
if lastScrollView.shouldRestoreScrollViewContentOffset == true && lastScrollView.contentOffset.equalTo(_startingContentOffset) == false {
showLog("Restoring contentOffset to: \(_startingContentOffset)")
var animatedContentOffset = false // (Bug ID: #1365, #1508, #1541)
if #available(iOS 9, *) {
animatedContentOffset = textFieldView.superviewOfClassType(UIStackView.self, belowView: lastScrollView) != nil
}
if animatedContentOffset {
lastScrollView.setContentOffset(_startingContentOffset, animated: UIView.areAnimationsEnabled)
} else {
lastScrollView.contentOffset = _startingContentOffset
}
}
_startingContentInsets = UIEdgeInsets()
_startingScrollIndicatorInsets = UIEdgeInsets()
_startingContentOffset = CGPoint.zero
_lastScrollView = nil
} else if superScrollView != lastScrollView { //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView.
if lastScrollView.contentInset != self._startingContentInsets {
showLog("Restoring contentInset to: \(_startingContentInsets)")
UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
})
}
if lastScrollView.shouldRestoreScrollViewContentOffset == true && lastScrollView.contentOffset.equalTo(_startingContentOffset) == false {
showLog("Restoring contentOffset to: \(_startingContentOffset)")
var animatedContentOffset = false // (Bug ID: #1365, #1508, #1541)
if #available(iOS 9, *) {
animatedContentOffset = textFieldView.superviewOfClassType(UIStackView.self, belowView: lastScrollView) != nil
}
if animatedContentOffset {
lastScrollView.setContentOffset(_startingContentOffset, animated: UIView.areAnimationsEnabled)
} else {
lastScrollView.contentOffset = _startingContentOffset
}
}
_lastScrollView = superScrollView
if let scrollView = superScrollView {
_startingContentInsets = scrollView.contentInset
_startingContentOffset = scrollView.contentOffset
#if swift(>=5.1)
if #available(iOS 11.1, *) {
_startingScrollIndicatorInsets = scrollView.verticalScrollIndicatorInsets
} else {
_startingScrollIndicatorInsets = scrollView.scrollIndicatorInsets
}
#else
_startingScrollIndicatorInsets = scrollView.scrollIndicatorInsets
#endif
}
showLog("Saving ScrollView New contentInset: \(_startingContentInsets) and contentOffset: \(_startingContentOffset)")
}
//Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead
} else if let unwrappedSuperScrollView = superScrollView { //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView.
_lastScrollView = unwrappedSuperScrollView
_startingContentInsets = unwrappedSuperScrollView.contentInset
_startingContentOffset = unwrappedSuperScrollView.contentOffset
#if swift(>=5.1)
if #available(iOS 11.1, *) {
_startingScrollIndicatorInsets = unwrappedSuperScrollView.verticalScrollIndicatorInsets
} else {
_startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets
}
#else
_startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets
#endif
showLog("Saving ScrollView contentInset: \(_startingContentInsets) and contentOffset: \(_startingContentOffset)")
}
// Special case for ScrollView.
// If we found lastScrollView then setting it's contentOffset to show textField.
if let lastScrollView = _lastScrollView {
//Saving
var lastView = textFieldView
var superScrollView = _lastScrollView
while let scrollView = superScrollView {
var shouldContinue = false
if move > 0 {
shouldContinue = move > (-scrollView.contentOffset.y - scrollView.contentInset.top)
} else if let tableView = scrollView.superviewOfClassType(UITableView.self) as? UITableView {
shouldContinue = scrollView.contentOffset.y > 0
if shouldContinue == true, let tableCell = textFieldView.superviewOfClassType(UITableViewCell.self) as? UITableViewCell, let indexPath = tableView.indexPath(for: tableCell), let previousIndexPath = tableView.previousIndexPath(of: indexPath) {
let previousCellRect = tableView.rectForRow(at: previousIndexPath)
if previousCellRect.isEmpty == false {
let previousCellRectInRootSuperview = tableView.convert(previousCellRect, to: rootController.view.superview)
move = min(0, previousCellRectInRootSuperview.maxY - topLayoutGuide)
}
}
} else if let collectionView = scrollView.superviewOfClassType(UICollectionView.self) as? UICollectionView {
shouldContinue = scrollView.contentOffset.y > 0
if shouldContinue == true, let collectionCell = textFieldView.superviewOfClassType(UICollectionViewCell.self) as? UICollectionViewCell, let indexPath = collectionView.indexPath(for: collectionCell), let previousIndexPath = collectionView.previousIndexPath(of: indexPath), let attributes = collectionView.layoutAttributesForItem(at: previousIndexPath) {
let previousCellRect = attributes.frame
if previousCellRect.isEmpty == false {
let previousCellRectInRootSuperview = collectionView.convert(previousCellRect, to: rootController.view.superview)
move = min(0, previousCellRectInRootSuperview.maxY - topLayoutGuide)
}
}
} else {
shouldContinue = textFieldViewRectInRootSuperview.origin.y < topLayoutGuide
if shouldContinue {
move = min(0, textFieldViewRectInRootSuperview.origin.y - topLayoutGuide)
}
}
//Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object.
if shouldContinue {
var tempScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
var nextScrollView: UIScrollView?
while let view = tempScrollView {
if view.isScrollEnabled && view.shouldIgnoreScrollingAdjustment == false {
nextScrollView = view
break
} else {
tempScrollView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}
//Getting lastViewRect.
if let lastViewRect = lastView.superview?.convert(lastView.frame, to: scrollView) {
//Calculating the expected Y offset from move and scrollView's contentOffset.
var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y, -move)
//Rearranging the expected Y offset according to the view.
shouldOffsetY = min(shouldOffsetY, lastViewRect.origin.y)
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//nextScrollView == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierrchy.)
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//shouldOffsetY >= 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92)
if textFieldView is UITextView == true &&
nextScrollView == nil &&
shouldOffsetY >= 0 {
// Converting Rectangle according to window bounds.
if let currentTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: window) {
//Calculating expected fix distance which needs to be managed from navigation bar
let expectedFixDistance = currentTextFieldViewRect.minY - topLayoutGuide
//Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance)
shouldOffsetY = min(shouldOffsetY, scrollView.contentOffset.y + expectedFixDistance)
//Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic.
move = 0
} else {
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
} else {
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
let newContentOffset = CGPoint(x: scrollView.contentOffset.x, y: shouldOffsetY)
if scrollView.contentOffset.equalTo(newContentOffset) == false {
showLog("old contentOffset: \(scrollView.contentOffset) new contentOffset: \(newContentOffset)")
self.showLog("Remaining Move: \(move)")
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
var animatedContentOffset = false // (Bug ID: #1365, #1508, #1541)
if #available(iOS 9, *) {
animatedContentOffset = textFieldView.superviewOfClassType(UIStackView.self, belowView: scrollView) != nil
}
if animatedContentOffset {
scrollView.setContentOffset(newContentOffset, animated: UIView.areAnimationsEnabled)
} else {
scrollView.contentOffset = newContentOffset
}
}) { _ in
if scrollView is UITableView || scrollView is UICollectionView {
//This will update the next/previous states
self.addToolbarIfRequired()
}
}
}
}
// Getting next lastView & superScrollView.
lastView = scrollView
superScrollView = nextScrollView
} else {
move = 0
break
}
}
//Updating contentInset
if let lastScrollViewRect = lastScrollView.superview?.convert(lastScrollView.frame, to: window) {
let bottom: CGFloat = (kbSize.height-newKeyboardDistanceFromTextField)-(window.frame.height-lastScrollViewRect.maxY)
// Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view.
var movedInsets = lastScrollView.contentInset
movedInsets.bottom = max(_startingContentInsets.bottom, bottom)
if lastScrollView.contentInset != movedInsets {
showLog("old ContentInset: \(lastScrollView.contentInset) new ContentInset: \(movedInsets)")
UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
lastScrollView.contentInset = movedInsets
var newInset : UIEdgeInsets
#if swift(>=5.1)
if #available(iOS 11.1, *) {
newInset = lastScrollView.verticalScrollIndicatorInsets
} else {
newInset = lastScrollView.scrollIndicatorInsets
}
#else
newInset = lastScrollView.scrollIndicatorInsets
#endif
newInset.bottom = movedInsets.bottom
lastScrollView.scrollIndicatorInsets = newInset
})
}
}
}
//Going ahead. No else if.
//Special case for UITextView(Readjusting textView.contentInset when textView hight is too big to fit on screen)
//_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView.
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
if let textView = textFieldView as? UITextView {
// CGRect rootSuperViewFrameInWindow = [_rootViewController.view.superview convertRect:_rootViewController.view.superview.bounds toView:keyWindow];
//
// CGFloat keyboardOverlapping = CGRectGetMaxY(rootSuperViewFrameInWindow) - keyboardYPosition;
//
// CGFloat textViewHeight = MIN(CGRectGetHeight(_textFieldView.frame), (CGRectGetHeight(rootSuperViewFrameInWindow)-topLayoutGuide-keyboardOverlapping));
let keyboardYPosition = window.frame.height - (kbSize.height-newKeyboardDistanceFromTextField)
var rootSuperViewFrameInWindow = window.frame
if let rootSuperview = rootController.view.superview {
rootSuperViewFrameInWindow = rootSuperview.convert(rootSuperview.bounds, to: window)
}
let keyboardOverlapping = rootSuperViewFrameInWindow.maxY - keyboardYPosition
let textViewHeight = min(textView.frame.height, rootSuperViewFrameInWindow.height-topLayoutGuide-keyboardOverlapping)
if textView.frame.size.height-textView.contentInset.bottom>textViewHeight {
//_isTextViewContentInsetChanged, If frame is not change by library in past, then saving user textView properties (Bug ID: #92)
if self.isTextViewContentInsetChanged == false {
self.startingTextViewContentInsets = textView.contentInset
#if swift(>=5.1)
if #available(iOS 11.1, *) {
self.startingTextViewScrollIndicatorInsets = textView.verticalScrollIndicatorInsets
} else {
self.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets
}
#else
self.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets
#endif
}
self.isTextViewContentInsetChanged = true
var newContentInset = textView.contentInset
newContentInset.bottom = textView.frame.size.height-textViewHeight
if textView.contentInset != newContentInset {
self.showLog("\(textFieldView) Old UITextView.contentInset: \(textView.contentInset) New UITextView.contentInset: \(newContentInset)")
UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
textView.contentInset = newContentInset
textView.scrollIndicatorInsets = newContentInset
}, completion: { (_) -> Void in })
}
}
}
// +Positive or zero.
if move >= 0 {
rootViewOrigin.y = max(rootViewOrigin.y - move, min(0, -(kbSize.height-newKeyboardDistanceFromTextField)))
if rootController.view.frame.origin.equalTo(rootViewOrigin) == false {
showLog("Moving Upward")
UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
var rect = rootController.view.frame
rect.origin = rootViewOrigin
rootController.view.frame = rect
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
rootController.view.setNeedsLayout()
rootController.view.layoutIfNeeded()
}
self.showLog("Set \(rootController) origin to: \(rootViewOrigin)")
})
}
_privateMovedDistance = (_topViewBeginOrigin.y-rootViewOrigin.y)
} else { // -Negative
let disturbDistance: CGFloat = rootViewOrigin.y-_topViewBeginOrigin.y
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance <= 0 {
rootViewOrigin.y -= max(move, disturbDistance)
if rootController.view.frame.origin.equalTo(rootViewOrigin) == false {
showLog("Moving Downward")
// Setting adjusted rootViewRect
// Setting adjusted rootViewRect
UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
var rect = rootController.view.frame
rect.origin = rootViewOrigin
rootController.view.frame = rect
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
rootController.view.setNeedsLayout()
rootController.view.layoutIfNeeded()
}
self.showLog("Set \(rootController) origin to: \(rootViewOrigin)")
})
}
_privateMovedDistance = (_topViewBeginOrigin.y-rootViewOrigin.y)
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
}
private func restorePosition() {
_privateHasPendingAdjustRequest = false
// Setting rootViewController frame to it's original position. // (Bug ID: #18)
if _topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) == false {
if let rootViewController = _rootViewController {
if rootViewController.view.frame.origin.equalTo(self._topViewBeginOrigin) == false {
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
self.showLog("Restoring \(rootViewController) origin to: \(self._topViewBeginOrigin)")
// Setting it's new frame
var rect = rootViewController.view.frame
rect.origin = self._topViewBeginOrigin
rootViewController.view.frame = rect
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}
})
}
self._privateMovedDistance = 0
if rootViewController.navigationController?.interactivePopGestureRecognizer?.state == .began {
self._rootViewControllerWhilePopGestureRecognizerActive = rootViewController
self._topViewBeginOriginWhilePopGestureRecognizerActive = self._topViewBeginOrigin
}
_rootViewController = nil
}
}
}
///---------------------
/// MARK: Public Methods
///---------------------
/* Refreshes textField/textView position if any external changes is explicitly made by user. */
@objc public func reloadLayoutIfNeeded() {
if privateIsEnabled() == true {
if _privateIsKeyboardShowing == true,
_topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) == false,
let textFieldView = _textFieldView,
textFieldView.isAlertViewTextField() == false {
optimizedAdjustPosition()
}
}
}
///-------------------------------
/// MARK: UIKeyboard Notifications
///-------------------------------
/* UIKeyboardWillShowNotification. */
@objc internal func keyboardWillShow(_ notification: Notification?) {
_kbShowNotification = notification
// Boolean to know keyboard is showing/hiding
_privateIsKeyboardShowing = true
let oldKBFrame = _kbFrame
if let info = notification?.userInfo {
#if swift(>=4.2)
let curveUserInfoKey = UIResponder.keyboardAnimationCurveUserInfoKey
let durationUserInfoKey = UIResponder.keyboardAnimationDurationUserInfoKey
let frameEndUserInfoKey = UIResponder.keyboardFrameEndUserInfoKey
#else
let curveUserInfoKey = UIKeyboardAnimationCurveUserInfoKey
let durationUserInfoKey = UIKeyboardAnimationDurationUserInfoKey
let frameEndUserInfoKey = UIKeyboardFrameEndUserInfoKey
#endif
// Getting keyboard animation.
if let curve = info[curveUserInfoKey] as? UInt {
_animationCurve = .init(rawValue: curve)
} else {
_animationCurve = .curveEaseOut
}
// Getting keyboard animation duration
if let duration = info[durationUserInfoKey] as? TimeInterval {
//Saving animation duration
if duration != 0.0 {
_animationDuration = duration
}
} else {
_animationDuration = 0.25
}
// Getting UIKeyboardSize.
if let kbFrame = info[frameEndUserInfoKey] as? CGRect {
_kbFrame = kbFrame
showLog("UIKeyboard Frame: \(_kbFrame)")
}
}
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
// (Bug ID: #5)
if let textFieldView = _textFieldView, _topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) == true {
// keyboard is not showing(At the beginning only). We should save rootViewRect.
_rootViewController = textFieldView.parentContainerViewController()
if let controller = _rootViewController {
if _rootViewControllerWhilePopGestureRecognizerActive == controller {
_topViewBeginOrigin = _topViewBeginOriginWhilePopGestureRecognizerActive
} else {
_topViewBeginOrigin = controller.view.frame.origin
}
_rootViewControllerWhilePopGestureRecognizerActive = nil
_topViewBeginOriginWhilePopGestureRecognizerActive = IQKeyboardManager.kIQCGPointInvalid
self.showLog("Saving \(controller) beginning origin: \(self._topViewBeginOrigin)")
}
}
//If last restored keyboard size is different(any orientation accure), then refresh. otherwise not.
if _kbFrame.equalTo(oldKBFrame) == false {
//If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true,
let textFieldView = _textFieldView,
textFieldView.isAlertViewTextField() == false {
// keyboard is already showing. adjust position.
optimizedAdjustPosition()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
/* UIKeyboardDidShowNotification. */
@objc internal func keyboardDidShow(_ notification: Notification?) {
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
if let textFieldView = _textFieldView,
let parentController = textFieldView.parentContainerViewController(), (parentController.modalPresentationStyle == UIModalPresentationStyle.formSheet || parentController.modalPresentationStyle == UIModalPresentationStyle.pageSheet),
textFieldView.isAlertViewTextField() == false {
self.optimizedAdjustPosition()
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
/* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */
@objc internal func keyboardWillHide(_ notification: Notification?) {
//If it's not a fake notification generated by [self setEnable:NO].
if notification != nil {
_kbShowNotification = nil
}
// Boolean to know keyboard is showing/hiding
_privateIsKeyboardShowing = false
if let info = notification?.userInfo {
#if swift(>=4.2)
let durationUserInfoKey = UIResponder.keyboardAnimationDurationUserInfoKey
#else
let durationUserInfoKey = UIKeyboardAnimationDurationUserInfoKey
#endif
// Getting keyboard animation duration
if let duration = info[durationUserInfoKey] as? TimeInterval {
if duration != 0 {
// Setitng keyboard animation duration
_animationDuration = duration
}
}
}
//If not enabled then do nothing.
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
//Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56)
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
// if (_textFieldView == nil) return
//Restoring the contentOffset of the lastScrollView
if let lastScrollView = _lastScrollView {
UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
if lastScrollView.contentInset != self._startingContentInsets {
self.showLog("Restoring contentInset to: \(self._startingContentInsets)")
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
}
if lastScrollView.shouldRestoreScrollViewContentOffset == true && lastScrollView.contentOffset.equalTo(self._startingContentOffset) == false {
self.showLog("Restoring contentOffset to: \(self._startingContentOffset)")
var animatedContentOffset = false // (Bug ID: #1365, #1508, #1541)
if #available(iOS 9, *) {
animatedContentOffset = self._textFieldView?.superviewOfClassType(UIStackView.self, belowView: lastScrollView) != nil
}
if animatedContentOffset {
lastScrollView.setContentOffset(self._startingContentOffset, animated: UIView.areAnimationsEnabled)
} else {
lastScrollView.contentOffset = self._startingContentOffset
}
}
// TODO: restore scrollView state
// This is temporary solution. Have to implement the save and restore scrollView state
var superScrollView: UIScrollView? = lastScrollView
while let scrollView = superScrollView {
let contentSize = CGSize(width: max(scrollView.contentSize.width, scrollView.frame.width), height: max(scrollView.contentSize.height, scrollView.frame.height))
let minimumY = contentSize.height - scrollView.frame.height
if minimumY < scrollView.contentOffset.y {
let newContentOffset = CGPoint(x: scrollView.contentOffset.x, y: minimumY)
if scrollView.contentOffset.equalTo(newContentOffset) == false {
var animatedContentOffset = false // (Bug ID: #1365, #1508, #1541)
if #available(iOS 9, *) {
animatedContentOffset = self._textFieldView?.superviewOfClassType(UIStackView.self, belowView: scrollView) != nil
}
if animatedContentOffset {
scrollView.setContentOffset(newContentOffset, animated: UIView.areAnimationsEnabled)
} else {
scrollView.contentOffset = newContentOffset
}
self.showLog("Restoring contentOffset to: \(self._startingContentOffset)")
}
}
superScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
})
}
restorePosition()
//Reset all values
_lastScrollView = nil
_kbFrame = CGRect.zero
_startingContentInsets = UIEdgeInsets()
_startingScrollIndicatorInsets = UIEdgeInsets()
_startingContentOffset = CGPoint.zero
// topViewBeginRect = CGRectZero //Commented due to #82
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
@objc internal func keyboardDidHide(_ notification: Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
_topViewBeginOrigin = IQKeyboardManager.kIQCGPointInvalid
_kbFrame = CGRect.zero
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
///-------------------------------------------
/// MARK: UITextField/UITextView Notifications
///-------------------------------------------
/** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
@objc internal func textFieldViewDidBeginEditing(_ notification: Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
// Getting object
_textFieldView = notification.object as? UIView
if overrideKeyboardAppearance == true {
if let textFieldView = _textFieldView as? UITextField {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
} else if let textFieldView = _textFieldView as? UITextView {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
}
}
//If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
if privateIsEnableAutoToolbar() == true {
//UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it.
if let textView = _textFieldView as? UITextView,
textView.inputAccessoryView == nil {
UIView.animate(withDuration: 0.00001, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
self.addToolbarIfRequired()
}, completion: { (_) -> Void in
//On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews.
textView.reloadInputViews()
})
} else {
//Adding toolbar
addToolbarIfRequired()
}
} else {
removeToolbarIfRequired()
}
resignFirstResponderGesture.isEnabled = privateShouldResignOnTouchOutside()
_textFieldView?.window?.addGestureRecognizer(resignFirstResponderGesture) // (Enhancement ID: #14)
if privateIsEnabled() == true {
if _topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) == true { // (Bug ID: #5)
_rootViewController = _textFieldView?.parentContainerViewController()
if let controller = _rootViewController {
if _rootViewControllerWhilePopGestureRecognizerActive == controller {
_topViewBeginOrigin = _topViewBeginOriginWhilePopGestureRecognizerActive
} else {
_topViewBeginOrigin = controller.view.frame.origin
}
_rootViewControllerWhilePopGestureRecognizerActive = nil
_topViewBeginOriginWhilePopGestureRecognizerActive = IQKeyboardManager.kIQCGPointInvalid
self.showLog("Saving \(controller) beginning origin: \(self._topViewBeginOrigin)")
}
}
//If _textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76)
//See notes:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true,
let textFieldView = _textFieldView,
textFieldView.isAlertViewTextField() == false {
// keyboard is already showing. adjust position.
optimizedAdjustPosition()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
/** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
@objc internal func textFieldViewDidEndEditing(_ notification: Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
//Removing gesture recognizer (Enhancement ID: #14)
_textFieldView?.window?.removeGestureRecognizer(resignFirstResponderGesture)
// We check if there's a change in original frame or not.
if let textView = _textFieldView as? UITextView {
if isTextViewContentInsetChanged == true {
self.isTextViewContentInsetChanged = false
if textView.contentInset != self.startingTextViewContentInsets {
self.showLog("Restoring textView.contentInset to: \(self.startingTextViewContentInsets)")
UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
//Setting textField to it's initial contentInset
textView.contentInset = self.startingTextViewContentInsets
textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
}, completion: { (_) -> Void in })
}
}
}
//Setting object to nil
_textFieldView = nil
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
///---------------------------------------
/// MARK: UIStatusBar Notification methods
///---------------------------------------
/** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/
@objc internal func willChangeStatusBarOrientation(_ notification: Notification) {
let currentStatusBarOrientation : UIInterfaceOrientation
#if swift(>=5.1)
if #available(iOS 13, *) {
currentStatusBarOrientation = keyWindow()?.windowScene?.interfaceOrientation ?? UIInterfaceOrientation.unknown
} else {
currentStatusBarOrientation = UIApplication.shared.statusBarOrientation
}
#else
currentStatusBarOrientation = UIApplication.shared.statusBarOrientation
#endif
guard let statusBarOrientation = notification.userInfo?[UIApplication.statusBarOrientationUserInfoKey] as? Int, currentStatusBarOrientation.rawValue != statusBarOrientation else {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
//If textViewContentInsetChanged is saved then restore it.
if let textView = _textFieldView as? UITextView {
if isTextViewContentInsetChanged == true {
self.isTextViewContentInsetChanged = false
if textView.contentInset != self.startingTextViewContentInsets {
UIView.animate(withDuration: _animationDuration, delay: 0, options: _animationCurve.union(.beginFromCurrentState), animations: { () -> Void in
self.showLog("Restoring textView.contentInset to: \(self.startingTextViewContentInsets)")
//Setting textField to it's initial contentInset
textView.contentInset = self.startingTextViewContentInsets
textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
}, completion: { (_) -> Void in })
}
}
}
restorePosition()
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
///------------------
/// MARK: AutoToolbar
///------------------
/** Get all UITextField/UITextView siblings of textFieldView. */
private func responderViews() -> [UIView]? {
var superConsideredView: UIView?
//If find any consider responderView in it's upper hierarchy then will get deepResponderView.
for disabledClass in toolbarPreviousNextAllowedClasses {
superConsideredView = _textFieldView?.superviewOfClassType(disabledClass)
if superConsideredView != nil {
break
}
}
//If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position. (Enhancement ID: #22)
if let view = superConsideredView {
return view.deepResponderViews()
} else { //Otherwise fetching all the siblings
if let textFields = _textFieldView?.responderSiblings() {
//Sorting textFields according to behaviour
switch toolbarManageBehaviour {
//If autoToolbar behaviour is bySubviews, then returning it.
case IQAutoToolbarManageBehaviour.bySubviews: return textFields
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.byTag: return textFields.sortedArrayByTag()
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.byPosition: return textFields.sortedArrayByPosition()
}
} else {
return nil
}
}
}
/** Add toolbar if it is required to add on textFields and it's siblings. */
private func addToolbarIfRequired() {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
// Getting all the sibling textFields.
if let siblings = responderViews(), !siblings.isEmpty {
showLog("Found \(siblings.count) responder sibling(s)")
if let textField = _textFieldView {
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar).
//setInputAccessoryView: check (Bug ID: #307)
if textField.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
if textField.inputAccessoryView == nil ||
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag ||
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
let rightConfiguration: IQBarButtonItemConfiguration
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
rightConfiguration = IQBarButtonItemConfiguration(image: doneBarButtonItemImage, action: #selector(self.doneAction(_:)))
} else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
rightConfiguration = IQBarButtonItemConfiguration(title: doneBarButtonItemText, action: #selector(self.doneAction(_:)))
} else {
rightConfiguration = IQBarButtonItemConfiguration(barButtonSystemItem: .done, action: #selector(self.doneAction(_:)))
}
// If only one object is found, then adding only Done button.
if (siblings.count == 1 && previousNextDisplayMode == .default) || previousNextDisplayMode == .alwaysHide {
textField.addKeyboardToolbarWithTarget(target: self, titleText: (shouldShowToolbarPlaceholder ? textField.drawingToolbarPlaceholder: nil), rightBarButtonConfiguration: rightConfiguration, previousBarButtonConfiguration: nil, nextBarButtonConfiguration: nil)
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78)
} else if (siblings.count > 1 && previousNextDisplayMode == .default) || previousNextDisplayMode == .alwaysShow {
let prevConfiguration: IQBarButtonItemConfiguration
if let doneBarButtonItemImage = toolbarPreviousBarButtonItemImage {
prevConfiguration = IQBarButtonItemConfiguration(image: doneBarButtonItemImage, action: #selector(self.previousAction(_:)))
} else if let doneBarButtonItemText = toolbarPreviousBarButtonItemText {
prevConfiguration = IQBarButtonItemConfiguration(title: doneBarButtonItemText, action: #selector(self.previousAction(_:)))
} else {
prevConfiguration = IQBarButtonItemConfiguration(image: (UIImage.keyboardPreviousImage() ?? UIImage()), action: #selector(self.previousAction(_:)))
}
let nextConfiguration: IQBarButtonItemConfiguration
if let doneBarButtonItemImage = toolbarNextBarButtonItemImage {
nextConfiguration = IQBarButtonItemConfiguration(image: doneBarButtonItemImage, action: #selector(self.nextAction(_:)))
} else if let doneBarButtonItemText = toolbarNextBarButtonItemText {
nextConfiguration = IQBarButtonItemConfiguration(title: doneBarButtonItemText, action: #selector(self.nextAction(_:)))
} else {
nextConfiguration = IQBarButtonItemConfiguration(image: (UIImage.keyboardNextImage() ?? UIImage()), action: #selector(self.nextAction(_:)))
}
textField.addKeyboardToolbarWithTarget(target: self, titleText: (shouldShowToolbarPlaceholder ? textField.drawingToolbarPlaceholder: nil), rightBarButtonConfiguration: rightConfiguration, previousBarButtonConfiguration: prevConfiguration, nextBarButtonConfiguration: nextConfiguration)
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQPreviousNextButtonToolbarTag // (Bug ID: #78)
}
let toolbar = textField.keyboardToolbar
// Setting toolbar to keyboard.
if let textField = textField as? UITextField {
//Bar style according to keyboard appearance
switch textField.keyboardAppearance {
case .dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
toolbar.barTintColor = nil
default:
toolbar.barStyle = UIBarStyle.default
toolbar.barTintColor = toolbarBarTintColor
//Setting toolbar tintColor // (Enhancement ID: #30)
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = textField.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
} else if let textView = textField as? UITextView {
//Bar style according to keyboard appearance
switch textView.keyboardAppearance {
case .dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
toolbar.barTintColor = nil
default:
toolbar.barStyle = UIBarStyle.default
toolbar.barTintColor = toolbarBarTintColor
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = textView.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowToolbarPlaceholder == true &&
textField.shouldHideToolbarPlaceholder == false {
//Updating placeholder font to toolbar. //(Bug ID: #148, #272)
if toolbar.titleBarButton.title == nil ||
toolbar.titleBarButton.title != textField.drawingToolbarPlaceholder {
toolbar.titleBarButton.title = textField.drawingToolbarPlaceholder
}
//Setting toolbar title font. // (Enhancement ID: #30)
if let font = placeholderFont {
toolbar.titleBarButton.titleFont = font
}
//Setting toolbar title color. // (Enhancement ID: #880)
if let color = placeholderColor {
toolbar.titleBarButton.titleColor = color
}
//Setting toolbar button title color. // (Enhancement ID: #880)
if let color = placeholderButtonColor {
toolbar.titleBarButton.selectableTitleColor = color
}
} else {
toolbar.titleBarButton.title = nil
}
//In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56)
// If firstTextField, then previous should not be enabled.
if siblings.first == textField {
if siblings.count == 1 {
textField.keyboardToolbar.previousBarButton.isEnabled = false
textField.keyboardToolbar.nextBarButton.isEnabled = false
} else {
textField.keyboardToolbar.previousBarButton.isEnabled = false
textField.keyboardToolbar.nextBarButton.isEnabled = true
}
} else if siblings.last == textField { // If lastTextField then next should not be enaled.
textField.keyboardToolbar.previousBarButton.isEnabled = true
textField.keyboardToolbar.nextBarButton.isEnabled = false
} else {
textField.keyboardToolbar.previousBarButton.isEnabled = true
textField.keyboardToolbar.nextBarButton.isEnabled = true
}
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
/** Remove any toolbar if it is IQToolbar. */
private func removeToolbarIfRequired() { // (Bug ID: #18)
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
// Getting all the sibling textFields.
if let siblings = responderViews() {
showLog("Found \(siblings.count) responder sibling(s)")
for view in siblings {
if let toolbar = view.inputAccessoryView as? IQToolbar {
//setInputAccessoryView: check (Bug ID: #307)
if view.responds(to: #selector(setter: UITextField.inputAccessoryView)) &&
(toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag || toolbar.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) {
if let textField = view as? UITextField {
textField.inputAccessoryView = nil
textField.reloadInputViews()
} else if let textView = view as? UITextView {
textView.inputAccessoryView = nil
textView.reloadInputViews()
}
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
/** reloadInputViews to reload toolbar buttons enable/disable state on the fly Enhancement ID #434. */
@objc public func reloadInputViews() {
//If enabled then adding toolbar.
if privateIsEnableAutoToolbar() == true {
self.addToolbarIfRequired()
} else {
self.removeToolbarIfRequired()
}
}
///------------------------------------
/// MARK: Debugging & Developer options
///------------------------------------
@objc public var enableDebugging = false
/**
@warning Use below methods to completely enable/disable notifications registered by library internally. Please keep in mind that library is totally dependent on NSNotification of UITextField, UITextField, Keyboard etc. If you do unregisterAllNotifications then library will not work at all. You should only use below methods if you want to completedly disable all library functions. You should use below methods at your own risk.
*/
@objc public func registerAllNotifications() {
#if swift(>=4.2)
let UIKeyboardWillShow = UIResponder.keyboardWillShowNotification
let UIKeyboardDidShow = UIResponder.keyboardDidShowNotification
let UIKeyboardWillHide = UIResponder.keyboardWillHideNotification
let UIKeyboardDidHide = UIResponder.keyboardDidHideNotification
let UITextFieldTextDidBeginEditing = UITextField.textDidBeginEditingNotification
let UITextFieldTextDidEndEditing = UITextField.textDidEndEditingNotification
let UITextViewTextDidBeginEditing = UITextView.textDidBeginEditingNotification
let UITextViewTextDidEndEditing = UITextView.textDidEndEditingNotification
let UIApplicationWillChangeStatusBarOrientation = UIApplication.willChangeStatusBarOrientationNotification
#else
let UIKeyboardWillShow = Notification.Name.UIKeyboardWillShow
let UIKeyboardDidShow = Notification.Name.UIKeyboardDidShow
let UIKeyboardWillHide = Notification.Name.UIKeyboardWillHide
let UIKeyboardDidHide = Notification.Name.UIKeyboardDidHide
let UITextFieldTextDidBeginEditing = Notification.Name.UITextFieldTextDidBeginEditing
let UITextFieldTextDidEndEditing = Notification.Name.UITextFieldTextDidEndEditing
let UITextViewTextDidBeginEditing = Notification.Name.UITextViewTextDidBeginEditing
let UITextViewTextDidEndEditing = Notification.Name.UITextViewTextDidEndEditing
let UIApplicationWillChangeStatusBarOrientation = Notification.Name.UIApplicationWillChangeStatusBarOrientation
#endif
// Registering for keyboard notification.
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: UIKeyboardDidHide, object: nil)
// Registering for UITextField notification.
registerTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: UITextFieldTextDidEndEditing.rawValue)
// Registering for UITextView notification.
registerTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: UITextViewTextDidEndEditing.rawValue)
// Registering for orientation changes notification
NotificationCenter.default.addObserver(self, selector: #selector(self.willChangeStatusBarOrientation(_:)), name: UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared)
}
@objc public func unregisterAllNotifications() {
#if swift(>=4.2)
let UIKeyboardWillShow = UIResponder.keyboardWillShowNotification
let UIKeyboardDidShow = UIResponder.keyboardDidShowNotification
let UIKeyboardWillHide = UIResponder.keyboardWillHideNotification
let UIKeyboardDidHide = UIResponder.keyboardDidHideNotification
let UITextFieldTextDidBeginEditing = UITextField.textDidBeginEditingNotification
let UITextFieldTextDidEndEditing = UITextField.textDidEndEditingNotification
let UITextViewTextDidBeginEditing = UITextView.textDidBeginEditingNotification
let UITextViewTextDidEndEditing = UITextView.textDidEndEditingNotification
let UIApplicationWillChangeStatusBarOrientation = UIApplication.willChangeStatusBarOrientationNotification
#else
let UIKeyboardWillShow = Notification.Name.UIKeyboardWillShow
let UIKeyboardDidShow = Notification.Name.UIKeyboardDidShow
let UIKeyboardWillHide = Notification.Name.UIKeyboardWillHide
let UIKeyboardDidHide = Notification.Name.UIKeyboardDidHide
let UITextFieldTextDidBeginEditing = Notification.Name.UITextFieldTextDidBeginEditing
let UITextFieldTextDidEndEditing = Notification.Name.UITextFieldTextDidEndEditing
let UITextViewTextDidBeginEditing = Notification.Name.UITextViewTextDidBeginEditing
let UITextViewTextDidEndEditing = Notification.Name.UITextViewTextDidEndEditing
let UIApplicationWillChangeStatusBarOrientation = Notification.Name.UIApplicationWillChangeStatusBarOrientation
#endif
// Unregistering for keyboard notification.
NotificationCenter.default.removeObserver(self, name: UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: UIKeyboardDidShow, object: nil)
NotificationCenter.default.removeObserver(self, name: UIKeyboardWillHide, object: nil)
NotificationCenter.default.removeObserver(self, name: UIKeyboardDidHide, object: nil)
// Unregistering for UITextField notification.
unregisterTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: UITextFieldTextDidEndEditing.rawValue)
// Unregistering for UITextView notification.
unregisterTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: UITextViewTextDidEndEditing.rawValue)
// Unregistering for orientation changes notification
NotificationCenter.default.removeObserver(self, name: UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared)
}
private func showLog(_ logString: String, indentation: Int = 0) {
struct Static {
static var indentation = 0
}
if indentation < 0 {
Static.indentation = max(0, Static.indentation + indentation)
}
if enableDebugging {
var preLog = "IQKeyboardManager"
for _ in 0 ... Static.indentation {
preLog += "|\t"
}
print(preLog + logString)
}
if indentation > 0 {
Static.indentation += indentation
}
}
}
| mit | 4d156474e3ac5767c0e1974fbfaf080e | 47.631094 | 434 | 0.568548 | 7.263085 | false | false | false | false |
fuzza/functional-swift-examples | functional-swift-playground.playground/Pages/diagrams.xcplaygroundpage/Contents.swift | 1 | 7163 | //: [Previous](@previous)
import Foundation
import Cocoa
import CoreGraphics
enum Primitive {
case Ellipse
case Rectangle
case Text(String)
}
indirect enum Diagram {
case Primitive(CGSize, Primitive)
case Beside(Diagram, Diagram)
case Below(Diagram, Diagram)
case Align(CGVector, Diagram)
case Attributed(Attribute, Diagram)
}
enum Attribute {
case FillColor(NSColor)
}
extension Diagram {
var size: CGSize {
switch self {
case .Primitive(let s, _):
return s
case .Beside(let l, let r):
let leftSize = l.size
let rightSize = r.size
return CGSize(width: leftSize.width + rightSize.width, height: max(leftSize.height,rightSize.height))
case .Below(let t, let b):
let topSize = t.size
let botSize = b.size
return CGSize(width: max(topSize.width, botSize.width), height: topSize.height + b.size.height)
case .Align(_, let x):
return x.size
case .Attributed(_, let x):
return x.size
}
}
}
func *(l: CGFloat, r: CGSize) -> CGSize {
return CGSize(width: l * r.width, height: l * r.height)
}
func /(l: CGSize, r: CGSize) -> CGSize {
return CGSize(width: l.width / r.width, height: l.height / r.height)
}
func *(l: CGSize, r: CGSize) -> CGSize {
return CGSize(width: l.width * r.width, height: l.height * r.height)
}
func -(l: CGSize, r: CGSize) -> CGSize {
return CGSize(width: l.width - r.width, height: l.height - r.height)
}
func -(l: CGPoint, r: CGPoint) -> CGPoint {
return CGPoint(x: l.x - r.x, y: l.y - r.y)
}
extension CGSize {
var point: CGPoint {
return CGPoint(x: self.width, y: self.height)
}
}
extension CGVector {
var point: CGPoint {
return CGPoint(x: dx, y: dy)
}
var size: CGSize {
return CGSize(width: dx, height: dy)
}
}
extension CGSize {
func fit(_ vector: CGVector, _ rect: CGRect) -> CGRect {
let scaleSize = rect.size / self
let scale = min(scaleSize.width, scaleSize.height)
let size = scale * self
let space = vector.size * (size - rect.size)
return CGRect(origin: rect.origin - space.point, size: size)
}
}
let centerRect = CGSize(width: 1, height: 1).fit(
CGVector(dx:0.5, dy:0.5), CGRect(x: 0, y: 0, width: 200, height: 100))
let leftRect = CGSize(width: 1, height: 1).fit(
CGVector(dx:0, dy:0.5), CGRect(x: 0, y: 0, width: 200, height: 100))
extension CGRect {
func split(_ ratio: CGFloat, edge:CGRectEdge) -> (CGRect, CGRect) {
let length = edge.isHorizontal ? width : height
return divided(atDistance: length * ratio, from: edge)
}
}
extension CGRectEdge {
var isHorizontal: Bool {
return self == .maxXEdge || self == .minXEdge
}
}
extension CGContext {
func draw(_ diagram: Diagram, _ bounds: CGRect) {
switch diagram {
case .Primitive(let size, .Ellipse):
let frame = size.fit(CGVector(dx:0.5, dy:0.5), bounds)
self.fillEllipse(in: frame)
case .Primitive(let size, .Rectangle):
let frame = size.fit(CGVector(dx:0.5, dy:0.5), bounds)
self.fill(frame)
case .Primitive(let size, .Text(let text)):
let frame = size.fit(CGVector(dx:0.5, dy:0.5), bounds)
let font = NSFont.systemFont(ofSize: 12.0)
let attributes = [NSFontAttributeName: font]
let attributedText = NSAttributedString(string: text, attributes: attributes)
attributedText.draw(in: frame)
case .Attributed(.FillColor(let color), let d):
CGContext.saveGState(self)
color.set()
draw(d, bounds)
CGContext.restoreGState(self)
case .Beside(let left, let right):
let (lFrame, rFrame) = bounds.split(
left.size.width / diagram.size.width, edge: .minXEdge)
draw(left, lFrame)
draw(right, rFrame)
case .Below(let top, let bot):
let (lFrame, rFrame) = bounds.split(
bot.size.height, edge: .minYEdge)
draw(bot, lFrame)
draw(top, rFrame)
case .Align(let vec, let d):
let frame = d.size.fit(vec, bounds)
draw(d, frame)
} }
}
class Draw: NSView {
let diagram: Diagram
init(frame frameRect: NSRect, diagram: Diagram) {
self.diagram = diagram
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ dirtyRect: NSRect) {
guard let context = NSGraphicsContext.current() else { return }
context.cgContext.draw(self.diagram, self.bounds)
}
}
let rect = NSRect(x: 0, y: 0, width: 1000, height: 1000)
let view = Draw(frame: rect, diagram: .Primitive(CGSize(width:10, height:10), .Ellipse))
// Combinators
func rect(width: CGFloat, height: CGFloat) -> Diagram {
return .Primitive(CGSize(width: width, height: height), .Rectangle)
}
func circle(diameter: CGFloat) -> Diagram {
return .Primitive(CGSize(width: diameter, height: diameter), .Ellipse)
}
func text(theText: String, width: CGFloat, height: CGFloat) -> Diagram {
return .Primitive(CGSize(width: width, height: height), .Text(theText))
}
func square(side: CGFloat) -> Diagram {
return rect(width:side, height:side)
}
infix operator |||
func ||| (l: Diagram, r: Diagram) -> Diagram {
return Diagram.Beside(l, r)
}
infix operator ---
func --- (l: Diagram, r: Diagram) -> Diagram {
return Diagram.Below(l, r)
}
extension Diagram {
func fill(_ color: NSColor) -> Diagram {
return .Attributed(.FillColor(color), self)
}
func alignTop() -> Diagram {
return .Align(CGVector(dx: 0.5, dy: 1), self)
}
func alignBottom() -> Diagram {
return .Align(CGVector(dx: 0.5, dy: 0), self)
}
}
let empty: Diagram = rect(width:0, height:0)
func hcat(diagrams: [Diagram]) -> Diagram {
return diagrams.reduce(empty, |||)
}
// Example
extension Array where Element == CGFloat {
func normalize() -> [Element] {
let max: CGFloat = self.reduce(0, { i, x in return i < x ? x : i })
return self.map { $0 / max }
}
}
func barGraph(input: [(String, Double)]) -> Diagram {
let values: [CGFloat] = input.map { CGFloat($0.1) }
let hValues = values.normalize()
let bars = hcat(diagrams: hValues.map { (x: CGFloat) -> Diagram in
return rect(width: 1, height: 3 * x).fill(.black).alignBottom()
})
let labels = hcat(diagrams: input.map { x in
return text(theText: x.0, width: 1, height: 0.3).alignTop() })
return bars --- labels }
let cities = ["Shanghai": 14.01, "Istanbul": 13.3, "Moscow": 10.56, "New York": 8.33, "Berlin": 3.43]
let example3 = barGraph(input: Array(cities))
let view2 = Draw(frame: rect, diagram: example3)
//: [Next](@next) | mit | 37d4ceee9ee557a9dae94c3770eaceab | 28.240816 | 113 | 0.588441 | 3.634196 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Models/Search/Query/DeleteByQuery.swift | 1 | 3813 | //
// DeleteByQuery.swift
//
//
// Created by Vladislav Fitc on 26/03/2020.
//
import Foundation
/// Proxy for a Query object keeping visible fields for deletion
public struct DeleteByQuery {
var query: Query = .empty
/**
Filter the query with numeric, facet and/or tag filters.
- Engine default: ""
- [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/filters/?language=swift)
*/
public var filters: String? {
get {
return query.filters
}
set {
query.filters = newValue
}
}
/**
Filter hits by facet value.
- Engine default: []
- [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/?language=swift)
*/
public var facetFilters: FiltersStorage? {
get {
return query.facetFilters
}
set {
query.facetFilters = newValue
}
}
/**
Filter on numeric attributes.
- Engine default: []
- [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/numericFilters/?language=swift)
*/
public var numericFilters: FiltersStorage? {
get {
return query.numericFilters
}
set {
query.numericFilters = newValue
}
}
/**
Filter hits by tags.
- Engine default: []
- [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/tagFilters/?language=swift)
*/
public var tagFilters: FiltersStorage? {
get {
return query.tagFilters
}
set {
query.tagFilters = newValue
}
}
/**
Search for entries around a central geolocation, enabling a geo search within a circular area.
- Engine default: null
- [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLng/?language=swift)
*/
public var aroundLatLng: Point? {
get {
return query.aroundLatLng
}
set {
query.aroundLatLng = newValue
}
}
/**
Define the maximum radius for a geo search (in meters).
- Engine default: null
- [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/aroundRadius/?language=swift)
*/
public var aroundRadius: AroundRadius? {
get {
return query.aroundRadius
}
set {
query.aroundRadius = newValue
}
}
/**
Precision of geo search (in meters), to add grouping by geo location to the ranking formula.
- Engine default: 1
- [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/aroundPrecision/?language=swift)
*/
public var aroundPrecision: [AroundPrecision]? {
get {
return query.aroundPrecision
}
set {
query.aroundPrecision = newValue
}
}
/**
Search inside a rectangular area (in geo coordinates).
- Engine default: null
- [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/insideBoundingBox/?language=swift)
*/
public var insideBoundingBox: [BoundingBox]? {
get {
return query.insideBoundingBox
}
set {
query.insideBoundingBox = newValue
}
}
/**
Search inside a polygon (in geo coordinates).
- Engine default: null
- [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/insidePolygon/?language=swift)
*/
public var insidePolygon: [Polygon]? {
get {
return query.insidePolygon
}
set {
query.insidePolygon = newValue
}
}
public init() {
}
}
extension DeleteByQuery: Codable {
public init(from decoder: Decoder) throws {
query = try Query(from: decoder)
}
public func encode(to encoder: Encoder) throws {
try query.encode(to: encoder)
}
}
extension DeleteByQuery: URLEncodable {
public var urlEncodedString: String {
return query.urlEncodedString
}
}
extension DeleteByQuery: Builder {}
| mit | 5ffed287a4867fb0dd992e105a6cb957 | 18.654639 | 112 | 0.655652 | 4.078075 | false | false | false | false |
mathcamp/Carlos | FuturesTests/Future+FlatMapTests.swift | 1 | 12631 | import Quick
import Nimble
import PiedPiper
class FutureFlatMapTests: QuickSpec {
override func spec() {
describe("FlatMapping a Future") {
var promise: Promise<String>!
var mappedFuture: Future<Int>!
var successValue: Int?
var failureValue: ErrorType?
var wasCanceled: Bool!
beforeEach {
promise = Promise<String>()
wasCanceled = false
successValue = nil
failureValue = nil
}
context("when done through a closure that can return nil") {
let mappingClosure: String -> Int? = { str in
if str == "nil" {
return nil
} else {
return 1
}
}
beforeEach {
mappedFuture = promise.future
.flatMap(mappingClosure)
mappedFuture.onCompletion { result in
switch result {
case .Success(let value):
successValue = value
case .Error(let error):
failureValue = error
case .Cancelled:
wasCanceled = true
}
}
}
context("when the original future fails") {
let error = TestError.SimpleError
beforeEach {
promise.fail(error)
}
it("should also fail the mapped future") {
expect(failureValue).notTo(beNil())
}
it("should fail the mapped future with the same error") {
expect(failureValue as? TestError).to(equal(error))
}
it("should not succeed the mapped future") {
expect(successValue).to(beNil())
}
it("should not cancel the mapped future") {
expect(wasCanceled).to(beFalse())
}
}
context("when the original future is canceled") {
beforeEach {
promise.cancel()
}
it("should also cancel the mapped future") {
expect(wasCanceled).to(beTrue())
}
it("should not succeed the mapped future") {
expect(successValue).to(beNil())
}
it("should not fail the mapped future") {
expect(failureValue).to(beNil())
}
}
context("when the original future succeeds") {
context("when the closure doesn't return nil") {
let result = "Eureka!"
beforeEach {
promise.succeed(result)
}
it("should also succeed the mapped future") {
expect(successValue).notTo(beNil())
}
it("should succeed the mapped future with the mapped value") {
expect(successValue).to(equal(mappingClosure(result)))
}
it("should not fail the mapped future") {
expect(failureValue).to(beNil())
}
it("should not cancel the mapped future") {
expect(wasCanceled).to(beFalse())
}
}
context("when the closure returns nil") {
let result = "nil"
beforeEach {
promise.succeed(result)
}
it("should not succeed the mapped future") {
expect(successValue).to(beNil())
}
it("should fail the mapped future") {
expect(failureValue).notTo(beNil())
}
it("should fail the mapped future with the right error") {
expect(failureValue as? FutureMappingError).to(equal(FutureMappingError.CantMapValue))
}
it("should not cancel the mapped future") {
expect(wasCanceled).to(beFalse())
}
}
}
}
context("when done through a closure that returns a Result") {
let mappingClosure: String -> Result<Int> = { str in
if str == "cancel" {
return Result.Cancelled
} else if str == "failure" {
return Result.Error(TestError.SimpleError)
} else {
return Result.Success(1)
}
}
beforeEach {
mappedFuture = promise.future
.flatMap(mappingClosure)
mappedFuture.onCompletion { result in
switch result {
case .Success(let value):
successValue = value
case .Error(let error):
failureValue = error
case .Cancelled:
wasCanceled = true
}
}
}
context("when the original future fails") {
let error = TestError.SimpleError
beforeEach {
promise.fail(error)
}
it("should also fail the mapped future") {
expect(failureValue).notTo(beNil())
}
it("should fail the mapped future with the same error") {
expect(failureValue as? TestError).to(equal(error))
}
it("should not succeed the mapped future") {
expect(successValue).to(beNil())
}
it("should not cancel the mapped future") {
expect(wasCanceled).to(beFalse())
}
}
context("when the original future is canceled") {
beforeEach {
promise.cancel()
}
it("should also cancel the mapped future") {
expect(wasCanceled).to(beTrue())
}
it("should not succeed the mapped future") {
expect(successValue).to(beNil())
}
it("should not fail the mapped future") {
expect(failureValue).to(beNil())
}
}
context("when the original future succeeds") {
context("when the closure returns a success") {
let result = "Eureka!"
beforeEach {
promise.succeed(result)
}
it("should also succeed the mapped future") {
expect(successValue).notTo(beNil())
}
it("should succeed the mapped future with the right value") {
expect(successValue).to(equal(1))
}
it("should not fail the mapped future") {
expect(failureValue).to(beNil())
}
it("should not cancel the mapped future") {
expect(wasCanceled).to(beFalse())
}
}
context("when the closure returns a failure") {
let result = "failure"
beforeEach {
promise.succeed(result)
}
it("should not succeed the mapped future") {
expect(successValue).to(beNil())
}
it("should fail the mapped future") {
expect(failureValue).notTo(beNil())
}
it("should fail the mapped future with the right error") {
expect(failureValue as? TestError).to(equal(TestError.SimpleError))
}
it("should not cancel the mapped future") {
expect(wasCanceled).to(beFalse())
}
}
context("when the closure returns a cancelled result") {
let result = "cancel"
beforeEach {
promise.succeed(result)
}
it("should not succeed the mapped future") {
expect(successValue).to(beNil())
}
it("should not fail the mapped future") {
expect(failureValue).to(beNil())
}
it("should cancel the mapped future") {
expect(wasCanceled).to(beTrue())
}
}
}
}
context("when done through a closure that returns a Future") {
let mappingClosure: String -> Future<Int> = { str in
let result: Future<Int>
if str == "cancel" {
let intermediate = Promise<Int>()
intermediate.cancel()
result = intermediate.future
} else if str == "failure" {
result = Future(TestError.SimpleError)
} else {
result = Future(1)
}
return result
}
beforeEach {
mappedFuture = promise.future
.flatMap(mappingClosure)
mappedFuture.onCompletion { result in
switch result {
case .Success(let value):
successValue = value
case .Error(let error):
failureValue = error
case .Cancelled:
wasCanceled = true
}
}
}
context("when the original future fails") {
let error = TestError.SimpleError
beforeEach {
promise.fail(error)
}
it("should also fail the mapped future") {
expect(failureValue).notTo(beNil())
}
it("should fail the mapped future with the same error") {
expect(failureValue as? TestError).to(equal(error))
}
it("should not succeed the mapped future") {
expect(successValue).to(beNil())
}
it("should not cancel the mapped future") {
expect(wasCanceled).to(beFalse())
}
}
context("when the original future is canceled") {
beforeEach {
promise.cancel()
}
it("should also cancel the mapped future") {
expect(wasCanceled).to(beTrue())
}
it("should not succeed the mapped future") {
expect(successValue).to(beNil())
}
it("should not fail the mapped future") {
expect(failureValue).to(beNil())
}
}
context("when the original future succeeds") {
context("when the closure returns a success") {
let result = "Eureka!"
beforeEach {
promise.succeed(result)
}
it("should also succeed the mapped future") {
expect(successValue).notTo(beNil())
}
it("should succeed the mapped future with the right value") {
expect(successValue).to(equal(1))
}
it("should not fail the mapped future") {
expect(failureValue).to(beNil())
}
it("should not cancel the mapped future") {
expect(wasCanceled).to(beFalse())
}
}
context("when the closure returns a failure") {
let result = "failure"
beforeEach {
promise.succeed(result)
}
it("should not succeed the mapped future") {
expect(successValue).to(beNil())
}
it("should fail the mapped future") {
expect(failureValue).notTo(beNil())
}
it("should fail the mapped future with the right error") {
expect(failureValue as? TestError).to(equal(TestError.SimpleError))
}
it("should not cancel the mapped future") {
expect(wasCanceled).to(beFalse())
}
}
context("when the closure returns a cancelled future") {
let result = "cancel"
beforeEach {
promise.succeed(result)
}
it("should not succeed the mapped future") {
expect(successValue).to(beNil())
}
it("should not fail the mapped future") {
expect(failureValue).to(beNil())
}
it("should cancel the mapped future") {
expect(wasCanceled).to(beTrue())
}
}
}
}
}
}
} | mit | d11428c34a7265526c5d5c2ee573d49c | 28.583138 | 100 | 0.465205 | 5.802021 | false | false | false | false |
marklin2012/iOS_Animation | Section3/Chapter16/O2Iris_completed/O2Iris/ViewController.swift | 1 | 5928 | //
// ViewController.swift
// O2Iris
//
// Created by O2.LinYi on 16/3/18.
// Copyright © 2016年 jd.com. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var meterLabel: UILabel!
@IBOutlet weak var speakButton: UIButton!
let monitor = MicMonitor()
let assistant = Assistant()
let replicator = CAReplicatorLayer()
let dot = CALayer()
let dotLength: CGFloat = 6.0
let dotOffset: CGFloat = 8.0
var lastTransformScale: CGFloat = 0
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
replicator.frame = view.bounds
view.layer.addSublayer(replicator)
// dress up the dot layer
dot.frame = CGRect(x: replicator.frame.size.width - dotLength, y: replicator.position.y, width: dotLength, height: dotLength)
dot.backgroundColor = UIColor.lightGrayColor().CGColor
dot.borderColor = UIColor(white: 1, alpha: 1).CGColor
dot.borderWidth = 0.5
dot.cornerRadius = 1.5
replicator.addSublayer(dot)
// set number of copies (including the original copy)
replicator.instanceCount = Int(view.frame.size.width / dotOffset)
// apply transform to show
replicator.instanceTransform = CATransform3DMakeTranslation(-dotOffset, 0, 0)
replicator.instanceDelay = 0.02
}
// MARK: - button action
@IBAction func actionStartMonitoring(sender: AnyObject) {
dot.backgroundColor = UIColor.greenColor().CGColor
monitor.startMonitoringWithHandler { (level) -> Void in
self.meterLabel.text = String(format: "%.2f db", level)
let scaleFactor = max(0.2, CGFloat(level) + 50) / 2
let scale = CABasicAnimation(keyPath: "transform.scale.y")
scale.fromValue = self.lastTransformScale
scale.toValue = scaleFactor
scale.duration = 0.1
scale.removedOnCompletion = false
scale.fillMode = kCAFillModeForwards
self.dot.addAnimation(scale, forKey: nil)
self.lastTransformScale = scaleFactor
}
}
@IBAction func actionEndMonitoring(sender: AnyObject) {
monitor.stopMonitoring()
dot.removeAllAnimations()
// speak after 1s
delay(seconds: 1, completion: {
self.startSpeaking()
})
}
// MARK: - further methods
func startSpeaking() {
print("speak back")
// get
meterLabel.text = assistant.randomAnswer()
assistant.speak(meterLabel.text!, completion: endSpeaking)
speakButton.hidden = true
let scale = CABasicAnimation(keyPath: "transform")
scale.fromValue = NSValue(CATransform3D: CATransform3DIdentity)
scale.toValue = NSValue(CATransform3D: CATransform3DMakeScale(1.4, 15, 1))
scale.duration = 0.33
scale.repeatCount = Float.infinity
scale.autoreverses = true
scale.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
dot.addAnimation(scale, forKey: "dotScale")
// add fade animation
let fade = CABasicAnimation(keyPath: "opacity")
fade.fromValue = 1
fade.toValue = 0.2
fade.duration = 0.33
fade.beginTime = CACurrentMediaTime() + 0.33
fade.repeatCount = Float.infinity
fade.autoreverses = true
fade.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
dot.addAnimation(fade, forKey: "dotOpacity")
// animate the backgroundColor
let tint = CABasicAnimation(keyPath: "backgroundColor")
tint.fromValue = UIColor.magentaColor().CGColor
tint.toValue = UIColor.cyanColor().CGColor
tint.duration = 0.66
tint.beginTime = CACurrentMediaTime() + 0.28
tint.fillMode = kCAFillModeBackwards
tint.repeatCount = Float.infinity
tint.autoreverses = true
tint.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
dot.addAnimation(tint, forKey: "dotColor")
// rotate
let initialRotation = CABasicAnimation(keyPath: "instanceTransform.rotation")
initialRotation.fromValue = 0
initialRotation.toValue = 0.01
initialRotation.duration = 0.33
initialRotation.removedOnCompletion = false
initialRotation.fillMode = kCAFillModeForwards
initialRotation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
replicator.addAnimation(initialRotation, forKey: "initialRotation")
// complete the effect
let rotation = CABasicAnimation(keyPath: "instanceTransform.rotation")
rotation.fromValue = 0.01
rotation.toValue = -0.01
rotation.duration = 0.00
rotation.beginTime = CACurrentMediaTime() + 0.33
rotation.repeatCount = Float.infinity
rotation.autoreverses = true
rotation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
replicator.addAnimation(rotation, forKey: "replicatorRotation")
}
func endSpeaking() {
replicator.removeAllAnimations()
let scale = CABasicAnimation(keyPath: "transform")
scale.toValue = NSValue(CATransform3D: CATransform3DIdentity)
scale.duration = 0.33
scale.removedOnCompletion = false
scale.fillMode = kCAFillModeForwards
dot.addAnimation(scale, forKey: nil)
dot.removeAnimationForKey("dotColor")
dot.removeAnimationForKey("dotOpacity")
dot.backgroundColor = UIColor.lightGrayColor().CGColor
speakButton.hidden = false
}
}
| mit | 07cbcf1d03f0b929734c6061e188901f | 35.128049 | 133 | 0.640338 | 5.201932 | false | false | false | false |
zybug/firefox-ios | Sync/TabsPayload.swift | 2 | 3944 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import XCGLogger
private let log = Logger.browserLogger
public class TabsPayload: CleartextPayloadJSON {
public class Tab {
let title: String
let urlHistory: [String]
let lastUsed: Timestamp
let icon: String?
private init(title: String, urlHistory: [String], lastUsed: Timestamp, icon: String?) {
self.title = title
self.urlHistory = urlHistory
self.lastUsed = lastUsed
self.icon = icon
}
func toRemoteTabForClient(guid: GUID) -> RemoteTab? {
let urls = optFilter(urlHistory.map({ $0.asURL }))
if urls.isEmpty {
log.debug("Bug 1201875 - discarding tab for \(title), \(urlHistory) as history has no conforming URLs")
return nil
}
return RemoteTab(clientGUID: guid, URL: urls[0], title: self.title, history: urls, lastUsed: self.lastUsed, icon: self.icon?.asURL)
}
class func remoteTabFromJSON(json: JSON, clientGUID: GUID) -> RemoteTab? {
return fromJSON(json)?.toRemoteTabForClient(clientGUID)
}
class func fromJSON(json: JSON) -> Tab? {
func getLastUsed(json: JSON) -> Timestamp? {
// This might be a string or a number.
if let num = json["lastUsed"].asNumber {
return Timestamp(num * 1000)
}
if let num = json["lastUsed"].asString {
// Try parsing.
return decimalSecondsStringToTimestamp(num)
}
return nil
}
if let title = json["title"].asString,
let urlHistory = jsonsToStrings(json["urlHistory"].asArray),
let lastUsed = getLastUsed(json) {
return Tab(title: title, urlHistory: urlHistory, lastUsed: lastUsed, icon: json["icon"].asString)
}
return nil
}
}
override public func isValid() -> Bool {
if !super.isValid() {
return false
}
if self["deleted"].asBool ?? false {
return true
}
return self["clientName"].isString &&
self["tabs"].isArray
}
// Eventually it'd be nice to unify RemoteTab and Tab. We want to kill the GUID in RemoteTab,
// at which point the only distinction between the two is that RemoteTab is "simple" and
// lives in Storage, and Tab is more closely tied to TabsPayload.
var remoteTabs: [RemoteTab] {
if let clientGUID = self["id"].asString {
let payloadTabs = self["tabs"].asArray!
let remoteTabs = optFilter(payloadTabs.map({ Tab.remoteTabFromJSON($0, clientGUID: clientGUID) }))
if payloadTabs.count != remoteTabs.count {
log.debug("Bug 1201875 - Missing remote tabs from sync")
}
return remoteTabs
}
log.debug("no client ID for remote tabs")
return []
}
var tabs: [Tab] {
return optFilter(self["tabs"].asArray!.map(Tab.fromJSON))
}
var clientName: String {
return self["clientName"].asString!
}
override public func equalPayloads(obj: CleartextPayloadJSON) -> Bool {
if !(obj is TabsPayload) {
return false;
}
if !super.equalPayloads(obj) {
return false;
}
let p = obj as! TabsPayload
if p.clientName != self.clientName {
return false
}
// TODO: compare tabs.
/*
if p.tabs != self.tabs {
return false;
}
*/
return true
}
}
| mpl-2.0 | b8443302fde5ab4683432cbe617438bc | 30.301587 | 143 | 0.561866 | 4.845209 | false | false | false | false |
OneBestWay/EasyCode | NetWork/NetWork/StringExtension.swift | 1 | 5216 | //
// StringExtension.swift
// NetWork
//
// Created by GK on 2017/1/11.
// Copyright © 2017年 GK. All rights reserved.
//
import Foundation
extension String {
//输入的文字音译
func transliterationToPinYin() -> String {
let str = NSMutableString(string: self) as CFMutableString
var cfRange = CFRangeMake(0, CFStringGetLength(str))
//转变为拉丁文
let latinSuccess = CFStringTransform(str, &cfRange, kCFStringTransformToLatin, false)
//去掉音调
if latinSuccess {
let combiningMarksSuccess = CFStringTransform(str, &cfRange, kCFStringTransformStripCombiningMarks, false)
if combiningMarksSuccess {
//转为小写
CFStringLowercase(str, nil)
//去掉空格
CFStringTrimWhitespace(str)
}
}
return str as String
}
//首字母大写
func wordFirstLetterUpperCase() -> String {
let str = NSMutableString(string: self) as CFMutableString
var cfRange = CFRangeMake(0, CFStringGetLength(str))
CFStringTransform(str, &cfRange, "Any-Title" as CFString, false)
return str as String
}
//保证输出的都是ASCII字符
func transferToASCII() -> String {
let str = NSMutableString(string: self) as CFMutableString
var cfRange = CFRangeMake(0, CFStringGetLength(str))
CFStringTransform(str, &cfRange, "Any-Latin; Latin-ASCII; [:^ASCII:] Remove" as CFString, false)
return str as String
}
//去掉首尾空格
func removeWhiteSpaceAndNewLine() -> String {
let whitespace = CharacterSet.whitespacesAndNewlines
return self.trimmingCharacters(in: whitespace)
}
//去掉所有的空格
func removeAllWhiteSpace() -> String {
let words = self.tokenize()
let resultString = words.joined(separator: "")
return resultString
}
//分词
func separatedByCharacter() -> [String] {
var characters = CharacterSet.whitespacesAndNewlines
let punctuation = CharacterSet.punctuationCharacters
characters.formUnion(punctuation)
characters.remove(charactersIn: "'")
let words = self.components(separatedBy: characters).filter({ x in !x.isEmpty
})
return words
}
func tokenize() -> [String] {
let inputRange = CFRangeMake(0, self.utf16.count)
let flag = UInt(kCFStringTokenizerUnitWord)
let locale = CFLocaleCopyCurrent()
let tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, self as CFString!, inputRange, flag, locale)
var tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)
var tokens: [String] = []
while tokenType == CFStringTokenizerTokenType.normal {
let currentTokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer)
let subString = self.substringWithRange(aRange: currentTokenRange)
tokens.append(subString)
tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)
}
return tokens
}
private func substringWithRange(aRange: CFRange) -> String {
let range = NSMakeRange(aRange.location, aRange.length)
let subString = (self as NSString).substring(with: range)
return subString
}
func separateString() -> [String] {
var words = [String]()
let range = self.startIndex ..< self.endIndex
self.enumerateSubstrings(in: range, options: String.EnumerationOptions.byWords) {
w,_,_,_ in
guard let word = w else { return }
words.append(word)
}
return words
}
func linguisticTokenize() -> [String] {
let options: NSLinguisticTagger.Options = [.omitWhitespace,.omitPunctuation,.omitOther]
let schemes = [NSLinguisticTagSchemeLexicalClass]
let tagger = NSLinguisticTagger(tagSchemes: schemes, options: Int(options.rawValue))
let range = NSMakeRange(0, (self as NSString).length)
tagger.string = self
var tokens: [String] = []
tagger.enumerateTags(in: range, scheme: NSLinguisticTagSchemeLexicalClass, options: options) { (tag, tokenRange,_,_) in
let token = (self as NSString).substring(with: tokenRange)
tokens.append(token)
}
return tokens
}
}
extension String {
static func UUIDString() -> String {
return UUID().uuidString
}
}
extension String {
func MD5() -> String {
let context = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: 1)
var digest = Array<UInt8>(repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5_Init(context)
CC_MD5_Update(context, self, CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8)))
CC_MD5_Final(&digest, context)
context.deinitialize(count: 1)
var hexString = ""
for byte in digest {
hexString += String(format: "%02x", byte)
}
return hexString
}
}
| mit | ed01ec8f312749f80f646734dc83ed74 | 27.361111 | 127 | 0.619785 | 4.838863 | false | false | false | false |
AlwaysRightInstitute/SwiftyHTTP | Sources/SwiftyHTTP/Parser/HTTPParser.swift | 1 | 14853 | //
// HTTPParser.swift
// SwiftyHTTP
//
// Created by Helge Heß on 6/18/14.
// Copyright (c) 2014 Always Right Institute. All rights reserved.
//
public enum HTTPParserType {
case Request, Response, Both
}
public final class HTTPParser {
enum ParseState {
case Idle, URL, HeaderName, HeaderValue, Body
}
var parser = http_parser()
var settings = http_parser_settings()
let buffer = RawByteBuffer(capacity: 4096)
var parseState = ParseState.Idle
var isWiredUp = false
var url : String?
var lastName : String?
var headers = Dictionary<String, String>(minimumCapacity: 32)
var body : [UInt8]?
var message : HTTPMessage?
public init(type: HTTPParserType = .Both) {
var cType: http_parser_type
switch type {
case .Request: cType = HTTP_REQUEST
case .Response: cType = HTTP_RESPONSE
case .Both: cType = HTTP_BOTH
}
http_parser_init(&parser, cType)
/* configure callbacks */
// TBD: what is the better way to do this?
let ud = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
parser.data = ud
}
/* callbacks */
public func onRequest(cb: ((HTTPRequest) -> Void)?) -> Self {
requestCB = cb
return self
}
public func onResponse(cb: ((HTTPResponse) -> Void)?) -> Self {
responseCB = cb
return self
}
public func onHeaders(cb: ((HTTPMessage) -> Bool)?) -> Self {
headersCB = cb
return self
}
public func onBodyData
(cb: ((HTTPMessage, UnsafePointer<CChar>, UInt) -> Bool)?) -> Self
{
bodyDataCB = cb
return self
}
public func resetEventHandlers() {
requestCB = nil
responseCB = nil
headersCB = nil
bodyDataCB = nil
}
var requestCB : ((HTTPRequest) -> Void)?
var responseCB : ((HTTPResponse) -> Void)?
var headersCB : ((HTTPMessage) -> Bool)?
var bodyDataCB : ((HTTPMessage, UnsafePointer<CChar>, UInt) -> Bool)?
/* write */
public var bodyIsFinal: Bool {
return http_body_is_final(&parser) == 0 ? false:true
}
public func write
(buffer: UnsafePointer<CChar>, _ count: Int) -> HTTPParserError
{
// Note: the parser doesn't expect this to be 0-terminated.
let len = count
if !isWiredUp {
wireUpCallbacks()
}
let bytesConsumed = http_parser_execute(&parser, &settings, buffer, len)
let errno = http_errno(parser.http_errno)
let err = HTTPParserError(errno)
if err != .OK {
// Now hitting this, not quite sure why. Maybe a Safari feature?
let s = http_errno_name(errno)
let d = http_errno_description(errno)
debugPrint("BYTES consumed \(bytesConsumed) from \(buffer)[\(len)] " +
"ERRNO: \(err) \(s) \(d)")
}
return err
}
public func write(buffer: [CChar]) -> HTTPParserError {
let count = buffer.count
return write(buffer, count)
}
/* pending data handling */
func clearState() {
self.url = nil
self.lastName = nil
self.body = nil
self.headers.removeAll(keepCapacity: true)
}
public func addData(data: UnsafePointer<Int8>, length: Int) -> Int32 {
if parseState == .Body && bodyDataCB != nil && message != nil {
return bodyDataCB!(message!, data, UInt(length)) ? 42 : 0
}
else {
buffer.add(data, length: length)
}
return 0
}
func processDataForState
(state: ParseState, d: UnsafePointer<Int8>, l: Int) -> Int32
{
if (state == parseState) { // more data for same field
return addData(d, length: l)
}
switch parseState {
case .HeaderValue:
// finished parsing a header
assert(lastName != nil)
if let n = lastName {
headers[n] = buffer.asString()
}
buffer.reset()
lastName = nil
case .HeaderName:
assert(lastName == nil)
lastName = buffer.asString()
buffer.reset()
case .URL:
assert(url == nil)
url = buffer.asString()
buffer.reset()
case .Body:
if bodyDataCB == nil {
body = buffer.asByteArray()
}
buffer.reset()
default: // needs some block, no empty default possible
break
}
/* start a new state */
parseState = state
buffer.reset()
return addData(d, length: l)
}
public var isRequest : Bool { return parser.type == 0 }
public var isResponse : Bool { return parser.type == 1 }
public class func parserCodeToMethod(rq: UInt8) -> HTTPMethod? {
return parserCodeToMethod(http_method(CUnsignedInt(rq)))
}
public class func parserCodeToMethod(rq: http_method) -> HTTPMethod? {
var method : HTTPMethod?
// Trying to use HTTP_DELETE gives http_method not convertible to
// _OptionalNilComparisonType
switch rq { // hardcode C enum value, defines from http_parser n/a
case HTTP_DELETE: method = HTTPMethod.DELETE
case HTTP_GET: method = HTTPMethod.GET
case HTTP_HEAD: method = HTTPMethod.HEAD
case HTTP_POST: method = HTTPMethod.POST
case HTTP_PUT: method = HTTPMethod.PUT
case HTTP_CONNECT: method = HTTPMethod.CONNECT
case HTTP_OPTIONS: method = HTTPMethod.OPTIONS
case HTTP_TRACE: method = HTTPMethod.TRACE
case HTTP_COPY: method = HTTPMethod.COPY
case HTTP_LOCK: method = HTTPMethod.LOCK
case HTTP_MKCOL: method = HTTPMethod.MKCOL
case HTTP_MOVE: method = HTTPMethod.MOVE
case HTTP_PROPFIND: method = HTTPMethod.PROPFIND
case HTTP_PROPPATCH: method = HTTPMethod.PROPPATCH
case HTTP_SEARCH: method = HTTPMethod.SEARCH
case HTTP_UNLOCK: method = HTTPMethod.UNLOCK
case HTTP_REPORT: method = HTTPMethod.REPORT((nil, nil))
// FIXME: peek body ..
case HTTP_MKACTIVITY: method = HTTPMethod.MKACTIVITY
case HTTP_CHECKOUT: method = HTTPMethod.CHECKOUT
case HTTP_MERGE: method = HTTPMethod.MERGE
case HTTP_MSEARCH: method = HTTPMethod.MSEARCH
case HTTP_NOTIFY: method = HTTPMethod.NOTIFY
case HTTP_SUBSCRIBE: method = HTTPMethod.SUBSCRIBE
case HTTP_UNSUBSCRIBE: method = HTTPMethod.UNSUBSCRIBE
case HTTP_PATCH: method = HTTPMethod.PATCH
case HTTP_PURGE: method = HTTPMethod.PURGE
case HTTP_MKCALENDAR: method = HTTPMethod.MKCALENDAR
default:
// Note: extra custom methods don't work (I think)
method = nil
}
return method
}
func headerFinished() -> Int32 {
self.processDataForState(.Body, d: "", l: 0)
message = nil
let major = parser.http_major
let minor = parser.http_minor
if isRequest {
let method = HTTPParser.parserCodeToMethod(http_method(parser.method))
message = HTTPRequest(method: method!, url: url!,
version: ( Int(major), Int(minor) ),
headers: headers)
self.clearState()
}
else if isResponse {
let status = parser.status_code
// TBD: also grab status text? Doesn't matter in the real world ...
message = HTTPResponse(status: HTTPStatus(rawValue: Int(status))!,
version: ( Int(major), Int(minor) ),
headers: headers)
self.clearState()
}
else { // FIXME: PS style great error handling
debugPrint("Unexpected message? \(parser.type)")
assert(parser.type == 0 || parser.type == 1)
}
if let m = message {
if let cb = headersCB {
return cb(m) ? 0 : 42
}
}
return 0
}
func messageFinished() -> Int32 {
self.processDataForState(.Idle, d: "", l: 0)
if let m = message {
m.bodyAsByteArray = body
if let rq = m as? HTTPRequest {
if let cb = requestCB {
cb(rq)
}
}
else if let res = m as? HTTPResponse {
if let cb = responseCB {
cb(res)
}
}
else {
assert(false, "Expected Request or Response object")
}
return 0
}
else {
debugPrint("did not parse a message ...")
return 42
}
}
/* callbacks */
func wireUpCallbacks() {
// Note: CString is NOT a real C string, it's length terminated
settings.on_message_begin = { parser in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.message = nil
me.clearState()
return 0
}
settings.on_message_complete = { parser in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.messageFinished()
return 0
}
settings.on_headers_complete = { parser in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.headerFinished()
return 0
}
settings.on_url = { parser, data, len in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.processDataForState(ParseState.URL, d: data, l: len)
return 0
}
settings.on_header_field = { parser, data, len in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.processDataForState(ParseState.HeaderName, d: data, l: len)
return 0
}
settings.on_header_value = { parser, data, len in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.processDataForState(ParseState.HeaderValue, d: data, l: len)
return 0
}
settings.on_body = { parser, data, len in
let me = unsafeBitCast(parser.memory.data, HTTPParser.self)
me.processDataForState(ParseState.Body, d: data, l: len)
return 0
}
}
}
extension HTTPParser : CustomStringConvertible {
public var description : String {
return "<HTTPParser \(parseState) @\(buffer.count)>"
}
}
public enum HTTPParserError : CustomStringConvertible {
// manual mapping, Swift doesn't directly bridge the http_parser macros but
// rather creates constants for them
case OK
case cbMessageBegin, cbURL, cbBody, cbMessageComplete, cbStatus
case cbHeaderField, cbHeaderValue, cbHeadersComplete
case InvalidEOFState, HeaderOverflow, ClosedConnection
case InvalidVersion, InvalidStatus, InvalidMethod, InvalidURL
case InvalidHost, InvalidPort, InvalidPath, InvalidQueryString
case InvalidFragment
case LineFeedExpected
case InvalidHeaderToken, InvalidContentLength, InvalidChunkSize
case InvalidConstant, InvalidInternalState
case NotStrict, Paused
case Unknown
public init(_ errcode: http_errno) {
switch (errcode) {
case HPE_OK: self = .OK
case HPE_CB_message_begin: self = .cbMessageBegin
case HPE_CB_url: self = .cbURL
case HPE_CB_header_field: self = .cbHeaderField
case HPE_CB_header_value: self = .cbHeaderValue
case HPE_CB_headers_complete: self = .cbHeadersComplete
case HPE_CB_body: self = .cbBody
case HPE_CB_message_complete: self = .cbMessageComplete
case HPE_CB_status: self = .cbStatus
case HPE_INVALID_EOF_STATE: self = .InvalidEOFState
case HPE_HEADER_OVERFLOW: self = .HeaderOverflow
case HPE_CLOSED_CONNECTION: self = .ClosedConnection
case HPE_INVALID_VERSION: self = .InvalidVersion
case HPE_INVALID_STATUS: self = .InvalidStatus
case HPE_INVALID_METHOD: self = .InvalidMethod
case HPE_INVALID_URL: self = .InvalidURL
case HPE_INVALID_HOST: self = .InvalidHost
case HPE_INVALID_PORT: self = .InvalidPort
case HPE_INVALID_PATH: self = .InvalidPath
case HPE_INVALID_QUERY_STRING: self = .InvalidQueryString
case HPE_INVALID_FRAGMENT: self = .InvalidFragment
case HPE_LF_EXPECTED: self = .LineFeedExpected
case HPE_INVALID_HEADER_TOKEN: self = .InvalidHeaderToken
case HPE_INVALID_CONTENT_LENGTH: self = .InvalidContentLength
case HPE_INVALID_CHUNK_SIZE: self = .InvalidChunkSize
case HPE_INVALID_CONSTANT: self = .InvalidConstant
case HPE_INVALID_INTERNAL_STATE: self = .InvalidInternalState
case HPE_STRICT: self = .NotStrict
case HPE_PAUSED: self = .Paused
case HPE_UNKNOWN: self = .Unknown
default: self = .Unknown
}
}
public var description : String { return errorDescription }
public var errorDescription : String {
switch self {
case OK: return "Success"
case cbMessageBegin: return "The on_message_begin callback failed"
case cbURL: return "The on_url callback failed"
case cbBody: return "The on_body callback failed"
case cbMessageComplete:
return "The on_message_complete callback failed"
case cbStatus: return "The on_status callback failed"
case cbHeaderField: return "The on_header_field callback failed"
case cbHeaderValue: return "The on_header_value callback failed"
case cbHeadersComplete:
return "The on_headers_complete callback failed"
case InvalidEOFState: return "Stream ended at an unexpected time"
case HeaderOverflow:
return "Too many header bytes seen; overflow detected"
case ClosedConnection:
return "Data received after completed connection: close message"
case InvalidVersion: return "Invalid HTTP version"
case InvalidStatus: return "Invalid HTTP status code"
case InvalidMethod: return "Invalid HTTP method"
case InvalidURL: return "Invalid URL"
case InvalidHost: return "Invalid host"
case InvalidPort: return "Invalid port"
case InvalidPath: return "Invalid path"
case InvalidQueryString: return "Invalid query string"
case InvalidFragment: return "Invalid fragment"
case LineFeedExpected: return "LF character expected"
case InvalidHeaderToken: return "Invalid character in header"
case InvalidContentLength:
return "Invalid character in content-length header"
case InvalidChunkSize: return "Invalid character in chunk size header"
case InvalidConstant: return "Invalid constant string"
case InvalidInternalState: return "Encountered unexpected internal state"
case NotStrict: return "Strict mode assertion failed"
case Paused: return "Parser is paused"
default: return "Unknown Error"
}
}
}
| mit | a9fb2765ee3bc622678c028ceebf0b39 | 32.300448 | 80 | 0.615203 | 4.364384 | false | false | false | false |
abarisain/skugga | Apple/UpdAPI/UpdAPI/Models/RemoteFile.swift | 1 | 3084 | //
// RemoteFile.swift
// Skugga
//
// Created by Arnaud Barisain Monrose on 09/02/2015.
//
//
import Foundation
import CoreData
private struct LocalCoreDataKeys
{
static let Filename = "filename"
static let UploadDate = "uploadDate"
static let Url = "url"
static let DeleteKey = "deleteKey"
}
public struct RemoteFile: Codable
{
static let dateFormatter: DateFormatter =
{
var formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSZZZZZ"
return formatter
}()
public let filename: String
public let uploadDate: Date
public let url: String
public let deleteKey: String
enum CodingKeys: String, CodingKey {
case filename = "original"
case uploadDate = "creation_time"
case url = "name"
case deleteKey = "delete_key"
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
filename = (try? values.decode(String.self, forKey: .filename)) ?? "<unknown original name>"
url = try values.decode(String.self, forKey: .url)
deleteKey = try values.decode(String.self, forKey: .deleteKey)
let rawUploadDate = try? values.decode(String.self, forKey: .uploadDate)
if let rawUploadDate = rawUploadDate,
let parsedDate = RemoteFile.dateFormatter.date(from: rawUploadDate) {
uploadDate = parsedDate
} else {
uploadDate = Date()
}
}
public init(fromNSDict dict: [AnyHashable: Any])
{
filename = dict["original"] as? String ?? "<unknown original name>"
uploadDate = RemoteFile.dateFormatter.date(from: dict["creation_time"] as? String ?? "") ?? Date()
url = dict["name"] as! String
deleteKey = dict["delete_key"] as! String
}
public init(fromNSManagedObject managedObject: NSManagedObject)
{
filename = managedObject.value(forKey: LocalCoreDataKeys.Filename) as! String
uploadDate = managedObject.value(forKey: LocalCoreDataKeys.UploadDate) as! Date
url = managedObject.value(forKey: LocalCoreDataKeys.Url) as! String
deleteKey = managedObject.value(forKey: LocalCoreDataKeys.DeleteKey) as! String
}
public func toNSManagedObject(_ context: NSManagedObjectContext, entity: NSEntityDescription) -> NSManagedObject
{
let managedObject = NSManagedObject(entity: entity, insertInto: context)
managedObject.setValue(filename, forKey: LocalCoreDataKeys.Filename)
managedObject.setValue(uploadDate, forKey: LocalCoreDataKeys.UploadDate)
managedObject.setValue(url, forKey: LocalCoreDataKeys.Url)
managedObject.setValue(deleteKey, forKey: LocalCoreDataKeys.DeleteKey)
return managedObject
}
public func absoluteURL(baseURL: String) -> URL? {
return URL(string: baseURL)?.appendingPathComponent(self.url)
}
}
| apache-2.0 | 74029241fcdcd0c5de0dfca2220a4d51 | 33.266667 | 116 | 0.660182 | 4.722818 | false | false | false | false |
larryhou/swift | TexasHoldem/TexasHoldem/Math.swift | 1 | 794 | //
// Math.swift
// TexasHoldem
//
// Created by larryhou on 6/3/2016.
// Copyright © 2016 larryhou. All rights reserved.
//
import Foundation
func combinate(_ num: UInt, select: UInt) -> UInt {
return permutate(num, select: select) / permuate(select)
}
func permutate(_ num: UInt, select: UInt) -> UInt {
var result: UInt = 1
for i in 0..<select {
result *= num - i
}
return result
}
func permuate(_ num: UInt) -> UInt {
var result: UInt = 1
for i in 0..<num {
result *= num - i
}
return result
}
func pow(_ base: UInt, exponent: UInt) -> UInt {
var result: UInt = 1
for _ in 1...exponent {
result *= base
}
return result
}
extension UInt {
var double: Double {
return Double(self)
}
}
| mit | 5ed3b0622481f6995db06af0d27ce950 | 15.87234 | 60 | 0.572509 | 3.374468 | false | false | false | false |
dfortuna/theCraic3 | theCraic3/Networking/Facebook/FacebookUser.swift | 1 | 1411 | //
// FacebookUser.swift
// theCraic3
//
// Created by Denis Fortuna on 5/5/18.
// Copyright © 2018 Denis. All rights reserved.
//
import Foundation
struct FacebookUser {
var id = String()
var email = String()
var name = String()
var gender = String()
var firstName = String()
var lastName = String()
var friends = [String]()
var userPicURL = String()
init(with dictionary: [String: AnyObject]) {
self.id = dictionary["id"] as? String ?? ""
self.email = dictionary["email"] as? String ?? ""
self.name = dictionary["name"] as? String ?? ""
self.gender = dictionary["gender"] as? String ?? ""
self.firstName = dictionary["firstName"] as? String ?? ""
self.lastName = dictionary["lastName"] as? String ?? ""
if let picture = dictionary["picture"] as? [String : AnyObject] {
if let picData = picture["data"] as? [String : AnyObject] {
self.userPicURL = picData["url"] as? String ?? ""
}
}
if let friends = dictionary["friends"] as? [String : AnyObject] {
if let friendsData = friends["data"] as? [[String: String]] {
for friend in friendsData {
if let friendID = friend["id"] {
self.friends.append(friendID)
}
}
}
}
}
}
| apache-2.0 | e1e9c5df7a3b180763605a65c108d137 | 31.790698 | 74 | 0.532624 | 4.221557 | false | false | false | false |
n42corp/N42WebView | Example/Tests/Tests.swift | 1 | 1191 | // https://github.com/Quick/Quick
//import Quick
//import Nimble
//import N42WebView
/*
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
*/
| mit | 8147db1b5920dad7ec8844c9870bd0b4 | 21.358491 | 63 | 0.359494 | 5.337838 | false | false | false | false |
victorchee/CollectionView | WaterfallColletionView/WaterfallCollectionView/ViewController.swift | 2 | 2012 | //
// ViewController.swift
// WaterfallCollectionView
//
// Created by Victor Chee on 16/5/12.
// Copyright © 2016年 VictorChee. All rights reserved.
//
import UIKit
class ViewController: UICollectionViewController, WaterfallFlowLayoutDataSource {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let layout = self.collectionView?.collectionViewLayout as? WaterfallFlowLayout {
layout.dataSource = self
layout.sectionInset = UIEdgeInsets(top: 10, left: 20, bottom: 20, right: 20)
layout.columnCount = 5
layout.lineSpacing = 10
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - WaterfallFlowLayoutDataSource
func collectionView(collectionView: UICollectionView, layout: WaterfallFlowLayout, sizeForItemAtIndexPath: NSIndexPath) -> CGSize {
let width = (collectionView.frame.width - layout.sectionInset.left - layout.sectionInset.right - layout.interitemSpacing * CGFloat(layout.columnCount - 1)) / CGFloat(layout.columnCount)
let height = CGFloat(sizeForItemAtIndexPath.item * 10 + 20)
return CGSize(width: width, height: height)
}
// MARK: - UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 30;
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.label.text = "\(indexPath.section) - \(indexPath.item)"
return cell;
}
}
| mit | b88248cad8ca32f9b8ceeb937ea3a27d | 38.392157 | 193 | 0.696864 | 5.286842 | false | false | false | false |
dnevera/ImageMetalling | ImageMetalling-02/ImageMetalling-02/IMPSHLViewController.swift | 1 | 1986 | //
// ViewController.swift
// ImageMetalling-02
//
// Created by denis svinarchuk on 27.10.15.
// Copyright © 2015 ImageMetalling. All rights reserved.
//
import UIKit
/**
* ViewController для небольшой манипуляции картинкой и параметрами фильтра.
*/
class IMPSHLViewController: UIViewController {
/**
* Контрол степени осветдения тени
*/
@IBOutlet weak var levelSlider: UISlider!
/**
* Контрол тональной ширины теней
*/
@IBOutlet weak var shadowsWidthSlider: UISlider!
/**
* Контрол наклона кривой перехода между тенью и светами
*/
@IBOutlet weak var highlightsWidthSlider: UISlider!
/**
* И представление и фильтр в одном флаконе.
*/
@IBOutlet weak var renderingView: IMPSHLView!
/**
* Ловим события от слайдера
*/
@IBAction func valueChanged(sender: UISlider) {
switch(sender){
case levelSlider:
self.renderingView.level = sender.value
case shadowsWidthSlider:
self.renderingView.shadowsWidth = sender.value;
case highlightsWidthSlider:
self.renderingView.highlightsWidth = sender.value;
default:
NSLog(" *** Unknown slider")
}
self.renderingView.refresh();
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
renderingView.loadImage("shadows_highlights.jpg")
self.levelSlider.value = self.renderingView.level
self.shadowsWidthSlider.value = self.renderingView.shadowsWidth
self.highlightsWidthSlider.value = self.renderingView.highlightsWidth
self.renderingView.refresh();
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
| mit | 9edebdf3714a74ae13f24aaf58fb638a | 24.385714 | 77 | 0.64547 | 4.191038 | false | false | false | false |
kishikawakatsumi/KeychainAccess | Examples/Example-iOS/Example-iOS/AccountsViewController.swift | 1 | 5060 | //
// AccountsViewController.swift
// Example
//
// Created by kishikawa katsumi on 2014/12/25.
// Copyright (c) 2014 kishikawa katsumi. 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
import KeychainAccess
class AccountsViewController: UITableViewController {
var itemsGroupedByService: [String: [[String: Any]]]?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reloadData()
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK:
override func numberOfSections(in tableView: UITableView) -> Int {
if itemsGroupedByService != nil {
let services = Array(itemsGroupedByService!.keys)
return services.count
}
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let services = Array(itemsGroupedByService!.keys)
let service = services[section]
let items = Keychain(service: service).allItems()
return items.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let services = Array(itemsGroupedByService!.keys)
return services[section]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let services = Array(itemsGroupedByService!.keys)
let service = services[indexPath.section]
let items = Keychain(service: service).allItems()
let item = items[indexPath.row]
cell.textLabel?.text = item["key"] as? String
cell.detailTextLabel?.text = item["value"] as? String
return cell
}
#if swift(>=4.2)
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
let services = Array(itemsGroupedByService!.keys)
let service = services[indexPath.section]
let keychain = Keychain(service: service)
let items = keychain.allItems()
let item = items[indexPath.row]
let key = item["key"] as! String
keychain[key] = nil
if items.count == 1 {
reloadData()
tableView.deleteSections(IndexSet(integer: indexPath.section), with: .automatic)
} else {
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
#else
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let services = Array(itemsGroupedByService!.keys)
let service = services[indexPath.section]
let keychain = Keychain(service: service)
let items = keychain.allItems()
let item = items[indexPath.row]
let key = item["key"] as! String
keychain[key] = nil
if items.count == 1 {
reloadData()
tableView.deleteSections(IndexSet(integer: indexPath.section), with: .automatic)
} else {
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
#endif
// MARK:
func reloadData() {
let items = Keychain.allItems(.genericPassword)
itemsGroupedByService = groupBy(items) { item -> String in
if let service = item["service"] as? String {
return service
}
return ""
}
}
}
private func groupBy<C: Collection, K: Hashable>(_ xs: C, key: (C.Iterator.Element) -> K) -> [K:[C.Iterator.Element]] {
var gs: [K:[C.Iterator.Element]] = [:]
for x in xs {
let k = key(x)
var ys = gs[k] ?? []
ys.append(x)
gs.updateValue(ys, forKey: k)
}
return gs
}
| mit | ac3b6d7f7f4056508395aec9b14c9b68 | 32.959732 | 137 | 0.657312 | 4.791667 | false | false | false | false |
ngageoint/mage-ios | Mage/ObservationEditCoordinator.swift | 1 | 14876 | //
// ObservationEditCoordinator.swift
// MAGE
//
// Created by Daniel Barela on 12/1/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import MaterialComponents.MaterialBottomSheet
@objc protocol ObservationEditListener {
@objc func fieldValueChanged(_ field: [String: Any], value: Any?);
// @objc optional func fieldSelected(_ field: [String: Any], currentValue: Any?);
@objc optional func formUpdated(_ form: [String: Any], eventForm: [String: Any], form index: Int);
}
@objc protocol ObservationEditDelegate {
@objc func editCancel(_ coordinator: NSObject);
@objc func editComplete(_ observation: Observation, coordinator: NSObject);
}
protocol ObservationCommonPropertiesListener: AnyObject {
func geometryUpdated(_ geometry: SFGeometry?, accuracy: String?, delta: Double?, provider: String?);
func timestampUpdated(_ date: Date?);
}
@objc class ObservationEditCoordinator: NSObject {
var newObservation = false;
var observation: Observation?;
weak var rootViewController: UIViewController?;
var navigationController: UINavigationController?;
weak var delegate: ObservationEditDelegate?;
var observationEditController: ObservationEditCardCollectionViewController?;
var observationFormReorder: ObservationFormReorder?;
var bottomSheet: MDCBottomSheetController?;
var currentEditField: [String: Any]?;
var currentEditValue: Any?;
var scheme: MDCContainerScheming?;
private lazy var managedObjectContext: NSManagedObjectContext = {
var managedObjectContext: NSManagedObjectContext = .mr_newMainQueue();
managedObjectContext.parent = .mr_rootSaving();
managedObjectContext.stalenessInterval = 0.0;
managedObjectContext.mr_setWorkingName(newObservation ? "Observation New Context" : "Observation Edit Context");
return managedObjectContext;
} ()
private lazy var event: Event? = {
return Event.getCurrentEvent(context: self.managedObjectContext);
} ()
private lazy var eventForms: [Form] = {
return event?.forms ?? [];
}()
private lazy var user: User? = {
return User.fetchCurrentUser(context: self.managedObjectContext);
}()
@objc public func applyTheme(withContainerScheme containerScheme: MDCContainerScheming?) {
self.scheme = containerScheme;
}
@objc public init(rootViewController: UIViewController!, delegate: ObservationEditDelegate, location: SFGeometry?, accuracy: CLLocationAccuracy, provider: String, delta: Double) {
super.init();
observation = createObservation(location: location, accuracy: accuracy, provider: provider, delta: delta);
setupCoordinator(rootViewController: rootViewController, delegate: delegate);
}
@objc public init(rootViewController: UIViewController!, delegate: ObservationEditDelegate, observation: Observation) {
super.init();
self.observation = setupObservation(observation: observation);
setupCoordinator(rootViewController: rootViewController, delegate: delegate);
}
@objc public func start() {
guard let event = event, let user = user else {
let alert = UIAlertController(title: "You are not part of this event", message: "You cannot create or edit observations for an event you are not part of.", preferredStyle: .alert);
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil));
self.rootViewController?.present(alert, animated: true, completion: nil);
return
}
if (!event.isUserInEvent(user: user)) {
let alert = UIAlertController(title: "You are not part of this event", message: "You cannot create or edit observations for an event you are not part of.", preferredStyle: .alert);
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil));
self.rootViewController?.present(alert, animated: true, completion: nil);
} else {
if let navigationController = navigationController {
navigationController.modalPresentationStyle = .custom;
navigationController.modalTransitionStyle = .crossDissolve;
self.rootViewController?.present(navigationController, animated: true, completion: nil);
observationEditController = ObservationEditCardCollectionViewController(delegate: self, observation: observation!, newObservation: newObservation, containerScheme: self.scheme);
navigationController.pushViewController(observationEditController!, animated: true);
if let scheme = self.scheme {
observationEditController?.applyTheme(withContainerScheme: scheme);
}
}
}
}
@objc public func startFormReorder() {
guard let event = event, let user = user else {
let alert = UIAlertController(title: "You are not part of this event", message: "You cannot edit this observation.", preferredStyle: .alert);
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil));
self.rootViewController?.present(alert, animated: true, completion: nil);
return
}
if (!event.isUserInEvent(user: user)) {
let alert = UIAlertController(title: "You are not part of this event", message: "You cannot edit this observation.", preferredStyle: .alert);
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil));
self.rootViewController?.present(alert, animated: true, completion: nil);
} else {
if let navigationController = navigationController {
navigationController.modalPresentationStyle = .custom;
navigationController.modalTransitionStyle = .crossDissolve;
self.rootViewController?.present(navigationController, animated: true, completion: nil);
observationFormReorder = ObservationFormReorder(observation: observation!, delegate: self, containerScheme: self.scheme);
navigationController.pushViewController(self.observationFormReorder!, animated: true);
self.observationFormReorder!.applyTheme(withContainerScheme: scheme);
}
}
}
func setupCoordinator(rootViewController: UIViewController, delegate: ObservationEditDelegate) {
self.rootViewController = rootViewController;
self.delegate = delegate;
self.navigationController = UINavigationController();
}
func createObservation(location: SFGeometry?, accuracy: CLLocationAccuracy, provider: String, delta: Double) -> Observation? {
newObservation = true;
let observation = Observation.create(geometry: location, accuracy: accuracy, provider: provider, delta: delta, context: managedObjectContext);
observation.dirty = true;
addRequiredForms(observation: observation);
return observation;
}
func setupObservation(observation: Observation) -> Observation? {
let observationInContext = observation.mr_(in: self.managedObjectContext);
observationInContext?.dirty = true;
return observationInContext;
}
func setupFormWithDefaults(observation: Observation, form: Form) -> [String: AnyHashable] {
guard let formId = form.formId?.intValue else {
return [:]
}
var newForm: [String: AnyHashable] = [EventKey.formId.key: formId];
let defaults: FormDefaults = FormDefaults(eventId: observation.eventId as! Int, formId: formId);
let formDefaults: [String: AnyHashable] = defaults.getDefaults() as! [String: AnyHashable];
let fields: [[String : AnyHashable]] = (form.fields ?? []).filter { (($0[FieldKey.archived.key] as? Bool) == nil || ($0[FieldKey.archived.key] as? Bool) == false) };
if (formDefaults.count > 0) { // user defaults
for (_, field) in fields.enumerated() {
var value: AnyHashable? = nil;
if let defaultField: AnyHashable = formDefaults[field[FieldKey.name.key] as! String] {
value = defaultField
}
if (value != nil) {
newForm[field[FieldKey.name.key] as! String] = value;
}
}
} else { // server defaults
for (_, field) in fields.enumerated() {
// grab the server default from the form fields value property
if let value: AnyHashable = field[FieldKey.value.key] {
newForm[field[FieldKey.name.key] as! String] = value;
}
}
}
return newForm;
}
func addFormToObservation(observation: Observation, form: Form) {
var observationProperties: [String: Any] = [ObservationKey.forms.key:[]];
var observationForms: [[String: Any]] = [];
if let properties = observation.properties as? [String: Any] {
if (properties.keys.contains(ObservationKey.forms.key)) {
observationForms = properties[ObservationKey.forms.key] as! [[String: Any]];
}
observationProperties = properties;
}
observationForms.append(setupFormWithDefaults(observation: observation, form: form));
observationProperties[ObservationKey.forms.key] = observationForms;
observation.properties = observationProperties;
}
func addRequiredForms(observation: Observation) {
// ignore archived forms when adding required forms
for eventForm in eventForms where !eventForm.archived {
let eventFormMin: Int = eventForm.min ?? 0;
if (eventFormMin > 0) {
for _ in 1...eventFormMin {
addFormToObservation(observation: observation, form: eventForm);
}
} else if eventForm.isDefault {
addFormToObservation(observation: observation, form: eventForm);
}
}
}
}
extension ObservationEditCoordinator: FormPickedDelegate {
func formPicked(form: Form) {
observationEditController?.formAdded(form: form);
bottomSheet?.dismiss(animated: true, completion: nil);
bottomSheet = nil;
}
func cancelSelection() {
bottomSheet?.dismiss(animated: true, completion: nil);
bottomSheet = nil;
}
}
extension ObservationEditCoordinator: FieldSelectionDelegate {
func launchFieldSelectionViewController(viewController: UIViewController) {
self.navigationController?.pushViewController(viewController, animated: true);
}
}
extension ObservationEditCoordinator: ObservationFormReorderDelegate {
func formsReordered(observation: Observation) {
self.observation = observation;
if let user = user {
self.observation!.userId = user.remoteId;
}
if let observationEditController = self.observationEditController {
observationEditController.formsReordered(observation: self.observation!);
self.navigationController?.popViewController(animated: true);
} else {
self.managedObjectContext.mr_saveToPersistentStore { [self] (contextDidSave, error) in
if (!contextDidSave) {
print("Error saving observation to persistent store, context did not save");
}
if let safeError = error {
print("Error saving observation to persistent store \(safeError)");
}
delegate?.editComplete(self.observation!, coordinator: self as NSObject);
self.navigationController?.dismiss(animated: true, completion: nil);
}
}
}
func cancelReorder() {
if (self.observationEditController != nil) {
self.navigationController?.popViewController(animated: true);
} else {
self.managedObjectContext.reset();
self.navigationController?.dismiss(animated: true, completion: nil);
}
}
}
extension ObservationEditCoordinator: ObservationEditCardDelegate {
func reorderForms(observation: Observation) {
self.observationFormReorder = ObservationFormReorder(observation: observation, delegate: self, containerScheme: self.scheme);
self.navigationController?.pushViewController(self.observationFormReorder!, animated: true);
}
func addForm() {
let forms: [Form] = event?.nonArchivedForms ?? []
let formPicker: FormPickerViewController = FormPickerViewController(delegate: self, forms: forms, observation: observation, scheme: self.scheme);
formPicker.applyTheme(withScheme: scheme);
bottomSheet = MDCBottomSheetController(contentViewController: formPicker);
bottomSheet?.trackingScrollView = formPicker.collectionView
self.navigationController?.present(bottomSheet!, animated: true, completion: nil);
}
func saveObservation(observation: Observation) {
print("Save observation");
if let user = user {
self.observation!.userId = user.remoteId;
}
self.managedObjectContext.mr_saveToPersistentStore { [self] (contextDidSave, error) in
if (!contextDidSave) {
print("Error saving observation to persistent store, context did not save");
}
if let safeError = error {
print("Error saving observation to persistent store \(safeError)");
}
print("Saved the observation \(observation.remoteId ?? "")");
delegate?.editComplete(observation, coordinator: self as NSObject);
rootViewController?.dismiss(animated: true, completion: nil);
observationEditController = nil;
navigationController = nil;
}
}
func cancelEdit() {
print("Cancel the edit")
let alert = UIAlertController(title: "Discard Changes", message: "Do you want to discard your changes?", preferredStyle: .alert);
alert.addAction(UIAlertAction(title: "Yes, Discard", style: .destructive, handler: { [self] (action) in
self.navigationController?.dismiss(animated: true, completion: nil);
self.managedObjectContext.reset();
delegate?.editCancel(self as NSObject);
observationEditController = nil;
navigationController = nil;
}));
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil));
self.navigationController?.present(alert, animated: true, completion: nil);
}
}
| apache-2.0 | 4bb0a353ab3d83c367b62088ae7a5ab5 | 46.222222 | 193 | 0.656471 | 5.442737 | false | false | false | false |
nakau1/Formations | Formations/Sources/Models/IdentifierGeneratable.swift | 1 | 875 | // =============================================================================
// Formations
// Copyright 2017 yuichi.nakayasu All rights reserved.
// =============================================================================
import Foundation
protocol IdentifierGeneratable {}
extension IdentifierGeneratable {
func generateIdentifier() -> String {
let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let count = chars.characters.count
let ret = (0..<54).reduce("") { res, _ in
let distance = String.IndexDistance(arc4random_uniform(UInt32(count)))
let s = chars.index(chars.startIndex, offsetBy: distance)
let e = chars.index(chars.startIndex, offsetBy: distance + 1)
return res + chars[s..<e]
}
return ret + "\(UInt64(Date().timeIntervalSince1970))"
}
}
| apache-2.0 | ed2d027cc042cafa0288e656b5ba779a | 37.043478 | 82 | 0.518857 | 5.271084 | false | false | false | false |
jbannister/RoyalOfUr | GameOfUr/GameOfUr/RandomController.swift | 1 | 3126 | //
// RandomController.swift
// GameOfUr
//
// Created by Jan Bannister on 09/06/2017.
// Copyright © 2017 Jan Bannister. All rights reserved.
//
import UIKit
class RandomController: UIViewController {
var game : GameUrDatabase!
var autoID : String!
let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
@IBOutlet weak var randomPlayerButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
GameUrDatabase.beginDatabase { (game, autoID) in
if (game != nil) {
//Others
print("game: \(game)")
self.game = game
} else {
//Mine
print("autoId: \(autoID)")
self.autoID = autoID
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction func signOutToggle(_ sender: UIBarButtonItem) {
appDelegate.signOut()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "LoginGameOfUr")
self.present(controller, animated: true, completion: nil)
}
// MARK: - Navigation
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if identifier == "randomPlayerCreate" {
if randomPlayerButton.currentTitle == "Random Player" {
self.randomPlayerButton.setTitle("Cancel...", for: .normal)
if self.game == nil {
self.game = GameUrDatabase.createGameUrDatabase(autoID: autoID)
self.game.randomPlayerDatabase(callback: {
self.randomPlayerButton.setTitle("Random Player", for: .normal)
self.performSegue(withIdentifier: "randomPlayerCreate", sender: nil)
})
return false
} else {
self.game.randomPlayerDatabase(callback: {
self.randomPlayerButton.setTitle("Random Player", for: .normal)
})
return true
}
} else {
self.randomPlayerButton.setTitle("Random Player", for: .normal)
return false
}
}
return true
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
switch segue.identifier! {
case "randomPlayerCreate":
let navcon = segue.destination as! UINavigationController
let dest = navcon.visibleViewController as! GameOfUrController
dest.update(game: game)
default: break
}
}
}
| mit | ab7c2bc78855741edf0d3614233ef517 | 33.340659 | 106 | 0.55936 | 5.360206 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionUI/EnterAmount/AmountTranslationView/AmountTranslationPriceProvider.swift | 1 | 3002 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import MoneyKit
import PlatformKit
import PlatformUIKit
import RxSwift
import ToolKit
final class AmountTranslationPriceProvider: AmountTranslationPriceProviding {
private let transactionModel: TransactionModel
init(transactionModel: TransactionModel) {
self.transactionModel = transactionModel
}
func pairFromFiatInput(
cryptoCurrency: CryptoCurrency,
fiatCurrency: FiatCurrency,
amount: String
) -> Single<MoneyValuePair> {
transactionModel
.state
.compactMap(\.amountExchangeRateForTradingUsingFiatAsInput)
.map { exchangeRate -> MoneyValuePair in
let amount = amount.isEmpty ? "0" : amount
let moneyValue = MoneyValue.create(majorDisplay: amount, currency: fiatCurrency.currencyType)!
return MoneyValuePair(base: moneyValue, exchangeRate: exchangeRate)
}
.take(1)
.asSingle()
}
func pairFromCryptoInput(
cryptoCurrency: CryptoCurrency,
fiatCurrency: FiatCurrency,
amount: String
) -> Single<MoneyValuePair> {
transactionModel
.state
.compactMap(\.amountExchangeRateForTradingUsingCryptoAsInput)
.map { exchangeRate -> MoneyValuePair in
let amount = amount.isEmpty ? "0" : amount
let moneyValue = MoneyValue.create(majorDisplay: amount, currency: cryptoCurrency.currencyType)!
return MoneyValuePair(base: moneyValue, exchangeRate: exchangeRate)
}
.take(1)
.asSingle()
}
}
extension TransactionState {
fileprivate var amountExchangeRateForTradingUsingFiatAsInput: MoneyValue? {
let exchangeRate: MoneyValue?
switch action {
case .buy:
// the input refers to the destination but needs to expressed in fiat, so the exchange rate must be fiat -> destination
// source is always fiat for buy
exchangeRate = exchangeRates?.sourceToDestinationTradingCurrencyRate
default:
// the input refers to the source account, so the exchange rate must be fiat -> source
exchangeRate = exchangeRates?.fiatTradingCurrencyToSourceRate
}
return exchangeRate
}
fileprivate var amountExchangeRateForTradingUsingCryptoAsInput: MoneyValue? {
let exchangeRate: MoneyValue?
switch action {
case .buy:
// the input refers to the destination account and the input is in that account's currency.
exchangeRate = exchangeRates?.destinationToFiatTradingCurrencyRate
default:
// the source may be in crypto or fiat, if source is fiat, the fiat -> fiat rate will be one, the crypto -> fiat rate otherwise.
exchangeRate = exchangeRates?.sourceToFiatTradingCurrencyRate
}
return exchangeRate
}
}
| lgpl-3.0 | d6d6e167b791f983422bd58535991aae | 36.5125 | 140 | 0.659114 | 5.651601 | false | false | false | false |
460467069/smzdm | 什么值得买7.1.1版本/什么值得买(5月12日)/Classes/GoodArticle(好文)/SectionController/ZZChoicenessListSectionController.swift | 1 | 8108 | //
// ZZChoicenessListSectionController.swift
// 什么值得买
//
// Created by Wang_ruzhou on 2017/9/8.
// Copyright © 2017年 Wang_ruzhou. All rights reserved.
//
import UIKit
import IGListKit
class ZZChoicenessListSectionController: ListSectionController {
lazy var adapter: ListAdapter = {
let adapter = ListAdapter.init(updater: ListAdapterUpdater(), viewController: self.viewController)
adapter.dataSource = self
return adapter
}()
var listModel: ZZListModel?
lazy var dataSource: [ZZListModel] = {
let dataSource = [ZZListModel]()
return dataSource
}()
override init() {
super.init()
supplementaryViewSource = self
}
override func numberOfItems() -> Int {
if let count = listModel?.subItems.count {
return count
}
return 0
}
override func sizeForItem(at index: Int) -> CGSize {
let list = listModel?.subItems as! [ZZChoicenessListModel]
let choicenessModel = list[index]
let cellType = choicenessModel.cell_type
var height:CGFloat = 270
let promotion_type = choicenessModel.promotion_type
if promotion_type == "6" {
height = 225
} else if promotion_type == "9" {
height = 205
} else {
if cellType == "41" {
height = 200
} else if cellType == "30" {
height = 150
} else if cellType == "38" {
height = 150
}
}
return CGSize(width: collectionContext!.containerSize.width, height: height)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
let list = listModel?.subItems as! [ZZChoicenessListModel]
let choicenessModel = list[index]
let cellType = choicenessModel.cell_type
let promotion_type = choicenessModel.promotion_type
if promotion_type == "6" {
guard let cell = collectionContext?.dequeueReusableCell(withNibName: "ZZPromotionType6Cell",
bundle: nil,
for: self,
at: index) as? ZZPromotionType6Cell else {
fatalError()
}
let promotionType6Model = ZZListModel.init(subItems: choicenessModel.yc_rows,
sectionController: ZZPromotionType6SectionController())
dataSource.removeAll()
dataSource.append(promotionType6Model!)
cell.choicenessModel = choicenessModel
adapter.collectionView = cell.collectionView
adapter.performUpdates(animated: false, completion: nil)
return cell
} else if promotion_type == "9" {
guard let cell = collectionContext?.dequeueReusableCell(withNibName: "ZZPromotionType9Cell",
bundle: nil,
for: self,
at: index) as? ZZPromotionType9Cell else {
fatalError()
}
let promotionType6Model = ZZListModel.init(subItems: choicenessModel.rows,
sectionController: ZZPromotionType9SectionController())
dataSource.removeAll()
dataSource.append(promotionType6Model!)
adapter.collectionView = cell.collectionView
adapter.performUpdates(animated: false, completion: nil)
return cell
}
if cellType == "41" {
guard let cell = collectionContext?.dequeueReusableCell(withNibName: "ZZType41Cell",
bundle: nil,
for: self,
at: index) as? ZZType41Cell else {
fatalError()
}
cell.choicenessModel = choicenessModel
return cell
} else if cellType == "30" {
guard let cell = collectionContext?.dequeueReusableCell(withNibName: "ZZType30Cell",
bundle: nil,
for: self,
at: index) as? ZZType30Cell else {
fatalError()
}
cell.article = choicenessModel.article?.first
return cell
} else if cellType == "38" {
guard let cell = collectionContext?.dequeueReusableCell(withNibName: "ZZType38Cell",
bundle: nil,
for: self,
at: index) as? ZZType38Cell else {
fatalError()
}
cell.choicenessModel = choicenessModel
return cell
}
guard let cell = collectionContext?.dequeueReusableCell(withNibName: "ZZChoicenessListCell",
bundle: nil,
for: self,
at: index) as? ZZChoicenessListCell else {
fatalError()
}
cell.article = choicenessModel.article?.first
return cell
}
override func didUpdate(to object: Any) {
if let model = object as? ZZListModel {
listModel = model
}
}
}
extension ZZChoicenessListSectionController: ListSupplementaryViewSource{
func supportedElementKinds() -> [String] {
return [UICollectionView.elementKindSectionHeader]
}
func viewForSupplementaryElement(ofKind elementKind: String, at index: Int) -> UICollectionReusableView {
guard let view = collectionContext?.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader,
for: self,
nibName: "ZZTopicHeaderView",
bundle: nil,
at: index) as? ZZTopicHeaderView else {
fatalError()
}
view.titleLabel.text = "好文推荐"
view.moreBtn.isHidden = true
return view
}
func sizeForSupplementaryView(ofKind elementKind: String, at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 60)
}
}
extension ZZChoicenessListSectionController: ListAdapterDataSource {
func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
return dataSource
}
func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
guard let listModel = object as? ZZListModel else { fatalError() }
return listModel.sectionController
}
func emptyView(for listAdapter: ListAdapter) -> UIView? {
return nil
}
}
| mit | 99924c1f4dc7156cb5754f3c9bb12771 | 44.432584 | 127 | 0.469519 | 6.824473 | false | false | false | false |
lerigos/music-service | iOS_9/Pods/ActiveLabel/ActiveLabel/ActiveLabel.swift | 1 | 15739 | //
// ActiveLabel.swift
// ActiveLabel
//
// Created by Johannes Schickling on 9/4/15.
// Copyright © 2015 Optonaut. All rights reserved.
//
import Foundation
import UIKit
public protocol ActiveLabelDelegate: class {
func didSelectText(text: String, type: ActiveType)
}
@IBDesignable public class ActiveLabel: UILabel {
// MARK: - public properties
public weak var delegate: ActiveLabelDelegate?
@IBInspectable public var mentionColor: UIColor = .blueColor() {
didSet { updateTextStorage(parseText: false) }
}
@IBInspectable public var mentionSelectedColor: UIColor? {
didSet { updateTextStorage(parseText: false) }
}
@IBInspectable public var hashtagColor: UIColor = .blueColor() {
didSet { updateTextStorage(parseText: false) }
}
@IBInspectable public var hashtagSelectedColor: UIColor? {
didSet { updateTextStorage(parseText: false) }
}
@IBInspectable public var URLColor: UIColor = .blueColor() {
didSet { updateTextStorage(parseText: false) }
}
@IBInspectable public var URLSelectedColor: UIColor? {
didSet { updateTextStorage(parseText: false) }
}
@IBInspectable public var lineSpacing: Float = 0 {
didSet { updateTextStorage(parseText: false) }
}
// MARK: - public methods
public func handleMentionTap(handler: (String) -> ()) {
mentionTapHandler = handler
}
public func handleHashtagTap(handler: (String) -> ()) {
hashtagTapHandler = handler
}
public func handleURLTap(handler: (NSURL) -> ()) {
urlTapHandler = handler
}
public func filterMention(predicate: (String) -> Bool) {
mentionFilterPredicate = predicate
updateTextStorage()
}
public func filterHashtag(predicate: (String) -> Bool) {
hashtagFilterPredicate = predicate
updateTextStorage()
}
// MARK: - override UILabel properties
override public var text: String? {
didSet { updateTextStorage() }
}
override public var attributedText: NSAttributedString? {
didSet { updateTextStorage() }
}
override public var font: UIFont! {
didSet { updateTextStorage(parseText: false) }
}
override public var textColor: UIColor! {
didSet { updateTextStorage(parseText: false) }
}
override public var textAlignment: NSTextAlignment {
didSet { updateTextStorage(parseText: false)}
}
public override var numberOfLines: Int {
didSet { textContainer.maximumNumberOfLines = numberOfLines }
}
public override var lineBreakMode: NSLineBreakMode {
didSet { textContainer.lineBreakMode = lineBreakMode }
}
// MARK: - init functions
override public init(frame: CGRect) {
super.init(frame: frame)
_customizing = false
setupLabel()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_customizing = false
setupLabel()
}
public override func awakeFromNib() {
super.awakeFromNib()
updateTextStorage()
}
public override func drawTextInRect(rect: CGRect) {
let range = NSRange(location: 0, length: textStorage.length)
textContainer.size = rect.size
let newOrigin = textOrigin(inRect: rect)
layoutManager.drawBackgroundForGlyphRange(range, atPoint: newOrigin)
layoutManager.drawGlyphsForGlyphRange(range, atPoint: newOrigin)
}
// MARK: - customzation
public func customize(block: (label: ActiveLabel) -> ()) -> ActiveLabel{
_customizing = true
block(label: self)
_customizing = false
updateTextStorage()
return self
}
// MARK: - Auto layout
public override func intrinsicContentSize() -> CGSize {
let superSize = super.intrinsicContentSize()
textContainer.size = CGSize(width: superSize.width, height: CGFloat.max)
let size = layoutManager.usedRectForTextContainer(textContainer)
return CGSize(width: ceil(size.width), height: ceil(size.height))
}
// MARK: - touch events
func onTouch(touch: UITouch) -> Bool {
let location = touch.locationInView(self)
var avoidSuperCall = false
switch touch.phase {
case .Began, .Moved:
if let element = elementAtLocation(location) {
if element.range.location != selectedElement?.range.location || element.range.length != selectedElement?.range.length {
updateAttributesWhenSelected(false)
selectedElement = element
updateAttributesWhenSelected(true)
}
avoidSuperCall = true
} else {
updateAttributesWhenSelected(false)
selectedElement = nil
}
case .Ended:
guard let selectedElement = selectedElement else { return avoidSuperCall }
switch selectedElement.element {
case .Mention(let userHandle): didTapMention(userHandle)
case .Hashtag(let hashtag): didTapHashtag(hashtag)
case .URL(let url): didTapStringURL(url)
case .None: ()
}
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC)))
dispatch_after(when, dispatch_get_main_queue()) {
self.updateAttributesWhenSelected(false)
self.selectedElement = nil
}
avoidSuperCall = true
case .Cancelled:
updateAttributesWhenSelected(false)
selectedElement = nil
case .Stationary:
break
}
return avoidSuperCall
}
// MARK: - private properties
private var _customizing: Bool = true
private var mentionTapHandler: ((String) -> ())?
private var hashtagTapHandler: ((String) -> ())?
private var urlTapHandler: ((NSURL) -> ())?
private var mentionFilterPredicate: ((String) -> Bool)?
private var hashtagFilterPredicate: ((String) -> Bool)?
private var selectedElement: (range: NSRange, element: ActiveElement)?
private var heightCorrection: CGFloat = 0
private lazy var textStorage = NSTextStorage()
private lazy var layoutManager = NSLayoutManager()
private lazy var textContainer = NSTextContainer()
internal lazy var activeElements: [ActiveType: [(range: NSRange, element: ActiveElement)]] = [
.Mention: [],
.Hashtag: [],
.URL: [],
]
// MARK: - helper functions
private func setupLabel() {
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
textContainer.lineFragmentPadding = 0
textContainer.lineBreakMode = lineBreakMode
textContainer.maximumNumberOfLines = numberOfLines
userInteractionEnabled = true
}
private func updateTextStorage(parseText parseText: Bool = true) {
if _customizing { return }
// clean up previous active elements
guard let attributedText = attributedText where attributedText.length > 0 else {
clearActiveElements()
textStorage.setAttributedString(NSAttributedString())
setNeedsDisplay()
return
}
let mutAttrString = addLineBreak(attributedText)
if parseText {
clearActiveElements()
parseTextAndExtractActiveElements(mutAttrString)
}
self.addLinkAttribute(mutAttrString)
self.textStorage.setAttributedString(mutAttrString)
self.setNeedsDisplay()
}
private func clearActiveElements() {
selectedElement = nil
for (type, _) in activeElements {
activeElements[type]?.removeAll()
}
}
private func textOrigin(inRect rect: CGRect) -> CGPoint {
let usedRect = layoutManager.usedRectForTextContainer(textContainer)
heightCorrection = (rect.height - usedRect.height)/2
let glyphOriginY = heightCorrection > 0 ? rect.origin.y + heightCorrection : rect.origin.y
return CGPoint(x: rect.origin.x, y: glyphOriginY)
}
/// add link attribute
private func addLinkAttribute(mutAttrString: NSMutableAttributedString) {
var range = NSRange(location: 0, length: 0)
var attributes = mutAttrString.attributesAtIndex(0, effectiveRange: &range)
attributes[NSFontAttributeName] = font!
attributes[NSForegroundColorAttributeName] = textColor
mutAttrString.addAttributes(attributes, range: range)
attributes[NSForegroundColorAttributeName] = mentionColor
for (type, elements) in activeElements {
switch type {
case .Mention: attributes[NSForegroundColorAttributeName] = mentionColor
case .Hashtag: attributes[NSForegroundColorAttributeName] = hashtagColor
case .URL: attributes[NSForegroundColorAttributeName] = URLColor
case .None: ()
}
for element in elements {
mutAttrString.setAttributes(attributes, range: element.range)
}
}
}
/// use regex check all link ranges
private func parseTextAndExtractActiveElements(attrString: NSAttributedString) {
let textString = attrString.string
let textLength = textString.utf16.count
let textRange = NSRange(location: 0, length: textLength)
//URLS
let urlElements = ActiveBuilder.createURLElements(fromText: textString, range: textRange)
activeElements[.URL]?.appendContentsOf(urlElements)
//HASHTAGS
let hashtagElements = ActiveBuilder.createHashtagElements(fromText: textString, range: textRange, filterPredicate: hashtagFilterPredicate)
activeElements[.Hashtag]?.appendContentsOf(hashtagElements)
//MENTIONS
let mentionElements = ActiveBuilder.createMentionElements(fromText: textString, range: textRange, filterPredicate: mentionFilterPredicate)
activeElements[.Mention]?.appendContentsOf(mentionElements)
}
/// add line break mode
private func addLineBreak(attrString: NSAttributedString) -> NSMutableAttributedString {
let mutAttrString = NSMutableAttributedString(attributedString: attrString)
var range = NSRange(location: 0, length: 0)
var attributes = mutAttrString.attributesAtIndex(0, effectiveRange: &range)
let paragraphStyle = attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping
paragraphStyle.alignment = textAlignment
paragraphStyle.lineSpacing = CGFloat(lineSpacing)
attributes[NSParagraphStyleAttributeName] = paragraphStyle
mutAttrString.setAttributes(attributes, range: range)
return mutAttrString
}
private func updateAttributesWhenSelected(isSelected: Bool) {
guard let selectedElement = selectedElement else {
return
}
var attributes = textStorage.attributesAtIndex(0, effectiveRange: nil)
if isSelected {
switch selectedElement.element {
case .Mention(_): attributes[NSForegroundColorAttributeName] = mentionSelectedColor ?? mentionColor
case .Hashtag(_): attributes[NSForegroundColorAttributeName] = hashtagSelectedColor ?? hashtagColor
case .URL(_): attributes[NSForegroundColorAttributeName] = URLSelectedColor ?? URLColor
case .None: ()
}
} else {
switch selectedElement.element {
case .Mention(_): attributes[NSForegroundColorAttributeName] = mentionColor
case .Hashtag(_): attributes[NSForegroundColorAttributeName] = hashtagColor
case .URL(_): attributes[NSForegroundColorAttributeName] = URLColor
case .None: ()
}
}
textStorage.addAttributes(attributes, range: selectedElement.range)
setNeedsDisplay()
}
private func elementAtLocation(location: CGPoint) -> (range: NSRange, element: ActiveElement)? {
guard textStorage.length > 0 else {
return nil
}
var correctLocation = location
correctLocation.y -= heightCorrection
let boundingRect = layoutManager.boundingRectForGlyphRange(NSRange(location: 0, length: textStorage.length), inTextContainer: textContainer)
guard boundingRect.contains(correctLocation) else {
return nil
}
let index = layoutManager.glyphIndexForPoint(correctLocation, inTextContainer: textContainer)
for element in activeElements.map({ $0.1 }).flatten() {
if index >= element.range.location && index <= element.range.location + element.range.length {
return element
}
}
return nil
}
//MARK: - Handle UI Responder touches
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else { return }
if onTouch(touch) { return }
super.touchesBegan(touches, withEvent: event)
}
public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else { return }
if onTouch(touch) { return }
super.touchesMoved(touches, withEvent: event)
}
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
guard let touch = touches?.first else { return }
onTouch(touch)
super.touchesCancelled(touches, withEvent: event)
}
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else { return }
if onTouch(touch) { return }
super.touchesEnded(touches, withEvent: event)
}
//MARK: - ActiveLabel handler
private func didTapMention(username: String) {
guard let mentionHandler = mentionTapHandler else {
delegate?.didSelectText(username, type: .Mention)
return
}
mentionHandler(username)
}
private func didTapHashtag(hashtag: String) {
guard let hashtagHandler = hashtagTapHandler else {
delegate?.didSelectText(hashtag, type: .Hashtag)
return
}
hashtagHandler(hashtag)
}
private func didTapStringURL(stringURL: String) {
guard let urlHandler = urlTapHandler, let url = NSURL(string: stringURL) else {
delegate?.didSelectText(stringURL, type: .URL)
return
}
urlHandler(url)
}
}
extension ActiveLabel: UIGestureRecognizerDelegate {
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOfGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| apache-2.0 | da01ef5760fce5bfe4bbc699fb8ff681 | 35.515081 | 179 | 0.64716 | 5.681588 | false | false | false | false |
imkevinxu/Spring | Spring/SpringTextField.swift | 1 | 2977 | //
// SpringTextField.swift
// https://github.com/MengTo/Spring
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// 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 SpringTextField: UITextField, Springable {
// MARK: Advanced Values
@IBInspectable public var animation: String = ""
@IBInspectable public var curve: String = ""
@IBInspectable public var autostart: Bool = false
@IBInspectable public var autohide: Bool = false
@IBInspectable public var delay: CGFloat = 0
@IBInspectable public var duration: CGFloat = 0.7
@IBInspectable public var force: CGFloat = 1
@IBInspectable public var damping: CGFloat = 0.7
@IBInspectable public var velocity: CGFloat = 0.7
@IBInspectable public var rotateDegrees: CGFloat = 0
@IBInspectable public var repeatCount: Float = 1
// MARK: Basic Values
@IBInspectable public var x: CGFloat = 0
@IBInspectable public var y: CGFloat = 0
@IBInspectable public var scaleX: CGFloat = 1
@IBInspectable public var scaleY: CGFloat = 1
@IBInspectable public var rotate: CGFloat = 0
public var opacity: CGFloat = 1
public var animateFrom: Bool = false
lazy private var spring: Spring = Spring(self)
// MARK: - View Lifecycle
override public func awakeFromNib() {
super.awakeFromNib()
self.spring.customAwakeFromNib()
}
override public func didMoveToWindow() {
super.didMoveToWindow()
self.spring.customDidMoveToWindow()
}
// MARK: - Animation Methods
public func animate() {
self.spring.animate()
}
public func animateNext(completion: () -> ()) {
self.spring.animateNext(completion)
}
public func animateTo() {
self.spring.animateTo()
}
public func animateToNext(completion: () -> ()) {
self.spring.animateToNext(completion)
}
} | mit | 994ef8b6e07b7b23943a535f81a6acc8 | 33.229885 | 82 | 0.701041 | 4.531202 | false | false | false | false |
Jnosh/swift | stdlib/public/SDK/Foundation/IndexSet.swift | 6 | 40192 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
extension IndexSet.Index {
public static func ==(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool {
return lhs.value == rhs.value
}
public static func <(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool {
return lhs.value < rhs.value
}
public static func <=(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool {
return lhs.value <= rhs.value
}
public static func >(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool {
return lhs.value > rhs.value
}
public static func >=(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool {
return lhs.value >= rhs.value
}
}
extension IndexSet.RangeView {
public static func ==(lhs: IndexSet.RangeView, rhs: IndexSet.RangeView) -> Bool {
return lhs.startIndex == rhs.startIndex && lhs.endIndex == rhs.endIndex && lhs.indexSet == rhs.indexSet
}
}
/// Manages a `Set` of integer values, which are commonly used as an index type in Cocoa API.
///
/// The range of valid integer values is 0..<INT_MAX-1. Anything outside this range is an error.
public struct IndexSet : ReferenceConvertible, Equatable, BidirectionalCollection, SetAlgebra {
/// An view of the contents of an IndexSet, organized by range.
///
/// For example, if an IndexSet is composed of:
/// `[1..<5]` and `[7..<10]` and `[13]`
/// then calling `next()` on this view's iterator will produce 3 ranges before returning nil.
public struct RangeView : Equatable, BidirectionalCollection {
public typealias Index = Int
public let startIndex: Index
public let endIndex: Index
fileprivate var indexSet: IndexSet
// Range of element values
private var intersectingRange : Range<IndexSet.Element>?
fileprivate init(indexSet : IndexSet, intersecting range : Range<IndexSet.Element>?) {
self.indexSet = indexSet
self.intersectingRange = range
if let r = range {
if r.lowerBound == r.upperBound {
startIndex = 0
endIndex = 0
} else {
let minIndex = indexSet._indexOfRange(containing: r.lowerBound)
let maxIndex = indexSet._indexOfRange(containing: r.upperBound)
switch (minIndex, maxIndex) {
case (nil, nil):
startIndex = 0
endIndex = 0
case (nil, .some(let max)):
// Start is before our first range
startIndex = 0
endIndex = max + 1
case (.some(let min), nil):
// End is after our last range
startIndex = min
endIndex = indexSet._rangeCount
case (.some(let min), .some(let max)):
startIndex = min
endIndex = max + 1
}
}
} else {
startIndex = 0
endIndex = indexSet._rangeCount
}
}
public func makeIterator() -> IndexingIterator<RangeView> {
return IndexingIterator(_elements: self)
}
public subscript(index : Index) -> CountableRange<IndexSet.Element> {
let indexSetRange = indexSet._range(at: index)
if let intersectingRange = intersectingRange {
return Swift.max(intersectingRange.lowerBound, indexSetRange.lowerBound)..<Swift.min(intersectingRange.upperBound, indexSetRange.upperBound)
} else {
return indexSetRange.lowerBound..<indexSetRange.upperBound
}
}
public subscript(bounds: Range<Index>) -> BidirectionalSlice<RangeView> {
return BidirectionalSlice(base: self, bounds: bounds)
}
public func index(after i: Index) -> Index {
return i + 1
}
public func index(before i: Index) -> Index {
return i - 1
}
}
/// The mechanism for accessing the integers stored in an IndexSet.
public struct Index : CustomStringConvertible, Comparable {
fileprivate var value: IndexSet.Element
fileprivate var extent: Range<IndexSet.Element>
fileprivate var rangeIndex: Int
fileprivate let rangeCount: Int
fileprivate init(value: Int, extent: Range<Int>, rangeIndex: Int, rangeCount: Int) {
self.value = value
self.extent = extent
self.rangeCount = rangeCount
self.rangeIndex = rangeIndex
}
public var description: String {
return "index \(value) in a range of \(extent) [range #\(rangeIndex + 1)/\(rangeCount)]"
}
}
public typealias ReferenceType = NSIndexSet
public typealias Element = Int
fileprivate var _handle: _MutablePairHandle<NSIndexSet, NSMutableIndexSet>
/// Initialize an `IndexSet` with a range of integers.
public init(integersIn range: Range<Element>) {
_handle = _MutablePairHandle(NSIndexSet(indexesIn: _toNSRange(range)), copying: false)
}
/// Initialize an `IndexSet` with a range of integers.
public init(integersIn range: ClosedRange<Element>) { self.init(integersIn: Range(range)) }
/// Initialize an `IndexSet` with a range of integers.
public init(integersIn range: CountableClosedRange<Element>) { self.init(integersIn: Range(range)) }
/// Initialize an `IndexSet` with a range of integers.
public init(integersIn range: CountableRange<Element>) { self.init(integersIn: Range(range)) }
/// Initialize an `IndexSet` with a single integer.
public init(integer: Element) {
_handle = _MutablePairHandle(NSIndexSet(index: integer), copying: false)
}
/// Initialize an empty `IndexSet`.
public init() {
_handle = _MutablePairHandle(NSIndexSet(), copying: false)
}
public var hashValue: Int {
return _handle.map { $0.hash }
}
/// Returns the number of integers in `self`.
public var count: Int {
return _handle.map { $0.count }
}
public func makeIterator() -> IndexingIterator<IndexSet> {
return IndexingIterator(_elements: self)
}
/// Returns a `Range`-based view of the entire contents of `self`.
///
/// - seealso: rangeView(of:)
public var rangeView: RangeView {
return RangeView(indexSet: self, intersecting: nil)
}
/// Returns a `Range`-based view of `self`.
///
/// - parameter range: A subrange of `self` to view.
public func rangeView(of range : Range<Element>) -> RangeView {
return RangeView(indexSet: self, intersecting: range)
}
/// Returns a `Range`-based view of `self`.
///
/// - parameter range: A subrange of `self` to view.
public func rangeView(of range : ClosedRange<Element>) -> RangeView { return self.rangeView(of: Range(range)) }
/// Returns a `Range`-based view of `self`.
///
/// - parameter range: A subrange of `self` to view.
public func rangeView(of range : CountableClosedRange<Element>) -> RangeView { return self.rangeView(of: Range(range)) }
/// Returns a `Range`-based view of `self`.
///
/// - parameter range: A subrange of `self` to view.
public func rangeView(of range : CountableRange<Element>) -> RangeView { return self.rangeView(of: Range(range)) }
private func _indexOfRange(containing integer : Element) -> RangeView.Index? {
let result = _handle.map {
__NSIndexSetIndexOfRangeContainingIndex($0, integer)
}
if result == NSNotFound {
return nil
} else {
return Int(result)
}
}
private func _range(at index: RangeView.Index) -> Range<Element> {
return _handle.map {
var location: Int = 0
var length: Int = 0
__NSIndexSetRangeAtIndex($0, index, &location, &length)
return Int(location)..<Int(location)+Int(length)
}
}
private var _rangeCount : Int {
return _handle.map {
Int(__NSIndexSetRangeCount($0))
}
}
public var startIndex: Index {
let rangeCount = _rangeCount
if rangeCount > 0 {
// If this winds up being NSNotFound, that's ok because then endIndex is also NSNotFound, and empty collections have startIndex == endIndex
let extent = _range(at: 0)
return Index(value: extent.lowerBound, extent: extent, rangeIndex: 0, rangeCount: _rangeCount)
} else {
return Index(value: 0, extent: 0..<0, rangeIndex: -1, rangeCount: rangeCount)
}
}
public var endIndex: Index {
let rangeCount = _rangeCount
let rangeIndex = rangeCount - 1
let extent: Range<Int>
let value: Int
if rangeCount > 0 {
extent = _range(at: rangeCount - 1)
value = extent.upperBound // "1 past the end" position is the last range, 1 + the end of that range's extent
} else {
extent = 0..<0
value = 0
}
return Index(value: value, extent: extent, rangeIndex: rangeIndex, rangeCount: rangeCount)
}
public subscript(index : Index) -> Element {
return index.value
}
public subscript(bounds: Range<Index>) -> BidirectionalSlice<IndexSet> {
return BidirectionalSlice(base: self, bounds: bounds)
}
// We adopt the default implementation of subscript(range: Range<Index>) from MutableCollection
private func _toOptional(_ x : Int) -> Int? {
if x == NSNotFound { return nil } else { return x }
}
/// Returns the first integer in `self`, or nil if `self` is empty.
public var first: Element? {
return _handle.map { _toOptional($0.firstIndex) }
}
/// Returns the last integer in `self`, or nil if `self` is empty.
public var last: Element? {
return _handle.map { _toOptional($0.lastIndex) }
}
/// Returns an integer contained in `self` which is greater than `integer`, or `nil` if a result could not be found.
public func integerGreaterThan(_ integer: Element) -> Element? {
return _handle.map { _toOptional($0.indexGreaterThanIndex(integer)) }
}
/// Returns an integer contained in `self` which is less than `integer`, or `nil` if a result could not be found.
public func integerLessThan(_ integer: Element) -> Element? {
return _handle.map { _toOptional($0.indexLessThanIndex(integer)) }
}
/// Returns an integer contained in `self` which is greater than or equal to `integer`, or `nil` if a result could not be found.
public func integerGreaterThanOrEqualTo(_ integer: Element) -> Element? {
return _handle.map { _toOptional($0.indexGreaterThanOrEqual(to: integer)) }
}
/// Returns an integer contained in `self` which is less than or equal to `integer`, or `nil` if a result could not be found.
public func integerLessThanOrEqualTo(_ integer: Element) -> Element? {
return _handle.map { _toOptional($0.indexLessThanOrEqual(to: integer)) }
}
/// Return a `Range<IndexSet.Index>` which can be used to subscript the index set.
///
/// The resulting range is the range of the intersection of the integers in `range` with the index set. The resulting range will be `isEmpty` if the intersection is empty.
///
/// - parameter range: The range of integers to include.
public func indexRange(in range: Range<Element>) -> Range<Index> {
guard !range.isEmpty, let first = first, let last = last else {
let i = _index(ofInteger: 0)
return i..<i
}
if range.lowerBound > last || (range.upperBound - 1) < first {
let i = _index(ofInteger: 0)
return i..<i
}
if let start = integerGreaterThanOrEqualTo(range.lowerBound), let end = integerLessThanOrEqualTo(range.upperBound - 1) {
let resultFirst = _index(ofInteger: start)
let resultLast = _index(ofInteger: end)
return resultFirst..<index(after: resultLast)
} else {
let i = _index(ofInteger: 0)
return i..<i
}
}
/// Return a `Range<IndexSet.Index>` which can be used to subscript the index set.
///
/// The resulting range is the range of the intersection of the integers in `range` with the index set.
///
/// - parameter range: The range of integers to include.
public func indexRange(in range: CountableRange<Element>) -> Range<Index> { return self.indexRange(in: Range(range)) }
/// Return a `Range<IndexSet.Index>` which can be used to subscript the index set.
///
/// The resulting range is the range of the intersection of the integers in `range` with the index set.
///
/// - parameter range: The range of integers to include.
public func indexRange(in range: ClosedRange<Element>) -> Range<Index> { return self.indexRange(in: Range(range)) }
/// Return a `Range<IndexSet.Index>` which can be used to subscript the index set.
///
/// The resulting range is the range of the intersection of the integers in `range` with the index set.
///
/// - parameter range: The range of integers to include.
public func indexRange(in range: CountableClosedRange<Element>) -> Range<Index> { return self.indexRange(in: Range(range)) }
/// Returns the count of integers in `self` that intersect `range`.
public func count(in range: Range<Element>) -> Int {
return _handle.map { $0.countOfIndexes(in: _toNSRange(range)) }
}
/// Returns the count of integers in `self` that intersect `range`.
public func count(in range: CountableRange<Element>) -> Int { return self.count(in: Range(range)) }
/// Returns the count of integers in `self` that intersect `range`.
public func count(in range: ClosedRange<Element>) -> Int { return self.count(in: Range(range)) }
/// Returns the count of integers in `self` that intersect `range`.
public func count(in range: CountableClosedRange<Element>) -> Int { return self.count(in: Range(range)) }
/// Returns `true` if `self` contains `integer`.
public func contains(_ integer: Element) -> Bool {
return _handle.map { $0.contains(integer) }
}
/// Returns `true` if `self` contains all of the integers in `range`.
public func contains(integersIn range: Range<Element>) -> Bool {
return _handle.map { $0.contains(in: _toNSRange(range)) }
}
/// Returns `true` if `self` contains all of the integers in `range`.
public func contains(integersIn range: CountableRange<Element>) -> Bool { return self.contains(integersIn: Range(range)) }
/// Returns `true` if `self` contains all of the integers in `range`.
public func contains(integersIn range: ClosedRange<Element>) -> Bool { return self.contains(integersIn: Range(range)) }
/// Returns `true` if `self` contains all of the integers in `range`.
public func contains(integersIn range: CountableClosedRange<Element>) -> Bool { return self.contains(integersIn: Range(range)) }
/// Returns `true` if `self` contains all of the integers in `indexSet`.
public func contains(integersIn indexSet: IndexSet) -> Bool {
return _handle.map { $0.contains(indexSet) }
}
/// Returns `true` if `self` intersects any of the integers in `range`.
public func intersects(integersIn range: Range<Element>) -> Bool {
return _handle.map { $0.intersects(in: _toNSRange(range)) }
}
/// Returns `true` if `self` intersects any of the integers in `range`.
public func intersects(integersIn range: CountableRange<Element>) -> Bool { return self.intersects(integersIn: Range(range)) }
/// Returns `true` if `self` intersects any of the integers in `range`.
public func intersects(integersIn range: ClosedRange<Element>) -> Bool { return self.intersects(integersIn: Range(range)) }
/// Returns `true` if `self` intersects any of the integers in `range`.
public func intersects(integersIn range: CountableClosedRange<Element>) -> Bool { return self.intersects(integersIn: Range(range)) }
// MARK: -
// Indexable
public func index(after i: Index) -> Index {
if i.value + 1 == i.extent.upperBound {
// Move to the next range
if i.rangeIndex + 1 == i.rangeCount {
// We have no more to go; return a 'past the end' index
return Index(value: i.value + 1, extent: i.extent, rangeIndex: i.rangeIndex, rangeCount: i.rangeCount)
} else {
let rangeIndex = i.rangeIndex + 1
let rangeCount = i.rangeCount
let extent = _range(at: rangeIndex)
let value = extent.lowerBound
return Index(value: value, extent: extent, rangeIndex: rangeIndex, rangeCount: rangeCount)
}
} else {
// Move to the next value in this range
return Index(value: i.value + 1, extent: i.extent, rangeIndex: i.rangeIndex, rangeCount: i.rangeCount)
}
}
public func formIndex(after i: inout Index) {
if i.value + 1 == i.extent.upperBound {
// Move to the next range
if i.rangeIndex + 1 == i.rangeCount {
// We have no more to go; return a 'past the end' index
i.value += 1
} else {
i.rangeIndex += 1
i.extent = _range(at: i.rangeIndex)
i.value = i.extent.lowerBound
}
} else {
// Move to the next value in this range
i.value += 1
}
}
public func index(before i: Index) -> Index {
if i.value == i.extent.lowerBound {
// Move to the next range
if i.rangeIndex == 0 {
// We have no more to go
return Index(value: i.value, extent: i.extent, rangeIndex: i.rangeIndex, rangeCount: i.rangeCount)
} else {
let rangeIndex = i.rangeIndex - 1
let rangeCount = i.rangeCount
let extent = _range(at: rangeIndex)
let value = extent.upperBound - 1
return Index(value: value, extent: extent, rangeIndex: rangeIndex, rangeCount: rangeCount)
}
} else {
// Move to the previous value in this range
return Index(value: i.value - 1, extent: i.extent, rangeIndex: i.rangeIndex, rangeCount: i.rangeCount)
}
}
public func formIndex(before i: inout Index) {
if i.value == i.extent.lowerBound {
// Move to the next range
if i.rangeIndex == 0 {
// We have no more to go
} else {
i.rangeIndex -= 1
i.extent = _range(at: i.rangeIndex)
i.value = i.extent.upperBound - 1
}
} else {
// Move to the previous value in this range
i.value -= 1
}
}
private func _index(ofInteger integer: Element) -> Index {
let rangeCount = _rangeCount
let value = integer
if let rangeIndex = _indexOfRange(containing: integer) {
let extent = _range(at: rangeIndex)
let rangeIndex = rangeIndex
return Index(value: value, extent: extent, rangeIndex: rangeIndex, rangeCount: rangeCount)
} else {
let extent = 0..<0
let rangeIndex = 0
return Index(value: value, extent: Range(extent), rangeIndex: rangeIndex, rangeCount: rangeCount)
}
}
// MARK: -
// MARK: SetAlgebra
/// Union the `IndexSet` with `other`.
public mutating func formUnion(_ other: IndexSet) {
self = self.union(other)
}
/// Union the `IndexSet` with `other`.
public func union(_ other: IndexSet) -> IndexSet {
// This algorithm is naïve but it works. We could avoid calling insert in some cases.
var result = IndexSet()
for r in self.rangeView {
result.insert(integersIn: Range(r))
}
for r in other.rangeView {
result.insert(integersIn: Range(r))
}
return result
}
/// Exclusive or the `IndexSet` with `other`.
public func symmetricDifference(_ other: IndexSet) -> IndexSet {
var result = IndexSet()
var boundaryIterator = IndexSetBoundaryIterator(self, other)
var flag = false
var start = 0
while let i = boundaryIterator.next() {
if !flag {
// Start a range if one set contains but not the other.
if self.contains(i) != other.contains(i) {
flag = true
start = i
}
} else {
// End a range if both sets contain or both sets do not contain.
if self.contains(i) == other.contains(i) {
flag = false
result.insert(integersIn: start..<i)
}
}
// We never have to worry about having flag set to false after exiting this loop because the last boundary is guaranteed to be past the end of ranges in both index sets
}
return result
}
/// Exclusive or the `IndexSet` with `other`.
public mutating func formSymmetricDifference(_ other: IndexSet) {
self = self.symmetricDifference(other)
}
/// Intersect the `IndexSet` with `other`.
public func intersection(_ other: IndexSet) -> IndexSet {
var result = IndexSet()
var boundaryIterator = IndexSetBoundaryIterator(self, other)
var flag = false
var start = 0
while let i = boundaryIterator.next() {
if !flag {
// If both sets contain then start a range.
if self.contains(i) && other.contains(i) {
flag = true
start = i
}
} else {
// If both sets do not contain then end a range.
if !self.contains(i) || !other.contains(i) {
flag = false
result.insert(integersIn: start..<i)
}
}
}
return result
}
/// Intersect the `IndexSet` with `other`.
public mutating func formIntersection(_ other: IndexSet) {
self = self.intersection(other)
}
/// Insert an integer into the `IndexSet`.
@discardableResult
public mutating func insert(_ integer: Element) -> (inserted: Bool, memberAfterInsert: Element) {
_applyMutation { $0.add(integer) }
// TODO: figure out how to return the truth here
return (true, integer)
}
/// Insert an integer into the `IndexSet`.
@discardableResult
public mutating func update(with integer: Element) -> Element? {
_applyMutation { $0.add(integer) }
// TODO: figure out how to return the truth here
return integer
}
/// Remove an integer from the `IndexSet`.
@discardableResult
public mutating func remove(_ integer: Element) -> Element? {
// TODO: Add method to NSIndexSet to do this in one call
let result : Element? = contains(integer) ? integer : nil
_applyMutation { $0.remove(integer) }
return result
}
// MARK: -
/// Remove all values from the `IndexSet`.
public mutating func removeAll() {
_applyMutation { $0.removeAllIndexes() }
}
/// Insert a range of integers into the `IndexSet`.
public mutating func insert(integersIn range: Range<Element>) {
_applyMutation { $0.add(in: _toNSRange(range)) }
}
/// Insert a range of integers into the `IndexSet`.
public mutating func insert(integersIn range: CountableRange<Element>) { self.insert(integersIn: Range(range)) }
/// Insert a range of integers into the `IndexSet`.
public mutating func insert(integersIn range: ClosedRange<Element>) { self.insert(integersIn: Range(range)) }
/// Insert a range of integers into the `IndexSet`.
public mutating func insert(integersIn range: CountableClosedRange<Element>) { self.insert(integersIn: Range(range)) }
/// Remove a range of integers from the `IndexSet`.
public mutating func remove(integersIn range: Range<Element>) {
_applyMutation { $0.remove(in: _toNSRange(range)) }
}
/// Remove a range of integers from the `IndexSet`.
public mutating func remove(integersIn range: CountableRange<Element>) { self.remove(integersIn: Range(range)) }
/// Remove a range of integers from the `IndexSet`.
public mutating func remove(integersIn range: ClosedRange<Element>) { self.remove(integersIn: Range(range)) }
/// Remove a range of integers from the `IndexSet`.
public mutating func remove(integersIn range: CountableClosedRange<Element>) { self.remove(integersIn: Range(range)) }
/// Returns `true` if self contains no values.
public var isEmpty : Bool {
return self.count == 0
}
/// Returns an IndexSet filtered according to the result of `includeInteger`.
///
/// - parameter range: A range of integers. For each integer in the range that intersects the integers in the IndexSet, then the `includeInteger` predicate will be invoked.
/// - parameter includeInteger: The predicate which decides if an integer will be included in the result or not.
public func filteredIndexSet(in range : Range<Element>, includeInteger: (Element) throws -> Bool) rethrows -> IndexSet {
let r : NSRange = _toNSRange(range)
return try _handle.map {
var error: Error?
let result = $0.indexes(in: r, options: [], passingTest: { (i, stop) -> Bool in
do {
let include = try includeInteger(i)
return include
} catch let e {
error = e
stop.pointee = true
return false
}
}) as IndexSet
if let e = error {
throw e
} else {
return result
}
}
}
/// Returns an IndexSet filtered according to the result of `includeInteger`.
///
/// - parameter range: A range of integers. For each integer in the range that intersects the integers in the IndexSet, then the `includeInteger` predicate will be invoked.
/// - parameter includeInteger: The predicate which decides if an integer will be included in the result or not.
public func filteredIndexSet(in range : CountableRange<Element>, includeInteger: (Element) throws -> Bool) rethrows -> IndexSet { return try self.filteredIndexSet(in: Range(range), includeInteger: includeInteger) }
/// Returns an IndexSet filtered according to the result of `includeInteger`.
///
/// - parameter range: A range of integers. For each integer in the range that intersects the integers in the IndexSet, then the `includeInteger` predicate will be invoked.
/// - parameter includeInteger: The predicate which decides if an integer will be included in the result or not.
public func filteredIndexSet(in range : ClosedRange<Element>, includeInteger: (Element) throws -> Bool) rethrows -> IndexSet { return try self.filteredIndexSet(in: Range(range), includeInteger: includeInteger) }
/// Returns an IndexSet filtered according to the result of `includeInteger`.
///
/// - parameter range: A range of integers. For each integer in the range that intersects the integers in the IndexSet, then the `includeInteger` predicate will be invoked.
/// - parameter includeInteger: The predicate which decides if an integer will be included in the result or not.
public func filteredIndexSet(in range : CountableClosedRange<Element>, includeInteger: (Element) throws -> Bool) rethrows -> IndexSet { return try self.filteredIndexSet(in: Range(range), includeInteger: includeInteger) }
/// Returns an IndexSet filtered according to the result of `includeInteger`.
///
/// - parameter includeInteger: The predicate which decides if an integer will be included in the result or not.
public func filteredIndexSet(includeInteger: (Element) throws -> Bool) rethrows -> IndexSet {
return try self.filteredIndexSet(in: 0..<NSNotFound-1, includeInteger: includeInteger)
}
/// For a positive delta, shifts the indexes in [index, INT_MAX] to the right, thereby inserting an "empty space" [index, delta], for a negative delta, shifts the indexes in [index, INT_MAX] to the left, thereby deleting the indexes in the range [index - delta, delta].
public mutating func shift(startingAt integer: Element, by delta: IndexSet.IndexDistance) {
_applyMutation { $0.shiftIndexesStarting(at: integer, by: delta) }
}
// Temporary boxing function, until we can get a native Swift type for NSIndexSet
@inline(__always)
mutating func _applyMutation<ReturnType>(_ whatToDo : (NSMutableIndexSet) throws -> ReturnType) rethrows -> ReturnType {
// This check is done twice because: <rdar://problem/24939065> Value kept live for too long causing uniqueness check to fail
var unique = true
switch _handle._pointer {
case .Default(_):
break
case .Mutable(_):
unique = isKnownUniquelyReferenced(&_handle)
}
switch _handle._pointer {
case .Default(let i):
// We need to become mutable; by creating a new box we also become unique
let copy = i.mutableCopy() as! NSMutableIndexSet
// Be sure to set the _handle before calling out; otherwise references to the struct in the closure may be looking at the old _handle
_handle = _MutablePairHandle(copy, copying: false)
let result = try whatToDo(copy)
return result
case .Mutable(let m):
// Only create a new box if we are not uniquely referenced
if !unique {
let copy = m.mutableCopy() as! NSMutableIndexSet
_handle = _MutablePairHandle(copy, copying: false)
let result = try whatToDo(copy)
return result
} else {
return try whatToDo(m)
}
}
}
// MARK: - Bridging Support
fileprivate var reference: NSIndexSet {
return _handle.reference
}
fileprivate init(reference: NSIndexSet) {
_handle = _MutablePairHandle(reference)
}
}
extension IndexSet : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return "\(count) indexes"
}
public var debugDescription: String {
return "\(count) indexes"
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "ranges", value: Array(rangeView)))
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}
/// Iterate two index sets on the boundaries of their ranges. This is where all of the interesting stuff happens for exclusive or, intersect, etc.
private struct IndexSetBoundaryIterator : IteratorProtocol {
typealias Element = IndexSet.Element
private var i1: IndexSet.RangeView.Iterator
private var i2: IndexSet.RangeView.Iterator
private var i1Range: CountableRange<Element>?
private var i2Range: CountableRange<Element>?
private var i1UsedLower: Bool
private var i2UsedLower: Bool
fileprivate init(_ is1: IndexSet, _ is2: IndexSet) {
i1 = is1.rangeView.makeIterator()
i2 = is2.rangeView.makeIterator()
i1Range = i1.next()
i2Range = i2.next()
// A sort of cheap iterator on [i1Range.lowerBound, i1Range.upperBound]
i1UsedLower = false
i2UsedLower = false
}
fileprivate mutating func next() -> Element? {
if i1Range == nil && i2Range == nil {
return nil
}
let nextIn1: Element
if let r = i1Range {
nextIn1 = i1UsedLower ? r.upperBound : r.lowerBound
} else {
nextIn1 = Int.max
}
let nextIn2: Element
if let r = i2Range {
nextIn2 = i2UsedLower ? r.upperBound : r.lowerBound
} else {
nextIn2 = Int.max
}
var result: Element
if nextIn1 <= nextIn2 {
// 1 has the next element, or they are the same.
result = nextIn1
if i1UsedLower { i1Range = i1.next() }
// We need to iterate both the value from is1 and is2 in the == case.
if result == nextIn2 {
if i2UsedLower { i2Range = i2.next() }
i2UsedLower = !i2UsedLower
}
i1UsedLower = !i1UsedLower
} else {
// 2 has the next element
result = nextIn2
if i2UsedLower { i2Range = i2.next() }
i2UsedLower = !i2UsedLower
}
return result
}
}
extension IndexSet {
public static func ==(lhs: IndexSet, rhs: IndexSet) -> Bool {
return lhs._handle.map { $0.isEqual(to: rhs) }
}
}
private func _toNSRange(_ r: Range<IndexSet.Element>) -> NSRange {
return NSMakeRange(r.lowerBound, r.upperBound - r.lowerBound)
}
extension IndexSet : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSIndexSet.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSIndexSet {
return reference
}
public static func _forceBridgeFromObjectiveC(_ x: NSIndexSet, result: inout IndexSet?) {
result = IndexSet(reference: x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSIndexSet, result: inout IndexSet?) -> Bool {
result = IndexSet(reference: x)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSIndexSet?) -> IndexSet {
guard let src = source else { return IndexSet() }
return IndexSet(reference: src)
}
}
extension NSIndexSet : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as IndexSet)
}
}
// MARK: Protocol
// TODO: This protocol should be replaced with a native Swift object like the other Foundation bridged types. However, NSIndexSet does not have an abstract zero-storage base class like NSCharacterSet, NSData, and NSAttributedString. Therefore the same trick of laying it out with Swift ref counting does not work.and
/// Holds either the immutable or mutable version of a Foundation type.
///
/// In many cases, the immutable type has optimizations which make it preferred when we know we do not need mutation.
private enum _MutablePair<ImmutableType, MutableType> {
case Default(ImmutableType)
case Mutable(MutableType)
}
/// A class type which acts as a handle (pointer-to-pointer) to a Foundation reference type which has both an immutable and mutable class (e.g., NSData, NSMutableData).
///
/// a.k.a. Box
private final class _MutablePairHandle<ImmutableType : NSObject, MutableType : NSObject>
where ImmutableType : NSMutableCopying, MutableType : NSMutableCopying {
fileprivate var _pointer: _MutablePair<ImmutableType, MutableType>
/// Initialize with an immutable reference instance.
///
/// - parameter immutable: The thing to stash.
/// - parameter copying: Should be true unless you just created the instance (or called copy) and want to transfer ownership to this handle.
init(_ immutable: ImmutableType, copying: Bool = true) {
if copying {
self._pointer = _MutablePair.Default(immutable.copy() as! ImmutableType)
} else {
self._pointer = _MutablePair.Default(immutable)
}
}
/// Initialize with a mutable reference instance.
///
/// - parameter mutable: The thing to stash.
/// - parameter copying: Should be true unless you just created the instance (or called copy) and want to transfer ownership to this handle.
init(_ mutable: MutableType, copying: Bool = true) {
if copying {
self._pointer = _MutablePair.Mutable(mutable.mutableCopy() as! MutableType)
} else {
self._pointer = _MutablePair.Mutable(mutable)
}
}
/// Apply a closure to the reference type, regardless if it is mutable or immutable.
@inline(__always)
func map<ReturnType>(_ whatToDo: (ImmutableType) throws -> ReturnType) rethrows -> ReturnType {
switch _pointer {
case .Default(let i):
return try whatToDo(i)
case .Mutable(let m):
// TODO: It should be possible to reflect the constraint that MutableType is a subtype of ImmutableType in the generics for the class, but I haven't figured out how yet. For now, cheat and unsafe bit cast.
return try whatToDo(unsafeDowncast(m, to: ImmutableType.self))
}
}
var reference: ImmutableType {
switch _pointer {
case .Default(let i):
return i
case .Mutable(let m):
// TODO: It should be possible to reflect the constraint that MutableType is a subtype of ImmutableType in the generics for the class, but I haven't figured out how yet. For now, cheat and unsafe bit cast.
return unsafeDowncast(m, to: ImmutableType.self)
}
}
}
extension IndexSet : Codable {
private enum CodingKeys : Int, CodingKey {
case indexes
}
private enum RangeCodingKeys : Int, CodingKey {
case location
case length
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
var indexesContainer = try container.nestedUnkeyedContainer(forKey: .indexes)
self.init()
while !indexesContainer.isAtEnd {
let rangeContainer = try indexesContainer.nestedContainer(keyedBy: RangeCodingKeys.self)
let startIndex = try rangeContainer.decode(Int.self, forKey: .location)
let count = try rangeContainer.decode(Int.self, forKey: .length)
self.insert(integersIn: startIndex ..< (startIndex + count))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var indexesContainer = container.nestedUnkeyedContainer(forKey: .indexes)
for range in self.rangeView {
var rangeContainer = indexesContainer.nestedContainer(keyedBy: RangeCodingKeys.self)
try rangeContainer.encode(range.startIndex, forKey: .location)
try rangeContainer.encode(range.count, forKey: .length)
}
}
}
| apache-2.0 | fbc4b59770e75c5134be0fcf15afbf7d | 40.909281 | 316 | 0.61362 | 4.792631 | false | false | false | false |
Jnosh/swift | test/ClangImporter/serialization-sil.swift | 2 | 3527 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-frontend -emit-module-path %t/Test.swiftmodule -emit-sil -o /dev/null -module-name Test %s -sdk "" -import-objc-header %S/Inputs/serialization-sil.h
// RUN: %target-sil-func-extractor %t/Test.swiftmodule -sil-print-debuginfo -func=_T04Test16testPartialApplyySoAA_pF -o - | %FileCheck %s
// REQUIRES: objc_interop
// @_transparent to force serialization.
@_transparent
public func testPartialApply(_ obj: Test) {
// CHECK-LABEL: @_T04Test16testPartialApplyySoAA_pF : $@convention(thin) (@owned Test) -> () {
if let curried1 = obj.normalObject {
// CHECK: dynamic_method_br [[CURRIED1_OBJ:%.+]] : $@opened([[CURRIED1_EXISTENTIAL:.+]]) Test, #Test.normalObject!1.foreign, [[CURRIED1_TRUE:[^,]+]], [[CURRIED1_FALSE:[^,]+]]
// CHECK: [[CURRIED1_FALSE]]:
// CHECK: [[CURRIED1_TRUE]]([[CURRIED1_METHOD:%.+]] : $@convention(objc_method) (@opened([[CURRIED1_EXISTENTIAL]]) Test) -> @autoreleased AnyObject):
// CHECK: [[CURRIED1_PARTIAL:%.+]] = partial_apply [[CURRIED1_METHOD]]([[CURRIED1_OBJ]]) : $@convention(objc_method) (@opened([[CURRIED1_EXISTENTIAL]]) Test) -> @autoreleased AnyObject
// CHECK: [[CURRIED1_THUNK:%.+]] = function_ref @_T0yXlIxo_ypIxr_TR : $@convention(thin) (@owned @callee_owned () -> @owned AnyObject) -> @out Any
// CHECK: = partial_apply [[CURRIED1_THUNK]]([[CURRIED1_PARTIAL]])
curried1()
}
if let curried2 = obj.innerPointer {
// CHECK: dynamic_method_br [[CURRIED2_OBJ:%.+]] : $@opened([[CURRIED2_EXISTENTIAL:.+]]) Test, #Test.innerPointer!1.foreign, [[CURRIED2_TRUE:[^,]+]], [[CURRIED2_FALSE:[^,]+]]
// CHECK: [[CURRIED2_FALSE]]:
// CHECK: [[CURRIED2_TRUE]]([[CURRIED2_METHOD:%.+]] : $@convention(objc_method) (@opened([[CURRIED2_EXISTENTIAL]]) Test) -> @unowned_inner_pointer UnsafeMutableRawPointer):
// CHECK: [[CURRIED2_PARTIAL:%.+]] = partial_apply [[CURRIED2_METHOD]]([[CURRIED2_OBJ]]) : $@convention(objc_method) (@opened([[CURRIED2_EXISTENTIAL]]) Test) -> @unowned_inner_pointer UnsafeMutableRawPointer
curried2()
}
if let prop1 = obj.normalObjectProp {
// CHECK: dynamic_method_br [[PROP1_OBJ:%.+]] : $@opened([[PROP1_EXISTENTIAL:.+]]) Test, #Test.normalObjectProp!getter.1.foreign, [[PROP1_TRUE:[^,]+]], [[PROP1_FALSE:[^,]+]]
// CHECK: [[PROP1_FALSE]]:
// CHECK: [[PROP1_TRUE]]([[PROP1_METHOD:%.+]] : $@convention(objc_method) (@opened([[PROP1_EXISTENTIAL]]) Test) -> @autoreleased AnyObject):
// CHECK: [[PROP1_PARTIAL:%.+]] = partial_apply [[PROP1_METHOD]]([[PROP1_OBJ]]) : $@convention(objc_method) (@opened([[PROP1_EXISTENTIAL]]) Test) -> @autoreleased AnyObject
// CHECK: = apply [[PROP1_PARTIAL]]() : $@callee_owned () -> @owned AnyObject
_ = prop1
}
if let prop2 = obj.innerPointerProp {
// CHECK: dynamic_method_br [[PROP2_OBJ:%.+]] : $@opened([[PROP2_EXISTENTIAL:.+]]) Test, #Test.innerPointerProp!getter.1.foreign, [[PROP2_TRUE:[^,]+]], [[PROP2_FALSE:[^,]+]]
// CHECK: [[PROP2_FALSE]]:
// CHECK: [[PROP2_TRUE]]([[PROP2_METHOD:%.+]] : $@convention(objc_method) (@opened([[PROP2_EXISTENTIAL]]) Test) -> @unowned_inner_pointer UnsafeMutableRawPointer):
// CHECK: [[PROP2_PARTIAL:%.+]] = partial_apply [[PROP2_METHOD]]([[PROP2_OBJ]]) : $@convention(objc_method) (@opened([[PROP2_EXISTENTIAL]]) Test) -> @unowned_inner_pointer UnsafeMutableRawPointer
// CHECK: = apply [[PROP2_PARTIAL]]() : $@callee_owned () -> UnsafeMutableRawPointer
_ = prop2
}
} // CHECK: // end sil function '_T04Test16testPartialApplyySoAA_pF'
| apache-2.0 | 0dd8681e990a31e906dd569d734ec961 | 81.023256 | 211 | 0.648993 | 3.566229 | false | true | false | false |
ozgur/AutoLayoutAnimation | autolayoutanimation/NestedObjectMapperViewController.swift | 1 | 2790 | //
// NestedObjectMapperViewController.swift
// AutoLayoutAnimation
//
// Created by Ozgur Vatansever on 10/20/15.
// Copyright © 2015 Techshed. All rights reserved.
//
import UIKit
import ObjectMapper
import Cartography
extension Mapper {
}
class NestedObjectMapperViewController: UIViewController {
@IBOutlet fileprivate weak var imageView: UIImageView!
convenience init() {
self.init(nibName: "NestedObjectMapperViewController", bundle: Bundle.main)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
edgesForExtendedLayout = UIRectEdge()
title = "Nesting Objects"
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let city = Mapper<City>().map(readJSONFile("City"))
imageView.image = city?.image
}
}
class ZipcodeTransform: TransformType {
typealias Object = [String]
typealias JSON = String
func transformFromJSON(_ value: AnyObject?) -> [String]? {
if let value = value as? String {
return value.components(separatedBy: ",").map { value in
return value.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
return nil
}
func transformToJSON(_ value: [String]?) -> String? {
guard let value = value else {
return nil
}
return value.joined(separator: ",")
}
}
class City: Mappable {
var name: String!
var state: String!
var population: Int!
var zipcode: [String]!
var image: UIImage!
var elevation: Float!
var water: Float!
var land: Float!
var government: CityGovernment!
required init?(_ map: Map) {
}
func mapping(_ map: Map) {
name <- map["name"]
state <- map["state"]
population <- map["population"]
zipcode <- (map["zipcode"], ZipcodeTransform())
elevation <- map["area.elevation"]
water <- map["area.water"]
land <- map["area.land"]
government <- map["government"]
let imageTransform = TransformOf<UIImage, String>(
fromJSON: { (imageName) -> UIImage? in
guard let imageName = imageName else {
return nil
}
let image = UIImage(named: imageName)
image?.accessibilityIdentifier = imageName
return image
},
toJSON: { (image) -> String? in
return image?.accessibilityIdentifier
}
)
image <- (map["image"], imageTransform)
}
}
class CityGovernment: CustomStringConvertible, Mappable {
var type: String!
var mayor: String!
var supervisors: [String]!
required init?(_ map: Map) {
}
func mapping(_ map: Map) {
type <- map["type"]
mayor <- map["mayor"]
supervisors <- map["supervisors"]
}
var description: String {
return "<Government: \(type) | \(mayor)>"
}
}
| mit | 11e8bd123804edf36381240caf64fb62 | 21.860656 | 80 | 0.642166 | 4.290769 | false | false | false | false |
NocturneZX/TTT-Pre-Internship-Exercises | Swift/class 4/iTunesSearch/iTunesSearch/ViewController.swift | 1 | 2988 | //
// ViewController.swift
// iTunesSearch
//
// Created by Oren Goldberg on 7/23/14.
// Copyright (c) 2014 Red Cloud Creations. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var searchTextField: UITextField!
@IBAction func asyncNetworkCall(sender: AnyObject) {
//1. Get search term
var searchTerm:String = searchTextField.text
//2. Create URL with HTTP Request
let urlPath = "https://itunes.apple.com/search?term=\(searchTerm)&media=music&entity=album"
println("iTunes GET REQUEST \n\n \(urlPath)\n\n")
//3. Create connection object
let url: NSURL! = NSURL(string: urlPath)
let request: NSURLRequest = NSURLRequest(URL: url)
//4. Make async call and declare 'closure on the fly' to accept the response whenever it is ready
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{//closure starts here
(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if (error != nil) {
println("ERROR: \(error.localizedDescription)")
}//if
else {
var error: NSError?
var alert = UIAlertController(title: "Connection Successful", message: "Data Received for \(searchTerm)", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
//5. Convert JSON to Dictionary
let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
// Now send the JSON result to our delegate object
if error != nil{
println("HTTP Error: \(error?.localizedDescription)")
}//if
else {
println("\n\n-------- Response from iTunes --------\n\n")
println(jsonResult)
}//else
}//else
}//closure ends here
println("last line")
}
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-2.0 | 43f05895b4f9816a5ec9cb027d23fc4e | 35 | 176 | 0.54083 | 5.870334 | false | false | false | false |
nFiction/StackOverflow | StackOverflow/Classes/View/QuestionCell.swift | 1 | 1848 | import UIKit
final class QuestionCell: UITableViewCell {
let titleLabel: UILabel = {
let label = UILabel(frame: .zero)
label.font = UIFont.systemFont(ofSize: 14)
label.textColor = .darkGray
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let tagsLabel: UILabel = {
let label = UILabel(frame: .zero)
label.font = UIFont.systemFont(ofSize: 12)
label.textColor = .gray
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViewConfiguration()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension QuestionCell: ViewConfiguration {
func buildViewHierarchy() {
contentView.addSubview(titleLabel)
contentView.addSubview(tagsLabel)
}
func setupConstraints() {
titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8).isActive = true
titleLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16).isActive = true
titleLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -4).isActive = true
tagsLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 4).isActive = true
tagsLabel.leftAnchor.constraint(equalTo: titleLabel.leftAnchor).isActive = true
tagsLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -4).isActive = true
tagsLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8).isActive = true
}
}
| mit | f67891927356daabd0c26551df6e8619 | 34.538462 | 106 | 0.698593 | 5.119114 | false | false | false | false |
HarveyHu/TicTacToe-in-Swift | TicTacToe/Chessboard.swift | 1 | 3774 | //
// Chessboard.swift
// TicTacToe
//
// Created by HarveyHu on 7/30/15.
// Copyright (c) 2015 HarveyHu. All rights reserved.
//
import Foundation
protocol ChessboardDelegate {
func show(chessboard: Array<Chessboard.Status>)
func onGameOver(winner: Chessboard.Status)
}
class Chessboard: NSCopying {
static let sharedInstance = Chessboard()
enum Status: Int {
case Empty = 0
case Nought = 1
case Cross = 2
}
var chessboardDelegate: ChessboardDelegate?
var firstHand: Status = Status.Nought
private var _currentBoard = Array<Status>(count: 9, repeatedValue: Status.Empty)
private let _lineSets: Set<Set<Int>> = [[0, 4, 8], [2, 4, 6], [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8]]
func copy() -> AnyObject! {
if let asCopying = ((self as AnyObject) as? NSCopying) {
return asCopying.copyWithZone(nil)
}
else {
assert(false, "This class doesn't implement NSCopying")
return nil
}
}
@objc func copyWithZone(zone: NSZone) -> AnyObject {
let newValue = Chessboard()
newValue._currentBoard = _currentBoard
newValue.firstHand = firstHand
return newValue
}
func chess(position: Int, status: Status, isShow: Bool = false) -> Bool {
if position < 9 && _currentBoard[position] == Status.Empty {
_currentBoard[position] = status
if isShow {
dispatch_async(dispatch_get_main_queue()) { [weak self] () -> Void in
if let strongSelf = self {
strongSelf.chessboardDelegate?.show(strongSelf._currentBoard)
if strongSelf.checkGameOver() {
strongSelf.chessboardDelegate?.onGameOver(strongSelf.checkWin())
}
}
}
}
return true
}
return false
}
func chessShow(position: Int, status: Status) -> Bool {
return chess(position, status: status, isShow: true)
}
func generateLegalMoves() -> [Int]? {
var legalMoves = Array<Int>()
for position in 0 ..< 9 {
if _currentBoard[position] == Status.Empty {
legalMoves.append(position)
}
}
if legalMoves.count > 0 {
return legalMoves
}
return nil
}
func newGame() {
_currentBoard.removeAll()
_currentBoard = Array<Status>(count: 9, repeatedValue: Status.Empty)
chessboardDelegate?.show(_currentBoard)
}
func checkWin() -> Status {
var noughtSet = Set<Int>()
var crossSet = Set<Int>()
for index in 0 ..< _currentBoard.count {
switch _currentBoard[index] {
case Status.Nought:
noughtSet.insert(index)
break
case Status.Cross:
crossSet.insert(index)
break
default:
break
}
}
for lineSet in _lineSets {
if lineSet.isSubsetOf(noughtSet) {
return Status.Nought
} else if lineSet.isSubsetOf(crossSet) {
return Status.Cross
}
}
//not end yet
return Status.Empty
}
func checkGameOver() -> Bool {
var isFull = true
for index in 0 ..< _currentBoard.count {
if _currentBoard[index] == Status.Empty {
isFull = false
break
}
}
if checkWin() == Status.Empty && !isFull {
return false
}
return true
}
} | mit | 3a914bcc7de498c47ea6a8d623e181dc | 28.492188 | 131 | 0.520933 | 4.602439 | false | false | false | false |
eliasbagley/Pesticide | debugdrawer/DeviceUtils.swift | 1 | 687 | //
// DeviceUtils.swift
// debugdrawer
//
// Created by Elias Bagley on 11/21/14.
// Copyright (c) 2014 Rocketmade. All rights reserved.
//
import Foundation
class DeviceUtils {
class func getDeviceVersionString() -> String {
let version = UIDevice.currentDevice().systemVersion
let model = UIDevice.currentDevice().model
return "\(model) \(version)"
}
class func getResolutionString() -> String {
let screenSize = UIScreen.mainScreen().bounds
let scale = UIScreen.mainScreen().scale
let width = Int(screenSize.width*scale)
let height = Int(screenSize.height*scale)
return "\(width)x\(height)"
}
}
| mit | 07963507d297845afa799aa3bc70daaf | 24.444444 | 60 | 0.647744 | 4.29375 | false | false | false | false |
imobilize/Molib | Molib/Classes/Networking/DownloadManager/DownloadUtilities.swift | 1 | 3967 |
import UIKit
public class DownloadUtility: NSObject {
class var fileManager: FileManager {
get { return FileManager.`default` }
}
public static let DownloadCompletedNotif: String = {
return "com.Downloader.DownloadCompletedNotif"
}()
public static let baseFilePath: String = {
return NSHomeDirectory() + "/Documents"
}()
public class func getUniqueFileNameWithPath(filePath : String) -> String {
let fileURL = URL(fileURLWithPath: filePath)
let fileExtension = fileURL.pathExtension
let fileName = fileURL.deletingPathExtension().lastPathComponent
var suggestedFileName = fileName
var isUnique : Bool = false
var fileNumber : Int = 0
let fileManger = self.fileManager
repeat {
var fileDocDirectoryPath : String?
if fileExtension.count > 0 {
fileDocDirectoryPath = "\(fileURL.deletingLastPathComponent())/\(suggestedFileName).\(fileExtension)"
} else {
fileDocDirectoryPath = "\(fileURL.deletingLastPathComponent)/\(suggestedFileName)"
}
let isFileAlreadyExists : Bool = fileManger.fileExists(atPath: fileDocDirectoryPath!)
if isFileAlreadyExists {
fileNumber += 1
suggestedFileName = "\(fileName)(\(fileNumber))"
} else {
isUnique = true
if fileExtension.count > 0 {
suggestedFileName = "\(suggestedFileName).\(fileExtension)"
}
}
} while isUnique == false
return suggestedFileName
}
public class func calculateFileSizeInUnit(contentLength : Int64) -> Float {
let dataLength : Float64 = Float64(contentLength)
if dataLength >= (1024.0*1024.0*1024.0) {
return Float(dataLength/(1024.0*1024.0*1024.0))
} else if dataLength >= 1024.0*1024.0 {
return Float(dataLength/(1024.0*1024.0))
} else if dataLength >= 1024.0 {
return Float(dataLength/1024.0)
} else {
return Float(dataLength)
}
}
public class func calculateUnit(contentLength : Int64) -> String {
if(contentLength >= (1024*1024*1024)) {
return "GB"
} else if contentLength >= (1024*1024) {
return "MB"
} else if contentLength >= 1024 {
return "KB"
} else {
return "Bytes"
}
}
public class func addSkipBackupAttributeToItemAtURL(docDirectoryPath : String) -> Bool {
let url : NSURL = NSURL(fileURLWithPath: docDirectoryPath as String)
let fileManager = self.fileManager
if fileManager.fileExists(atPath: url.path!) {
do {
try url.setResourceValue(NSNumber(value: true), forKey: URLResourceKey.isExcludedFromBackupKey)
return true
} catch let error as NSError {
debugPrint("Error excluding \(String(describing: url.lastPathComponent)) from backup \(error)")
return false
}
} else {
return false
}
}
public class func getFreeDiskspace() -> Int64? {
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
do {
let systemAttributes = try self.fileManager.attributesOfFileSystem(forPath: documentDirectoryPath.last!)
let freeSize = systemAttributes[FileAttributeKey.systemFreeSize] as? NSNumber
return freeSize?.int64Value
} catch let error as NSError {
debugPrint("Error Obtaining System Memory Info: Domain = \(error.domain), Code = \(error.code)")
return nil
}
}
}
| apache-2.0 | d09c5ff14adbec2c3a37383ac2b674b8 | 35.394495 | 117 | 0.577767 | 5.732659 | false | false | false | false |
ello/ello-ios | Sources/Networking/AuthToken.swift | 1 | 2575 | ////
/// AuthToken.swift
//
import SwiftyJSON
struct AuthToken {
static var sharedKeychain: KeychainType = ElloKeychain()
var keychain: KeychainType
init() {
keychain = AuthToken.sharedKeychain
}
var tokenWithBearer: String? {
guard let key = keychain.authToken else { return nil }
return "Bearer \(key)"
}
var token: String? {
get { return keychain.authToken }
set(newToken) { keychain.authToken = newToken }
}
var type: String? {
get { return keychain.authTokenType }
set(newType) { keychain.authTokenType = newType }
}
var refreshToken: String? {
get { return keychain.refreshAuthToken }
set(newRefreshToken) { keychain.refreshAuthToken = newRefreshToken }
}
var isPresent: Bool {
return !(token?.isEmpty ?? true)
}
var isPasswordBased: Bool {
get { return isPresent && keychain.isPasswordBased ?? false }
set { keychain.isPasswordBased = newValue }
}
var isAnonymous: Bool {
return isPresent && !isPasswordBased
}
var username: String? {
get { return keychain.username }
set { keychain.username = newValue }
}
var password: String? {
get { return keychain.password }
set { keychain.password = newValue }
}
var isStaff: Bool {
get { return keychain.isStaff ?? false }
set { keychain.isStaff = newValue }
}
var isNabaroo: Bool {
get { return keychain.isNabaroo ?? false }
set { keychain.isNabaroo = newValue }
}
static func storeToken(
_ data: Data,
isPasswordBased: Bool,
email: String? = nil,
password: String? = nil
) {
guard let json = try? JSON(data: data) else { return }
var authToken = AuthToken()
authToken.isPasswordBased = isPasswordBased
if let email = email {
authToken.username = email
}
if let password = password {
authToken.password = password
}
authToken.token = json["access_token"].stringValue
authToken.type = json["token_type"].stringValue
authToken.refreshToken = json["refresh_token"].stringValue
JWT.refresh()
}
static func reset() {
var keychain = sharedKeychain
keychain.authToken = nil
keychain.refreshAuthToken = nil
keychain.authTokenType = nil
keychain.isPasswordBased = false
keychain.username = nil
keychain.password = nil
}
}
| mit | b76bc105a201b4970e73f887f3d7f578 | 24.245098 | 76 | 0.597282 | 4.716117 | false | false | false | false |
PrashantMangukiya/SwiftUIDemo | Demo26-UIStackViewHorizontal/Demo26-UIStackViewHorizontal/ViewController.swift | 1 | 2353 | //
// ViewController.swift
// Demo26-UIStackViewHorizontal
//
// Created by Prashant on 18/10/15.
// Copyright © 2015 PrashantKumar Mangukiya. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// variable maintain how many images added to stack view
var imageCount = 0
// array stores image names
var imageList: [String] = ["bg-1", "bg-2", "bg-3","bg-4","bg-5"]
// outlet - stack view
@IBOutlet var stackView: UIStackView!
// outlet & action - add button
@IBOutlet var addButton: UIBarButtonItem!
@IBAction func addButtonClicked(_ sender: UIBarButtonItem) {
// add image to stack view
self.addImageToStackView()
}
// MARK: - View functions
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// add image to stack view
self.addImageToStackView()
// add image to stack view
self.addImageToStackView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Utility functions
// function - It will add new image to stack view and disable add
// button if five images added.
fileprivate func addImageToStackView(){
// find image name based on image index
let imageName : String = self.imageList[self.imageCount]
// create new image object
let newImage: UIImage = UIImage(named: imageName)!
// create new image view
let newImageView = UIImageView(image: newImage)
// set image view content mode
newImageView.contentMode = UIViewContentMode.scaleAspectFill
// clip subview for image view
newImageView.clipsToBounds = true
// add image view into stack view
self.stackView.addArrangedSubview(newImageView)
// increase image index
self.imageCount += 1
// image image index go neyod 4 the disable add button
if self.imageCount >= 5 {
self.addButton.isEnabled = false
}
}
}
| mit | 53885f6ea650c5783532be9d89a78271 | 24.846154 | 80 | 0.598214 | 5.321267 | false | false | false | false |
LiuDeng/turns | q/AuthenticationsViewController.swift | 2 | 1474 | //
// AuthenticationsViewController.swift
// q
//
// Created by Jesse Shawl on 5/7/15.
// Copyright (c) 2015 Jesse Shawl. All rights reserved.
//
import UIKit
class AuthenticationsViewController: UIViewController, UITableViewDelegate {
@IBOutlet weak var email: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var signUpButton: UIButton!
var sendingView:GroupsTableViewController?
override func viewDidLoad() {
super.viewDidLoad()
loginButton.layer.borderWidth = 2.0
loginButton.layer.borderColor = UIColor.whiteColor().CGColor
loginButton.layer.cornerRadius = 3
signUpButton.layer.borderWidth = 2.0
signUpButton.layer.borderColor = UIColor.whiteColor().CGColor
signUpButton.layer.cornerRadius = 3
// Do any additional setup after loading the view.
}
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.
}
/**/
}
| mit | 8bc7c7858de9c732826e0645b116fda9 | 28.48 | 106 | 0.689959 | 5.100346 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/Examples/iOS/AnalogSynthX/AnalogSynthX/CustomControls/WaveformSegmentedView.swift | 3 | 537 | //
// WaveformSegmentedView.swift
// AnalogSynthX
//
// Created by Matthew Fecher on 1/15/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import UIKit
class WaveformSegmentedView: SMSegmentView {
func setOscColors() {
separatorColour = UIColor.clearColor()
separatorWidth = 0.5
segmentOnSelectionColour = UIColor(red: 34.0/255.0, green: 34.0/255.0, blue: 34.0/255.0, alpha: 1.0)
segmentOffSelectionColour = UIColor.clearColor()
segmentVerticalMargin = CGFloat(10.0)
}
}
| apache-2.0 | 35ca2b1b591896bc4bbc4ccd05d65102 | 24.52381 | 108 | 0.677239 | 3.722222 | false | false | false | false |
zyuanming/EffectDesignerX | EffectDesignerX/View/Style.swift | 1 | 6486 | //
// Style.swift
// KPCTabsControl
//
// Created by Christian Tietze on 10/08/16.
// Licensed under the MIT License (see LICENSE file)
//
import Cocoa
public typealias IconFrames = (iconFrame: NSRect, alternativeTitleIconFrame: NSRect)
public typealias TitleEditorSettings = (textColor: NSColor, font: NSFont, alignment: NSTextAlignment)
/**
* The Style protocol defines all the necessary things to let KPCTabsControl draw itself with tabs.
*/
public protocol Style {
// Tab Buttons
var tabButtonWidth: TabWidth { get }
func tabButtonOffset(position: TabPosition) -> Offset
func tabButtonBorderMask(_ position: TabPosition) -> BorderMask?
// Tab Button Titles
func iconFrames(tabRect rect: NSRect) -> IconFrames
func titleRect(title: NSAttributedString, inBounds rect: NSRect, showingIcon: Bool) -> NSRect
func titleEditorSettings() -> TitleEditorSettings
func attributedTitle(content: String, selectionState: TabSelectionState) -> NSAttributedString
// Tabs Control
var tabsControlRecommendedHeight: CGFloat { get }
func tabsControlBorderMask() -> BorderMask?
// Drawing
func drawTabButtonBezel(frame: NSRect, position: TabPosition, isSelected: Bool)
func drawTabsControlBezel(frame: NSRect)
}
/**
* The default Style protocol doesn't necessary have a theme associated with it, for custom styles.
* However, provided styles (Numbers.app-like, Safari and Chrome) have an associated theme.
*/
public protocol ThemedStyle : Style {
var theme: Theme { get }
}
public extension ThemedStyle {
// MARK: - Tab Buttons
public func tabButtonOffset(position: TabPosition) -> Offset {
return NSPoint()
}
public func tabButtonBorderMask(_ position: TabPosition) -> BorderMask? {
return BorderMask.all()
}
// MARK: - Tab Button Titles
public func iconFrames(tabRect rect: NSRect) -> IconFrames {
let verticalPadding: CGFloat = 4.0
let paddedHeight = rect.height - 2*verticalPadding
let x = rect.width / 2.0 - paddedHeight / 2.0
return (NSMakeRect(10.0, verticalPadding, paddedHeight, paddedHeight),
NSMakeRect(x, verticalPadding, paddedHeight, paddedHeight))
}
public func titleRect(title: NSAttributedString, inBounds rect: NSRect, showingIcon: Bool) -> NSRect {
let titleSize = title.size()
let fullWidthRect = NSRect(x: NSMinX(rect),
y: NSMidY(rect) - titleSize.height/2.0 - 0.5,
width: NSWidth(rect),
height: titleSize.height)
return self.paddedRectForIcon(fullWidthRect, showingIcon: showingIcon)
}
fileprivate func paddedRectForIcon(_ rect: NSRect, showingIcon: Bool) -> NSRect {
guard showingIcon else {
return rect
}
let iconRect = self.iconFrames(tabRect: rect).iconFrame
let pad = NSMaxX(iconRect)+titleMargin
return rect.offsetBy(dx: pad, dy: 0.0).shrinkBy(dx: pad, dy: 0.0)
}
public func titleEditorSettings() -> TitleEditorSettings {
return (textColor: NSColor(calibratedWhite: 1.0/6, alpha: 1.0),
font: self.theme.tabButtonTheme.titleFont,
alignment: NSTextAlignment.center)
}
public func attributedTitle(content: String, selectionState: TabSelectionState) -> NSAttributedString {
let activeTheme = self.theme.tabButtonTheme(fromSelectionState: selectionState)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
paragraphStyle.lineBreakMode = .byTruncatingMiddle
let attributes = [NSForegroundColorAttributeName : activeTheme.titleColor,
NSFontAttributeName : activeTheme.titleFont,
NSParagraphStyleAttributeName : paragraphStyle]
return NSAttributedString(string: content, attributes: attributes)
}
// MARK: - Tabs Control
public func tabsControlBorderMask() -> BorderMask? {
return BorderMask.top.union(BorderMask.bottom)
}
// MARK: - Drawing
public func drawTabsControlBezel(frame: NSRect) {
self.theme.tabsControlTheme.backgroundColor.setFill()
NSRectFill(frame)
let borderDrawing = BorderDrawing.fromMask(frame, borderMask: self.tabsControlBorderMask())
self.drawBorder(borderDrawing, color: self.theme.tabsControlTheme.borderColor)
}
public func drawTabButtonBezel(frame: NSRect, position: TabPosition, isSelected: Bool) {
let activeTheme = isSelected ? self.theme.selectedTabButtonTheme : self.theme.tabButtonTheme
activeTheme.backgroundColor.setFill()
NSRectFill(frame)
let borderDrawing = BorderDrawing.fromMask(frame, borderMask: self.tabButtonBorderMask(position))
self.drawBorder(borderDrawing, color: activeTheme.borderColor)
}
fileprivate func drawBorder(_ border: BorderDrawing, color: NSColor) {
guard case let .draw(borderRects: borderRects, rectCount: borderRectCount) = border
else { return }
color.setFill()
color.setStroke()
NSRectFillList(borderRects, borderRectCount)
}
}
private enum BorderDrawing {
case empty
case draw(borderRects: [NSRect], rectCount: Int)
fileprivate static func fromMask(_ sourceRect: NSRect, borderMask: BorderMask?) -> BorderDrawing {
guard let mask = borderMask else { return .empty }
var outputCount: Int = 0
var remainderRect = NSZeroRect
var borderRects: [NSRect] = [NSZeroRect, NSZeroRect, NSZeroRect, NSZeroRect]
if mask.contains(.top) {
NSDivideRect(sourceRect, &borderRects[outputCount], &remainderRect, 0.5, .minY)
outputCount += 1
}
if mask.contains(.left) {
NSDivideRect(sourceRect, &borderRects[outputCount], &remainderRect, 0.5, .minX)
outputCount += 1
}
if mask.contains(.right) {
NSDivideRect(sourceRect, &borderRects[outputCount], &remainderRect, 0.5, .maxX)
outputCount += 1
}
if mask.contains(.bottom) {
NSDivideRect(sourceRect, &borderRects[outputCount], &remainderRect, 0.5, .maxY)
outputCount += 1
}
guard outputCount > 0 else { return .empty }
return .draw(borderRects: borderRects, rectCount: outputCount)
}
}
| mit | e9155237369051c1458a21007180aa06 | 33.31746 | 107 | 0.669134 | 4.786716 | false | false | false | false |
avito-tech/Marshroute | Example/NavigationDemo/VIPER/Application/Presenter/ApplicationPresenter.swift | 1 | 2868 | import Foundation
final class ApplicationPresenter: ApplicationModuleInput {
// MARK: - Init
private let interactor: ApplicationInteractor
private let router: ApplicationRouter
init(interactor: ApplicationInteractor, router: ApplicationRouter) {
self.interactor = interactor
self.router = router
}
// MARK: - Weak properties
weak var view: ApplicationViewInput? {
didSet {
if oldValue !== view {
setupView()
}
}
}
weak var authorizationModuleInput: AuthorizationModuleInput?
weak var bannerModuleInput: BannerModuleInput?
// MARK: - Private
private func setupView() {
view?.onMemoryWarning = { [weak self] in
self?.showAuthorizationModule(nil)
}
view?.onDeviceShake = { [weak self] in
self?.interactor.bannerType { bannerType in
self?.showBanner(bannerType: bannerType)
}
}
}
// MARK: - ApplicationModuleInput
func showAuthorizationModule(_ completion: ((_ isAuthorized: Bool) -> ())?) {
router.authorizationStatus { [weak self] isPresented in
if isPresented {
debugPrint("Not showing second instance of Authorization module. Just replacing completion")
self?.authorizationModuleInput?.onComplete = completion
} else {
self?.router.showAuthorization { [weak self] moduleInput in
self?.authorizationModuleInput = moduleInput
moduleInput.onComplete = completion
}
}
}
}
// MARK: - Private
func showBanner(bannerType: BannerType) {
let onBannerTap: (() -> ())
switch bannerType {
case .categories:
bannerModuleInput?.setTitle("notification.toCategories".localized)
onBannerTap = { [weak self] in
self?.router.showCategories()
}
case .recursion:
bannerModuleInput?.setTitle("notification.toRecursion".localized)
onBannerTap = { [weak self] in
self?.router.showRecursion()
}
}
showBanner(onBannerTap: onBannerTap)
}
private func showBanner(onBannerTap: @escaping (() -> ())) {
view?.showBanner { [weak self] in
self?.bannerModuleInput?.setPresented()
self?.bannerModuleInput?.onBannerTap = {
self?.interactor.switchBannerType()
self?.view?.hideBanner()
onBannerTap()
}
self?.bannerModuleInput?.onBannerTimeout = {
self?.view?.hideBanner()
}
}
}
}
| mit | b9d5547f5aea0ced866117b752a90abf | 29.83871 | 108 | 0.549163 | 5.793939 | false | false | false | false |
yoavlt/LiquidLoader | Pod/Classes/LiquidCircleEffect.swift | 1 | 2688 | //
// LiquidCircleLoader.swift
// LiquidLoading
//
// Created by Takuma Yoshida on 2015/08/21.
// Copyright (c) 2015年 yoavlt. All rights reserved.
//
import Foundation
import UIKit
class LiquidCircleEffect : LiquidLoadEffect {
var radius: CGFloat {
get {
return loader!.frame.width * 0.5
}
}
override func setupShape() -> [LiquittableCircle] {
return Array(0..<numberOfCircles).map { i in
let angle = CGFloat(i) * CGFloat(2 * Double.pi) / 8.0
let frame = self.loader.frame
let center = CGMath.circlePoint(frame.center.minus(frame.origin), radius: self.radius - self.circleRadius, rad: angle)
return LiquittableCircle(
center: center,
radius: self.circleRadius,
color: self.color,
growColor: self.growColor
)
}
}
override func movePosition(_ key: CGFloat) -> CGPoint {
guard self.loader != nil else {return CGPoint.zero}
let frame = self.loader!.frame.center.minus(self.loader!.frame.origin)
return CGMath.circlePoint(
frame,
radius: self.radius - self.circleRadius,
rad: self.key * CGFloat(2 * Double.pi)
)
}
override func update() {
switch key {
case 0.0...1.0:
key += 1/(duration*60)
default:
key = key - 1.0
}
}
override func willSetup() {
self.circleRadius = loader.frame.width * 0.09
self.circleScale = 1.10
self.engine = SimpleCircleLiquidEngine(radiusThresh: self.circleRadius * 0.85, angleThresh: 0.5)
let moveCircleRadius = circleRadius * moveScale
moveCircle = LiquittableCircle(center: movePosition(0.0), radius: moveCircleRadius, color: self.color, growColor: self.growColor)
}
override func resize() {
guard moveCircle != nil else { return }
guard loader != nil else { return }
let moveVec = moveCircle!.center.minus(loader.center.minus(loader.frame.origin)).normalized()
circles.map { circle in
return (circle, moveVec.dot(circle.center.minus(self.loader.center.minus(self.loader.frame.origin)).normalized()))
}.each { (circle, dot) in
if 0.75 < dot && dot <= 1.0 {
let normalized = (dot - 0.75) / 0.25
let scale = normalized * normalized
circle.radius = self.circleRadius + (self.circleRadius * self.circleScale - self.circleRadius) * scale
} else {
circle.radius = self.circleRadius
}
}
}
}
| mit | e6ceb44abf55facfe7a0b21f52cfd1e3 | 32.575 | 137 | 0.5793 | 4.263492 | false | false | false | false |
tardieu/swift | test/attr/attr_dynamic.swift | 27 | 2417 | // RUN: %target-typecheck-verify-swift
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename=%s -print-implicit-attrs
struct NotObjCAble {
var c: Foo
}
@objc class ObjCClass {}
dynamic prefix operator +!+ // expected-error{{'dynamic' modifier cannot be applied to this declaration}} {{1-9=}}
class Foo {
dynamic init() {}
dynamic init(x: NotObjCAble) {} // expected-error{{method cannot be marked dynamic because the type of the parameter cannot be represented in Objective-C}} expected-note{{Swift structs cannot be represented in Objective-C}}
dynamic var x: Int
dynamic var nonObjcVar: NotObjCAble // expected-error{{property cannot be marked dynamic because its type cannot be represented in Objective-C}} expected-note{{Swift structs cannot be represented in Objective-C}}
dynamic func foo(x: Int) {}
dynamic func bar(x: Int) {}
dynamic func nonObjcFunc(x: NotObjCAble) {} // expected-error{{method cannot be marked dynamic because the type of the parameter cannot be represented in Objective-C}} expected-note{{Swift structs cannot be represented in Objective-C}}
dynamic subscript(x: Int) -> ObjCClass { get {} }
dynamic subscript(x: Int) -> NotObjCAble { get {} } // expected-error{{subscript cannot be marked dynamic because its type cannot be represented in Objective-C}} expected-note{{Swift structs cannot be represented in Objective-C}}
dynamic deinit {} // expected-error{{'dynamic' modifier cannot be applied to this declaration}} {{3-11=}}
func notDynamic() {}
final dynamic func indecisive() {} // expected-error{{a declaration cannot be both 'final' and 'dynamic'}} {{9-17=}}
}
struct Bar {
dynamic init() {} // expected-error{{only members of classes may be dynamic}} {{3-11=}}
dynamic var x: Int // expected-error{{only members of classes may be dynamic}} {{3-11=}}
dynamic subscript(x: Int) -> ObjCClass { get {} } // expected-error{{only members of classes may be dynamic}} {{3-11=}}
dynamic func foo(x: Int) {} // expected-error{{only members of classes may be dynamic}} {{3-11=}}
}
// CHECK-LABEL: class InheritsDynamic : Foo {
class InheritsDynamic: Foo {
// CHECK-LABEL: {{^}} dynamic override func foo(x: Int)
override func foo(x: Int) {}
// CHECK-LABEL: {{^}} dynamic override func foo(x: Int)
dynamic override func bar(x: Int) {}
// CHECK: {{^}} override func notDynamic()
override func notDynamic() {}
}
| apache-2.0 | da810b5332f3edbb56c48fb49f72231d | 42.945455 | 237 | 0.708316 | 4.001656 | false | false | false | false |
neonichu/yolo | Tests/SimSpec.swift | 1 | 389 | import Spectre
@testable import IPA
func describeSim() {
describe("Sim") {
$0.it("can determine the currently available iOS SDK") {
let sdkVersion = availableSDKVersion()
try expect(sdkVersion) == "9.2"
}
$0.it("can determine the developer directory") {
let devDir = developerDirectory()
try expect(devDir) == "/Applications/Xcode-7.2.app/Contents/Developer"
}
}
} | mit | 44b7b5c1bbbb6aff3d10d372e12b543d | 23.375 | 73 | 0.688946 | 3.324786 | false | true | false | false |
treejames/firefox-ios | Storage/SQL/SQLiteHistory.swift | 2 | 38486 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
private let log = Logger.syncLogger
private let LogPII = false
class NoSuchRecordError: ErrorType {
let guid: GUID
init(guid: GUID) {
self.guid = guid
}
var description: String {
return "No such record: \(guid)."
}
}
func failOrSucceed<T>(err: NSError?, op: String, val: T) -> Deferred<Result<T>> {
if let err = err {
log.debug("\(op) failed: \(err.localizedDescription)")
return deferResult(DatabaseError(err: err))
}
return deferResult(val)
}
func failOrSucceed(err: NSError?, op: String) -> Success {
return failOrSucceed(err, op, ())
}
private var ignoredSchemes = ["about"]
public func isIgnoredURL(url: NSURL) -> Bool {
if let scheme = url.scheme {
if let index = find(ignoredSchemes, scheme) {
return true
}
}
if url.host == "localhost" {
return true
}
return false
}
public func isIgnoredURL(url: String) -> Bool {
if let url = NSURL(string: url) {
return isIgnoredURL(url)
}
return false
}
/*
// Here's the Swift equivalent of the below.
func simulatedFrecency(now: MicrosecondTimestamp, then: MicrosecondTimestamp, visitCount: Int) -> Double {
let ageMicroseconds = (now - then)
let ageDays = Double(ageMicroseconds) / 86400000000.0 // In SQL the .0 does the coercion.
let f = 100 * 225 / ((ageSeconds * ageSeconds) + 225)
return Double(visitCount) * max(1.0, f)
}
*/
// The constants in these functions were arrived at by utterly unscientific experimentation.
func getRemoteFrecencySQL() -> String {
let visitCountExpression = "remoteVisitCount"
let now = NSDate.nowMicroseconds()
let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24
let ageDays = "((\(now) - remoteVisitDate) / \(microsecondsPerDay))"
return "\(visitCountExpression) * max(1, 100 * 110 / (\(ageDays) * \(ageDays) + 110))"
}
func getLocalFrecencySQL() -> String {
let visitCountExpression = "((2 + localVisitCount) * (2 + localVisitCount))"
let now = NSDate.nowMicroseconds()
let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24
let ageDays = "((\(now) - localVisitDate) / \(microsecondsPerDay))"
return "\(visitCountExpression) * max(2, 100 * 225 / (\(ageDays) * \(ageDays) + 225))"
}
extension SDRow {
func getTimestamp(column: String) -> Timestamp? {
return (self[column] as? NSNumber)?.unsignedLongLongValue
}
func getBoolean(column: String) -> Bool {
if let val = self[column] as? Int {
return val != 0
}
return false
}
}
/**
* The sqlite-backed implementation of the history protocol.
*/
public class SQLiteHistory {
let db: BrowserDB
let favicons: FaviconsTable<Favicon>
required public init?(db: BrowserDB, version: Int? = nil) {
self.db = db
self.favicons = FaviconsTable<Favicon>()
if !db.createOrUpdate(self.favicons) {
return nil
}
// BrowserTable exists only to perform create/update etc. operations -- it's not
// a queryable thing that needs to stick around.
if !db.createOrUpdate(BrowserTable(version: version ?? BrowserTable.DefaultVersion)) {
return nil
}
}
}
extension SQLiteHistory: BrowserHistory {
public func removeSiteFromTopSites(site: Site) -> Success {
if let host = site.url.asURL?.normalizedHost() {
return db.run([("UPDATE \(TableDomains) set showOnTopSites = 0 WHERE domain = ?", [host])])
}
return deferResult(DatabaseError(description: "Invalid url for site \(site.url)"))
}
public func removeHistoryForURL(url: String) -> Success {
let visitArgs: Args = [url]
let deleteVisits = "DELETE FROM \(TableVisits) WHERE siteID = (SELECT id FROM \(TableHistory) WHERE url = ?)"
let markArgs: Args = [NSDate.nowNumber(), url]
let markDeleted = "UPDATE \(TableHistory) SET url = NULL, is_deleted = 1, should_upload = 1, local_modified = ? WHERE url = ?"
return db.run([(deleteVisits, visitArgs),
(markDeleted, markArgs),
favicons.getCleanupCommands()])
}
// Note: clearing history isn't really a sane concept in the presence of Sync.
// This method should be split to do something else.
public func clearHistory() -> Success {
return db.run([("DELETE FROM \(TableVisits)", nil),
("DELETE FROM \(TableHistory)", nil),
("DELETE FROM \(TableDomains)", nil),
self.favicons.getCleanupCommands()])
}
func recordVisitedSite(site: Site) -> Success {
var error: NSError? = nil
// Don't store visits to sites with about: protocols
if isIgnoredURL(site.url) {
return deferResult(IgnoredSiteError())
}
db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in
let now = NSDate.nowNumber()
let i = self.updateSite(site, atTime: now, withConnection: conn)
if i > 0 {
return i
}
// Insert instead.
return self.insertSite(site, atTime: now, withConnection: conn)
}
return failOrSucceed(error, "Record site")
}
func updateSite(site: Site, atTime time: NSNumber, withConnection conn: SQLiteDBConnection) -> Int {
// We know we're adding a new visit, so we'll need to upload this record.
// If we ever switch to per-visit change flags, this should turn into a CASE statement like
// CASE WHEN title IS ? THEN max(should_upload, 1) ELSE should_upload END
// so that we don't flag this as changed unless the title changed.
//
// Note that we will never match against a deleted item, because deleted items have no URL,
// so we don't need to unset is_deleted here.
if let host = site.url.asURL?.normalizedHost() {
let update = "UPDATE \(TableHistory) SET title = ?, local_modified = ?, should_upload = 1, domain_id = (SELECT id FROM \(TableDomains) where domain = ?) WHERE url = ?"
let updateArgs: Args? = [site.title, time, host, site.url]
if LogPII {
log.debug("Setting title to \(site.title) for URL \(site.url)")
}
let error = conn.executeChange(update, withArgs: updateArgs)
if error != nil {
log.warning("Update failed with \(error?.localizedDescription)")
return 0
}
return conn.numberOfRowsModified
}
return 0
}
private func insertSite(site: Site, atTime time: NSNumber, withConnection conn: SQLiteDBConnection) -> Int {
var error: NSError? = nil
if let host = site.url.asURL?.normalizedHost() {
if let error = conn.executeChange("INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)", withArgs: [host]) {
log.warning("Domain insertion failed with \(error.localizedDescription)")
return 0
}
let insert = "INSERT INTO \(TableHistory) " +
"(guid, url, title, local_modified, is_deleted, should_upload, domain_id) " +
"SELECT ?, ?, ?, ?, 0, 1, id FROM \(TableDomains) WHERE domain = ?"
let insertArgs: Args? = [site.guid ?? Bytes.generateGUID(), site.url, site.title, time, host]
if let error = conn.executeChange(insert, withArgs: insertArgs) {
log.warning("Site insertion failed with \(error.localizedDescription)")
return 0
}
return 1
}
log.warning("Invalid URL \(site.url). Not stored in history.")
return 0
}
// TODO: thread siteID into this to avoid the need to do the lookup.
func addLocalVisitForExistingSite(visit: SiteVisit) -> Success {
var error: NSError? = nil
db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in
// INSERT OR IGNORE because we *might* have a clock error that causes a timestamp
// collision with an existing visit, and it would really suck to error out for that reason.
let insert = "INSERT OR IGNORE INTO \(TableVisits) (siteID, date, type, is_local) VALUES (" +
"(SELECT id FROM \(TableHistory) WHERE url = ?), ?, ?, 1)"
let realDate = NSNumber(unsignedLongLong: visit.date)
let insertArgs: Args? = [visit.site.url, realDate, visit.type.rawValue]
error = conn.executeChange(insert, withArgs: insertArgs)
if error != nil {
log.warning("Visit insertion failed with \(err?.localizedDescription)")
return 0
}
return 1
}
return failOrSucceed(error, "Record visit")
}
public func addLocalVisit(visit: SiteVisit) -> Success {
return recordVisitedSite(visit.site)
>>> { self.addLocalVisitForExistingSite(visit) }
}
public func getSitesByFrecencyWithLimit(limit: Int) -> Deferred<Result<Cursor<Site>>> {
return self.getSitesByFrecencyWithLimit(limit, includeIcon: true)
}
public func getSitesByFrecencyWithLimit(limit: Int, includeIcon: Bool) -> Deferred<Result<Cursor<Site>>> {
// Exclude redirect domains. Bug 1194852.
let whereData = "(\(TableDomains).showOnTopSites IS 1) AND (\(TableDomains).domain NOT LIKE 'r.%') "
let groupBy = "GROUP BY domain_id "
return self.getFilteredSitesByFrecencyWithLimit(limit, groupClause: groupBy, whereData: whereData, includeIcon: includeIcon)
}
public func getSitesByFrecencyWithLimit(limit: Int, whereURLContains filter: String) -> Deferred<Result<Cursor<Site>>> {
return self.getFilteredSitesByFrecencyWithLimit(limit, whereURLContains: filter)
}
public func getSitesByLastVisit(limit: Int) -> Deferred<Result<Cursor<Site>>> {
return self.getFilteredSitesByVisitDateWithLimit(limit, whereURLContains: nil, includeIcon: true)
}
private class func basicHistoryColumnFactory(row: SDRow) -> Site {
let id = row["historyID"] as! Int
let url = row["url"] as! String
let title = row["title"] as! String
let guid = row["guid"] as! String
let site = Site(url: url, title: title)
site.guid = guid
site.id = id
// Find the most recent visit, regardless of which column it might be in.
let local = row.getTimestamp("localVisitDate") ?? 0
let remote = row.getTimestamp("remoteVisitDate") ?? 0
let either = row.getTimestamp("visitDate") ?? 0
let latest = max(local, remote, either)
if latest > 0 {
site.latestVisit = Visit(date: latest, type: VisitType.Unknown)
}
return site
}
private class func iconColumnFactory(row: SDRow) -> Favicon? {
if let iconType = row["iconType"] as? Int,
let iconURL = row["iconURL"] as? String,
let iconDate = row["iconDate"] as? Double,
let iconID = row["iconID"] as? Int {
let date = NSDate(timeIntervalSince1970: iconDate)
return Favicon(url: iconURL, date: date, type: IconType(rawValue: iconType)!)
}
return nil
}
private class func iconHistoryColumnFactory(row: SDRow) -> Site {
let site = basicHistoryColumnFactory(row)
site.icon = iconColumnFactory(row)
return site
}
private func getFilteredSitesByVisitDateWithLimit(limit: Int,
whereURLContains filter: String? = nil,
includeIcon: Bool = true) -> Deferred<Result<Cursor<Site>>> {
let args: Args?
let whereClause: String
if let filter = filter {
args = ["%\(filter)%", "%\(filter)%"]
// No deleted item has a URL, so there is no need to explicitly add that here.
whereClause = "WHERE ((\(TableHistory).url LIKE ?) OR (\(TableHistory).title LIKE ?)) " +
"AND (\(TableHistory).is_deleted = 0)"
} else {
args = []
whereClause = "WHERE (\(TableHistory).is_deleted = 0)"
}
let ungroupedSQL =
"SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, domain_id, domain, " +
"COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate, " +
"COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate, " +
"COALESCE(count(\(TableVisits).is_local), 0) AS visitCount " +
"FROM \(TableHistory) " +
"INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id " +
"INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id " +
whereClause + " GROUP BY historyID"
let historySQL =
"SELECT historyID, url, title, guid, domain_id, domain, visitCount, " +
"max(localVisitDate) AS localVisitDate, " +
"max(remoteVisitDate) AS remoteVisitDate " +
"FROM (" + ungroupedSQL + ") " +
"WHERE (visitCount > 0) " + // Eliminate dead rows from coalescing.
"GROUP BY historyID " +
"ORDER BY max(localVisitDate, remoteVisitDate) DESC " +
"LIMIT \(limit) "
if includeIcon {
// We select the history items then immediately join to get the largest icon.
// We do this so that we limit and filter *before* joining against icons.
let sql = "SELECT " +
"historyID, url, title, guid, domain_id, domain, " +
"localVisitDate, remoteVisitDate, visitCount, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM (\(historySQL)) LEFT OUTER JOIN " +
"view_history_id_favicon ON historyID = view_history_id_favicon.id"
let factory = SQLiteHistory.iconHistoryColumnFactory
return db.runQuery(sql, args: args, factory: factory)
}
let factory = SQLiteHistory.basicHistoryColumnFactory
return db.runQuery(historySQL, args: args, factory: factory)
}
private func getFilteredSitesByFrecencyWithLimit(limit: Int,
whereURLContains filter: String? = nil,
groupClause: String = "GROUP BY historyID ",
whereData: String? = nil,
includeIcon: Bool = true) -> Deferred<Result<Cursor<Site>>> {
let localFrecencySQL = getLocalFrecencySQL()
let remoteFrecencySQL = getRemoteFrecencySQL()
let sixMonthsInMicroseconds: UInt64 = 15_724_800_000_000 // 182 * 1000 * 1000 * 60 * 60 * 24
let sixMonthsAgo = NSDate.nowMicroseconds() - sixMonthsInMicroseconds
let args: Args?
let whereClause: String
let whereFragment = (whereData == nil) ? "" : " AND (\(whereData!))"
if let filter = filter {
args = ["%\(filter)%", "%\(filter)%"]
// No deleted item has a URL, so there is no need to explicitly add that here.
whereClause = " WHERE ((\(TableHistory).url LIKE ?) OR (\(TableHistory).title LIKE ?)) \(whereFragment)"
} else {
args = []
whereClause = " WHERE (\(TableHistory).is_deleted = 0) \(whereFragment)"
}
// Innermost: grab history items and basic visit/domain metadata.
let ungroupedSQL =
"SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, domain_id, domain" +
", COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate" +
", COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate" +
", COALESCE(sum(\(TableVisits).is_local), 0) AS localVisitCount" +
", COALESCE(sum(case \(TableVisits).is_local when 1 then 0 else 1 end), 0) AS remoteVisitCount" +
" FROM \(TableHistory) " +
"INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id " +
"INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id " +
whereClause + " GROUP BY historyID"
// Next: limit to only those that have been visited at all within the last six months.
// (Don't do that in the innermost: we want to get the full count, even if some visits are older.)
// Discard all but the 1000 most frecent.
// Compute and return the frecency for all 1000 URLs.
let frecenciedSQL =
"SELECT *, (\(localFrecencySQL) + \(remoteFrecencySQL)) AS frecency" +
" FROM (" + ungroupedSQL + ")" +
" WHERE (" +
"((localVisitCount > 0) OR (remoteVisitCount > 0)) AND " + // Eliminate dead rows from coalescing.
"((localVisitDate > \(sixMonthsAgo)) OR (remoteVisitDate > \(sixMonthsAgo)))" + // Exclude really old items.
") ORDER BY frecency DESC" +
" LIMIT 1000" // Don't even look at a huge set. This avoids work.
// Next: merge by domain and sum frecency, ordering by that sum and reducing to a (typically much lower) limit.
let historySQL =
"SELECT historyID, url, title, guid, domain_id, domain" +
", max(localVisitDate) AS localVisitDate" +
", max(remoteVisitDate) AS remoteVisitDate" +
", sum(localVisitCount) AS localVisitCount" +
", sum(remoteVisitCount) AS remoteVisitCount" +
", sum(frecency) AS frecencies" +
" FROM (" + frecenciedSQL + ") " +
groupClause + " " +
"ORDER BY frecencies DESC " +
"LIMIT \(limit) "
// Finally: join this small list to the favicon data.
if includeIcon {
// We select the history items then immediately join to get the largest icon.
// We do this so that we limit and filter *before* joining against icons.
let sql = "SELECT" +
" historyID, url, title, guid, domain_id, domain" +
", localVisitDate, remoteVisitDate, localVisitCount, remoteVisitCount" +
", iconID, iconURL, iconDate, iconType, iconWidth" +
" FROM (\(historySQL)) LEFT OUTER JOIN " +
"view_history_id_favicon ON historyID = view_history_id_favicon.id"
let factory = SQLiteHistory.iconHistoryColumnFactory
return db.runQuery(sql, args: args, factory: factory)
}
let factory = SQLiteHistory.basicHistoryColumnFactory
return db.runQuery(historySQL, args: args, factory: factory)
}
}
extension SQLiteHistory: Favicons {
// These two getter functions are only exposed for testing purposes (and aren't part of the public interface).
func getFaviconsForURL(url: String) -> Deferred<Result<Cursor<Favicon?>>> {
let sql = "SELECT iconID AS id, iconURL AS url, iconDate AS date, iconType AS type, iconWidth AS width FROM " +
"\(ViewWidestFaviconsForSites), \(TableHistory) WHERE " +
"\(TableHistory).id = siteID AND \(TableHistory).url = ?"
let args: Args = [url]
return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory)
}
func getFaviconsForBookmarkedURL(url: String) -> Deferred<Result<Cursor<Favicon?>>> {
let sql = "SELECT \(TableFavicons).id AS id, \(TableFavicons).url AS url, \(TableFavicons).date AS date, \(TableFavicons).type AS type, \(TableFavicons).width AS width FROM \(TableFavicons), \(TableBookmarks) WHERE \(TableBookmarks).faviconID = \(TableFavicons).id AND \(TableBookmarks).url IS ?"
let args: Args = [url]
return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory)
}
public func clearAllFavicons() -> Success {
var err: NSError? = nil
db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in
err = conn.executeChange("DELETE FROM \(TableFaviconSites)", withArgs: nil)
if err == nil {
err = conn.executeChange("DELETE FROM \(TableFavicons)", withArgs: nil)
}
return 1
}
return failOrSucceed(err, "Clear favicons")
}
public func addFavicon(icon: Favicon) -> Deferred<Result<Int>> {
var err: NSError?
let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in
// Blind! We don't see failure here.
let id = self.favicons.insertOrUpdate(conn, obj: icon)
return id ?? 0
}
if err == nil {
return deferResult(res)
}
return deferResult(DatabaseError(err: err))
}
/**
* This method assumes that the site has already been recorded
* in the history table.
*/
public func addFavicon(icon: Favicon, forSite site: Site) -> Deferred<Result<Int>> {
if LogPII {
log.verbose("Adding favicon \(icon.url) for site \(site.url).")
}
func doChange(query: String, args: Args?) -> Deferred<Result<Int>> {
var err: NSError?
let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in
// Blind! We don't see failure here.
let id = self.favicons.insertOrUpdate(conn, obj: icon)
// Now set up the mapping.
err = conn.executeChange(query, withArgs: args)
if let err = err {
log.error("Got error adding icon: \(err).")
return 0
}
// Try to update the favicon ID column in the bookmarks table as well for this favicon
// if this site has been bookmarked
if let id = id {
conn.executeChange("UPDATE \(TableBookmarks) SET faviconID = ? WHERE url = ?", withArgs: [id, site.url])
}
return id ?? 0
}
if res == 0 {
return deferResult(DatabaseError(err: err))
}
return deferResult(icon.id!)
}
let siteSubselect = "(SELECT id FROM \(TableHistory) WHERE url = ?)"
let iconSubselect = "(SELECT id FROM \(TableFavicons) WHERE url = ?)"
let insertOrIgnore = "INSERT OR IGNORE INTO \(TableFaviconSites)(siteID, faviconID) VALUES "
if let iconID = icon.id {
// Easy!
if let siteID = site.id {
// So easy!
let args: Args? = [siteID, iconID]
return doChange("\(insertOrIgnore) (?, ?)", args)
}
// Nearly easy.
let args: Args? = [site.url, iconID]
return doChange("\(insertOrIgnore) (\(siteSubselect), ?)", args)
}
// Sigh.
if let siteID = site.id {
let args: Args? = [siteID, icon.url]
return doChange("\(insertOrIgnore) (?, \(iconSubselect))", args)
}
// The worst.
let args: Args? = [site.url, icon.url]
return doChange("\(insertOrIgnore) (\(siteSubselect), \(iconSubselect))", args)
}
}
extension SQLiteHistory: SyncableHistory {
/**
* TODO:
* When we replace an existing row, we want to create a deleted row with the old
* GUID and switch the new one in -- if the old record has escaped to a Sync server,
* we want to delete it so that we don't have two records with the same URL on the server.
* We will know if it's been uploaded because it'll have a server_modified time.
*/
public func ensurePlaceWithURL(url: String, hasGUID guid: GUID) -> Success {
let args: Args = [guid, url, guid]
// The additional IS NOT is to ensure that we don't do a write for no reason.
return db.run("UPDATE \(TableHistory) SET guid = ? WHERE url = ? AND guid IS NOT ?", withArgs: args)
}
public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success {
let args: Args = [guid]
// This relies on ON DELETE CASCADE to remove visits.
return db.run("DELETE FROM \(TableHistory) WHERE guid = ?", withArgs: args)
}
// Fails on non-existence.
private func getSiteIDForGUID(guid: GUID) -> Deferred<Result<Int>> {
let args: Args = [guid]
let query = "SELECT id FROM history WHERE guid = ?"
let factory: SDRow -> Int = { return $0["id"] as! Int }
return db.runQuery(query, args: args, factory: factory)
>>== { cursor in
if cursor.count == 0 {
return deferResult(NoSuchRecordError(guid: guid))
}
return deferResult(cursor[0]!)
}
}
public func storeRemoteVisits(visits: [Visit], forGUID guid: GUID) -> Success {
return self.getSiteIDForGUID(guid)
>>== { (siteID: Int) -> Success in
let visitArgs = visits.map { (visit: Visit) -> Args in
let realDate = NSNumber(unsignedLongLong: visit.date)
let isLocal = 0
let args: Args = [siteID, realDate, visit.type.rawValue, isLocal]
return args
}
// Magic happens here. The INSERT OR IGNORE relies on the multi-column uniqueness
// constraint on `visits`: we allow only one row for (siteID, date, type), so if a
// local visit already exists, this silently keeps it. End result? Any new remote
// visits are added with only one query, keeping any existing rows.
return self.db.bulkInsert(TableVisits, op: .InsertOrIgnore, columns: ["siteID", "date", "type", "is_local"], values: visitArgs)
}
}
private struct HistoryMetadata {
let id: Int
let serverModified: Timestamp?
let localModified: Timestamp?
let isDeleted: Bool
let shouldUpload: Bool
let title: String
}
private func metadataForGUID(guid: GUID) -> Deferred<Result<HistoryMetadata?>> {
let select = "SELECT id, server_modified, local_modified, is_deleted, should_upload, title FROM \(TableHistory) WHERE guid = ?"
let args: Args = [guid]
let factory = { (row: SDRow) -> HistoryMetadata in
return HistoryMetadata(
id: row["id"] as! Int,
serverModified: row.getTimestamp("server_modified"),
localModified: row.getTimestamp("local_modified"),
isDeleted: row.getBoolean("is_deleted"),
shouldUpload: row.getBoolean("should_upload"),
title: row["title"] as! String
)
}
return db.runQuery(select, args: args, factory: factory) >>== { cursor in
return deferResult(cursor[0])
}
}
public func insertOrUpdatePlace(place: Place, modified: Timestamp) -> Deferred<Result<GUID>> {
// One of these things will be true here.
// 0. The item is new.
// (a) We have a local place with the same URL but a different GUID.
// (b) We have never visited this place locally.
// In either case, reconcile and proceed.
// 1. The remote place is not modified when compared to our mirror of it. This
// can occur when we redownload after a partial failure.
// (a) And it's not modified locally, either. Nothing to do. Ideally we
// will short-circuit so we don't need to update visits. (TODO)
// (b) It's modified locally. Don't overwrite anything; let the upload happen.
// 2. The remote place is modified (either title or visits).
// (a) And it's not locally modified. Update the local entry.
// (b) And it's locally modified. Preserve the title of whichever was modified last.
// N.B., this is the only instance where we compare two timestamps to see
// which one wins.
// We use this throughout.
let serverModified = NSNumber(unsignedLongLong: modified)
// Check to see if our modified time is unchanged, if the record exists locally, etc.
let insertWithMetadata = { (metadata: HistoryMetadata?) -> Deferred<Result<GUID>> in
if let metadata = metadata {
// The item exists locally (perhaps originally with a different GUID).
if metadata.serverModified == modified {
log.debug("History item \(place.guid) is unchanged; skipping insert-or-update.")
return deferResult(place.guid)
}
// Otherwise, the server record must have changed since we last saw it.
if metadata.shouldUpload {
// Uh oh, it changed locally.
// This might well just be a visit change, but we can't tell. Usually this conflict is harmless.
log.debug("Warning: history item \(place.guid) changed both locally and remotely. Comparing timestamps from different clocks!")
if metadata.localModified > modified {
log.debug("Local changes overriding remote.")
// Update server modified time only. (Though it'll be overwritten again after a successful upload.)
let update = "UPDATE \(TableHistory) SET server_modified = ? WHERE id = ?"
let args: Args = [serverModified, metadata.id]
return self.db.run(update, withArgs: args) >>> always(place.guid)
}
log.debug("Remote changes overriding local.")
// Fall through.
}
// The record didn't change locally. Update it.
log.debug("Updating local history item for guid \(place.guid).")
let update = "UPDATE \(TableHistory) SET title = ?, server_modified = ?, is_deleted = 0 WHERE id = ?"
let args: Args = [place.title, serverModified, metadata.id]
return self.db.run(update, withArgs: args) >>> always(place.guid)
}
// The record doesn't exist locally. Insert it.
log.debug("Inserting remote history item for guid \(place.guid).")
if let host = place.url.asURL?.normalizedHost() {
if LogPII {
log.debug("Inserting: \(place.url).")
}
let insertDomain = "INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)"
let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " +
"SELECT ?, ?, ?, ?, 0, 0, id FROM \(TableDomains) where domain = ?"
return self.db.run([
(insertDomain, [host]),
(insertHistory, [place.guid, place.url, place.title, serverModified, host])
]) >>> always(place.guid)
} else {
// This is a URL with no domain. Insert it directly.
if LogPII {
log.debug("Inserting: \(place.url) with no domain.")
}
let insertDomain = "INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)"
let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " +
"(?, ?, ?, ?, 0, 0, NULL)"
return self.db.run([
(insertHistory, [place.guid, place.url, place.title, serverModified])
]) >>> always(place.guid)
}
}
// Make sure that we only need to compare GUIDs by pre-merging on URL.
return self.ensurePlaceWithURL(place.url, hasGUID: place.guid)
>>> { self.metadataForGUID(place.guid) >>== insertWithMetadata }
}
public func getDeletedHistoryToUpload() -> Deferred<Result<[GUID]>> {
// Use the partial index on should_upload to make this nice and quick.
let sql = "SELECT guid FROM \(TableHistory) WHERE \(TableHistory).should_upload = 1 AND \(TableHistory).is_deleted = 1"
let f: SDRow -> String = { $0["guid"] as! String }
return self.db.runQuery(sql, args: nil, factory: f) >>== { deferResult($0.asArray()) }
}
public func getModifiedHistoryToUpload() -> Deferred<Result<[(Place, [Visit])]>> {
// What we want to do: find all items flagged for update, selecting some number of their
// visits alongside.
//
// A difficulty here: we don't want to fetch *all* visits, only some number of the most recent.
// (It's not enough to only get new ones, because the server record should contain more.)
//
// That's the greatest-N-per-group problem in SQL. Please read and understand the solution
// to this (particularly how the LEFT OUTER JOIN/HAVING clause works) before changing this query!
//
// We can do this in a single query, rather than the N+1 that desktop takes.
// We then need to flatten the cursor. We do that by collecting
// places as a side-effect of the factory, producing visits as a result, and merging in memory.
let args: Args = [
20, // Maximum number of visits to retrieve.
]
// Exclude 'unknown' visits, because they're not syncable.
let filter = "history.should_upload = 1 AND v1.type IS NOT 0"
let sql =
"SELECT " +
"history.id AS siteID, history.guid AS guid, history.url AS url, history.title AS title, " +
"v1.siteID AS siteID, v1.date AS visitDate, v1.type AS visitType " +
"FROM " +
"visits AS v1 " +
"JOIN history ON history.id = v1.siteID AND \(filter) " +
"LEFT OUTER JOIN " +
"visits AS v2 " +
"ON v1.siteID = v2.siteID AND v1.date < v2.date " +
"GROUP BY v1.date " +
"HAVING COUNT(*) < ? " +
"ORDER BY v1.siteID, v1.date DESC"
var places = [Int: Place]()
var visits = [Int: [Visit]]()
// Add a place to the accumulator, prepare to accumulate visits, return the ID.
let ensurePlace: SDRow -> Int = { row in
let id = row["siteID"] as! Int
if places[id] == nil {
let guid = row["guid"] as! String
let url = row["url"] as! String
let title = row["title"] as! String
places[id] = Place(guid: guid, url: url, title: title)
visits[id] = Array()
}
return id
}
// Store the place and the visit.
let factory: SDRow -> Int = { row in
let date = row.getTimestamp("visitDate")!
let type = VisitType(rawValue: row["visitType"] as! Int)!
let visit = Visit(date: date, type: type)
let id = ensurePlace(row)
visits[id]?.append(visit)
return id
}
return db.runQuery(sql, args: args, factory: factory)
>>== { c in
// Consume every row, with the side effect of populating the places
// and visit accumulators.
let count = c.count
var ids = Set<Int>()
for row in c {
// Collect every ID first, so that we're guaranteed to have
// fully populated the visit lists, and we don't have to
// worry about only collecting each place once.
ids.insert(row!)
}
// Now we're done with the cursor. Close it.
c.close()
// Now collect the return value.
return deferResult(map(ids, { return (places[$0]!, visits[$0]!) }))
}
}
public func markAsDeleted(guids: [GUID]) -> Success {
// TODO: support longer GUID lists.
assert(guids.count < BrowserDB.MaxVariableNumber)
if guids.isEmpty {
return succeed()
}
log.debug("Wiping \(guids.count) deleted GUIDs.")
// We deliberately don't limit this to records marked as should_upload, just
// in case a coding error leaves records with is_deleted=1 but not flagged for
// upload -- this will catch those and throw them away.
let inClause = BrowserDB.varlist(guids.count)
let sql =
"DELETE FROM \(TableHistory) WHERE " +
"is_deleted = 1 AND guid IN \(inClause)"
let args: Args = guids.map { $0 as AnyObject }
return self.db.run(sql, withArgs: args)
}
public func markAsSynchronized(guids: [GUID], modified: Timestamp) -> Deferred<Result<Timestamp>> {
// TODO: support longer GUID lists.
assert(guids.count < 99)
if guids.isEmpty {
return deferResult(modified)
}
log.debug("Marking \(guids.count) GUIDs as synchronized. Returning timestamp \(modified).")
let inClause = BrowserDB.varlist(guids.count)
let sql =
"UPDATE \(TableHistory) SET " +
"should_upload = 0, server_modified = \(modified) " +
"WHERE guid IN \(inClause)"
let args: Args = guids.map { $0 as AnyObject }
return self.db.run(sql, withArgs: args) >>> always(modified)
}
public func onRemovedAccount() -> Success {
log.info("Clearing history metadata after account removal.")
let discard =
"DELETE FROM \(TableHistory) WHERE is_deleted = 1"
let flag =
"UPDATE \(TableHistory) SET " +
"should_upload = 1, server_modified = NULL "
return self.db.run(discard) >>> { self.db.run(flag) }
}
}
| mpl-2.0 | eee0bc9c969b46fff1d81422fa9314aa | 43.38985 | 304 | 0.584446 | 4.654814 | false | false | false | false |
filom/ASN1Decoder | ASN1DecoderTests/ASN1DecoderTests.swift | 1 | 7432 | //
// ASN1DecoderTests.swift
// ASN1DecoderTests
//
// Copyright © 2017 Filippo Maguolo.
//
// 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 XCTest
@testable import ASN1Decoder
class ASN1DecoderTests: XCTestCase {
func testDecodingPEM() throws {
let x509 = try X509Certificate(data: certPEMData)
XCTAssertEqual(x509.version, 3)
XCTAssertEqual(x509.serialNumber?.hexEncodedString(),
"0836BAA2556864172078584638D85C34")
XCTAssertEqual(x509.subjectDistinguishedName,
"businessCategory=Private Organization, jurisdictionC=US, jurisdictionST=Utah, SERIALNUMBER=5299537-0142, C=US, ST=Utah, L=Lehi, O=\"DigiCert, Inc.\", OU=SRE, CN=www.digicert.com")
XCTAssertEqual(x509.subject(oid: .commonName)?.first, "www.digicert.com")
XCTAssertEqual(x509.subject(oid: .serialNumber), ["5299537-0142"])
XCTAssertEqual(x509.subject(oid: .organizationName), ["DigiCert, Inc."])
}
func testDecoding() {
var serialNumber = ""
var subject = ""
if let certData = Data(base64Encoded: cert) {
do {
let x509 = try X509Certificate(data: certData)
serialNumber = x509.serialNumber?.hexEncodedString() ?? ""
subject = x509.subjectDistinguishedName ?? ""
} catch {
print(error)
}
}
XCTAssertEqual(serialNumber, "59A2F004")
XCTAssertEqual(subject, "C=US, L=New York, [email protected], CN=John Smith")
}
let cert =
"MIIDMzCCAhugAwIBAgIEWaLwBDANBgkqhkiG9w0BAQsFADBTMQswCQYDVQQGEwJV" +
"UzERMA8GA1UEBwwITmV3IFlvcmsxHDAaBgkqhkiG9w0BCQEWDWpvaG5AbWFpbC5j" +
"b20xEzARBgNVBAMMCkpvaG4gU21pdGgwHhcNMTcwODI3MTYxNTAwWhcNMTgwODI3" +
"MTYxNTAwWjBTMQswCQYDVQQGEwJVUzERMA8GA1UEBwwITmV3IFlvcmsxHDAaBgkq" +
"hkiG9w0BCQEWDWpvaG5AbWFpbC5jb20xEzARBgNVBAMMCkpvaG4gU21pdGgwggEi" +
"MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDHc/RdKvcz+Sakwykuq/+mJZCQ" +
"ELYYk3ceVrYOwefaFLent4JU+/ATm+CQFXqyiQM1BTtXUwA3gG0sCufMUG5wkHN0" +
"86KwclYhzPRZNGtLW2QshvvaN2wE4HxbFJ/DUUHPGuIlzewfecg/ZG9CwGeb/HQ4" +
"Qx+BI/U7JXykyNHFwMQrS5hGmvLH7MxSYiqt8X2VZ7vabxdqnvpufK34SyVQXkfR" +
"twLNj7GO807HNQ5EGFw1hxJN3tBXG4z+1eq4rgy1RJY7c6ntkzOczrqw7Ut4OUmC" +
"RjAEggqPrG6R94D2f8vgEXB42TPSEKWwHi6/RAEZ1WO5YsDmLHVNxp8FvThVAgMB" +
"AAGjDzANMAsGA1UdDwQEAwIGQDANBgkqhkiG9w0BAQsFAAOCAQEAhlIaMaE9YTJU" +
"uSCy0LAd+nHzuTdokgDCXdT75KtsiNtQHQIDtLhdJGYUzlWUwY8SQWytvJORKi3q" +
"rA45oLwSJjVY4hZuNcaWleDumnHc4rbK9o6GJhEk/T49Vrc9q4CNX0/siPBsHwXd" +
"rqrLOR00yfrMYCPAUCryPbdx/IPbo8Z3kvlQHn8cqOjgqdwuy7PTMIMz6sCsBcV0" +
"OeAp80GDRAHpjB3qYhzhebiRiM+Bbqva6f4bxNmDNQtL0jt0a8KeyQrFNdAhgjYk" +
"AKTucThCu1laJKGKABK90dMoLtbJFxfRhjzmjX9TJGYJgCnRNDDnXpVUOspv2YeH" +
"vC9gOdRhaA=="
let certPEM = """
-----BEGIN CERTIFICATE-----
MIIItzCCB5+gAwIBAgIQCDa6olVoZBcgeFhGONhcNDANBgkqhkiG9w0BAQsFADB1
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMTQwMgYDVQQDEytEaWdpQ2VydCBTSEEyIEV4dGVuZGVk
IFZhbGlkYXRpb24gU2VydmVyIENBMB4XDTE4MDYyNjAwMDAwMFoXDTIwMDYzMDEy
MDAwMFowgc8xHTAbBgNVBA8MFFByaXZhdGUgT3JnYW5pemF0aW9uMRMwEQYLKwYB
BAGCNzwCAQMTAlVTMRUwEwYLKwYBBAGCNzwCAQITBFV0YWgxFTATBgNVBAUTDDUy
OTk1MzctMDE0MjELMAkGA1UEBhMCVVMxDTALBgNVBAgTBFV0YWgxDTALBgNVBAcT
BExlaGkxFzAVBgNVBAoTDkRpZ2lDZXJ0LCBJbmMuMQwwCgYDVQQLEwNTUkUxGTAX
BgNVBAMTEHd3dy5kaWdpY2VydC5jb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw
ggIKAoICAQDOn4XKOTAwt/aYabScEF1QOyVj0OVo1NmlyizWNZWyPg0pi53ggUoE
98CeNUkz+6scEYqWNY6l3qKB56pJJIqNQmo9NoWO8k2G/jTIjFFGqNWYIq23i4+H
qaXi1/H/aWFgazk1qkyyAOQQA/p56bG9m5Ok/IBM/BZnLqVJLGJOx9ihgG1dI9Dr
6vap+8QaPRau3t9sEd2cxe4Ix7gLdaYG3vxsYf3BycKTSKtyrbkX1Qy0dsSxy+GC
M2ETxE1gMa7vRomQ/ZoZo8Ib55kFp6lIT6UOOkkdyiJdpWPXIZZlsZR5wkegWDsJ
P7Xv7nE0WMkY1+05iNYtrzZRhhlnBw2AoMGNI+tsBXLQKeZfWFmU30bhkzX99pmv
IYJ3f1fQGLao44nQEjdknIvpm0HMgvagYCnQVnnhJStzyYz324flWLPSp57OQeNM
tr6O5W0HdWyhUZU+D4R6wObYQMZ5biYjRhtAQjMg8EVQEfZzEdr0WGO5JRHLHyot
8tErXM9DiF5cCbzfcjeuoik2SHW+vbuPagMiHTM9+3lr0oRO+ZWwcM7fJvn1JfR2
PDLAaI3QUv7OLhSH32UfQsk+1ICq05m2HwSxiAviDRl5De66MEZDdvu03sUAQTHv
Wnw0Mr7Jgbjtn0DeUKLYwsRWg+spqoFTJHWGbb9RIb+3lxev7nIqOQIDAQABo4ID
5jCCA+IwHwYDVR0jBBgwFoAUPdNQpdagre7zSmAKZdMh1Pj41g8wHQYDVR0OBBYE
FGywQ1b+PegS7NkS9WPVxMoHr7B2MIGRBgNVHREEgYkwgYaCEHd3dy5kaWdpY2Vy
dC5jb22CDGRpZ2ljZXJ0LmNvbYIUY29udGVudC5kaWdpY2VydC5jb22CF3d3dy5v
cmlnaW4uZGlnaWNlcnQuY29tghJsb2dpbi5kaWdpY2VydC5jb22CEGFwaS5kaWdp
Y2VydC5jb22CD3dzLmRpZ2ljZXJ0LmNvbTAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0l
BBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMHUGA1UdHwRuMGwwNKAyoDCGLmh0dHA6
Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9zaGEyLWV2LXNlcnZlci1nMi5jcmwwNKAyoDCG
Lmh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9zaGEyLWV2LXNlcnZlci1nMi5jcmww
SwYDVR0gBEQwQjA3BglghkgBhv1sAgEwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93
d3cuZGlnaWNlcnQuY29tL0NQUzAHBgVngQwBATCBiAYIKwYBBQUHAQEEfDB6MCQG
CCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wUgYIKwYBBQUHMAKG
Rmh0dHA6Ly9jYWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFNIQTJFeHRlbmRl
ZFZhbGlkYXRpb25TZXJ2ZXJDQS5jcnQwDAYDVR0TAQH/BAIwADCCAX4GCisGAQQB
1nkCBAIEggFuBIIBagFoAHYAu9nfvB+KcbWTlCOXqpJ7RzhXlQqrUugakJZkNo4e
0YUAAAFkPjJMpQAABAMARzBFAiEAtvfxjDWBvpmqcq7+1X8lOyqKUJ8y5r31V4kV
4tzQSPcCIG8AAjqwQwLG6ObfgMe0B06AwM7K1JEAsyv8QP5r/EPUAHYAVhQGmi/X
wuzT9eG9RLI+x0Z2ubyZEVzA75SYVdaJ0N0AAAFkPjJMFgAABAMARzBFAiEAkDHY
U+MhibIUpVtiPAFyEzv35P3Vwn5ODseJmDI6dZkCICb4xzUGBy7aEQKJLOuM1F0A
vMjEEB1OQQc9IWEY7UdPAHYAh3W/51l8+IxDmV+9827/Vo1HVjb/SrVgwbTq/16g
gw8AAAFkPjJNlAAABAMARzBFAiBSMM3aExfTbMG1btIu+LCW9ALj4FT6scxUUgy5
+OSH/gIhAPtqsgHiH6m6Qml1E9smajxYa773+YZdxMKbtEEe2ZV8MA0GCSqGSIb3
DQEBCwUAA4IBAQCPcXLe1MjGJtwfihuI1S53GdokFAcl94ouoWxWd7ASfsufUyxs
FroxDhNwxd8mQOH7V3ehZTiot6P+xMZOrYxgJx5CXbcLt07RZHT0w/Pf052gq7bP
GbHsrjtlXq1MDn8c8D+Fnv2qSgE4f/9wQ1gMU4IKojaO4YH9FYoacA8puXUlK1pB
CuCK0jJykyAtD9z4oTD/ZLBQOmTJ4VwJ5rHNCfdI8akR9OYYyx9GCbeWYv5JCcIy
zPyvZe6ceICEnRGliU/EzryyWhq4Vx/zReBgoX6xOWfW1ZAota0etzo9pSWjOdrr
j1I7q0bAhL1eUuXE8FSm6M8ZogW/ZYkOHE2u
-----END CERTIFICATE-----
"""
var certPEMData: Data { return certPEM.data(using: .utf8)! }
}
extension Data {
func hexEncodedString(separation: String = "") -> String {
return reduce("") {$0 + String(format: "%02X\(separation)", $1)}
}
}
| mit | e4d6b4866ec8c0805f3bfe80fc883509 | 51.330986 | 203 | 0.802315 | 2.243659 | false | true | false | false |
sgr-ksmt/SUSwiftSugar | SUSwiftSugarTests/Tests/StringExtensionsTests.swift | 1 | 4176 | //
// StringExtensionsTests.swift
import XCTest
import SUSwiftSugar
class StringExtensionsTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func test_compatible_NSString_functions() {
let str = "Apple"
XCTAssertEqual(str.length, 5)
XCTAssertEqual(str.substringFromIndex(2), "ple")
XCTAssertEqual(str.substringToIndex(2), "Ap")
XCTAssertEqual(str.substringWithRange(NSRange(location: 1, length: 3)), "ppl")
var path = "path/to/hoge.txt"
XCTAssertEqual(path.lastPathComponent, "hoge.txt")
XCTAssertEqual(path.pathExtension, "txt")
XCTAssertEqual(path.stringByDeletingLastPathComponent, "path/to")
XCTAssertEqual(path.stringByDeletingPathExtension, "path/to/hoge")
XCTAssertEqual(path.pathComponents, ["path", "to", "hoge.txt"])
path = "path/to"
XCTAssertEqual(path.stringByAppendingPathComponent("fuga"), "path/to/fuga")
XCTAssertEqual(
path.stringByAppendingPathComponent("fuga").stringByAppendingPathExtension("png"),
"path/to/fuga.png"
)
}
func test_subscript() {
let str = "abcdefghijklmn"
XCTAssertEqual(str[4], "e")
XCTAssertEqual(str[str.length-1], "n")
XCTAssertEqual(str[-1], "n")
XCTAssertEqual(str[-3], "l")
XCTAssertEqual(str[0..<str.length], str)
XCTAssertEqual(str[4..<6], "ef")
}
func test_blank() {
let blank1 = " a "
let blank2 = " "
let blank3 = " \n \n "
let blank4 = " \n \na "
XCTAssertFalse(blank1.isBlank)
XCTAssertTrue(blank2.isBlank)
XCTAssertTrue(blank3.isBlank)
XCTAssertFalse(blank4.isBlank)
}
func test_contains() {
let str = "MacBook Air"
XCTAssertFalse(str.contains("macbook"))
XCTAssertTrue(str.contains("MacBook"))
XCTAssertTrue(str.contains("macbook", compareOption: [.CaseInsensitiveSearch]))
}
func test_replace() {
var str = "Apple, Banana, Orange"
XCTAssertEqual(str.replacedString("Orange", withString: "Candy"), "Apple, Banana, Candy")
XCTAssertNotEqual(str.replacedString("orange", withString: "Candy"), "Apple, Banana, Candy")
str.replace("banana", withString: "Pine")
XCTAssertNotEqual(str, "Apple, Pine, Orange")
str.replace("Banana", withString: "Pine")
XCTAssertEqual(str, "Apple, Pine, Orange")
}
func test_repeat_operator() {
let str = "a"
XCTAssertEqual(str * 1, str)
XCTAssertEqual(str * 0, "")
XCTAssertEqual(str * (-100), "")
XCTAssertEqual(str * 10, "aaaaaaaaaa")
XCTAssertEqual(str + "b" * 5, "abbbbb")
XCTAssertEqual(str * 5 + "b", "aaaaab")
XCTAssertEqual((str + "b") * 5, "ababababab")
}
func test_replace_operator() {
let str = "Apple, Banana, Orange"
var result1 = str <> ("apple", "Pine")
XCTAssertNotEqual(result1, "Pine, Banana, Orange")
result1 = str <> ("Apple", "Pine")
XCTAssertEqual(result1, "Pine, Banana, Orange")
let result2 = "Hoge, " + str <> ("Hoge", "Fuga") + ", Hoge"
XCTAssertEqual(result2, "Hoge, Apple, Banana, Orange, Hoge")
let result3 = ("Hoge, " + str) <> ("Hoge", "Fuga") + ", Hoge"
XCTAssertEqual(result3, "Fuga, Apple, Banana, Orange, Hoge")
let str2 = "Apple"
let result4 = str2 * 3 <> ("le", "") + "Hoge"
XCTAssertEqual(result4, "AppAppAppHoge")
let result5 = "Hoge, " * 2 + str <> ("oge", "") + ", Hoge"
XCTAssertEqual(result5, "Hoge, Hoge, Apple, Banana, Orange, Hoge")
let result6 = ("Hoge, " * 2 + str) <> ("oge", "") + ", Hoge"
XCTAssertEqual(result6, "H, H, Apple, Banana, Orange, Hoge")
var str3 = "Apple"
str3 <-> ("le","")
XCTAssertEqual(str3, "App")
}
}
| mit | 1cf34ed4459c5cb0a8c03d6deb8a8f65 | 32.677419 | 100 | 0.560584 | 4.226721 | false | true | false | false |
sdhzwm/HackerNews | HackerNews/MainViewController.swift | 3 | 6284 | //
// MainViewController.swift
// HackerNews
//
// Copyright (c) 2015 Amit Burstein. All rights reserved.
// See LICENSE for licensing information.
//
import UIKit
import SafariServices
class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SFSafariViewControllerDelegate {
// MARK: Properties
let PostCellIdentifier = "PostCell"
let ShowBrowserIdentifier = "ShowBrowser"
let PullToRefreshString = "Pull to Refresh"
let FetchErrorMessage = "Could Not Fetch Posts"
let ErrorMessageLabelTextColor = UIColor.grayColor()
let ErrorMessageFontSize: CGFloat = 16
let FirebaseRef = "https://hacker-news.firebaseio.com/v0/"
let ItemChildRef = "item"
let StoryTypeChildRefMap = [StoryType.Top: "topstories", .New: "newstories", .Show: "showstories"]
let StoryLimit: UInt = 30
let DefaultStoryType = StoryType.Top
var firebase: Firebase!
var stories: [Story]!
var storyType: StoryType!
var retrievingStories: Bool!
var refreshControl: UIRefreshControl!
var errorMessageLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
// MARK: Enums
enum StoryType {
case Top, New, Show
}
// MARK: Structs
struct Story {
var title: String
var url: String?
var by: String
var score: Int
}
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
firebase = Firebase(url: FirebaseRef)
stories = []
storyType = DefaultStoryType
retrievingStories = false
refreshControl = UIRefreshControl()
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
retrieveStories()
}
// MARK: Functions
func configureUI() {
refreshControl.addTarget(self, action: "retrieveStories", forControlEvents: .ValueChanged)
refreshControl.attributedTitle = NSAttributedString(string: PullToRefreshString)
tableView.insertSubview(refreshControl, atIndex: 0)
// Have to initialize this UILabel here because the view does not exist in init() yet.
errorMessageLabel = UILabel(frame: CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height))
errorMessageLabel.textColor = ErrorMessageLabelTextColor
errorMessageLabel.textAlignment = .Center
errorMessageLabel.font = UIFont.systemFontOfSize(ErrorMessageFontSize)
}
func retrieveStories() {
if retrievingStories! {
return
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
stories = []
retrievingStories = true
var storiesMap = [Int:Story]()
let query = firebase.childByAppendingPath(StoryTypeChildRefMap[storyType]).queryLimitedToFirst(StoryLimit)
query.observeSingleEventOfType(.Value, withBlock: { snapshot in
let storyIds = snapshot.value as! [Int]
for storyId in storyIds {
let query = self.firebase.childByAppendingPath(self.ItemChildRef).childByAppendingPath(String(storyId))
query.observeSingleEventOfType(.Value, withBlock: { snapshot in
let title = snapshot.value["title"] as! String
let url = snapshot.value["url"] as? String
let by = snapshot.value["by"] as! String
let score = snapshot.value["score"] as! Int
let story = Story(title: title, url: url, by: by, score: score)
storiesMap[storyId] = story
if storiesMap.count == Int(self.StoryLimit) {
var sortedStories = [Story]()
for storyId in storyIds {
sortedStories.append(storiesMap[storyId]!)
}
self.stories = sortedStories
self.tableView.reloadData()
self.refreshControl.endRefreshing()
self.retrievingStories = false
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}, withCancelBlock: { error in
self.retrievingStories = false
self.stories.removeAll()
self.tableView.reloadData()
self.showErrorMessage(self.FetchErrorMessage)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
}, withCancelBlock: { error in
self.retrievingStories = false
self.stories.removeAll()
self.tableView.reloadData()
self.showErrorMessage(self.FetchErrorMessage)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
func showErrorMessage(message: String) {
errorMessageLabel.text = message
self.tableView.backgroundView = errorMessageLabel
self.tableView.separatorStyle = .None
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stories.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let story = stories[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(PostCellIdentifier) as UITableViewCell!
cell.textLabel?.text = story.title
cell.detailTextLabel?.text = "\(story.score) points by \(story.by)"
return cell
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let story = stories[indexPath.row]
if let url = story.url {
let webViewController = SFSafariViewController(URL: NSURL(string: url)!)
webViewController.delegate = self
presentViewController(webViewController, animated: true, completion: nil)
}
}
// MARK: SFSafariViewControllerDelegate
func safariViewControllerDidFinish(controller: SFSafariViewController) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: IBActions
@IBAction func changeStoryType(sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
storyType = .Top
} else if sender.selectedSegmentIndex == 1 {
storyType = .New
} else if sender.selectedSegmentIndex == 2 {
storyType = .Show
} else {
print("Bad segment index!")
}
retrieveStories()
}
}
| mit | 00e8c0c9c32f74922da28e9128b5f5f5 | 32.073684 | 120 | 0.69478 | 5.035256 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Rules/ImplicitGetterRule.swift | 1 | 7956 | import Foundation
import SourceKittenFramework
public struct ImplicitGetterRule: ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "implicit_getter",
name: "Implicit Getter",
description: "Computed read-only properties and subscripts should avoid using the get keyword.",
kind: .style,
nonTriggeringExamples: ImplicitGetterRule.nonTriggeringExamples,
triggeringExamples: ImplicitGetterRule.triggeringExamples
)
private static var nonTriggeringExamples: [String] {
let commonExamples = [
"""
class Foo {
var foo: Int {
get { return 3 }
set { _abc = newValue }
}
}
""",
"""
class Foo {
var foo: Int {
return 20
}
}
""",
"""
class Foo {
static var foo: Int {
return 20
}
}
""",
"""
class Foo {
static var foo: Int {
get { return 3 }
set { _abc = newValue }
}
}
""",
"class Foo {\n var foo: Int\n}",
"""
class Foo {
var foo: Int {
return getValueFromDisk()
}
}
""",
"""
class Foo {
var foo: String {
return "get"
}
}
""",
"protocol Foo {\n var foo: Int { get }\n",
"protocol Foo {\n var foo: Int { get set }\n",
"""
class Foo {
var foo: Int {
struct Bar {
var bar: Int {
get { return 1 }
set { _ = newValue }
}
}
return Bar().bar
}
}
""",
"""
var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
""",
"""
var next: Int? {
mutating get {
defer { self.count += 1 }
return self.count
}
}
"""
]
guard SwiftVersion.current >= SwiftVersion.fourDotOne else {
return commonExamples
}
return commonExamples + [
"""
class Foo {
subscript(i: Int) -> Int {
return 20
}
}
""",
"""
class Foo {
subscript(i: Int) -> Int {
get { return 3 }
set { _abc = newValue }
}
}
""",
"protocol Foo {\n subscript(i: Int) -> Int { get }\n}",
"protocol Foo {\n subscript(i: Int) -> Int { get set }\n}"
]
}
private static var triggeringExamples: [String] {
let commonExamples = [
"""
class Foo {
var foo: Int {
↓get {
return 20
}
}
}
""",
"""
class Foo {
var foo: Int {
↓get{ return 20 }
}
}
""",
"""
class Foo {
static var foo: Int {
↓get {
return 20
}
}
}
""",
"var foo: Int {\n ↓get { return 20 }\n}",
"""
class Foo {
@objc func bar() {}
var foo: Int {
↓get {
return 20
}
}
}
"""
]
guard SwiftVersion.current >= SwiftVersion.fourDotOne else {
return commonExamples
}
return commonExamples + [
"""
class Foo {
subscript(i: Int) -> Int {
↓get {
return 20
}
}
}
"""
]
}
public func validate(file: File) -> [StyleViolation] {
let pattern = "\\{[^\\{]*?\\s+get\\b"
let attributesKinds: Set<SyntaxKind> = [.attributeBuiltin, .attributeID]
let getTokens: [SyntaxToken] = file.rangesAndTokens(matching: pattern).compactMap { _, tokens in
let kinds = tokens.compactMap { SyntaxKind(rawValue: $0.type) }
guard let token = tokens.last,
SyntaxKind(rawValue: token.type) == .keyword,
attributesKinds.isDisjoint(with: kinds) else {
return nil
}
return token
}
let violatingLocations = getTokens.compactMap { token -> (Int, SwiftDeclarationKind?)? in
// the last element is the deepest structure
guard let dict = declarations(forByteOffset: token.offset, structure: file.structure).last else {
return nil
}
// If there's a setter, `get` is allowed
guard dict.setterAccessibility == nil else {
return nil
}
let kind = dict.kind.flatMap(SwiftDeclarationKind.init(rawValue:))
return (token.offset, kind)
}
return violatingLocations.map { offset, kind in
let reason = kind.map { kind -> String in
let kindString = kind == .functionSubscript ? "subscripts" : "properties"
return "Computed read-only \(kindString) should avoid using the get keyword."
}
return StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset),
reason: reason)
}
}
private func declarations(forByteOffset byteOffset: Int,
structure: Structure) -> [[String: SourceKitRepresentable]] {
var results = [[String: SourceKitRepresentable]]()
let allowedKinds = SwiftDeclarationKind.variableKinds.subtracting([.varParameter])
.union([.functionSubscript])
func parse(dictionary: [String: SourceKitRepresentable], parentKind: SwiftDeclarationKind?) {
// Only accepts declarations which contains a body and contains the
// searched byteOffset
guard let kindString = dictionary.kind,
let kind = SwiftDeclarationKind(rawValue: kindString),
let bodyOffset = dictionary.bodyOffset,
let bodyLength = dictionary.bodyLength,
case let byteRange = NSRange(location: bodyOffset, length: bodyLength),
NSLocationInRange(byteOffset, byteRange) else {
return
}
if parentKind != .protocol && allowedKinds.contains(kind) {
results.append(dictionary)
}
for dictionary in dictionary.substructure {
parse(dictionary: dictionary, parentKind: kind)
}
}
for dictionary in structure.dictionary.substructure {
parse(dictionary: dictionary, parentKind: nil)
}
return results
}
}
| mit | 3f36617fb90f5bdd045c4afbd62fdca8 | 30.275591 | 109 | 0.427367 | 5.95949 | false | false | false | false |
sharath-cliqz/browser-ios | Storage/SQL/BrowserDB.swift | 2 | 19707 | /* 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 XCGLogger
import Deferred
import Shared
import Deferred
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
public let NotificationDatabaseWasRecreated = "NotificationDatabaseWasRecreated"
private let log = Logger.syncLogger
public typealias Args = [Any?]
protocol Changeable {
func run(_ sql: String, withArgs args: Args?) -> Success
func run(_ commands: [String]) -> Success
func run(_ commands: [(sql: String, args: Args?)]) -> Success
}
protocol Queryable {
func runQuery<T>(_ sql: String, args: Args?, factory: @escaping (SDRow) -> T) -> Deferred<Maybe<Cursor<T>>>
}
public enum DatabaseOpResult {
case success
case failure
case closed
}
// Version 1 - Basic history table.
// Version 2 - Added a visits table, refactored the history table to be a GenericTable.
// Version 3 - Added a favicons table.
// Version 4 - Added a readinglist table.
// Version 5 - Added the clients and the tabs tables.
// Version 6 - Visit timestamps are now microseconds.
// Version 7 - Eliminate most tables. See BrowserTable instead.
open class BrowserDB {
fileprivate let db: SwiftData
// XXX: Increasing this should blow away old history, since we currently don't support any upgrades.
fileprivate let Version: Int = 7
fileprivate let files: FileAccessor
fileprivate let filename: String
fileprivate let secretKey: String?
fileprivate let schemaTable: SchemaTable
fileprivate var initialized = [String]()
// SQLITE_MAX_VARIABLE_NUMBER = 999 by default. This controls how many ?s can
// appear in a query string.
open static let MaxVariableNumber = 999
public init(filename: String, secretKey: String? = nil, files: FileAccessor) {
log.debug("Initializing BrowserDB: \(filename).")
self.files = files
self.filename = filename
self.schemaTable = SchemaTable()
self.secretKey = secretKey
let file = ((try! files.getAndEnsureDirectory()) as NSString).appendingPathComponent(filename)
self.db = SwiftData(filename: file, key: secretKey, prevKey: nil)
if AppConstants.BuildChannel == .Developer && secretKey != nil {
log.debug("Creating db: \(file) with secret = \(secretKey)")
}
// Create or update will also delete and create the database if our key was incorrect.
switch self.createOrUpdate(self.schemaTable) {
case .failure:
log.error("Failed to create/update the scheme table. Aborting.")
fatalError()
case .closed:
log.info("Database not created as the SQLiteConnection is closed.")
case .success:
log.debug("db: \(file) with secret = \(secretKey) has been created")
}
if filename == "browser.db" {
// Cliqz: new method call to extend tables if needed
self.extendTables()
}
}
// Creates a table and writes its table info into the table-table database.
fileprivate func createTable(_ conn: SQLiteDBConnection, table: SectionCreator) -> TableResult {
log.debug("Try create \(table.name) version \(table.version)")
if !table.create(conn) {
// If creating failed, we'll bail without storing the table info
log.debug("Creation failed.")
return .failed
}
var err: NSError? = nil
return schemaTable.insert(conn, item: table, err: &err) > -1 ? .created : .failed
}
// Updates a table and writes its table into the table-table database.
// Exposed internally for testing.
func updateTable(_ conn: SQLiteDBConnection, table: SectionUpdater) -> TableResult {
log.debug("Trying update \(table.name) version \(table.version)")
var from = 0
// Try to find the stored version of the table
let cursor = schemaTable.query(conn, options: QueryOptions(filter: table.name))
if cursor.count > 0 {
if let info = cursor[0] as? TableInfoWrapper {
from = info.version
}
}
// If the versions match, no need to update
if from == table.version {
return .exists
}
if !table.updateTable(conn, from: from) {
// If the update failed, we'll bail without writing the change to the table-table.
log.debug("Updating failed.")
return .failed
}
var err: NSError? = nil
// Yes, we UPDATE OR INSERT… because we might be transferring ownership of a database table
// to a different Table. It'll trigger exists, and thus take the update path, but we won't
// necessarily have an existing schema entry -- i.e., we'll be updating from 0.
if schemaTable.update(conn, item: table, err: &err) > 0 ||
schemaTable.insert(conn, item: table, err: &err) > 0 {
return .updated
}
return .failed
}
// Utility for table classes. They should call this when they're initialized to force
// creation of the table in the database.
func createOrUpdate(_ tables: Table...) -> DatabaseOpResult {
guard !db.closed else {
log.info("Database is closed - skipping schema create/updates")
return .closed
}
var success = true
let doCreate = { (table: Table, connection: SQLiteDBConnection) -> () in
switch self.createTable(connection, table: table) {
case .created:
success = true
return
case .exists:
log.debug("Table already exists.")
success = true
return
default:
success = false
}
}
if let _ = self.db.transaction({ connection -> Bool in
let thread = Thread.current.description
// If the table doesn't exist, we'll create it.
for table in tables {
log.debug("Create or update \(table.name) version \(table.version) on \(thread).")
if !table.exists(connection) {
log.debug("Doesn't exist. Creating table \(table.name).")
doCreate(table, connection)
} else {
// Otherwise, we'll update it
switch self.updateTable(connection, table: table) {
case .updated:
log.debug("Updated table \(table.name).")
success = true
break
case .exists:
log.debug("Table \(table.name) already exists.")
success = true
break
default:
log.error("Update failed for \(table.name). Dropping and recreating.")
table.drop(connection)
var err: NSError? = nil
self.schemaTable.delete(connection, item: table, err: &err)
doCreate(table, connection)
}
}
if !success {
log.warning("Failed to configure multiple tables. Aborting.")
return false
}
}
// Cliqz: Added notification to notify when db creation is finished
let notify = Notification(name: Notification.Name(rawValue: NotificationDatabaseWasCreated), object: self.filename)
NotificationCenter.default.post(notify)
return success
}) {
// Err getting a transaction
success = false
}
// If we failed, move the file and try again. This will probably break things that are already
// attached and expecting a working DB, but at least we should be able to restart.
var notify: Notification? = nil
if !success {
log.debug("Couldn't create or update \(tables.map { $0.name }).")
log.debug("Attempting to move \(self.filename) to another location.")
// Make sure that we don't still have open the files that we want to move!
// Note that we use sqlite3_close_v2, which might actually _not_ close the
// database file yet. For this reason we move the -shm and -wal files, too.
db.forceClose()
// Note that a backup file might already exist! We append a counter to avoid this.
var bakCounter = 0
var bak: String
repeat {
bakCounter += 1
bak = "\(self.filename).bak.\(bakCounter)"
} while self.files.exists(bak)
do {
try self.files.move(self.filename, toRelativePath: bak)
let shm = self.filename + "-shm"
let wal = self.filename + "-wal"
log.debug("Moving \(shm) and \(wal)…")
if self.files.exists(shm) {
log.debug("\(shm) exists.")
try self.files.move(shm, toRelativePath: bak + "-shm")
}
if self.files.exists(wal) {
log.debug("\(wal) exists.")
try self.files.move(wal, toRelativePath: bak + "-wal")
}
success = true
// Notify the world that we moved the database. This allows us to
// reset sync and start over in the case of corruption.
let notification = NotificationDatabaseWasRecreated
notify = Notification(name: Notification.Name(rawValue: notification), object: self.filename)
} catch _ {
success = false
}
assert(success)
// Do this after the relevant tables have been created.
defer {
if let notify = notify {
NotificationCenter.default.post(notify)
}
}
self.reopenIfClosed()
if let _ = db.transaction({ connection -> Bool in
for table in tables {
doCreate(table, connection)
if !success {
return false
}
}
return success
}) {
success = false;
}
}
return success ? .success : .failure
}
typealias IntCallback = (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> Int
func withConnection<T>(flags: SwiftData.Flags, err: inout NSError?, callback: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> T) -> T {
var res: T!
err = db.withConnection(flags) { connection in
// This should never occur. Make it fail hard in debug builds.
assert(!(connection is FailedSQLiteDBConnection))
var err: NSError? = nil
res = callback(connection, &err)
return err
}
return res
}
func withWritableConnection<T>(_ err: inout NSError?, callback: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> T) -> T {
return withConnection(flags: SwiftData.Flags.readWrite, err: &err, callback: callback)
}
func withReadableConnection<T>(_ err: inout NSError?, callback: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> Cursor<T>) -> Cursor<T> {
return withConnection(flags: SwiftData.Flags.readOnly, err: &err, callback: callback)
}
func transaction(_ err: inout NSError?, callback: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> Bool) -> NSError? {
return self.transaction(synchronous: true, err: &err, callback: callback)
}
func transaction(synchronous: Bool=true, err: inout NSError?, callback: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> Bool) -> NSError? {
return db.transaction(synchronous: synchronous) { connection in
// Cliqz: Fixed bug: extra declaration of local variable which overrides method argument and cause wrong behaviour in the case of failing query
var error: NSError? = nil
return callback(connection, &error)
}
}
}
extension BrowserDB {
func vacuum() {
log.debug("Vacuuming a BrowserDB.")
db.withConnection(SwiftData.Flags.readWriteCreate, synchronous: true) { connection in
return connection.vacuum()
}
}
func checkpoint() {
log.debug("Checkpointing a BrowserDB.")
db.transaction(synchronous: true) { connection in
connection.checkpoint()
return true
}
}
}
extension BrowserDB {
public class func varlist(_ count: Int) -> String {
return "(" + Array(repeating: "?", count: count).joined(separator: ", ") + ")"
}
enum InsertOperation: String {
case Insert = "INSERT"
case Replace = "REPLACE"
case InsertOrIgnore = "INSERT OR IGNORE"
case InsertOrReplace = "INSERT OR REPLACE"
case InsertOrRollback = "INSERT OR ROLLBACK"
case InsertOrAbort = "INSERT OR ABORT"
case InsertOrFail = "INSERT OR FAIL"
}
/**
* Insert multiple sets of values into the given table.
*
* Assumptions:
* 1. The table exists and contains the provided columns.
* 2. Every item in `values` is the same length.
* 3. That length is the same as the length of `columns`.
* 4. Every value in each element of `values` is non-nil.
*
* If there are too many items to insert, multiple individual queries will run
* in sequence.
*
* A failure anywhere in the sequence will cause immediate return of failure, but
* will not roll back — use a transaction if you need one.
*/
func bulkInsert(_ table: String, op: InsertOperation, columns: [String], values: [Args]) -> Success {
// Note that there's a limit to how many ?s can be in a single query!
// So here we execute 999 / (columns * rows) insertions per query.
// Note that we can't use variables for the column names, so those don't affect the count.
if values.isEmpty {
log.debug("No values to insert.")
return succeed()
}
let variablesPerRow = columns.count
// Sanity check.
assert(values[0].count == variablesPerRow)
let cols = columns.joined(separator: ", ")
let queryStart = "\(op.rawValue) INTO \(table) (\(cols)) VALUES "
let varString = BrowserDB.varlist(variablesPerRow)
let insertChunk: ([Args]) -> Success = { vals -> Success in
let valuesString = Array(repeating: varString, count: vals.count).joined(separator: ", ")
let args: Args = vals.flatMap { $0 }
return self.run(queryStart + valuesString, withArgs: args)
}
let rowCount = values.count
if (variablesPerRow * rowCount) < BrowserDB.MaxVariableNumber {
return insertChunk(values)
}
log.debug("Splitting bulk insert across multiple runs. I hope you started a transaction!")
let rowsPerInsert = (999 / variablesPerRow)
let chunks = chunk(values, by: rowsPerInsert)
log.debug("Inserting in \(chunks.count) chunks.")
// There's no real reason why we can't pass the ArraySlice here, except that I don't
// want to keep fighting Swift.
return walk(chunks, f: { insertChunk(Array($0)) })
}
func runWithConnection<T>(_ block: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> T) -> Deferred<Maybe<T>> {
return DeferredDBOperation(db: self.db, block: block).start()
}
func write(_ sql: String, withArgs args: Args? = nil) -> Deferred<Maybe<Int>> {
return self.runWithConnection() { (connection, err) -> Int in
err = connection.executeChange(sql, withArgs: args)
if err == nil {
let modified = connection.numberOfRowsModified
log.debug("Modified rows: \(modified).")
return modified
}
return 0
}
}
public func forceClose() {
db.forceClose()
}
public func reopenIfClosed() {
db.reopenIfClosed()
}
}
extension BrowserDB: Changeable {
func run(_ sql: String, withArgs args: Args? = nil) -> Success {
return run([(sql, args)])
}
func run(_ commands: [String]) -> Success {
return self.run(commands.map { (sql: $0, args: nil) })
}
/**
* Runs an array of SQL commands. Note: These will all run in order in a transaction and will block
* the caller's thread until they've finished. If any of them fail the operation will abort (no more
* commands will be run) and the transaction will roll back, returning a DatabaseError.
*/
func run(_ commands: [(sql: String, args: Args?)]) -> Success {
if commands.isEmpty {
return succeed()
}
var err: NSError? = nil
let errorResult = self.transaction(&err) { (conn, err) -> Bool in
for (sql, args) in commands {
err = conn.executeChange(sql, withArgs: args)
if let err = err {
log.warning("SQL operation failed: \(err.localizedDescription)")
return false
}
}
return true
}
if let err = err ?? errorResult {
return deferMaybe(DatabaseError(err: err))
}
return succeed()
}
}
extension BrowserDB: Queryable {
func runQuery<T>(_ sql: String, args: Args?, factory: @escaping (SDRow) -> T) -> Deferred<Maybe<Cursor<T>>> {
return runWithConnection { (connection, err) -> Cursor<T> in
return connection.executeQuery(sql, factory: factory, withArgs: args)
}
}
func queryReturnsResults(_ sql: String, args: Args?=nil) -> Deferred<Maybe<Bool>> {
return self.runQuery(sql, args: args, factory: { row in true })
>>== { deferMaybe($0[0] ?? false) }
}
func queryReturnsNoResults(_ sql: String, args: Args?=nil) -> Deferred<Maybe<Bool>> {
return self.runQuery(sql, args: nil, factory: { row in false })
>>== { deferMaybe($0[0] ?? true) }
}
}
extension SQLiteDBConnection {
func tablesExist(_ names: [String]) -> Bool {
let count = names.count
let inClause = BrowserDB.varlist(names.count)
let tablesSQL = "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN \(inClause)"
let res = self.executeQuery(tablesSQL, factory: StringFactory, withArgs: names.map { $0 as AnyObject })
log.debug("\(res.count) tables exist. Expected \(count)")
return res.count > 0
}
}
| mpl-2.0 | 87f7d5b1466f288b6b6c0dc7ef5194c8 | 37.478516 | 166 | 0.589564 | 4.731268 | false | false | false | false |
orih/GitLabKit | GitLabKit/ProjectQueryParamBuilder.swift | 1 | 2742 | //
// ProjectQueryParamBuilder.swift
// GitLabKit
//
// Copyright (c) 2017 toricls. 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
open class ProjectQueryParamBuilder: GeneralQueryParamBuilder {
open func id(_ id: UInt) -> Self {
if params["id"] != nil || params["namespaceAndName"] != nil {
return self
}
params["id"] = id as AnyObject
return self
}
open func nameAndNamespace(_ name: String, namespace: String) -> Self {
if params["id"] != nil || params["namespaceAndName"] != nil {
return self
}
params["namespaceAndName"] = "\(namespace)/\(name)" as AnyObject
return self
}
open func owned(_ owned: Bool) -> Self {
params["owned"] = owned ? true as AnyObject? : nil as AnyObject?
return self
}
open func archived(_ archived: Bool) -> Self {
params["archived"] = archived ? "true" as AnyObject? : nil as AnyObject?
return self
}
open func orderBy(_ order: ProjectOrderBy?) -> Self {
params["order_by"] = order?.rawValue as AnyObject
return self
}
open func sort(_ sort: ProjectSort?) -> Self {
params["sort"] = sort?.rawValue as AnyObject
return self
}
open func search(_ str: String) -> Self {
params["search"] = str as AnyObject
return self
}
}
public enum ProjectOrderBy: String {
case Id = "id"
case Name = "name"
case CreatedAt = "created_at"
case LastActivityAt = "last_activity_at"
}
public enum ProjectSort: String {
case Asc = "asc"
case Desc = "desc"
}
| mit | 22685575de1fa06ad99195d21467c709 | 32.851852 | 81 | 0.649161 | 4.366242 | false | false | false | false |
CosmicMind/Motion | Sources/Preprocessors/ConditionalPreprocessor.swift | 3 | 3324 | /*
* The MIT License (MIT)
*
* Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>.
* 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 struct MotionConditionalContext {
internal weak var motion: MotionTransition!
public weak var view: UIView!
public private(set) var isAppearing: Bool
public var isPresenting: Bool {
return motion.isPresenting
}
public var isTabBarController: Bool {
return motion.isTabBarController
}
public var isNavigationController: Bool {
return motion.isNavigationController
}
public var isMatched: Bool {
return nil != matchedView
}
public var isAncestorViewMatched: Bool {
return nil != matchedAncestorView
}
public var matchedView: UIView? {
return motion.context.pairedView(for: view)
}
public var matchedAncestorView: (UIView, UIView)? {
var current = view.superview
while let ancestor = current, ancestor != motion.context.container {
if let pairedView = motion.context.pairedView(for: ancestor) {
return (ancestor, pairedView)
}
current = ancestor.superview
}
return nil
}
public var fromViewController: UIViewController {
return motion.fromViewController!
}
public var toViewController: UIViewController {
return motion.toViewController!
}
public var currentViewController: UIViewController {
return isAppearing ? toViewController : fromViewController
}
public var otherViewController: UIViewController {
return isAppearing ? fromViewController : toViewController
}
}
class ConditionalPreprocessor: MotionCorePreprocessor {
override func process(fromViews: [UIView], toViews: [UIView]) {
process(views: fromViews, isAppearing: false)
process(views: toViews, isAppearing: true)
}
func process(views: [UIView], isAppearing: Bool) {
for v in views {
guard let conditionalModifiers = context[v]?.conditionalModifiers else {
continue
}
for (condition, modifiers) in conditionalModifiers {
if condition(MotionConditionalContext(motion: motion, view: v, isAppearing: isAppearing)) {
context[v]!.append(contentsOf: modifiers)
}
}
}
}
}
| mit | 772cde310a6997edd4851b8ffe572583 | 29.495413 | 99 | 0.715704 | 4.782734 | false | false | false | false |
StachkaConf/ios-app | StachkaIOS/StachkaIOS/Classes/User Stories/Talks/Filters/ViewModel/FiltersViewModelImplementation.swift | 1 | 3081 | //
// FiltersViewModelImplementation.swift
// StachkaIOS
//
// Created by m.rakhmanov on 27.03.17.
// Copyright © 2017 m.rakhmanov. All rights reserved.
//
import RxSwift
import RealmSwift
class FiltersViewModelImplementation: FiltersViewModel {
var filters: Observable<[FilterCellViewModel]> {
return _filters.asObservable()
}
var title: Observable<String> {
return _title.asObservable()
}
var _filters: Variable<[FilterCellViewModel]> = Variable([])
var _title: Variable<String> = Variable("")
let disposeBag = DisposeBag()
fileprivate let filterFactory: FilterFactory
fileprivate let filterCellViewModelFactory: FilterCellViewModelFactory
fileprivate let filterService: FilterService
fileprivate let parentFilter: ParentFilter
fileprivate weak var view: FiltersView?
init(view: FiltersView,
filterService: FilterService,
filterFactory: FilterFactory,
filterCellViewModelFactory: FilterCellViewModelFactory,
parentFilter: ParentFilter) {
self.view = view
self.filterService = filterService
self.filterFactory = filterFactory
self.filterCellViewModelFactory = filterCellViewModelFactory
self.parentFilter = parentFilter
prepareViewModelsForParentFilter()
view.indexSelected
.subscribe(onNext: { [weak self] indexPath in
self?.changeFilterSelection(forIndex: indexPath.row)
})
.disposed(by: disposeBag)
view.dissappear
.subscribe(onCompleted: { [weak self] in
guard let strongSelf = self else { return }
let filters: [Filter] = [strongSelf.parentFilter] + strongSelf.parentFilter.childFilters
let updatedValues = strongSelf._filters.value.map { $0.selected }
strongSelf.filterService
.change(filters, using: updatedValues)
.subscribe()
.addDisposableTo(strongSelf.disposeBag)
})
.disposed(by: disposeBag)
}
private func prepareViewModelsForParentFilter() {
let viewModels = filterCellViewModelFactory.tickViewModels(fromParentFilter: parentFilter, filters: parentFilter.childFilters)
_filters.value = viewModels
_title.value = parentFilter.title
}
private func changeFilterSelection(forIndex index: Int) {
// если у нас родительская модель
if index == 0 {
let newValue = !_filters.value[0].selected
_filters.value = _filters.value.map {
var newModel = $0
newModel.selected = newValue
return newModel
}
} else {
_filters.value[0].selected = false
_filters.value[index].selected = !_filters.value[index].selected
if (_filters.value.filter { $0.selected }.count) == _filters.value.count - 1 {
_filters.value[0].selected = true
}
}
}
}
| mit | 90d1ca24cdc9590be2858fb0cf93f9ec | 34.103448 | 134 | 0.63425 | 5.185059 | false | false | false | false |
simonnarang/Fandom-IOS | Fandomm/PostViewController.swift | 1 | 2430 | //
// PostViewController.swift
// Fandomm
//
// Created by Simon Narang on 11/28/15.
// Copyright © 2015 Simon Narang. All rights reserved.
//
import UIKit
import MobileCoreServices
class PostViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
//vars
var userFandoms = [AnyObject]()
var usernameTwoTextThree = String()
//startup junk
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.tintColor = UIColor.purpleColor()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.purpleColor()]
print("the following array should be \(usernameTwoTextThree)'s fandoms, if it is empty thre is an err, likely network connection: \(userFandoms)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "segueTwo" {
let destViewContOne: ShareLinkViewController = segue.destinationViewController as! ShareLinkViewController
destViewContOne.usernameThreeTextOne = self.usernameTwoTextThree
destViewContOne.userFandoms = self.userFandoms
}else if segue.identifier == "segueFour" {
let desViewContThree: ShareCameraViewController = segue.destinationViewController as! ShareCameraViewController
desViewContThree.userFandoms = self.userFandoms
}else if segue.identifier == "segueFive" {
let destViewContTwo: ShareGalleryViewController = segue.destinationViewController as! ShareGalleryViewController
destViewContTwo.userFandoms = self.userFandoms
destViewContTwo.loggedInUsername = usernameTwoTextThree
}else {
print("there is an undocumented segue form the post tab")
}
}
/*
// 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.
}
*/
}
| unlicense | 441891906fa08ec694db5b4669fdd01c | 39.483333 | 154 | 0.706875 | 5.648837 | false | false | false | false |
naoyashiga/LegendTV | LegendTV/DeviceUtils.swift | 1 | 1000 | //
// DeviceUtils.swift
// Gaki
//
// Created by naoyashiga on 2015/08/05.
// Copyright (c) 2015年 naoyashiga. All rights reserved.
//
import Foundation
func iOSDevice() -> String {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
if 1.0 < UIScreen.mainScreen().scale {
let size = UIScreen.mainScreen().bounds.size
let scale = UIScreen.mainScreen().scale
let result = CGSizeMake(size.width * scale, size.height * scale)
switch result.height {
case 960:
return "4"
case 1136:
return "5"
case 1334:
return "6"
case 2208:
return "6Plus"
default:
return "unknown"
}
} else {
return "iPhone3"
}
} else {
if 1.0 < UIScreen.mainScreen().scale {
return "iPad Retina"
} else {
return "iPad"
}
}
} | mit | f9ad01c03e57cb3f671277496f5753b1 | 24.615385 | 76 | 0.492986 | 4.515837 | false | false | false | false |
practicalswift/swift | validation-test/Sema/type_checker_perf/fast/rdar46541800.swift | 6 | 2052 | // RUN: %target-typecheck-verify-swift
// RUN: %target-typecheck-verify-swift -solver-enable-operator-designated-types
// REQUIRES: OS=macosx
import simd
import CoreGraphics
import Foundation
class SomeView {
func layoutSubviews() {
let descriptionTextViewFrame = CGRect.zero
let availableBounds = CGRect()
let descriptionLabelProperties = SomeView.descriptionTextViewLabelProperties()
let textSize = descriptionTextView.sizeThatFits(availableBounds.size)
let textInset = descriptionTextView.textInset(forBounds: CGRect(origin: .zero, size: textSize))
let descriptionTextBaselineOffset: CGFloat = CGFloat()
let displayScale: CGFloat = CGFloat()
let _ = (descriptionTextViewFrame.height
+ (-descriptionTextView.lastBaselineOffsetFromBottom - textInset.bottom + descriptionLabelProperties.lastBaselineOffsetFromBottom)
+ (-descriptionTextView.firstBaselineOffsetFromTop - textInset.top + descriptionTextBaselineOffset).ceilingValue(scale: displayScale)
)
}
static func descriptionTextViewLabelProperties() -> FontDescriptorBaselineProperties {
fatalError()
}
lazy var descriptionTextView: SomeOtherView = SomeOtherView()
}
class SomeOtherView {
init() { }
func sizeThatFits(_ size: CGSize) -> CGSize { return size }
}
struct FontDescriptorBaselineProperties {
// let fontDescriptor: MPUFontDescriptor
let defaultFirstBaselineOffsetFromTop: CGFloat
let defaultLastBaselineOffsetFromBottom: CGFloat
var firstBaselineOffsetFromTop: CGFloat { fatalError() }
var lastBaselineOffsetFromBottom: CGFloat {
fatalError()
}
}
struct EdgeInsets {
var top: CGFloat
var bottom: CGFloat
}
extension SomeOtherView {
func textInset(forBounds bounds: CGRect) -> EdgeInsets { fatalError() }
var firstBaselineOffsetFromTop: CGFloat { fatalError() }
var lastBaselineOffsetFromBottom: CGFloat {
fatalError()
}
}
extension CGFloat {
public func ceilingValue(scale: CGFloat) -> CGFloat { fatalError() }
}
| apache-2.0 | c7589c198bd43262616b3f2cc78f942c | 32.096774 | 145 | 0.746101 | 5.13 | false | false | false | false |
practicalswift/swift | benchmark/single-source/ObjectiveCBridging.swift | 2 | 21912 | //===--- ObjectiveCBridging.swift -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Foundation
let t: [BenchmarkCategory] = [.validation, .bridging]
let ts: [BenchmarkCategory] = [.validation, .bridging, .String]
public let ObjectiveCBridging = [
BenchmarkInfo(name: "ObjectiveCBridgeFromNSString",
runFunction: run_ObjectiveCBridgeFromNSString, tags: t,
legacyFactor: 5),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSStringForced",
runFunction: run_ObjectiveCBridgeFromNSStringForced, tags: t,
legacyFactor: 5),
BenchmarkInfo(name: "ObjectiveCBridgeToNSString",
runFunction: run_ObjectiveCBridgeToNSString, tags: t),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSArrayAnyObject",
runFunction: run_ObjectiveCBridgeFromNSArrayAnyObject, tags: t,
legacyFactor: 100),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSArrayAnyObjectForced",
runFunction: run_ObjectiveCBridgeFromNSArrayAnyObjectForced, tags: t,
legacyFactor: 20),
BenchmarkInfo(name: "ObjectiveCBridgeToNSArray",
runFunction: run_ObjectiveCBridgeToNSArray, tags: t,
legacyFactor: 50),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSArrayAnyObjectToString",
runFunction: run_ObjectiveCBridgeFromNSArrayAnyObjectToString, tags: ts,
legacyFactor: 100),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSArrayAnyObjectToStringForced",
runFunction: run_ObjectiveCBridgeFromNSArrayAnyObjectToStringForced,
tags: ts, legacyFactor: 200),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSDictionaryAnyObject",
runFunction: run_ObjectiveCBridgeFromNSDictionaryAnyObject, tags: t,
legacyFactor: 100),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSDictionaryAnyObjectForced",
runFunction: run_ObjectiveCBridgeFromNSDictionaryAnyObjectForced, tags: t,
legacyFactor: 50),
BenchmarkInfo(name: "ObjectiveCBridgeToNSDictionary",
runFunction: run_ObjectiveCBridgeToNSDictionary, tags: t,
legacyFactor: 50),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSDictionaryAnyObjectToString",
runFunction: run_ObjectiveCBridgeFromNSDictionaryAnyObjectToString,
tags: ts, legacyFactor: 500),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced",
runFunction: run_ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced,
tags: ts, legacyFactor: 500),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSSetAnyObject",
runFunction: run_ObjectiveCBridgeFromNSSetAnyObject, tags: t,
legacyFactor: 200),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSSetAnyObjectForced",
runFunction: run_ObjectiveCBridgeFromNSSetAnyObjectForced, tags: t,
legacyFactor: 20),
BenchmarkInfo(name: "ObjectiveCBridgeToNSSet",
runFunction: run_ObjectiveCBridgeToNSSet, tags: t,
legacyFactor: 50),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSSetAnyObjectToString",
runFunction: run_ObjectiveCBridgeFromNSSetAnyObjectToString, tags: ts,
legacyFactor: 500),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSSetAnyObjectToStringForced",
runFunction: run_ObjectiveCBridgeFromNSSetAnyObjectToStringForced, tags: ts,
legacyFactor: 500),
BenchmarkInfo(name: "ObjectiveCBridgeFromNSDateComponents",
runFunction: run_ObjectiveCBridgeFromNSDateComponents, tags: t,
setUpFunction: setup_dateComponents),
]
#if _runtime(_ObjC)
@inline(never)
public func forcedCast<NS, T>(_ ns: NS) -> T {
return ns as! T
}
@inline(never)
public func conditionalCast<NS, T>(_ ns: NS) -> T? {
return ns as? T
}
#endif
// === String === //
#if _runtime(_ObjC)
func createNSString() -> NSString {
return NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!
}
@inline(never)
func testObjectiveCBridgeFromNSString() {
let nsString = createNSString()
var s: String?
for _ in 0 ..< 2_000 {
// Call _conditionallyBridgeFromObjectiveC.
let n : String? = conditionalCast(nsString)
if n != nil {
s = n!
}
}
CheckResults(s != nil && s == "NSString that does not fit in tagged pointer")
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSString(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSString()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeFromNSStringForced() {
let nsString = createNSString()
var s: String?
for _ in 0 ..< 2_000 {
// Call _forceBridgeFromObjectiveC
s = forcedCast(nsString)
}
CheckResults(s != nil && s == "NSString that does not fit in tagged pointer")
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSStringForced(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSStringForced()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeToNSString() {
let nativeString = "Native"
var s: NSString?
for _ in 0 ..< 10_000 {
// Call _BridgedToObjectiveC
s = nativeString as NSString
}
CheckResults(s != nil && s == "Native")
}
#endif
@inline(never)
public func run_ObjectiveCBridgeToNSString(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeToNSString()
}
}
#endif
}
// === Array === //
#if _runtime(_ObjC)
func createNSArray() -> NSArray {
let nsMutableArray = NSMutableArray()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
return nsMutableArray.copy() as! NSArray
}
@inline(never)
func testObjectiveCBridgeFromNSArrayAnyObject() {
let nsArray = createNSArray()
var nativeString : String?
for _ in 0 ..< 100 {
if let nativeArray : [NSString] = conditionalCast(nsArray) {
nativeString = forcedCast(nativeArray[0])
}
}
CheckResults(nativeString != nil && nativeString! == "NSString that does not fit in tagged pointer")
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSArrayAnyObject(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSArrayAnyObject()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeFromNSArrayAnyObjectForced() {
let nsArray = createNSArray()
var nativeString : String?
for _ in 0 ..< 500 {
let nativeArray : [NSString] = forcedCast(nsArray)
nativeString = forcedCast(nativeArray[0])
}
CheckResults(nativeString != nil && nativeString! == "NSString that does not fit in tagged pointer")
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSArrayAnyObjectForced(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSArrayAnyObjectForced()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeToNSArray() {
let nativeArray = ["abcde", "abcde", "abcde", "abcde", "abcde",
"abcde", "abcde", "abcde", "abcde", "abcde"]
var nsString : Any?
for _ in 0 ..< 200 {
let nsArray = nativeArray as NSArray
nsString = nsArray.object(at: 0)
}
CheckResults(nsString != nil && (nsString! as! NSString).isEqual("abcde"))
}
#endif
@inline(never)
public func run_ObjectiveCBridgeToNSArray(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeToNSArray()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeFromNSArrayAnyObjectToString() {
let nsArray = createNSArray()
var nativeString : String?
for _ in 0 ..< 100 {
if let nativeArray : [String] = conditionalCast(nsArray) {
nativeString = nativeArray[0]
}
}
CheckResults(nativeString != nil && nativeString == "NSString that does not fit in tagged pointer")
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSArrayAnyObjectToString(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSArrayAnyObjectToString()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeFromNSArrayAnyObjectToStringForced() {
let nsArray = createNSArray()
var nativeString : String?
for _ in 0 ..< 50 {
let nativeArray : [String] = forcedCast(nsArray)
nativeString = nativeArray[0]
}
CheckResults(nativeString != nil && nativeString == "NSString that does not fit in tagged pointer")
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSArrayAnyObjectToStringForced(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSArrayAnyObjectToStringForced()
}
}
#endif
}
// === Dictionary === //
#if _runtime(_ObjC)
func createNSDictionary() -> NSDictionary {
let nsMutableDictionary = NSMutableDictionary()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!
let nsString2 = NSString(cString: "NSString that does not fit in tagged pointer 2", encoding: String.Encoding.utf8.rawValue)!
let nsString3 = NSString(cString: "NSString that does not fit in tagged pointer 3", encoding: String.Encoding.utf8.rawValue)!
let nsString4 = NSString(cString: "NSString that does not fit in tagged pointer 4", encoding: String.Encoding.utf8.rawValue)!
let nsString5 = NSString(cString: "NSString that does not fit in tagged pointer 5", encoding: String.Encoding.utf8.rawValue)!
let nsString6 = NSString(cString: "NSString that does not fit in tagged pointer 6", encoding: String.Encoding.utf8.rawValue)!
let nsString7 = NSString(cString: "NSString that does not fit in tagged pointer 7", encoding: String.Encoding.utf8.rawValue)!
let nsString8 = NSString(cString: "NSString that does not fit in tagged pointer 8", encoding: String.Encoding.utf8.rawValue)!
let nsString9 = NSString(cString: "NSString that does not fit in tagged pointer 9", encoding: String.Encoding.utf8.rawValue)!
let nsString10 = NSString(cString: "NSString that does not fit in tagged pointer 10", encoding: String.Encoding.utf8.rawValue)!
nsMutableDictionary.setObject(1, forKey: nsString)
nsMutableDictionary.setObject(2, forKey: nsString2)
nsMutableDictionary.setObject(3, forKey: nsString3)
nsMutableDictionary.setObject(4, forKey: nsString4)
nsMutableDictionary.setObject(5, forKey: nsString5)
nsMutableDictionary.setObject(6, forKey: nsString6)
nsMutableDictionary.setObject(7, forKey: nsString7)
nsMutableDictionary.setObject(8, forKey: nsString8)
nsMutableDictionary.setObject(9, forKey: nsString9)
nsMutableDictionary.setObject(10, forKey: nsString10)
return nsMutableDictionary.copy() as! NSDictionary
}
@inline(never)
func testObjectiveCBridgeFromNSDictionaryAnyObject() {
let nsDictionary = createNSDictionary()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!
var nativeInt : Int?
for _ in 0 ..< 100 {
if let nativeDictionary : [NSString : NSNumber] = conditionalCast(nsDictionary) {
nativeInt = forcedCast(nativeDictionary[nsString])
}
}
CheckResults(nativeInt != nil && nativeInt == 1)
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSDictionaryAnyObject(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSDictionaryAnyObject()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeFromNSDictionaryAnyObjectForced() {
let nsDictionary = createNSDictionary()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!
var nativeInt : Int?
for _ in 0 ..< 200 {
if let nativeDictionary : [NSString : NSNumber] = forcedCast(nsDictionary) {
nativeInt = forcedCast(nativeDictionary[nsString])
}
}
CheckResults(nativeInt != nil && nativeInt == 1)
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSDictionaryAnyObjectForced(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSDictionaryAnyObjectForced()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeToNSDictionary() {
let nativeDictionary = ["abcde1": 1, "abcde2": 2, "abcde3": 3, "abcde4": 4,
"abcde5": 5, "abcde6": 6, "abcde7": 7, "abcde8": 8, "abcde9": 9,
"abcde10": 10]
let key = "abcde1" as NSString
var nsNumber : Any?
for _ in 0 ..< 200 {
let nsDict = nativeDictionary as NSDictionary
nsNumber = nsDict.object(forKey: key)
}
CheckResults(nsNumber != nil && (nsNumber as! Int) == 1)
}
#endif
@inline(never)
public func run_ObjectiveCBridgeToNSDictionary(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeToNSDictionary()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeFromNSDictionaryAnyObjectToString() {
let nsDictionary = createNSDictionary()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!
let nativeString = nsString as String
var nativeInt : Int?
for _ in 0 ..< 20 {
if let nativeDictionary : [String : Int] = conditionalCast(nsDictionary) {
nativeInt = nativeDictionary[nativeString]
}
}
CheckResults(nativeInt != nil && nativeInt == 1)
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSDictionaryAnyObjectToString(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSDictionaryAnyObjectToString()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced() {
let nsDictionary = createNSDictionary()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!
let nativeString = nsString as String
var nativeInt : Int?
for _ in 0 ..< 20 {
if let nativeDictionary : [String : Int] = forcedCast(nsDictionary) {
nativeInt = nativeDictionary[nativeString]
}
}
CheckResults(nativeInt != nil && nativeInt == 1)
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced()
}
}
#endif
}
// === Set === //
#if _runtime(_ObjC)
func createNSSet() -> NSSet {
let nsMutableSet = NSMutableSet()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!
let nsString2 = NSString(cString: "NSString that does not fit in tagged pointer 2", encoding: String.Encoding.utf8.rawValue)!
let nsString3 = NSString(cString: "NSString that does not fit in tagged pointer 3", encoding: String.Encoding.utf8.rawValue)!
let nsString4 = NSString(cString: "NSString that does not fit in tagged pointer 4", encoding: String.Encoding.utf8.rawValue)!
let nsString5 = NSString(cString: "NSString that does not fit in tagged pointer 5", encoding: String.Encoding.utf8.rawValue)!
let nsString6 = NSString(cString: "NSString that does not fit in tagged pointer 6", encoding: String.Encoding.utf8.rawValue)!
let nsString7 = NSString(cString: "NSString that does not fit in tagged pointer 7", encoding: String.Encoding.utf8.rawValue)!
let nsString8 = NSString(cString: "NSString that does not fit in tagged pointer 8", encoding: String.Encoding.utf8.rawValue)!
let nsString9 = NSString(cString: "NSString that does not fit in tagged pointer 9", encoding: String.Encoding.utf8.rawValue)!
let nsString10 = NSString(cString: "NSString that does not fit in tagged pointer 10", encoding: String.Encoding.utf8.rawValue)!
nsMutableSet.add(nsString)
nsMutableSet.add(nsString2)
nsMutableSet.add(nsString3)
nsMutableSet.add(nsString4)
nsMutableSet.add(nsString5)
nsMutableSet.add(nsString6)
nsMutableSet.add(nsString7)
nsMutableSet.add(nsString8)
nsMutableSet.add(nsString9)
nsMutableSet.add(nsString10)
return nsMutableSet.copy() as! NSSet
}
@inline(never)
func testObjectiveCBridgeFromNSSetAnyObject() {
let nsSet = createNSSet()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!
var result : Bool?
for _ in 0 ..< 50 {
if let nativeSet : Set<NSString> = conditionalCast(nsSet) {
result = nativeSet.contains(nsString)
}
}
CheckResults(result != nil && result!)
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSSetAnyObject(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSSetAnyObject()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeFromNSSetAnyObjectForced() {
let nsSet = createNSSet()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!
var result : Bool?
for _ in 0 ..< 500 {
if let nativeSet : Set<NSString> = forcedCast(nsSet) {
result = nativeSet.contains(nsString)
}
}
CheckResults(result != nil && result!)
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSSetAnyObjectForced(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSSetAnyObjectForced()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeToNSSet() {
let nativeSet = Set<String>(["abcde1", "abcde2", "abcde3", "abcde4", "abcde5",
"abcde6", "abcde7", "abcde8", "abcde9", "abcde10"])
let key = "abcde1" as NSString
var nsString : Any?
for _ in 0 ..< 200 {
let nsDict = nativeSet as NSSet
nsString = nsDict.member(key)
}
CheckResults(nsString != nil && (nsString as! String) == "abcde1")
}
#endif
@inline(never)
public func run_ObjectiveCBridgeToNSSet(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeToNSSet()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeFromNSSetAnyObjectToString() {
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!
let nativeString = nsString as String
let nsSet = createNSSet()
var result : Bool?
for _ in 0 ..< 20 {
if let nativeSet : Set<String> = conditionalCast(nsSet) {
result = nativeSet.contains(nativeString)
}
}
CheckResults(result != nil && result!)
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSSetAnyObjectToString(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSSetAnyObjectToString()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeFromNSSetAnyObjectToStringForced() {
let nsSet = createNSSet()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!
let nativeString = nsString as String
var result : Bool?
for _ in 0 ..< 20 {
if let nativeSet : Set<String> = forcedCast(nsSet) {
result = nativeSet.contains(nativeString)
}
}
CheckResults(result != nil && result!)
}
#endif
@inline(never)
public func run_ObjectiveCBridgeFromNSSetAnyObjectToStringForced(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
autoreleasepool {
testObjectiveCBridgeFromNSSetAnyObjectToStringForced()
}
}
#endif
}
#if _runtime(_ObjC)
//translated directly from an objc part of the original testcase
@objc class DictionaryContainer : NSObject {
@objc var _dictionary:NSDictionary
//simulate an objc property being imported via bridging
@objc var dictionary:Dictionary<DateComponents, String> {
@inline(never)
get {
return _dictionary as! Dictionary<DateComponents, String>
}
}
override init() {
_dictionary = NSDictionary()
super.init()
let dict = NSMutableDictionary()
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
let now = Date()
for day in 0..<36 {
let date = calendar.date(byAdding: .day, value: -day, to: now, options: NSCalendar.Options())
let components = calendar.components([.year, .month, .day], from: date!)
dict[components as NSDateComponents] = "TESTING"
}
_dictionary = NSDictionary(dictionary: dict)
}
}
var componentsContainer: DictionaryContainer? = nil
var componentsArray:[DateComponents]? = nil
#endif
public func setup_dateComponents() {
#if _runtime(_ObjC)
componentsContainer = DictionaryContainer()
let now = Date()
let calendar = Calendar(identifier: .gregorian)
componentsArray = (0..<10).compactMap { (day) -> DateComponents? in
guard let date = calendar.date(byAdding: .day, value: -day, to: now) else {
return nil
}
return calendar.dateComponents([.year, .month, .day], from: date)
}
#endif
}
@inline(never)
public func run_ObjectiveCBridgeFromNSDateComponents(_ N: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< N {
for components in componentsArray! {
let _ = componentsContainer!.dictionary[components]
}
}
#endif
}
| apache-2.0 | 14d5a83236f513b3b769589a393bd946 | 29.818565 | 129 | 0.718556 | 4.320189 | false | true | false | false |
Arnoymous/MappableObject | MappableObject/Classes/TransformType.swift | 1 | 1045 | //
// TransformType.swift
// Pods
//
// Created by Arnaud Dorgans on 02/09/2017.
//
//
import UIKit
import RealmSwift
import ObjectMapper
public class ListMappableObjectTransform<T: MappableObject>: TransformType {
public typealias JSON = [[String:Any]]
public typealias Object = List<T>
public let context: RealmMapContext?
public init(context: RealmMapContext? = nil) {
self.context = context
}
internal convenience init(map: Map) {
self.init(context: map.context as? RealmMapContext)
}
public func transformFromJSON(_ value: Any?) -> List<T>? {
if let objects = Mapper<T>(context: context).mapArray(JSONObject: value) {
let list = List<T>()
list.append(objectsIn: objects)
return list
}
return nil
}
public func transformToJSON(_ value: Object?) -> JSON? {
if let list = value {
return Mapper<T>(context: context).toJSONArray(Array(list))
}
return nil
}
}
| mit | 3c23441048c7f70f98f84607c8656c83 | 23.880952 | 82 | 0.609569 | 4.300412 | false | false | false | false |
koscida/Kos_AMAD_Spring2015 | Spring_16/IGNORE_work/projects/Girl_Game/Girl_Game/PlayerSprite.swift | 1 | 2711 | //
// CreateLevelSprite.swift
// Girl_Game
//
// Created by Brittany Kos on 4/14/16.
// Copyright © 2016 Kode Studios. All rights reserved.
//
import Foundation
import UIKit
import SpriteKit
class PlayerSprite: SKNode {
private var bodySprite = SKSpriteNode()
private var armorSprite = SKSpriteNode()
private var weaponSprite = SKSpriteNode()
private var size = CGSize()
private var max: CGFloat = 0
private var moveSpeed:CGFloat = 10
var topPosition: CGFloat = 0
var bottomPosition: CGFloat = 0
var leftPosition: CGFloat = 0
var rightPosition: CGFloat = 0
convenience init(name: String, bodyImageName: String, armorImageName: String, weaponImageName: String, x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, zPosition: CGFloat, maxHeight: CGFloat) {
self.init()
size = CGSize(width: width, height: height)
let position = CGPoint(x: x, y: y)
topPosition = y + (height/2)
bottomPosition = y - (height/2)
leftPosition = x - (width/2)
rightPosition = x + (width/2)
max = maxHeight
let bodyTexture = SKTexture(imageNamed: bodyImageName)
let armorTexture = SKTexture(imageNamed: armorImageName)
let weaponTexture = SKTexture(imageNamed: weaponImageName)
bodySprite.texture = bodyTexture
bodySprite.size = size
bodySprite.position = position
bodySprite.name = name
bodySprite.zPosition = zPosition
self.addChild(bodySprite)
armorSprite.texture = armorTexture
armorSprite.size = size
armorSprite.position = position
armorSprite.name = name
armorSprite.zPosition = (zPosition + 1)
self.addChild(armorSprite)
/*
weaponSprite.texture = weaponTexture
weaponSprite.size = size
weaponSprite.position = position
weaponSprite.name = name
weaponSprite.zPosition = (zPosition + 2)
self.addChild(weaponSprite)
*/
}
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func movePlayerUp() {
if super.position.y <= (max - (size.height/2)) {
super.position.y += moveSpeed
topPosition += moveSpeed
bottomPosition += moveSpeed
}
}
func movePlayerDown() {
if super.position.y >= (0 + (size.height/2)) {
super.position.y -= moveSpeed
topPosition -= moveSpeed
bottomPosition -= moveSpeed
}
}
} | gpl-3.0 | fbf7dc41ee72fe7dfd52dec52378508c | 26.663265 | 205 | 0.598893 | 4.83066 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/Demo/Modules/Demos/Components/QDImagePickerExampleViewController.swift | 1 | 13430 | //
// QDImagePickerExampleViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/5/9.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
let kAlbumContentType = QMUIAlbumContentType.all
let MaxSelectedImageCount: UInt = 9
let NormalImagePickingTag = 1045
let ModifiedImagePickingTag = 1046
let MultipleImagePickingTag = 1047
let SingleImagePickingTag = 1048
class QDImagePickerExampleViewController: QDCommonGroupListViewController {
private var selectedAvatarImage: UIImage?
private var imagesAsset: QMUIAsset?
override func initDataSource() {
super.initDataSource()
let od1 = QMUIOrderedDictionary(
dictionaryLiteral:
("默认", "选图控件包含相册列表,选图,预览大图三个界面"),
("自定义", "修改选图界面列数,预览大图界面 TopBar 背景色")
)
let od2 = QMUIOrderedDictionary(
dictionaryLiteral:
("选择多张图片", "模拟聊天发图,预览大图界面增加底部工具栏"),
("选择单张图片", "模拟设置头像,预览大图界面右上角增加按钮")
)
dataSource = QMUIOrderedDictionary(
dictionaryLiteral:
("选图控件使用示例", od1),
("通过重载进行添加 subview 等较大型的改动", od2))
}
override func didSelectCell(_ title: String) {
authorizationPresentAlbumViewController(with: title)
}
private func authorizationPresentAlbumViewController(with title: String) {
if QMUIAssetsManager.authorizationStatus == .notDetermined {
QMUIAssetsManager.requestAuthorization { (status) in
DispatchQueue.main.async {
self.presentAlbumViewController(with: title)
}
}
} else {
presentAlbumViewController(with: title)
}
}
private func presentAlbumViewController(with title: String) {
// 创建一个 QMUIAlbumViewController 实例用于呈现相簿列表
let albumViewController = QMUIAlbumViewController()
albumViewController.albumViewControllerDelegate = self
albumViewController.contentType = kAlbumContentType
albumViewController.title = title
if title == "选择单张图片" {
albumViewController.view.tag = SingleImagePickingTag
} else if title == "选择多张图片" {
albumViewController.view.tag = MultipleImagePickingTag
} else if title == "调整界面" {
albumViewController.view.tag = ModifiedImagePickingTag
albumViewController.albumTableViewCellHeight = 70
} else {
albumViewController.view.tag = NormalImagePickingTag
}
let navigationController = QDNavigationController(rootViewController: albumViewController)
// 获取最近发送图片时使用过的相簿,如果有则直接进入该相簿
albumViewController.pickLastAlbumGroupDirectlyIfCan()
present(navigationController, animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
let title = keyName(at: indexPath)
if title == "选择单张图片" {
let accessoryView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
accessoryView.layer.borderColor = UIColorSeparator.cgColor
accessoryView.layer.borderWidth = PixelOne
accessoryView.contentMode = .scaleAspectFill
accessoryView.clipsToBounds = true
accessoryView.image = selectedAvatarImage
cell.accessoryView = accessoryView
} else {
cell.accessoryType = .disclosureIndicator
}
return cell
}
// MARK: 业务方法
fileprivate func startLoading(text: String? = nil) {
QMUITips.showLoading(text: text, in: view)
}
fileprivate func stopLoading() {
QMUITips.hideAllToast(in: view, animated: true)
}
@objc fileprivate func showTipLabel(_ text: String) {
DispatchQueue.main.async {
self.stopLoading()
QMUITips.show(text: text, in: self.view, hideAfterDelay: 1.0)
}
}
fileprivate func hideTipLabel() {
QMUITips.hideAllToast(in: view, animated: true)
}
fileprivate func sendImageWithImagesAssetArrayIfDownloadStatusSucceed(_ imagesAssetArray: [QMUIAsset]) {
if QMUIImagePickerHelper.imageAssetsDownloaded(imagesAssetArray: imagesAssetArray) {
// 所有资源从 iCloud 下载成功,模拟发送图片到服务器
// 显示发送中
showTipLabel("发送中")
// 使用 delay 模拟网络请求时长
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
Thread.detachNewThreadSelector(#selector(self.showTipLabel(_:)), toTarget:self, with: "成功发送\(imagesAssetArray.count)个资源")
}
}
}
fileprivate func sendImage(with imagesAssetArray: [QMUIAsset]) {
for asset in imagesAssetArray {
QMUIImagePickerHelper.requestImageAssetIfNeeded(asset: asset) { [weak self] (downloadStatus, error) in
if downloadStatus == .downloading {
self?.startLoading(text: "从 iCloud 加载中")
} else if downloadStatus == .succeed {
self?.sendImageWithImagesAssetArrayIfDownloadStatusSucceed(imagesAssetArray)
} else {
self?.showTipLabel("iCloud 下载错误,请重新选图")
}
}
}
}
@objc fileprivate func setAvatar(with avatarImage: UIImage) {
DispatchQueue.main.async {
self.stopLoading()
self.selectedAvatarImage = avatarImage
let indexPath = IndexPath(row: 1, section: 1)
self.tableView.reloadRows(at: [indexPath], with: .fade)
}
}
}
extension QDImagePickerExampleViewController: QMUIAlbumViewControllerDelegate {
func imagePickerViewController(for albumViewController: QMUIAlbumViewController) -> QMUIImagePickerViewController {
let imagePickerViewController = QMUIImagePickerViewController()
imagePickerViewController.imagePickerViewControllerDelegate = self
imagePickerViewController.maximumSelectImageCount = MaxSelectedImageCount
imagePickerViewController.view.tag = albumViewController.view.tag
if albumViewController.view.tag == SingleImagePickingTag {
imagePickerViewController.allowsMultipleSelection = false
}
if albumViewController.view.tag == ModifiedImagePickingTag {
imagePickerViewController.minimumImageWidth = 65
}
return imagePickerViewController
}
}
extension QDImagePickerExampleViewController: QMUIImagePickerViewControllerDelegate {
func imagePickerViewController(_ imagePickerViewController: QMUIImagePickerViewController, didFinishPickingImageWith imagesAssetArray: [QMUIAsset]) {
// 储存最近选择了图片的相册,方便下次直接进入该相册
if let assetsGroup = imagePickerViewController.assetsGroup {
QMUIImagePickerHelper.updateLastestAlbum(with: assetsGroup, albumContentType: kAlbumContentType, userIdentify: nil)
}
sendImage(with: imagesAssetArray)
}
func imagePickerPreviewViewController(for imagePickerViewController: QMUIImagePickerViewController) -> QMUIImagePickerPreviewViewController {
if imagePickerViewController.view.tag == MultipleImagePickingTag {
let imagePickerPreviewViewController = QDMultipleImagePickerPreviewViewController()
imagePickerPreviewViewController.multipleDelegate = self
imagePickerPreviewViewController.maximumSelectImageCount = MaxSelectedImageCount
imagePickerPreviewViewController.assetsGroup = imagePickerViewController.assetsGroup
imagePickerPreviewViewController.view.tag = imagePickerViewController.view.tag
return imagePickerPreviewViewController
} else if imagePickerViewController.view.tag == SingleImagePickingTag {
let imagePickerPreviewViewController = QDSingleImagePickerPreviewViewController()
imagePickerPreviewViewController.singleDelegate = self
imagePickerPreviewViewController.assetsGroup = imagePickerViewController.assetsGroup
imagePickerPreviewViewController.view.tag = imagePickerViewController.view.tag
return imagePickerPreviewViewController
} else if imagePickerViewController.view.tag == ModifiedImagePickingTag {
let imagePickerPreviewViewController = QMUIImagePickerPreviewViewController()
imagePickerPreviewViewController.delegate = self
imagePickerPreviewViewController.view.tag = imagePickerViewController.view.tag
imagePickerPreviewViewController.toolBarBackgroundColor = UIColor(r: 66, g: 66, b: 66)
return imagePickerPreviewViewController
} else {
let imagePickerPreviewViewController = QMUIImagePickerPreviewViewController()
imagePickerPreviewViewController.delegate = self
imagePickerPreviewViewController.view.tag = imagePickerViewController.view.tag
return imagePickerPreviewViewController
}
}
}
extension QDImagePickerExampleViewController: QMUIImagePickerPreviewViewControllerDelegate {
func imagePickerPreviewViewController(_ imagePickerPreviewViewController: QMUIImagePickerPreviewViewController, didCheckImageAt index: Int) {
updateImageCountLabel(for: imagePickerPreviewViewController)
}
func imagePickerPreviewViewController(_ imagePickerPreviewViewController: QMUIImagePickerPreviewViewController, didUncheckImageAtIndex: Int) {
updateImageCountLabel(for: imagePickerPreviewViewController)
}
// 更新选中的图片数量
private func updateImageCountLabel(for imagePickerPreviewViewController: QMUIImagePickerPreviewViewController) {
if imagePickerPreviewViewController.view.tag == MultipleImagePickingTag {
guard let customImagePickerPreviewViewController = imagePickerPreviewViewController as? QDMultipleImagePickerPreviewViewController else {
return
}
let selectedCount = imagePickerPreviewViewController.selectedImageAssetArray.pointee.count
if selectedCount > 0 {
customImagePickerPreviewViewController.imageCountLabel.text = "\(selectedCount)"
customImagePickerPreviewViewController.imageCountLabel.isHidden = false
QMUIImagePickerHelper.springAnimationOfImageSelectedCountChange(with: customImagePickerPreviewViewController.imageCountLabel)
} else {
customImagePickerPreviewViewController.imageCountLabel.isHidden = true
}
}
}
}
extension QDImagePickerExampleViewController: QDMultipleImagePickerPreviewViewControllerDelegate {
func imagePickerPreviewViewController(_ imagePickerPreviewViewController: QDMultipleImagePickerPreviewViewController, sendImageWithImagesAssetArray imagesAssetArray: [QMUIAsset]) {
// 储存最近选择了图片的相册,方便下次直接进入该相册
QMUIImagePickerHelper.updateLastestAlbum(with: imagePickerPreviewViewController.assetsGroup!, albumContentType: kAlbumContentType, userIdentify: nil)
sendImage(with: imagesAssetArray)
}
}
extension QDImagePickerExampleViewController: QDSingleImagePickerPreviewViewControllerDelegate {
func imagePickerPreviewViewController(_ imagePickerPreviewViewController: QDSingleImagePickerPreviewViewController, didSelectImageWithImagesAsset imagesAsset: QMUIAsset) {
// 储存最近选择了图片的相册,方便下次直接进入该相册
QMUIImagePickerHelper.updateLastestAlbum(with: imagePickerPreviewViewController.assetsGroup!, albumContentType: kAlbumContentType, userIdentify: nil)
// 显示 loading
startLoading()
self.imagesAsset = imagesAsset
imagesAsset.requestImageData { (imageData, info, isGif, isHEIC) in
guard let imageData = imageData else {
return
}
var targetImage = UIImage(data: imageData)
if isHEIC {
// iOS 11 中新增 HEIF/HEVC 格式的资源,直接发送新格式的照片到不支持新格式的设备,照片可能会无法识别,可以先转换为通用的 JPEG 格式再进行使用。
// 详细请浏览:https://github.com/QMUI/QMUI_iOS/issues/224
guard let tmpImage = targetImage, let data = tmpImage.jpegData(compressionQuality: 1) else {
return
}
targetImage = UIImage(data: data)
} else {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.8) {
Thread.detachNewThreadSelector(#selector(self.setAvatar(with:)), toTarget:self, with: targetImage)
}
}
}
}
}
| mit | 893c9cad03f27c1bb3812dcf713c9a71 | 44.293907 | 184 | 0.693836 | 6.031981 | false | false | false | false |
glassonion1/R9HTTPRequest | R9HTTPRequest/HttpDataClient.swift | 1 | 901 | //
// HttpDataClient.swift
// R9HTTPRequest
//
// Created by taisuke fujita on 2017/10/03.
// Copyright © 2017年 Revolution9. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
public class HttpDataClient: HttpClient {
public typealias ResponseType = Data
public init() {
}
public func action(method: HttpClientMethodType, url: URL, requestBody: Data?, headers: HTTPHeaders?) -> Observable<Data> {
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
request.allHTTPHeaderFields = headers
request.addValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
request.httpBody = requestBody
let scheduler = ConcurrentDispatchQueueScheduler(qos: .background)
return URLSession.shared.rx.data(request: request).timeout(30, scheduler: scheduler)
}
}
| mit | 8dda6dff806cb2fb5d15c5962e891f54 | 28.933333 | 127 | 0.698218 | 4.558376 | false | false | false | false |
akihiko-fujii/dualmap_af | mapruler1/mapruler1/citySelectViewController.swift | 2 | 3497 | //
// citySelectViewController.swift
// mapruler1
//
// Created by af2 on 11/11/15.
// Copyright © 2015 af2. All rights reserved.
//
import UIKit
class citySelectViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// let barHeight: CGFloat = UIApplication.sharedApplication().statusBarFrame.size.height
// let barHeight: CGFloat = UIApplication.sharedApplication().statusBarFrame.size.height
let barHeight: CGFloat = 60
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height
myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight - barHeight))
myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
myTableView.dataSource = self
myTableView.delegate = self
self.view.addSubview(myTableView)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var dict:Dictionary = Dictionary<String,String>()
if(indexPath.row<appDelegate.dictionaries.count){
dict = appDelegate.dictionaries[indexPath.row]
}
// let myDoubl = (dict["latitude"]! as NSString).doubleValue
// set the city1 name.
print("selected city is",dict["cityName"]!)
appDelegate.selectedCityName1 = dict["cityName"]!
// set the value of city1 latitude.
let numberFormatter = NSNumberFormatter()
var number = numberFormatter.numberFromString(dict["latitude"]!)
appDelegate.selectedCityLatitude1 = number!.doubleValue
// set the value of city1 longitude.
number = numberFormatter.numberFromString(dict["longitude"]!)
appDelegate.selectedCityLongitude1 = number!.doubleValue
// set the value of city1 scale.
number = numberFormatter.numberFromString(dict["scale"]!)
appDelegate.selectedCityScale1 = number!.doubleValue
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
return appDelegate.dictionaries.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath)
cell.backgroundColor = UIColor.grayColor()
cell.textLabel?.textColor = UIColor.whiteColor()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var dict:Dictionary = Dictionary<String,String>()
if(indexPath.row<appDelegate.dictionaries.count){
dict = appDelegate.dictionaries[indexPath.row]
}
// let myDoubl = (dict["latitude"]! as NSString).doubleValue
cell.textLabel!.text = dict["cityName"]
// cell.imageView!.image = UIImage(named: String(dict["countryName"]))
return cell
}
@IBAction func firstViewReturnActionForSegue(segue: UIStoryboardSegue) {
}
}
| gpl-2.0 | b18a29a47f9c2e225949cac008b57da7 | 36.591398 | 124 | 0.665332 | 5.558029 | false | false | false | false |
peaks-cc/iOS11_samplecode | chapter_12/HomeKitSample/App/Code/Controller/ServicesViewController.swift | 1 | 4085 | //
// ServicesViewController.swift
//
// Created by ToKoRo on 2017-08-21.
//
import UIKit
import HomeKit
class ServicesViewController: UITableViewController, ContextHandler {
typealias ContextType = ServiceStore
@IBInspectable var isSelectMode: Bool = false
var store: ServiceStore { return context! }
var services: [HMService] { return store.services }
var selectedService: HMService?
override func viewDidLoad() {
super.viewDidLoad()
if !isSelectMode && !store.isServiceAddable {
navigationItem.rightBarButtonItem = nil
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refresh()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "Service"?:
sendContext((selectedService, store), to: segue.destination)
case "SelectService"?:
let context: ServiceStore = {
switch store.serviceStoreKind {
case .accessory(let accessory):
return accessory.home ?? accessory
case .serviceGroup(let serviceGroup):
return serviceGroup.home ?? serviceGroup
case .home(let home):
return home
}
}()
sendContext(context, to: segue.destination)
default:
break
}
}
func refresh() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
func service(at indexPath: IndexPath) -> HMService? {
return services.safe[indexPath.row]
}
@IBAction func addButtonDidTap(sender: AnyObject) {
performSegue(withIdentifier: "SelectService", sender: nil)
}
@IBAction func cancelButtonDidTap(sender: AnyObject) {
dismiss(animated: true)
}
}
// MARK: - UITableViewDataSource
extension ServicesViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return services.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Service", for: indexPath)
if let service = service(at: indexPath) {
cell.textLabel?.text = service.name
cell.detailTextLabel?.text = service.localizedDescription
}
return cell
}
}
// MARK: - UITableViewDelegate
extension ServicesViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
defer { tableView.deselectRow(at: indexPath, animated: true) }
self.selectedService = service(at: indexPath)
if isSelectMode, let service = selectedService {
ResponderChain(from: self).send(service, protocol: ServiceSelector.self) { service, handler in
handler.selectService(service)
}
dismiss(animated: true)
} else {
performSegue(withIdentifier: "Service", sender: nil)
}
}
}
// MARK: - ServiceSelector
extension ServicesViewController: ServiceSelector {
func selectService(_ service: HMService) {
guard case .serviceGroup(let serviceGroup) = store.serviceStoreKind else {
return
}
serviceGroup.addService(service) { [weak self] error in
if let error = error {
print("# error: \(error)")
}
self?.refresh()
}
}
}
// MARK: - ServiceActionHandler
extension ServicesViewController: ServiceActionHandler {
func handleRemove(_ service: HMService) {
guard case .serviceGroup(let serviceGroup) = store.serviceStoreKind else {
return
}
serviceGroup.removeService(service) { [weak self] error in
if let error = error {
print("# error: \(error)")
}
self?.refresh()
}
}
}
| mit | ff03b4b141001b4ddb7746ad02a6220b | 27.767606 | 109 | 0.614688 | 5.138365 | false | false | false | false |
xuduo/socket.io-push-ios | source/SocketIOClientSwift/SocketIOClientOption.swift | 5 | 5251 | //
// SocketIOClientOption .swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/17/15.
//
// 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 ClientOption: CustomStringConvertible, Hashable {
func getSocketIOOptionValue() -> AnyObject?
}
public enum SocketIOClientOption: ClientOption {
case ConnectParams([String: AnyObject])
case Cookies([NSHTTPCookie])
case ExtraHeaders([String: String])
case ForceNew(Bool)
case ForcePolling(Bool)
case ForceWebsockets(Bool)
case HandleQueue(dispatch_queue_t)
case Log(Bool)
case Logger(SocketLogger)
case Nsp(String)
case Path(String)
case Reconnects(Bool)
case ReconnectAttempts(Int)
case ReconnectWait(Int)
case Secure(Bool)
case SelfSigned(Bool)
case SessionDelegate(NSURLSessionDelegate)
case VoipEnabled(Bool)
public var description: String {
if let label = Mirror(reflecting: self).children.first?.label {
return String(label[label.startIndex]).lowercaseString + String(label.characters.dropFirst())
} else {
return ""
}
}
public var hashValue: Int {
return description.hashValue
}
static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
switch (key, value) {
case ("connectParams", let params as [String: AnyObject]):
return .ConnectParams(params)
case ("reconnects", let reconnects as Bool):
return .Reconnects(reconnects)
case ("reconnectAttempts", let attempts as Int):
return .ReconnectAttempts(attempts)
case ("reconnectWait", let wait as Int):
return .ReconnectWait(wait)
case ("forceNew", let force as Bool):
return .ForceNew(force)
case ("forcePolling", let force as Bool):
return .ForcePolling(force)
case ("forceWebsockets", let force as Bool):
return .ForceWebsockets(force)
case ("nsp", let nsp as String):
return .Nsp(nsp)
case ("cookies", let cookies as [NSHTTPCookie]):
return .Cookies(cookies)
case ("log", let log as Bool):
return .Log(log)
case ("logger", let logger as SocketLogger):
return .Logger(logger)
case ("sessionDelegate", let delegate as NSURLSessionDelegate):
return .SessionDelegate(delegate)
case ("path", let path as String):
return .Path(path)
case ("extraHeaders", let headers as [String: String]):
return .ExtraHeaders(headers)
case ("handleQueue", let queue as dispatch_queue_t):
return .HandleQueue(queue)
case ("voipEnabled", let enable as Bool):
return .VoipEnabled(enable)
case ("secure", let secure as Bool):
return .Secure(secure)
case ("selfSigned", let selfSigned as Bool):
return .SelfSigned(selfSigned)
default:
return nil
}
}
func getSocketIOOptionValue() -> AnyObject? {
return Mirror(reflecting: self).children.first?.value as? AnyObject
}
}
public func ==(lhs: SocketIOClientOption, rhs: SocketIOClientOption) -> Bool {
return lhs.description == rhs.description
}
extension Set where Element: ClientOption {
mutating func insertIgnore(element: Element) {
if !contains(element) {
insert(element)
}
}
static func NSDictionaryToSocketOptionsSet(dict: NSDictionary) -> Set<SocketIOClientOption> {
var options = Set<SocketIOClientOption>()
for (rawKey, value) in dict {
if let key = rawKey as? String, opt = SocketIOClientOption.keyValueToSocketIOClientOption(key, value: value) {
options.insertIgnore(opt)
}
}
return options
}
func SocketOptionsSetToNSDictionary() -> NSDictionary {
let options = NSMutableDictionary()
for option in self {
options[option.description] = option.getSocketIOOptionValue()
}
return options
}
}
| mit | 4947b1f97081ed9c52a18a7322c68ed8 | 35.72028 | 122 | 0.650543 | 4.743451 | false | false | false | false |
benlangmuir/swift | test/IRGen/prespecialized-metadata/struct-outmodule-resilient-1argument-1distinct_use-struct-outmodule-resilient-samemodule.swift | 16 | 1303 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-nonfrozen-1argument.swift %S/Inputs/struct-public-nonfrozen-0argument.swift -emit-library -o %t/%target-library-name(Generic) -emit-module -module-name Generic -emit-module-path %t/Generic.swiftmodule -enable-library-evolution
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -L %t -I %t -lGeneric | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK-NOT: @"$s7Generic11OneArgumentVyAA7IntegerVGMN" =
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
import Generic
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: [[METADATA:%[0-9]+]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledName({ i32, i32 }* @"$s7Generic11OneArgumentVyAA7IntegerVGMD")
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture {{%[0-9]+}}, %swift.type* [[METADATA]])
// CHECK: }
func doit() {
consume( OneArgument(Integer(13)) )
}
doit()
| apache-2.0 | fdd8671ae5d4d4dd44480592addeaee8 | 45.535714 | 351 | 0.713738 | 3.307107 | false | false | false | false |
bradleymackey/WWDC-2017 | EmojiSort.playground/Sources/EmojiTeacher.swift | 1 | 2835 | import Foundation
import UIKit
public final class EmojiTeacher: UILabel {
// MARK: Enums
public enum Emotion: String {
case talking = "😄😁"
case happy = "😄" // resting happy face
case happyTalk = "😁" // chatting face
case confused = "😕" // this is confusing
case unimpressed = "😒" // unimpressive algorithm
case shocked = "😮" // shockingly good (or bad)
case cool = "😎" // this is a cool algorithm
case love = "😍" // he likes an algorithm
case sleeping = "😴" // he's sleeping
}
// MARK: Properties
public var currentEmotion:Emotion = .sleeping {
didSet {
stopTalking()
if currentEmotion == .talking {
startTalking()
} else {
self.text = currentEmotion.rawValue
}
}
}
private var talkingTimer:Timer?
private var talkingMouthOpen = true
// MARK: Speech
public var introPhrases = [String]()
public var bubbleSortPhrases = [String]()
public var selectionSortPhrases = [String]()
public var insertionSortPhrases = [String]()
public var mergeSortPhrases = [String]()
public var stupidSortPhrases = [String]()
// MARK: Init
public init() {
super.init(frame: .zero)
self.font = UIFont.systemFont(ofSize: 26)
self.text = currentEmotion.rawValue
self.textAlignment = .center
self.sizeToFit()
self.populatePhrases(fromPlist: "TeacherTalk")
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
talkingTimer?.invalidate()
}
// MARK: Methods
private func startTalking() {
talkingMouthOpen = true
let fullTalking = Emotion.talking.rawValue
let oneOffset = fullTalking.index(fullTalking.startIndex, offsetBy: 1)
self.text = String(fullTalking[..<oneOffset])
talkingTimer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { [unowned self, fullTalking, oneOffset] (timer) in
if self.talkingMouthOpen {
self.text = String(fullTalking[oneOffset...])
} else {
self.text = String(fullTalking[..<oneOffset])
}
self.talkingMouthOpen = !self.talkingMouthOpen
}
}
private func stopTalking() {
self.talkingTimer?.invalidate()
self.talkingMouthOpen = true
}
private func populatePhrases(fromPlist filename:String) {
guard let path = Bundle.main.path(forResource: filename, ofType: "plist") else { fatalError("Cannot find file.") }
guard let phrasesDict = NSDictionary(contentsOfFile: path) as? [String:[String]] else { fatalError("Cannot read phrases.") }
self.introPhrases = phrasesDict["introduction"]!
self.bubbleSortPhrases = phrasesDict["bubble_sort"]!
self.insertionSortPhrases = phrasesDict["insertion_sort"]!
self.selectionSortPhrases = phrasesDict["selection_sort"]!
self.mergeSortPhrases = phrasesDict["merge_sort"]!
self.stupidSortPhrases = phrasesDict["stupid_sort"]!
}
}
| mit | efb64b387b5ced3e697fed56fd1cc760 | 27.333333 | 127 | 0.703387 | 3.690789 | false | false | false | false |
ProcedureKit/ProcedureKit | Sources/ProcedureKit/Identity.swift | 2 | 1291 | //
// ProcedureKit
//
// Copyright © 2015-2018 ProcedureKit. All rights reserved.
//
import Foundation
/// `Identifiable` is a generic protocol for defining property based identity.
public protocol Identifiable {
associatedtype Identity: Hashable
/// An identifier
var identity: Identity { get }
}
public func ==<T: Identifiable> (lhs: T, rhs: T) -> Bool {
return lhs.identity == rhs.identity
}
public func ==<T, V> (lhs: T, rhs: V) -> Bool where T: Identifiable, V: Identifiable, T.Identity == V.Identity {
return lhs.identity == rhs.identity
}
extension Procedure: Identifiable {
public struct Identity: Identifiable, Hashable {
public let identity: ObjectIdentifier
public let name: String?
public var description: String {
return name.map { "\($0) #\(identity)" } ?? "Unnamed Procedure #\(identity)"
}
public func hash(into hasher: inout Hasher) {
hasher.combine(identity)
}
}
/// A Procedure's identity (often used for debugging purposes) provides a unique identifier
/// for a `Procedure` instance, comprised of the Procedure's `name` and a `UUID`.
public var identity: Identity {
return Identity(identity: ObjectIdentifier(self), name: name)
}
}
| mit | 83efdf858c5d84008194aac42001085d | 27.043478 | 112 | 0.655039 | 4.387755 | false | false | false | false |
ndleon09/SwiftSample500px | pictures/RootWireFrame.swift | 1 | 761 | //
// RootWireFrame.swift
// pictures
//
// Created by Nelson Dominguez on 04/11/15.
// Copyright © 2015 Nelson Dominguez. All rights reserved.
//
import Foundation
import UIKit
class RootWireFrame {
let container: ServiceLocator
init(container: ServiceLocator) {
self.container = container
}
func installRootViewController(in window : UIWindow) {
let navigationController = UINavigationController()
window.backgroundColor = UIColor.white
window.rootViewController = navigationController
let listWireFrame: ListWireFrameProtocol? = container.getService()
listWireFrame?.showList(in: navigationController)
window.makeKeyAndVisible()
}
}
| mit | 03800cb5dafc5e35f4e08b4249645210 | 23.516129 | 74 | 0.673684 | 5.352113 | false | false | false | false |
hooman/swift | test/Concurrency/async_let_isolation.swift | 12 | 834 | // RUN: %target-typecheck-verify-swift -disable-availability-checking
// REQUIRES: concurrency
actor MyActor {
let immutable: Int = 17
var text: [String] = []
func synchronous() -> String { text.first ?? "nothing" }
func asynchronous() async -> String { synchronous() }
func testAsyncLetIsolation() async {
async let x = self.synchronous()
async let y = await self.asynchronous()
async let z = synchronous()
var localText = text
async let w = localText.removeLast() // expected-error{{mutation of captured var 'localText' in concurrently-executing code}}
_ = await x
_ = await y
_ = await z
_ = await w
}
}
func outside() async {
let a = MyActor()
async let x = a.synchronous() // okay, await is implicit
async let y = await a.synchronous()
_ = await x
_ = await y
}
| apache-2.0 | 1b0f53a9864de35288bc8fb7d09b610d | 23.529412 | 129 | 0.646283 | 3.897196 | false | false | false | false |
bvic23/VinceRP | VinceRP/Extension/UIKit/UISearchBar+didChange.swift | 1 | 966 | //
// Created by Viktor Belenyesi on 26/09/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
import UIKit
private typealias EventHandler = (UISearchBar) -> ()
private var eventHandlers = [UISearchBar: [EventHandler]]()
extension UISearchBar {
public func addChangeHandler(handler: (UISearchBar) -> ()) {
if let handlers = eventHandlers[self] {
eventHandlers[self] = handlers.arrayByAppending(handler)
} else {
eventHandlers[self] = [handler]
}
self.delegate = self
}
public func removeAllChangeHandler() {
self.delegate = nil
eventHandlers[self] = []
}
}
extension UISearchBar : UISearchBarDelegate {
public func searchBar(sender: UISearchBar, textDidChange searchText: String) {
if let handlers = eventHandlers[sender] {
for handler in handlers {
handler(sender)
}
}
}
} | mit | 2b28a5d907c4e49e62922718b7e75f31 | 23.794872 | 82 | 0.613872 | 4.903553 | false | false | false | false |
wangyuanou/Operation | testQueue/CLData.swift | 1 | 2585 | //
// CLData.swift
// testQueue
//
// Created by 王渊鸥 on 16/5/3.
// Copyright © 2016年 王渊鸥. All rights reserved.
//
import Foundation
import UIKit
class CLData {
var source:NSMutableData
var boundry:String
init(source:NSMutableData, boundry:String) {
self.boundry = boundry
self.source = source
}
func set(key:String, value:String) -> CLData {
source.set(key, value: value, boundry: boundry)
return self
}
func set(file:String, data:NSData) -> CLData {
source.set(file, data: data, boundry: boundry)
return self
}
func set(file:String, image:UIImage, compose:CGFloat = 1.0) -> CLData {
var data:NSData? = nil
if compose == 1.0 {
data = UIImagePNGRepresentation(image)
} else {
data = UIImageJPEGRepresentation(image, compose)
}
if let data = data {
source.set(file, data: data, boundry: boundry)
}
return self
}
func setting(action:(CLData)->()) -> NSData {
action(self)
source.closeBoundry(boundry)
return NSData(data: source)
}
}
extension NSData {
class func parameters(boundry:String = "_COASTLINE_STUDIO_") -> CLData {
return CLData(source: NSMutableData(), boundry: boundry)
}
class func setting(action:(CLData)->()) -> NSData {
let data = NSData.parameters()
return data.setting(action)
}
}
extension NSMutableData {
func set(key:String, value:String, boundry:String) {
let leadString = "\n--\(boundry)"
+ "\nContent-Disposition:form-data;name=\"\(key)\"\n"
+ "\n\(value)"
self.appendData((leadString as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
}
func set(file:String, data:NSData, boundry:String) {
let leadString = "\n--\(boundry)"
+ "\nContent-Disposition:form-data;name=\"file\";filename=\"\(file)\""
+ "\nContent-Type:application/octet-stream"
+ "\nContent-Transfer-Encoding:binary\n\n"
self.appendData((leadString as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
self.appendData(data)
}
func closeBoundry(boundry:String) {
let endString = "\n--\(boundry)--"
self.appendData((endString as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
}
}
func test() {
NSData.setting{
$0.set("aaa", value: "bbbb")
$0.set("ccc", value: "dddd")
}
} | apache-2.0 | 31a03874ca63f6c908197a80af2eff55 | 25.78125 | 90 | 0.582879 | 4.192496 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Room/ContextualMenu/RoomContextualMenuAction.swift | 1 | 2170 | /*
Copyright 2019 New Vector Ltd
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
@objc enum RoomContextualMenuAction: Int {
case copy
case reply
case replyInThread
case edit
case more
case resend
case delete
// MARK: - Properties
var title: String {
let title: String
switch self {
case .copy:
title = VectorL10n.roomEventActionCopy
case .reply:
title = VectorL10n.roomEventActionReply
case .replyInThread:
title = VectorL10n.roomEventActionReplyInThread
case .edit:
title = VectorL10n.roomEventActionEdit
case .more:
title = VectorL10n.roomEventActionMore
case .resend:
title = VectorL10n.retry
case .delete:
title = VectorL10n.roomEventActionDelete
}
return title
}
var image: UIImage? {
let image: UIImage?
switch self {
case .copy:
image = Asset.Images.roomContextMenuCopy.image
case .reply:
image = Asset.Images.roomContextMenuReply.image
case .replyInThread:
image = Asset.Images.roomContextMenuThread.image
case .edit:
image = Asset.Images.roomContextMenuEdit.image
case .more:
image = Asset.Images.roomContextMenuMore.image
case .resend:
image = Asset.Images.roomContextMenuRetry.image
case .delete:
image = Asset.Images.roomContextMenuDelete.image
default:
image = nil
}
return image
}
}
| apache-2.0 | c86e03965a0fb3423323dc77bab8619e | 27.181818 | 73 | 0.623502 | 4.943052 | false | false | false | false |
uasys/swift | test/Migrator/appkit.swift | 12 | 2490 | // REQUIRES: OS=macosx
// RUN: %target-swift-frontend -typecheck %s -swift-version 3
// RUN: %target-swift-frontend -typecheck -update-code -primary-file %s -emit-migrated-file-path %t.result -swift-version 3 -disable-migrator-fixits
// RUN: diff -u %s.expected %t.result
import AppKit
func a(_ outlineView: NSOutlineView) {
let cell: NSTableCellView = outlineView.make(withIdentifier: "HeaderCell", owner: outlineView) as! NSTableCellView
}
NSApplicationLoad()
NSBeep()
NSRectFill(NSRect.zero)
NSRectClip(NSRect.zero)
NSFrameRect(NSRect.zero)
// NSRect.zero.fill(using: NSCompositingOperation.clear)
NSRectFillUsingOperation(NSRect.zero, NSCompositingOperation.clear)
// NSRect.zero.frame(withWidth: 0.0)
NSFrameRectWithWidth(NSRect.zero, 0.0)
// NSRect.zero.frame(withWidth: 0.0, using: NSCompositingOperation.clear)
NSFrameRectWithWidthUsingOperation(NSRect.zero, 0.0, NSCompositingOperation.clear)
let isTrue = true
// (isTrue ? NSRect.zero : NSRect.zero).frame(withWidth: 0.0)
NSFrameRectWithWidth(isTrue ? NSRect.zero : NSRect.zero, 0.0)
var rekts = [NSRect.zero]
var kolors = [NSColor.red]
var grays = [CGFloat(0)]
// rekts.fill()
NSRectFillList(&rekts, 1)
// rekts.fill(using: NSCompositingOperation.clear)
NSRectFillListUsingOperation(rekts, 1, NSCompositingOperation.clear)
// rekts.clip()
NSRectClipList(&rekts, 1)
// TODO: zip2(rekts, kolors).fill()
// NSRectFillListWithColors(&rekts, &kolors, 1)
// TODO: zip2(rekts, kolors).fill(using: NSCompositingOperation.clear)
// NSRectFillListWithColorsUsingOperation(&rekts, &kolors, 1, NSCompositingOperation.clear)
// TODO: zip2(rekts, grays).fill()
// NSRectFillListWithGrays(&rekts, &grays, 1)
// TODO: NSAnimationEffect.poof.show(centeredAt: NSPoint.zero, size: NSSize.zero)
// NSShowAnimationEffect(NSAnimationEffect.poof, NSPoint.zero, NSSize.zero, nil, nil, nil)
// _ = NSWindow.Depth.availableDepths
_ = NSAvailableWindowDepths()
// TODO: _ = NSWindow.Depth.bestDepth("", 24, 0, false)
// _ = NSBestDepth("", 24, 0, false, nil)
var cacheSize: GLint = 0
// cacheSize = NSOpenGLGOFormatCacheSize.globalValue
NSOpenGLGetOption(NSOpenGLGOFormatCacheSize, &cacheSize)
// NSOpenGLGOFormatCacheSize.globalValue = 5
NSOpenGLSetOption(NSOpenGLGOFormatCacheSize, 5)
var major = GLint(0)
var minor = GLint(0)
// TODO: (major, minor) = NSOpenGLContext.openGLVersion
// NSOpenGLGetVersion(&major, &minor)
class MyDocument : NSDocument {
override class func autosavesInPlace() -> Bool {
return false
}
}
| apache-2.0 | c98e810ed792b438e9ade91310847bc9 | 29.365854 | 148 | 0.757028 | 3.392371 | false | false | false | false |
visenze/visearch-sdk-swift | Example/Example/SearchViewController.swift | 1 | 16116 | //
// SearchViewController.swift
// Example
//
// Created by Hung on 7/10/16.
// Copyright © 2016 ViSenze. All rights reserved.
//
import UIKit
import ViSearchSDK
class SearchViewController: UIViewController, UITextFieldDelegate, SwiftHUEColorPickerDelegate {
public var demoApi : ViAPIEndPoints = ViAPIEndPoints.ID_SEARCH
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var paramLabel: UILabel!
@IBOutlet weak var searchBtn: UIBarButtonItem!
private var recentResponseData: ViResponseData?
@IBOutlet weak var colorView: UIView!
@IBOutlet weak var colorPicker: SwiftHUEColorPicker!
@IBOutlet weak var saturationColorPicker: SwiftHUEColorPicker!
@IBOutlet weak var brightnessColorPicker: SwiftHUEColorPicker!
@IBOutlet weak var alphaColorPicker: SwiftHUEColorPicker!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
textField.delegate = self
colorPicker.isHidden = true
saturationColorPicker.isHidden = true
brightnessColorPicker.isHidden = true
alphaColorPicker.isHidden = true
colorView.isHidden = true
if demoApi == ViAPIEndPoints.ID_SEARCH || demoApi == ViAPIEndPoints.REC_SEARCH {
paramLabel.text = "Existing image name (im_name):"
}
else if demoApi == ViAPIEndPoints.COLOR_SEARCH {
colorView.isHidden = false
textField.isEnabled = false
paramLabel.text = "Color code (6 characters hex): "
colorPicker.isHidden = false
colorPicker.delegate = self
colorPicker.direction = SwiftHUEColorPicker.PickerDirection.horizontal
colorPicker.type = SwiftHUEColorPicker.PickerType.color
saturationColorPicker.isHidden = false
saturationColorPicker.direction = SwiftHUEColorPicker.PickerDirection.horizontal
saturationColorPicker.delegate = self
saturationColorPicker.type = SwiftHUEColorPicker.PickerType.saturation
brightnessColorPicker.isHidden = false
brightnessColorPicker.direction = SwiftHUEColorPicker.PickerDirection.horizontal
brightnessColorPicker.delegate = self
brightnessColorPicker.type = SwiftHUEColorPicker.PickerType.brightness
alphaColorPicker.isHidden = false
alphaColorPicker.direction = SwiftHUEColorPicker.PickerDirection.horizontal
alphaColorPicker.delegate = self
alphaColorPicker.type = SwiftHUEColorPicker.PickerType.alpha
}
checkValidParam()
}
func checkValidParam() {
// Disable the Save button if the text field is empty.
let text = textField.text!.trimmingCharacters(in: .whitespaces)
searchBtn.isEnabled = !text.isEmpty
}
private func showHud(){
KRProgressHUD.show()
}
private func dismissHud() {
KRProgressHUD.dismiss()
}
@IBAction func searchBtnTap(_ sender: UIBarButtonItem) {
if demoApi == ViAPIEndPoints.ID_SEARCH {
findSimilar()
}
else if demoApi == ViAPIEndPoints.REC_SEARCH {
recSearch()
}
else if demoApi == ViAPIEndPoints.COLOR_SEARCH {
colorSearch()
}
}
// MARK: color picker delegate
func valuePicked(_ color: UIColor, type: SwiftHUEColorPicker.PickerType) {
textField.text = color.hexString()
colorView.backgroundColor = color
switch type {
case SwiftHUEColorPicker.PickerType.color:
saturationColorPicker.currentColor = color
brightnessColorPicker.currentColor = color
alphaColorPicker.currentColor = color
break
case SwiftHUEColorPicker.PickerType.saturation:
colorPicker.currentColor = color
brightnessColorPicker.currentColor = color
alphaColorPicker.currentColor = color
break
case SwiftHUEColorPicker.PickerType.brightness:
colorPicker.currentColor = color
saturationColorPicker.currentColor = color
alphaColorPicker.currentColor = color
break
case SwiftHUEColorPicker.PickerType.alpha:
colorPicker.currentColor = color
saturationColorPicker.currentColor = color
brightnessColorPicker.currentColor = color
break
}
checkValidParam()
}
//MARK: API calls
private func colorSearch() -> Void{
showHud()
let param = textField.text!.trimmingCharacters(in: .whitespaces)
let params = ViColorSearchParams(color: param)
params?.score = true // optional: display score in result
params!.fl = ["im_url"] // retrieve image url. By default the API only return im_name if does not specify fl parameter
params!.limit = 15 // display 15 results per page
// params?.facets = ["price", "brand"]
// params?.facetsLimit = 10
// params?.facetShowCount = true
ViSearch.sharedInstance.colorSearch( params: params!,
successHandler: {
(data : ViResponseData?) -> Void in
// Do something when request succeeds
// preview by calling : dump(data)
// check ViResponseData.hasError and ViResponseData.error for any errors return by ViSenze server
if let data = data {
if data.hasError {
let errMsgs = data.error.joined(separator: ",")
// error message from server e.g. invalid parameter
DispatchQueue.main.async {
self.alert(message: "API error: \(errMsgs)", title: "Error")
}
}
else {
// perform segue here
// dump(data)
self.recentResponseData = data
DispatchQueue.main.async {
self.performSegue(withIdentifier: "showSearchResults", sender: self)
}
}
}
self.dismissHud()
},
failureHandler: {
(err) -> Void in
DispatchQueue.main.async {
// Do something when request fails e.g. due to network error
self.alert(message: "An error has occured: \(err.localizedDescription)", title: "Error")
self.dismissHud()
}
})
}
private func findSimilar() -> Void{
// show progress hud
showHud()
let param = textField.text!.trimmingCharacters(in: .whitespaces)
let params = ViSearchParams(imName: param)
params?.score = true // optional: display score in result
params!.fl = ["im_url"] // retrieve image url. By default the API only return im_name if does not specify fl parameter
params!.limit = 15 // display 15 results per page
ViSearch.sharedInstance.findSimilar( params: params!,
successHandler: {
(data : ViResponseData?) -> Void in
// Do something when request succeeds
// preview by calling : dump(data)
// check ViResponseData.hasError and ViResponseData.error for any errors return by ViSenze server
if let data = data {
if data.hasError {
let errMsgs = data.error.joined(separator: ",")
DispatchQueue.main.async {
// error message from server e.g. invalid parameter
self.alert(message: "API error: \(errMsgs)", title: "Error")
}
}
else {
// perform segue here
//dump(data)
self.recentResponseData = data
DispatchQueue.main.async {
self.performSegue(withIdentifier: "showSearchResults", sender: self)
}
}
}
self.dismissHud()
},
failureHandler: {
(err) -> Void in
DispatchQueue.main.async {
// Do something when request fails e.g. due to network error
self.alert(message: "An error has occured: \(err.localizedDescription)", title: "Error")
self.dismissHud()
}
})
}
private func recSearch() -> Void{
// show progress hud
showHud()
let param = textField.text!.trimmingCharacters(in: .whitespaces)
let params = ViRecParams(imName: param)
params?.score = true // optional: display score in result
params!.fl = ["im_url"] // retrieve image url. By default the API only return im_name if does not specify fl parameter
params!.limit = 15 // display 15 results per page
ViSearch.sharedInstance.recommendation( params: params!,
successHandler: {
(data : ViResponseData?) -> Void in
// Do something when request succeeds
// preview by calling : dump(data)
// check ViResponseData.hasError and ViResponseData.error for any errors return by ViSenze server
if let data = data {
if data.hasError {
let errMsgs = data.error.joined(separator: ",")
// error message from server e.g. invalid parameter
DispatchQueue.main.async {
self.alert(message: "API error: \(errMsgs)", title: "Error")
}
}
else {
// perform segue here
//dump(data)
self.recentResponseData = data
DispatchQueue.main.async {
self.performSegue(withIdentifier: "showSearchResults", sender: self)
}
}
}
self.dismissHud()
},
failureHandler: {
(err) -> Void in
// Do something when request fails e.g. due to network error
DispatchQueue.main.async {
self.alert(message: "An error has occured: \(err.localizedDescription)", title: "Error")
self.dismissHud()
}
})
}
// MARK: text events
@IBAction func textEditingChanged(_ sender: UITextField) {
checkValidParam()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "showSearchResults" {
if let recentResponseData = recentResponseData {
let searchResultsController = segue.destination as! SearchResultsCollectionViewController
searchResultsController.photoResults = recentResponseData.result
searchResultsController.reqId = recentResponseData.reqId!
}
}
}
}
| mit | 807a0538cbd0888c3e8218f210897d1f | 47.833333 | 145 | 0.420478 | 8.073647 | false | false | false | false |
barbosa/clappr-ios | Pod/Classes/Factory/ContainerFactory.swift | 1 | 747 | public class ContainerFactory {
private var loader: Loader
private var options: Options
public init(loader: Loader = Loader(), options: Options = [:]) {
self.loader = loader
self.options = options
}
public func createContainer() -> Container {
let playbackFactory = PlaybackFactory(loader: loader, options: options)
let container = Container(playback: playbackFactory.createPlayback(), loader: loader, options: options)
return addPlugins(container)
}
private func addPlugins(container: Container) -> Container {
for type in loader.containerPlugins {
container.addPlugin(type.init() as! UIContainerPlugin)
}
return container
}
} | bsd-3-clause | 5f18bce77f0857ebccefa0ef8a0d7a20 | 33 | 111 | 0.655957 | 5.013423 | false | false | false | false |
IngmarStein/swift | test/Generics/associated_self_constraints.swift | 4 | 1512 | // RUN: %target-parse-verify-swift
protocol Observer {
associatedtype Value
func onNext(_ item: Value) -> Void
func onCompleted() -> Void
func onError(_ error: String) -> Void
}
protocol Observable {
associatedtype Value
func subscribe<O: Observer>(_ observer: O) -> Any where O.Value == Value
}
class Subject<T>: Observer, Observable {
typealias Value = T
// Observer implementation
var onNextFunc: ((T) -> Void)?
var onCompletedFunc: (() -> Void)?
var onErrorFunc: ((String) -> Void)?
func onNext(_ item: T) -> Void {
onNextFunc?(item)
}
func onCompleted() -> Void {
onCompletedFunc?()
}
func onError(_ error: String) -> Void {
onErrorFunc?(error)
}
// Observable implementation
func subscribe<O: Observer>(_ observer: O) -> Any where O.Value == T {
self.onNextFunc = { (item: T) -> Void in
observer.onNext(item)
}
self.onCompletedFunc = {
observer.onCompleted()
}
self.onErrorFunc = { (error: String) -> Void in
observer.onError(error)
}
return self
}
}
protocol P {
associatedtype A
func onNext(_ item: A) -> Void
}
struct IP<T> : P {
typealias A = T
init<O:P>(x:O) where O.A == IP.A {
_onNext = { (item: A) in x.onNext(item) }
}
func onNext(_ item: A) { _onNext(item) }
var _onNext: (A) -> ()
}
| apache-2.0 | 8a7307beefc1ccdb07f0d9b99a880445 | 19.712329 | 76 | 0.535714 | 4.021277 | false | false | false | false |
hughbe/ui-components | src/Placeholder/PlaceholderTextView.swift | 1 | 2660 | //
// PlaceholdTextView.swift
// UIComponents
//
// Created by Hugh Bellamy on 14/06/2015.
// Copyright (c) 2015 Hugh Bellamy. All rights reserved.
//
@IBDesignable
public class PlaceholderTextView: UITextView {
@IBInspectable public var placeholder: String = ""
@IBInspectable public var placeholderColor: UIColor = UIColor.lightGrayColor()
public override func awakeFromNib() {
super.awakeFromNib()
text = placeholder
updatePlaceholder()
NSNotificationCenter.defaultCenter().addObserverForName(UITextViewTextDidBeginEditingNotification, object: self, queue: NSOperationQueue.mainQueue()) { (notification) in
self.updatePlaceholderText()
}
NSNotificationCenter.defaultCenter().addObserverForName(UITextViewTextDidEndEditingNotification, object: self, queue: NSOperationQueue.mainQueue()) { (notification) in
self.updatePlaceholderText()
}
NSNotificationCenter.defaultCenter().addObserverForName(UITextViewTextDidChangeNotification, object: self, queue: NSOperationQueue.mainQueue()) { (notification) in
self.updatePlaceholderText()
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
public override var text: String? {
didSet {
updatePlaceholder()
}
}
public var naturalText: String {
if let text = text {
return (text as NSString).stringByReplacingOccurrencesOfString(placeholder, withString: "")
}
return ""
}
public func clearText() {
text = ""
updatePlaceholderText()
}
private func updatePlaceholderText() {
if self.text == nil {
self.text = self.placeholder
}
else if let text = self.text {
if text.isEmpty || text == self.placeholder {
self.text = self.placeholder
} else {
self.text = naturalText
}
}
self.updatePlaceholder()
}
private func updatePlaceholder() {
if text == placeholder {
textColor = placeholderColor
moveToBeginning()
} else {
textColor = UIColor.blackColor()
}
}
private func moveToBeginning() {
super.selectedTextRange = textRangeFromPosition(beginningOfDocument, toPosition: beginningOfDocument)
}
public override var selectedTextRange: UITextRange? {
didSet {
if text == placeholder {
moveToBeginning()
}
}
}
}
| mit | f6f17cd5b5d48f3017ccff8ccf39bf5e | 29.227273 | 177 | 0.61015 | 5.833333 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Linked List/876_Middle of the Linked List.swift | 1 | 1541 | // 876_Middle of the Linked List
// https://leetcode.com/problems/middle-of-the-linked-list/
//
// Created by Honghao Zhang on 9/7/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given a non-empty, singly linked list with head node head, return a middle node of linked list.
//
//If there are two middle nodes, return the second middle node.
//
//
//
//Example 1:
//
//Input: [1,2,3,4,5]
//Output: Node 3 from this list (Serialization: [3,4,5])
//The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
//Note that we returned a ListNode object ans, such that:
//ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
//Example 2:
//
//Input: [1,2,3,4,5,6]
//Output: Node 4 from this list (Serialization: [4,5,6])
//Since the list has two middle nodes with values 3 and 4, we return the second one.
//
//
//Note:
//
//The number of nodes in the given list will be between 1 and 100.
//
import Foundation
// 找到linked list的中间点
class Num876 {
// MARK: - 快慢pointer
func middleNode(_ head: ListNode?) -> ListNode? {
let root: ListNode? = ListNode(0)
root?.next = head
var slow = root
var fast = root
while fast?.next != nil {
slow = slow?.next
fast = fast?.next?.next
}
// if fast is just the last node, the slow is the last node of first half.
// should return the next node, which is the head of the right part.
if fast != nil {
return slow?.next
}
return slow
}
}
| mit | fd5f69e1c9472e6219d22ef4fc926ce6 | 26.214286 | 98 | 0.650919 | 3.249467 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.