repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
wordlessj/Bamboo
Source/Auto/Expression/ConstraintItem.swift
1
2854
// // ConstraintItem.swift // Bamboo // // Copyright (c) 2017 Javier Zhang (https://wordlessj.github.io/) // // 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 /// Item which has `bb` extensions, namely `UIView` and `UILayoutGuide`. public protocol ConstraintItem: XAxisItem, YAxisItem, DimensionItem { var bb_superview: View? { get } var leftAnchor: NSLayoutXAxisAnchor { get } var rightAnchor: NSLayoutXAxisAnchor { get } var topAnchor: NSLayoutYAxisAnchor { get } var bottomAnchor: NSLayoutYAxisAnchor { get } var leadingAnchor: NSLayoutXAxisAnchor { get } var trailingAnchor: NSLayoutXAxisAnchor { get } var widthAnchor: NSLayoutDimension { get } var heightAnchor: NSLayoutDimension { get } var centerXAnchor: NSLayoutXAxisAnchor { get } var centerYAnchor: NSLayoutYAxisAnchor { get } var bb_firstBaselineAnchor: NSLayoutYAxisAnchor { get } var bb_lastBaselineAnchor: NSLayoutYAxisAnchor { get } } extension ConstraintItem { /// Start an auto layout chain. public var bb: InitialChain<Self> { return InitialChain(item: self) } @available(*, deprecated, renamed: "bb") public var constrain: InitialChain<Self> { return bb } } extension View: ConstraintItem { public var bb_superview: View? { return superview } public var bb_firstBaselineAnchor: NSLayoutYAxisAnchor { return firstBaselineAnchor } public var bb_lastBaselineAnchor: NSLayoutYAxisAnchor { return lastBaselineAnchor } } #if os(iOS) || os(tvOS) extension UILayoutGuide: ConstraintItem { public var bb_superview: View? { return owningView } public var bb_firstBaselineAnchor: NSLayoutYAxisAnchor { return topAnchor } public var bb_lastBaselineAnchor: NSLayoutYAxisAnchor { return bottomAnchor } } #endif
mit
EricHein/Swift3.0Practice2016
00.ScratchWork/ParseServerStarterProject/ParseStarterProject/FeedTableViewCell.swift
1
632
// // FeedTableViewCell.swift // ParseStarterProject-Swift // // Created by Eric H on 26/12/2016. // Copyright © 2016 Parse. All rights reserved. // import UIKit class FeedTableViewCell: UITableViewCell { @IBOutlet var postedImage: UIImageView! @IBOutlet var usernameLabel: UILabel! @IBOutlet var messageLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-3.0
swizzlr/swift-redis
Sources/RedisIntegrationTests/Environment.swift
1
361
struct Environment { static let Environment = env static let IP = env["REDIS_PORT_6379_TCP_ADDR"]! static let Port = Int(env["REDIS_PORT_6379_TCP_PORT"]!)! } func newContext() -> redisContext { return redisConnect(ip: Environment.IP, port: Environment.Port) } private let env = NSProcessInfo.processInfo().environment import hiredis import Foundation
bsd-3-clause
Sajjon/Zeus
Zeus/Extensions/NSObject_Extension.swift
1
301
// // NSObject_Extension.swift // Zeus // // Created by Cyon Alexander on 22/08/16. // Copyright © 2016 com.cyon. All rights reserved. // import Foundation extension NSObject { class var className: String { return NSStringFromClass(self).components(separatedBy: ".").last! } }
apache-2.0
2RKowski/two-blobs
TwoBlobs/Observable+JustCompleted.swift
1
383
// // Observable+JustCompleted.swift // TwoBlobs // // Created by Lësha Turkowski on 13/01/2017. // Copyright © 2017 Amblyofetus. All rights reserved. // import RxSwift extension Observable { static func justCompleted<E>() -> Observable<E> { return Observable<E>.create { o in o.onCompleted() return Disposables.create() } } }
mit
inket/MacSymbolicator
MacSymbolicatorTests/TestProject/iOSCrashingTest/AppDelegate.swift
1
525
// // AppDelegate.swift // iOSCrashingTest // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() CrashClass.pleaseCrash() } } class CrashClass { @inline(never) // Or else the compiler will optimize this method into viewDidLoad static func pleaseCrash() { print("Crashing…") fatalError("Here's the crash") } }
gpl-2.0
iCrany/iOSExample
iOSExample/Module/HitTestExample/View/ContainView.swift
1
1008
// // ContainView.swift // iOSExample // // Created by iCrany on 2017/7/18. // Copyright (c) 2017 iCrany. All rights reserved. // import Foundation import UIKit class ContainView: UIView { required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) } // MARK: Event response override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let isInside = self.point(inside: point, with: event) print("ContainView isInside: \(isInside)") return super.hitTest(point, with: event) } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let isInside = super.point(inside: point, with: event) NSLog("bounds: \(self.bounds) point: \(point) isInside: \(isInside)") if isInside == false { return true } return super.point(inside: point, with: event) } }
mit
HabitRPG/habitrpg-ios
Habitica Models/Habitica Models/Tasks/WeekRepeatProtocol.swift
1
462
// // WeekRepeatProtocol.swift // Habitica Models // // Created by Phillip Thelen on 26.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation @objc public protocol WeekRepeatProtocol { var monday: Bool { get set } var tuesday: Bool { get set } var wednesday: Bool { get set } var thursday: Bool { get set } var friday: Bool { get set } var saturday: Bool { get set } var sunday: Bool { get set } }
gpl-3.0
izrie/DKImagePickerController
DKImagePickerController/DKPopoverViewController.swift
1
6556
// // DKPopoverViewController.swift // DKImagePickerController // // Created by ZhangAo on 15/6/27. // Copyright (c) 2015年 ZhangAo. All rights reserved. // import UIKit class DKPopoverViewController: UIViewController { class func popoverViewController(viewController: UIViewController, fromView: UIView) { let window = UIApplication.sharedApplication().keyWindow! let popoverViewController = DKPopoverViewController() popoverViewController.contentViewController = viewController popoverViewController.fromView = fromView popoverViewController.showInView(window) window.rootViewController!.addChildViewController(popoverViewController) } class func dismissPopoverViewController() { let window = UIApplication.sharedApplication().keyWindow! for vc in window.rootViewController!.childViewControllers { if vc is DKPopoverViewController { (vc as! DKPopoverViewController).dismiss() } } } class DKPopoverView: UIView { var contentView: UIView! { didSet { contentView.layer.cornerRadius = 5 contentView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] self.addSubview(contentView) } } let arrowWidth: CGFloat = 20 let arrowHeight: CGFloat = 10 private let arrowImageView: UIImageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } func commonInit() { arrowImageView.image = self.arrowImage() self.addSubview(arrowImageView) } override func layoutSubviews() { super.layoutSubviews() self.arrowImageView.frame = CGRect(x: (self.bounds.width - self.arrowWidth) / 2, y: 0, width: arrowWidth, height: arrowHeight) self.contentView.frame = CGRect(x: 0, y: self.arrowHeight, width: self.bounds.width, height: self.bounds.height - arrowHeight) } func arrowImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(CGSize(width: arrowWidth, height: arrowHeight), false, UIScreen.mainScreen().scale) let context = UIGraphicsGetCurrentContext() UIColor.clearColor().setFill() CGContextFillRect(context, CGRect(x: 0, y: 0, width: arrowWidth, height: arrowHeight)) let arrowPath = CGPathCreateMutable() CGPathMoveToPoint(arrowPath, nil, arrowWidth / 2, 0) CGPathAddLineToPoint(arrowPath, nil, arrowWidth, arrowHeight) CGPathAddLineToPoint(arrowPath, nil, 0, arrowHeight) CGPathCloseSubpath(arrowPath) CGContextAddPath(context, arrowPath) CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor) CGContextDrawPath(context, CGPathDrawingMode.Fill) let arrowImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return arrowImage } } var contentViewController: UIViewController! var fromView: UIView! private let popoverView = DKPopoverView() private var popoverViewHeight: CGFloat! override func loadView() { super.loadView() let backgroundView = UIControl(frame: self.view.frame) backgroundView.backgroundColor = UIColor.clearColor() backgroundView.addTarget(self, action: "dismiss", forControlEvents: .TouchUpInside) backgroundView.autoresizingMask = self.view.autoresizingMask self.view = backgroundView } override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(popoverView) } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition(nil, completion: { (context) -> Void in let popoverY = self.fromView.convertPoint(self.fromView.frame.origin, toView: self.view).y + self.fromView.bounds.height self.popoverViewHeight = min(self.contentViewController.preferredContentSize.height + self.popoverView.arrowHeight, self.view.bounds.height - popoverY - 40) UIView.animateWithDuration(0.2, animations: { self.popoverView.frame = CGRect(x: 0, y: popoverY, width: self.view.bounds.width, height: self.popoverViewHeight) }) }) } func showInView(view: UIView) { let popoverY = self.fromView.convertPoint(self.fromView.frame.origin, toView: view).y + self.fromView.bounds.height self.popoverViewHeight = min(self.contentViewController.preferredContentSize.height + self.popoverView.arrowHeight, view.bounds.height - popoverY - 40) self.popoverView.frame = CGRect(x: 0, y: popoverY, width: view.bounds.width, height: popoverViewHeight) self.popoverView.contentView = self.contentViewController.view view.addSubview(self.view) self.popoverView.transform = CGAffineTransformScale(CGAffineTransformTranslate(self.popoverView.transform, 0, -(self.popoverViewHeight / 2)), 0.1, 0.1) UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1.3, options: [.CurveEaseInOut, .AllowUserInteraction], animations: { self.popoverView.transform = CGAffineTransformIdentity self.view.backgroundColor = UIColor(white: 0.4, alpha: 0.4) }, completion: nil) } func dismiss() { UIView.animateWithDuration(0.2, animations: { self.popoverView.transform = CGAffineTransformScale(CGAffineTransformTranslate(self.popoverView.transform, 0, -(self.popoverViewHeight / 2)), 0.01, 0.01) self.view.backgroundColor = UIColor.clearColor() }) { (result) -> Void in self.view.removeFromSuperview() self.removeFromParentViewController() } } }
mit
blockchain/My-Wallet-V3-iOS
Modules/FeatureNFT/Sources/FeatureNFTUI/Localization+FeatureNFTUI.swift
1
1770
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization // swiftlint:disable all // MARK: Groups extension LocalizationConstants { public enum NFT { public enum Screen { public enum List {} public enum Empty {} public enum Detail {} } } } // MARK: - AssetListView extension LocalizationConstants.NFT.Screen.List { public static let fetchingYourNFTs = NSLocalizedString( "Fetching Your NFTs", comment: "" ) public static let shopOnOpenSea = NSLocalizedString( "Shop on OpenSea", comment: "" ) } extension LocalizationConstants.NFT.Screen.Empty { public static let headline = NSLocalizedString( "To get started, transfer your NFTs", comment: "" ) public static let subheadline = NSLocalizedString( "Send from any wallet, or buy from a marketplace!", comment: "" ) public static let copyEthAddress = NSLocalizedString( "Copy Ethereum Address", comment: "" ) public static let copied = NSLocalizedString( "Copied!", comment: "" ) } // MARK: - AssetDetailView extension LocalizationConstants.NFT.Screen.Detail { public static let viewOnOpenSea = NSLocalizedString( "View on OpenSea", comment: "" ) public static let properties = NSLocalizedString( "Properties", comment: "" ) public static let creator = NSLocalizedString("Creator", comment: "") public static let about = NSLocalizedString("About", comment: "") public static let descripton = NSLocalizedString("Description", comment: "") public static let readMore = NSLocalizedString("Read More", comment: "") }
lgpl-3.0
WickedColdfront/Slide-iOS
Pods/ImagePickerSheetController/ImagePickerSheetController/ImagePickerSheetController/Sheet/SheetController.swift
1
8665
// // SheetController.swift // ImagePickerSheetController // // Created by Laurin Brandner on 27/08/15. // Copyright © 2015 Laurin Brandner. All rights reserved. // import UIKit let sheetInset: CGFloat = 10 class SheetController: NSObject { fileprivate(set) lazy var sheetCollectionView: UICollectionView = { let layout = SheetCollectionViewLayout() let collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.accessibilityIdentifier = "ImagePickerSheet" collectionView.backgroundColor = .clear collectionView.alwaysBounceVertical = false collectionView.register(SheetPreviewCollectionViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(SheetPreviewCollectionViewCell.self)) collectionView.register(SheetActionCollectionViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(SheetActionCollectionViewCell.self)) return collectionView }() var previewCollectionView: PreviewCollectionView fileprivate(set) var actions = [ImagePickerAction]() var actionHandlingCallback: (() -> ())? fileprivate(set) var previewHeight: CGFloat = 0 var numberOfSelectedAssets = 0 var preferredSheetHeight: CGFloat { return allIndexPaths().map { self.sizeForSheetItemAtIndexPath($0).height } .reduce(0, +) } // MARK: - Initialization init(previewCollectionView: PreviewCollectionView) { self.previewCollectionView = previewCollectionView super.init() } // MARK: - Data Source // These methods are necessary so that no call cycles happen when calculating some design attributes fileprivate func numberOfSections() -> Int { return 2 } fileprivate func numberOfItemsInSection(_ section: Int) -> Int { if section == 0 { return 1 } return actions.count } fileprivate func allIndexPaths() -> [IndexPath] { let s = numberOfSections() return (0 ..< s).map { (section: Int) -> (Int, Int) in (self.numberOfItemsInSection(section), section) } .flatMap { (numberOfItems: Int, section: Int) -> [IndexPath] in (0 ..< numberOfItems).map { (item: Int) -> IndexPath in IndexPath(item: item, section: section) } } } fileprivate func sizeForSheetItemAtIndexPath(_ indexPath: IndexPath) -> CGSize { let height: CGFloat = { if indexPath.section == 0 { return previewHeight } let actionItemHeight: CGFloat = 57 let insets = attributesForItemAtIndexPath(indexPath).backgroundInsets return actionItemHeight + insets.top + insets.bottom }() return CGSize(width: sheetCollectionView.bounds.width, height: height) } // MARK: - Design fileprivate func attributesForItemAtIndexPath(_ indexPath: IndexPath) -> (corners: RoundedCorner, backgroundInsets: UIEdgeInsets) { let cornerRadius: CGFloat = 13 let innerInset: CGFloat = 4 var indexPaths = allIndexPaths() guard indexPaths.first != indexPath else { return (.top(cornerRadius), UIEdgeInsets(top: 0, left: sheetInset, bottom: 0, right: sheetInset)) } let cancelIndexPath = actions.index { $0.style == ImagePickerActionStyle.cancel } .map { IndexPath(item: $0, section: 1) } if let cancelIndexPath = cancelIndexPath { if cancelIndexPath == indexPath { return (.all(cornerRadius), UIEdgeInsets(top: innerInset, left: sheetInset, bottom: sheetInset, right: sheetInset)) } indexPaths.removeLast() if indexPath == indexPaths.last { return (.bottom(cornerRadius), UIEdgeInsets(top: 0, left: sheetInset, bottom: innerInset, right: sheetInset)) } } else if indexPath == indexPaths.last { return (.bottom(cornerRadius), UIEdgeInsets(top: 0, left: sheetInset, bottom: sheetInset, right: sheetInset)) } return (.none, UIEdgeInsets(top: 0, left: sheetInset, bottom: 0, right: sheetInset)) } fileprivate func fontForAction(_ action: ImagePickerAction) -> UIFont { if action.style == .cancel { return UIFont.boldSystemFont(ofSize: 21) } return UIFont.systemFont(ofSize: 21) } // MARK: - Actions func reloadActionItems() { sheetCollectionView.reloadSections(IndexSet(integer: 1)) } func addAction(_ action: ImagePickerAction) { if action.style == .cancel { actions = actions.filter { $0.style != .cancel } } actions.append(action) if let index = actions.index(where: { $0.style == .cancel }) { let cancelAction = actions.remove(at: index) actions.append(cancelAction) } reloadActionItems() } func removeAllActions() { actions = [] reloadActionItems() } fileprivate func handleAction(_ action: ImagePickerAction) { actionHandlingCallback?() action.handle(numberOfSelectedAssets) } func handleCancelAction() { let cancelAction = actions.filter { $0.style == .cancel } .first if let cancelAction = cancelAction { handleAction(cancelAction) } else { actionHandlingCallback?() } } // MARK: - func setPreviewHeight(_ height: CGFloat, invalidateLayout: Bool) { previewHeight = height if invalidateLayout { sheetCollectionView.collectionViewLayout.invalidateLayout() } } } extension SheetController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return numberOfSections() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return numberOfItemsInSection(section) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: SheetCollectionViewCell if indexPath.section == 0 { let previewCell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(SheetPreviewCollectionViewCell.self), for: indexPath) as! SheetPreviewCollectionViewCell previewCell.collectionView = previewCollectionView cell = previewCell } else { let action = actions[indexPath.item] let actionCell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(SheetActionCollectionViewCell.self), for: indexPath) as! SheetActionCollectionViewCell actionCell.textLabel.font = fontForAction(action) actionCell.textLabel.text = numberOfSelectedAssets > 0 ? action.secondaryTitle(numberOfSelectedAssets) : action.title cell = actionCell } cell.separatorVisible = (indexPath.section == 1) // iOS specific design (cell.roundedCorners, cell.backgroundInsets) = attributesForItemAtIndexPath(indexPath) cell.normalBackgroundColor = UIColor(white: 0.97, alpha: 1) cell.highlightedBackgroundColor = UIColor(white: 0.92, alpha: 1) cell.separatorColor = UIColor(white: 0.84, alpha: 1) return cell } } extension SheetController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return indexPath.section != 0 } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) handleAction(actions[indexPath.item]) } } extension SheetController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return sizeForSheetItemAtIndexPath(indexPath) } }
apache-2.0
kstaring/swift
validation-test/compiler_crashers_fixed/28084-swift-modulefile-loadallmembers.swift
11
444
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse class A class d:A{let h:A }struct B{ struct X<T:T.a
apache-2.0
mnorth719/BoneKit
Example/Tests/ObservableTests.swift
1
6092
// // ObservableTests.swift // BoneKit_Tests // // Created by Matt North on 10/5/17. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest import BoneKit class ObservableTests: XCTestCase { override func setUp() { super.setUp() } func testObservableStruct() { let testStruct: Observable<StructTestSubject> = Observable(StructTestSubject(identifier: "JetFuelMeme")) let newTestStruct = StructTestSubject(identifier: "WakeUpSheeple") let valueWillChange = expectation(description: "Value will change should notify listener") let valueDidChange = expectation(description: "Value did change should notify listener") testStruct.onEvent(.valueWillChange) { newValue in if newValue.identifier == newTestStruct.identifier { valueWillChange.fulfill() } } testStruct.onEvent(.valueDidChange) { newValue in if newValue.identifier == newTestStruct.identifier { valueDidChange.fulfill() } } testStruct.value = newTestStruct wait(for: [valueWillChange, valueDidChange], timeout: 0.2, enforceOrder: true) } func testObservableClass() { let testStruct: Observable<ClassTestSubject> = Observable(ClassTestSubject("JetFuelMeme")) let newTestStruct = ClassTestSubject("WakeUpSheeple") let valueWillChange = expectation(description: "Value will change should notify listener") let valueDidChange = expectation(description: "Value did change should notify listener") testStruct.onEvent(.valueWillChange) { newValue in if newValue.identifier == newTestStruct.identifier { valueWillChange.fulfill() } } testStruct.onEvent(.valueDidChange) { newValue in if newValue.identifier == newTestStruct.identifier { valueDidChange.fulfill() } } testStruct.value = newTestStruct wait(for: [valueWillChange, valueDidChange], timeout: 0.2, enforceOrder: true) } func testCustomOperator() { let testStruct: Observable<ClassTestSubject> = Observable(ClassTestSubject("JetFuelMeme")) let newTestStruct = ClassTestSubject("WakeUpSheeple") let valueWillChange = expectation(description: "Value will change should notify listener") let valueDidChange = expectation(description: "Value did change should notify listener") testStruct.onEvent(.valueWillChange) { newValue in if newValue.identifier == newTestStruct.identifier { valueWillChange.fulfill() } } testStruct.onEvent(.valueDidChange) { newValue in if newValue.identifier == newTestStruct.identifier { valueDidChange.fulfill() } } testStruct << newTestStruct wait(for: [valueWillChange, valueDidChange], timeout: 0.2, enforceOrder: true) } func testClassPropertyUpdate() { func testObservableClass() { let testStruct: Observable<ClassTestSubject> = Observable(ClassTestSubject("JetFuelMeme")) let valueWillChange = expectation(description: "Value will change should notify listener") let valueDidChange = expectation(description: "Value did change should notify listener") testStruct.onEvent(.valueWillChange) { newValue in if newValue.identifier == "FalseFlag" { valueWillChange.fulfill() } } testStruct.onEvent(.valueDidChange) { newValue in if newValue.identifier == "FalseFlag" { valueDidChange.fulfill() } } testStruct.value.identifier = "FalseFlag" wait(for: [valueWillChange, valueDidChange], timeout: 0.2, enforceOrder: true) } } func testUpdateStructProperty() { let testStruct: Observable<StructTestSubject> = Observable(StructTestSubject(identifier: "JetFuelMeme")) let valueWillChange = expectation(description: "Value will change should notify listener") let valueDidChange = expectation(description: "Value did change should notify listener") testStruct.onEvent(.valueWillChange) { newValue in if newValue.identifier == "FalseFlag" { valueWillChange.fulfill() } } testStruct.onEvent(.valueDidChange) { newValue in if newValue.identifier == "FalseFlag" { valueDidChange.fulfill() } } testStruct.value.identifier = "FalseFlag" wait(for: [valueWillChange, valueDidChange], timeout: 0.2, enforceOrder: true) } func testRemoveObserver() { let testStruct: Observable<StructTestSubject> = Observable(StructTestSubject(identifier: "JetFuelMeme")) testStruct.onEvent(.valueDidChange) { newValue in XCTFail("Handler should not be called after removal") } testStruct.removeObserver(.valueDidChange) testStruct.value.identifier = "FalseFlag" } func testRemoveAllObservers() { let testStruct: Observable<StructTestSubject> = Observable(StructTestSubject(identifier: "JetFuelMeme")) testStruct.onEvent(.valueWillChange) { newValue in XCTFail("Handler should not be called after removal") } testStruct.onEvent(.valueDidChange) { newValue in XCTFail("Handler should not be called after removal") } testStruct.removeObservers() testStruct.value.identifier = "FalseFlag" } } class ClassTestSubject { var identifier: String init(_ identifier: String) { self.identifier = identifier } } struct StructTestSubject { var identifier: String }
mit
uasys/swift
test/SourceKit/Refactoring/syntactic-rename.swift
2
5104
struct AStruct { /** A description - parameter a: The first param */ func foo(a: Int) -> Int { let z = a + 1 #if true return z #else return z + 1 #endif } } let aStruct = AStruct() let x = aStruct.foo(a: 2) let y = AStruct.foo(aStruct)(a: 3) print(x + 2) print(y + 1) let s = "a foo is here" #selector(AStruct.foo(a:)) #selector(AStruct.foo()) #selector(AStruct.foo) let y = "before foo \(foo(a:1)) foo after" func bar(a/* a comment */: Int, b c: Int, _: Int, _ d: Int) {} bar(a: 1, b: 2, 3, 4) /// a comment named example func example() {} /// another comment named example class Example {} class Init { init(x: Int) {} } _ = Init(x: 1) enum MyEnum { case first case second(Int) case third(x: Int) case fourth(x: Int, y: Int, Int) } let first = MyEnum.first let second = MyEnum.second(2) let _ = MyEnum.second(_: 2) let third = MyEnum.third(x: 1) let fourth = MyEnum.fourth(x: 1, y: 2, 3) switch fourth { case .first: print(1) case .second(_: let x): print(x) case .third(x: let x): print(x) case .fourth(let x, y: let y, _: let z): print(x + y + z) } struct Memberwise1 { let x: Int let y = 0 } struct Memberwise2 { let m: Memberwise1 let n: Memberwise1 } _ = Memberwise2(m: Memberwise1(x: 1), n: Memberwise1.init(x: 2)) // RUN: rm -rf %t.result && mkdir -p %t.result // RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/x.in.json %s >> %t.result/x.expected // RUN: diff -u %S/syntactic-rename/x.expected %t.result/x.expected // RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/z.in.json %s >> %t.result/z.expected // RUN: diff -u %S/syntactic-rename/z.expected %t.result/z.expected // RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/foo.in.json %s >> %t.result/foo_arity1.expected // RUN: diff -u %S/syntactic-rename/foo_arity1.expected %t.result/foo_arity1.expected // RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/foo_remove.in.json %s >> %t.result/foo_remove.expected // RUN: diff -u %S/syntactic-rename/foo_remove.expected %t.result/foo_remove.expected // RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/bar.in.json %s >> %t.result/bar.expected // RUN: diff -u %S/syntactic-rename/bar.expected %t.result/bar.expected // RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/bar_add_param.in.json %s >> %t.result/bar_add_param.expected // RUN: diff -u %S/syntactic-rename/bar_add_param.expected %t.result/bar_add_param.expected // RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/bar_drop_param.in.json %s >> %t.result/bar_drop_param.expected // RUN: diff -u %S/syntactic-rename/bar_drop_param.expected %t.result/bar_drop_param.expected // RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/comment.in.json %s >> %t.result/comment.expected // RUN: diff -u %S/syntactic-rename/comment.expected %t.result/comment.expected // RUN: not %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/invalid.in.json %s // RUN: %sourcekitd-test -req=syntactic-rename -rename-spec %S/syntactic-rename/rename-memberwise.in.json %s >> %t.result/rename-memberwise.expected // RUN: diff -u %S/syntactic-rename/rename-memberwise.expected %t.result/rename-memberwise.expected // RUN: rm -rf %t.ranges && mkdir -p %t.ranges // RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/x.in.json %s >> %t.ranges/x.expected // RUN: diff -u %S/find-rename-ranges/x.expected %t.ranges/x.expected // RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/z.in.json %s >> %t.ranges/z.expected // RUN: diff -u %S/find-rename-ranges/z.expected %t.ranges/z.expected // RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/foo.in.json %s >> %t.ranges/foo_arity1.expected // RUN: diff -u %S/find-rename-ranges/foo_arity1.expected %t.ranges/foo_arity1.expected // RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/bar.in.json %s >> %t.ranges/bar.expected // RUN: diff -u %S/find-rename-ranges/bar.expected %t.ranges/bar.expected // RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/comment.in.json %s >> %t.ranges/comment.expected // RUN: diff -u %S/find-rename-ranges/comment.expected %t.ranges/comment.expected // RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/init.in.json %s >> %t.ranges/init.expected // RUN: diff -u %S/find-rename-ranges/init.expected %t.ranges/init.expected // RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/enum_case.in.json %s >> %t.result/enum_case.expected // RUN: diff -u %S/syntactic-rename/enum_case.expected %t.result/enum_case.expected // RUN: %sourcekitd-test -req=find-rename-ranges -rename-spec %S/syntactic-rename/rename-memberwise.in.json %s >> %t.ranges/rename-memberwise.expected // RUN: diff -u %S/find-rename-ranges/rename-memberwise.expected %t.ranges/rename-memberwise.expected
apache-2.0
BridgeTheGap/KRMathInputView
Example/Pods/KRMathInputView/KRMathInputView/Classes/MathInputView.swift
1
4789
// // MathInputView.swift // TestScript // // Created by Joshua Park on 31/01/2017. // Copyright © 2017 Knowre. All rights reserved. // import UIKit @objc public protocol MathInputViewDelegate: NSObjectProtocol { func mathInputView(_ MathInputView: MathInputView, didParse ink: [Any], latex: String) func mathInputView(_ MathInputView: MathInputView, didFailToParse ink: [Any], with error: NSError) } open class MathInputView: UIView, MathInkManagerDelegate { open weak var delegate: MathInputViewDelegate? public var isWritingMode: Bool = true { willSet { tapGestureRecognizer.isEnabled = !newValue longPressGestureRecognizer.isEnabled = !newValue } } open var manager = MathInkManager() @IBOutlet open weak var undoButton: UIButton? @IBOutlet open weak var redoButton: UIButton? private let tapGestureRecognizer = UITapGestureRecognizer() private let longPressGestureRecognizer = UILongPressGestureRecognizer() override public init(frame: CGRect) { super.init(frame: frame) setUp() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUp() } private func setUp() { tapGestureRecognizer.addTarget(self, action: #selector(tapAction(_:))) tapGestureRecognizer.isEnabled = false addGestureRecognizer(tapGestureRecognizer) longPressGestureRecognizer.addTarget(self, action: #selector(longPressAction(_:))) longPressGestureRecognizer.isEnabled = false addGestureRecognizer(longPressGestureRecognizer) manager.delegate = self } // MARK: - Public override open func draw(_ rect: CGRect) { UIColor.black.setStroke() for ink in manager.ink { if let strokeInk = ink as? StrokeInk, rect.intersects(strokeInk.path.bounds) { strokeInk.path.stroke() } else { } } if let stroke = manager.buffer { stroke.stroke() } } // MARK: - Private private func selectNode(at point: CGPoint) -> Node? { guard let node = manager.selectNode(at: point) else { return nil } displaySelection(at: node.frame) return node } private func displaySelection(at: CGRect) { // TODO: Implement } private func showMenu(at: CGRect) { } private func showCursor(at: CGRect) { } private func register(touch: UITouch, isLast: Bool = false) { let rect = manager.inputStream(at: touch.location(in: self), previousPoint: touch.previousLocation(in: self), isLast: isLast) setNeedsDisplay(rect) } // MARK: - Touch override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { register(touch: touches.first!) } override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { register(touch: touches.first!) } override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { register(touch: touches.first!, isLast: true) manager.process() } override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { register(touch: touches.first!, isLast: true) manager.process() } // MARK: - Target action @objc private func tapAction(_ sender: UITapGestureRecognizer) { guard let node = selectNode(at: sender.location(in: self)) else { return } showMenu(at: node.frame) } @objc private func longPressAction(_ sender: UILongPressGestureRecognizer) { guard let node = selectNode(at: sender.location(in: self)) else { return } showCursor(at: node.frame) } @IBAction public func undoAction(_ sender: UIButton?) { if let rect = manager.undo() { setNeedsDisplay(rect) } } @IBAction public func redoAction(_ sender: UIButton?) { if let rect = manager.redo() { setNeedsDisplay(rect) } } // MARK: - MyScriptParser delegate open func manager(_ manager: MathInkManager, didParseTreeToLaTex string: String) { delegate?.mathInputView(self, didParse: manager.ink, latex: string) } open func manager(_ manager: MathInkManager, didFailToParseWith error: NSError) { delegate?.mathInputView(self, didFailToParse: manager.ink, with: error) } open func manager(_ manager: MathInkManager, didUpdateHistory state: (undo: Bool, redo: Bool)) { } }
mit
FunctioningFunctionalist/ramda.swift
Example/Tests/appendTests.swift
1
550
import Foundation import XCTest import Ramda class AppendTests: XCTestCase { func testAppend() { XCTAssertEqual(R.append([3], [1, 2]), [1, 2, 3]) } func testAppendAsFunction() { let lastDigits = R.append([7, 8, 9]) let numberSequence = lastDigits([1, 2, 3]) XCTAssertEqual(numberSequence, [1, 2, 3, 7, 8, 9]) } func testAppendStrings() { XCTAssertEqual(R.append("tests", ["write", "more"]), ["write", "more", "tests"]) XCTAssertEqual(R.append("tests", []), ["tests"]) } }
mit
TouchInstinct/LeadKit
TIUIKitCore/Sources/ConfigurableView/ConfigurableView.swift
1
1244
// // Copyright (c) 2020 Touch Instinct // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the Software), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // public protocol ConfigurableView { associatedtype ViewModelType func configure(with _: ViewModelType) }
apache-2.0
voyages-sncf-technologies/Collor
Example/Tests/CollectionDelegateTest.swift
1
6911
// // CollectionDelegateTest.swift // Collor // // Created by Guihal Gwenn on 10/05/17. // Copyright (c) 2017-present, Voyages-sncf.com. All rights reserved.. All rights reserved. // import XCTest @testable import Collor import UIKit class CollectionDelegateTest: XCTestCase { var collectionView:UICollectionView! var collectionDataSource:CollectionDataSource! var collectionDelegate:CollectionDelegate! var data:TestData! override func setUp() { super.setUp() collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout()) data = TestData() collectionDataSource = CollectionDataSource(delegate: nil) collectionDelegate = CollectionDelegate(delegate: nil) bind(collectionView: collectionView, with: data, and: collectionDelegate, and: collectionDataSource) collectionView.reloadData() } func testShouldSelectItem() { // given let indexPath = IndexPath(item: 0, section: 0) // selectable false XCTAssertFalse(collectionDelegate.collectionView(collectionView, shouldSelectItemAt: indexPath)) // selectable true let descriptor = data.cellDescribable(at: indexPath) as! TestCellDescriptor descriptor.selectable = true XCTAssertTrue(collectionDelegate.collectionView(collectionView, shouldSelectItemAt: indexPath)) collectionDelegate.collectionData = nil XCTAssertFalse(collectionDelegate.collectionView(collectionView, shouldSelectItemAt: indexPath)) } var expectation:XCTestExpectation? func testDidSelectItem() { // given let indexPath = IndexPath(item: 0, section: 0) expectation = expectation(description: "didSelect") collectionDelegate.delegate = self // when collectionDelegate.collectionView(collectionView, didSelectItemAt: indexPath) // then waitForExpectations(timeout: 1.0) { (error) in XCTAssertNil(error) } } func testFlowLayoutSizeForItem() { // given let indexPath = IndexPath(item: 0, section: 0) // when let size = collectionDelegate.collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAt: indexPath) // then XCTAssertEqual(size, CGSize(width: 0, height: 50)) } func testFlowLayoutSizeForItem_collectionDatasNil() { // given let indexPath = IndexPath(item: 0, section: 0) collectionDelegate.collectionData = nil // when let size = collectionDelegate.collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAt: indexPath) // then XCTAssertEqual(size, CGSize.zero) } func testInsetForSection() { // given let section = 0 // when let inset = collectionDelegate.collectionView(collectionView, layout: collectionView.collectionViewLayout, insetForSectionAt: section) // then XCTAssertEqual(inset, UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)) } func testInsetForSection_collectionDatasNil() { // given let section = 0 collectionDelegate.collectionData = nil // when let inset = collectionDelegate.collectionView(collectionView, layout: collectionView.collectionViewLayout, insetForSectionAt: section) // then XCTAssertEqual(inset, UIEdgeInsets.zero) } func testMinimumInteritemSpacingForSection() { // given let section = 0 // when let spacing = collectionDelegate.collectionView(collectionView, layout: collectionView.collectionViewLayout, minimumInteritemSpacingForSectionAt: section) // then XCTAssertEqual(spacing, 5) } func testMinimumInteritemSpacingForSection_default() { // given let section = 1 // when let spacing = collectionDelegate.collectionView(collectionView, layout: collectionView.collectionViewLayout, minimumInteritemSpacingForSectionAt: section) // then XCTAssertEqual(spacing, 10) } func testMinimumInteritemSpacingForSection_collectionDatasNil() { // given let section = 0 collectionDelegate.collectionData = nil // when let spacing = collectionDelegate.collectionView(collectionView, layout: collectionView.collectionViewLayout, minimumInteritemSpacingForSectionAt: section) // then XCTAssertEqual(spacing, 10) } func testMinimumInteritemSpacingForSection_noFlowLayout() { // given let section = 0 collectionView.collectionViewLayout = UICollectionViewLayout() collectionDelegate.collectionData = nil // when let spacing = collectionDelegate.collectionView(collectionView, layout: collectionView.collectionViewLayout, minimumInteritemSpacingForSectionAt: section) // then XCTAssertEqual(spacing, 0) } func testMinimumLineSpacingForSection() { // given let section = 0 // when let spacing = collectionDelegate.collectionView(collectionView, layout: collectionView.collectionViewLayout, minimumLineSpacingForSectionAt: section) // then XCTAssertEqual(spacing, 5) } func testMinimumLineSpacingForSection_default() { // given let section = 1 // when let spacing = collectionDelegate.collectionView(collectionView, layout: collectionView.collectionViewLayout, minimumLineSpacingForSectionAt: section) // then XCTAssertEqual(spacing, 10) } func testMinimumLineSpacingForSection_collectionDatasNil() { // given let section = 0 collectionDelegate.collectionData = nil // when let spacing = collectionDelegate.collectionView(collectionView, layout: collectionView.collectionViewLayout, minimumLineSpacingForSectionAt: section) // then XCTAssertEqual(spacing, 10) } func testMinimumLineSpacingForSection_noFlowLayout() { // given let section = 0 collectionView.collectionViewLayout = UICollectionViewLayout() collectionDelegate.collectionData = nil // when let spacing = collectionDelegate.collectionView(collectionView, layout: collectionView.collectionViewLayout, minimumLineSpacingForSectionAt: section) // then XCTAssertEqual(spacing, 0) } } extension CollectionDelegateTest : CollectionDidSelectCellDelegate { func didSelect(_ cellDescriptor: CollectionCellDescribable, sectionDescriptor: CollectionSectionDescribable, indexPath: IndexPath) { expectation?.fulfill() } }
bsd-3-clause
MarcoSantarossa/SwiftyToggler
Source/FeaturesList/ViewModel/FeaturesListViewModelProtocol.swift
1
1665
// // FeaturesListViewModelProtocol.swift // // Copyright (c) 2017 Marco Santarossa (https://marcosantadev.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // protocol FeaturesListViewModelProtocol { weak var delegate: FeaturesListViewModelDelegate? { get } } protocol FeaturesListViewModelUIBindingProtocol { var titleLabelHeight: CGFloat { get } var closeButtonHeight: CGFloat { get } var featuresCount: Int { get } var shouldShowPlaceholder: Bool { get } func featureStatus(at indexPath: IndexPath) -> FeatureStatus? func updateFeature(name: String, isEnabled: Bool) func closeButtonDidTap() }
mit
vector-im/vector-ios
Riot/Modules/CrossSigning/Banners/CrossSigningSetupBannerCell.swift
1
2793
/* Copyright 2020 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 UIKit @objc protocol CrossSigningSetupBannerCellDelegate: AnyObject { func crossSigningSetupBannerCellDidTapCloseAction(_ cell: CrossSigningSetupBannerCell) } @objcMembers final class CrossSigningSetupBannerCell: MXKTableViewCell, Themable { // MARK: - Properties // MARK: Outlets @IBOutlet private weak var shieldImageView: UIImageView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var subtitleLabel: UILabel! @IBOutlet private weak var closeButton: UIButton! // MARK: Public weak var delegate: CrossSigningSetupBannerCellDelegate? // MARK: - Overrides override class func defaultReuseIdentifier() -> String { return String(describing: self) } override class func nib() -> UINib { return UINib(nibName: String(describing: self), bundle: nil) } override func customizeRendering() { super.customizeRendering() let theme = ThemeService.shared().theme self.update(theme: theme) } // MARK: - Life cycle override func awakeFromNib() { super.awakeFromNib() // TODO: Image size is too small, use an higher resolution one. let shieldImage = Asset.Images.encryptionNormal.image.withRenderingMode(.alwaysTemplate) self.shieldImageView.image = shieldImage let closeImage = Asset.Images.closeBanner.image.withRenderingMode(.alwaysTemplate) self.closeButton.setImage(closeImage, for: .normal) self.titleLabel.text = VectorL10n.crossSigningSetupBannerTitle self.subtitleLabel.text = VectorL10n.crossSigningSetupBannerSubtitle } // MARK: - Public func update(theme: Theme) { self.shieldImageView.tintColor = theme.textPrimaryColor self.closeButton.tintColor = theme.textPrimaryColor self.titleLabel.textColor = theme.textPrimaryColor self.subtitleLabel.textColor = theme.textPrimaryColor } // MARK: - Actions @IBAction private func closeButtonAction(_ sender: Any) { self.delegate?.crossSigningSetupBannerCellDidTapCloseAction(self) } }
apache-2.0
vector-im/vector-ios
Riot/Modules/ServiceTerms/Modal/Modal/ServiceTermsModalTableHeaderView.swift
1
1704
// // Copyright 2021 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 UIKit import Reusable protocol ServiceTermsModalTableHeaderViewDelegate: AnyObject { func tableHeaderViewDidTapInformationButton() } class ServiceTermsModalTableHeaderView: UIView, NibLoadable, Themable { // MARK: - Properties weak var delegate: ServiceTermsModalTableHeaderViewDelegate? @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var serviceURLLabel: UILabel! // MARK: - Setup static func instantiate() -> Self { let view = Self.loadFromNib() view.translatesAutoresizingMaskIntoConstraints = false view.update(theme: ThemeService.shared().theme) return view } func update(theme: Theme) { titleLabel.font = theme.fonts.footnote titleLabel.textColor = theme.colors.secondaryContent serviceURLLabel.font = theme.fonts.callout serviceURLLabel.textColor = theme.colors.secondaryContent } // MARK: - Action @IBAction private func buttonAction(_ sender: Any) { delegate?.tableHeaderViewDidTapInformationButton() } }
apache-2.0
vector-im/vector-ios
Riot/Managers/Serialization/SerializationServiceType.swift
2
818
/* 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 protocol SerializationServiceType { func deserialize<T: Decodable>(_ data: Data) throws -> T func deserialize<T: Decodable>(_ object: Any) throws -> T func serialize<T: Encodable>(_ object: T) throws -> Data }
apache-2.0
vector-im/vector-ios
Riot/Modules/Room/TimelineCells/Styles/Bubble/Cells/Poll/Incoming/PollIncomingWithoutSenderInfoBubbleCell.swift
1
825
// // Copyright 2021 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 class PollIncomingWithoutSenderInfoBubbleCell: PollIncomingBubbleCell { override func setupViews() { super.setupViews() roomCellContentView?.showSenderInfo = false } }
apache-2.0
vector-im/vector-ios
Riot/Modules/SetPinCode/EnterPinCode/EnterPinCodeViewModel.swift
1
8979
// File created from ScreenTemplate // $ createScreen.sh SetPinCode/EnterPinCode EnterPinCode /* Copyright 2020 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 final class EnterPinCodeViewModel: EnterPinCodeViewModelType { // MARK: - Properties // MARK: Private private let session: MXSession? private var originalViewMode: SetPinCoordinatorViewMode private var viewMode: SetPinCoordinatorViewMode private var initialPin: String = "" private var firstPin: String = "" private var currentPin: String = "" { didSet { self.viewDelegate?.enterPinCodeViewModel(self, didUpdatePlaceholdersCount: currentPin.count) } } private var numberOfFailuresDuringEnterPIN: Int = 0 // MARK: Public weak var viewDelegate: EnterPinCodeViewModelViewDelegate? weak var coordinatorDelegate: EnterPinCodeViewModelCoordinatorDelegate? private let pinCodePreferences: PinCodePreferences private let localAuthenticationService: LocalAuthenticationService // MARK: - Setup init(session: MXSession?, viewMode: SetPinCoordinatorViewMode, pinCodePreferences: PinCodePreferences) { self.session = session self.originalViewMode = viewMode self.viewMode = viewMode self.pinCodePreferences = pinCodePreferences self.localAuthenticationService = LocalAuthenticationService(pinCodePreferences: pinCodePreferences) } // MARK: - Public func process(viewAction: EnterPinCodeViewAction) { switch viewAction { case .loadData: self.loadData() case .digitPressed(let tag): self.digitPressed(tag) case .forgotPinPressed: self.viewDelegate?.enterPinCodeViewModel(self, didUpdateViewState: .forgotPin) case .cancel: self.coordinatorDelegate?.enterPinCodeViewModelDidCancel(self) case .pinsDontMatchAlertAction: // reset pins firstPin.removeAll() currentPin.removeAll() // go back to first state self.update(viewState: .choosePin) case .forgotPinAlertResetAction: self.coordinatorDelegate?.enterPinCodeViewModelDidCompleteWithReset(self, dueToTooManyErrors: false) case .forgotPinAlertCancelAction: // no-op break } } // MARK: - Private private func digitPressed(_ tag: Int) { if tag == -1 { // delete tapped if currentPin.isEmpty { return } else { currentPin.removeLast() // switch to setPin if blocked if viewMode == .notAllowedPin { // clear error UI update(viewState: viewState(for: originalViewMode)) // switch back to original flow viewMode = originalViewMode } } } else { // a digit tapped // switch to setPin if blocked if viewMode == .notAllowedPin { // clear old pin first currentPin.removeAll() // clear error UI update(viewState: viewState(for: originalViewMode)) // switch back to original flow viewMode = originalViewMode } // add new digit currentPin += String(tag) if currentPin.count == pinCodePreferences.numberOfDigits { switch viewMode { case .setPin, .setPinAfterLogin, .setPinAfterRegister: // choosing pin updateAfterPinSet() case .unlock, .confirmPinToDeactivate: // unlocking if currentPin != pinCodePreferences.pin { // no match updateAfterUnlockFailed() } else { // match // we can use biometrics anymore, if set pinCodePreferences.canUseBiometricsToUnlock = nil pinCodePreferences.resetCounters() // complete with a little delay DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.coordinatorDelegate?.enterPinCodeViewModelDidComplete(self) } } case .changePin: // unlocking if initialPin.isEmpty && currentPin != pinCodePreferences.pin { // no match updateAfterUnlockFailed() } else if initialPin.isEmpty { // match or already unlocked // the user can choose a new Pin code initialPin = currentPin currentPin.removeAll() update(viewState: .choosePin) } else { // choosing pin updateAfterPinSet() } default: break } return } } } private func viewState(for mode: SetPinCoordinatorViewMode) -> EnterPinCodeViewState { switch mode { case .setPin: return .choosePin case .setPinAfterLogin: return .choosePinAfterLogin case .setPinAfterRegister: return .choosePinAfterRegister case .changePin: return .changePin default: return .inactive } } private func loadData() { switch viewMode { case .setPin, .setPinAfterLogin, .setPinAfterRegister: update(viewState: viewState(for: viewMode)) self.viewDelegate?.enterPinCodeViewModel(self, didUpdateCancelButtonHidden: pinCodePreferences.forcePinProtection) case .unlock: update(viewState: .unlock) case .confirmPinToDeactivate: update(viewState: .confirmPinToDisable) case .inactive: update(viewState: .inactive) case .changePin: update(viewState: .changePin) default: break } } private func update(viewState: EnterPinCodeViewState) { self.viewDelegate?.enterPinCodeViewModel(self, didUpdateViewState: viewState) } private func updateAfterUnlockFailed() { numberOfFailuresDuringEnterPIN += 1 pinCodePreferences.numberOfPinFailures += 1 if viewMode == .unlock && localAuthenticationService.shouldLogOutUser() { // log out user self.coordinatorDelegate?.enterPinCodeViewModelDidCompleteWithReset(self, dueToTooManyErrors: true) return } if numberOfFailuresDuringEnterPIN < pinCodePreferences.allowedNumberOfTrialsBeforeAlert { DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.viewDelegate?.enterPinCodeViewModel(self, didUpdateViewState: .wrongPin) self.currentPin.removeAll() } } else { viewDelegate?.enterPinCodeViewModel(self, didUpdateViewState: .wrongPinTooManyTimes) numberOfFailuresDuringEnterPIN = 0 currentPin.removeAll() } } private func updateAfterPinSet() { if firstPin.isEmpty { // check if this PIN is allowed if pinCodePreferences.notAllowedPINs.contains(currentPin) { viewMode = .notAllowedPin update(viewState: .notAllowedPin) return } // go to next screen firstPin = currentPin currentPin.removeAll() update(viewState: .confirmPin) } else if firstPin == currentPin { // check first and second pins // complete with a little delay DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.coordinatorDelegate?.enterPinCodeViewModel(self, didCompleteWithPin: self.firstPin) } } else { update(viewState: .pinsDontMatch) } } }
apache-2.0
jjochen/photostickers
MessagesExtension/Extensions/String+Extensions.swift
1
378
// // String+Extensions.swift // PhotoStickers // // Created by Jochen Pfeiffer on 08.04.17. // Copyright © 2017 Jochen Pfeiffer. All rights reserved. // import Foundation extension String { var localized: String { return localized() } func localized(comment: String = "") -> String { return NSLocalizedString(self, comment: comment) } }
mit
algolia/algoliasearch-client-swift
Tests/AlgoliaSearchClientTests/Unit/Settings/SnippetTests.swift
1
364
// // SnippetTests.swift // // // Created by Vladislav Fitc on 12.03.2020. // import Foundation import XCTest @testable import AlgoliaSearchClient class SnippetTests: XCTestCase { func testCoding() throws { try AssertEncodeDecode(Snippet(attribute: "attr"), "attr") try AssertEncodeDecode(Snippet(attribute: "attr", count: 20), "attr:20") } }
mit
tjw/swift
benchmark/single-source/SequenceAlgos.swift
3
4407
//===--- ArrayAppend.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 // This benchmark tests closureless versions of min and max, both contains, // repeatElement and reduce, on a number of different sequence types. // To avoid too many little micro benchmarks, it measures them all together // for each sequence type. public let SequenceAlgos = [ BenchmarkInfo(name: "SequenceAlgosList", runFunction: run_SequenceAlgosList, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosArray", runFunction: run_SequenceAlgosArray, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosContiguousArray", runFunction: run_SequenceAlgosContiguousArray, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosRange", runFunction: run_SequenceAlgosRange, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosUnfoldSequence", runFunction: run_SequenceAlgosUnfoldSequence, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosAnySequence", runFunction: run_SequenceAlgosAnySequence, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), ] extension List: Sequence { struct Iterator: IteratorProtocol { var _list: List<Element> mutating func next() -> Element? { guard case let .node(x,xs) = _list else { return nil } _list = xs return x } } func makeIterator() -> Iterator { return Iterator(_list: self) } } extension List: Equatable where Element: Equatable { static func == (lhs: List<Element>, rhs: List<Element>) -> Bool { return lhs.elementsEqual(rhs) } } func benchmarkSequenceAlgos<S: Sequence>(s: S, n: Int) where S.Element == Int { CheckResults(s.reduce(0, &+) == (n*(n-1))/2) let mn = s.min() let mx = s.max() CheckResults(mn == 0 && mx == n-1) CheckResults(s.starts(with: s)) } let n = 10_000 let r = 0..<(n*100) let l = List(0..<n) let c = ContiguousArray(0..<(n*100)) let a = Array(0..<(n*100)) let y = AnySequence(0..<n) let s = sequence(first: 0, next: { $0 < n&-1 ? $0&+1 : nil}) func buildWorkload() { _ = l.makeIterator() _ = c.makeIterator() _ = a.makeIterator() _ = y.makeIterator() _ = s.makeIterator() } func benchmarkEquatableSequenceAlgos<S: Sequence>(s: S, n: Int) where S.Element == Int, S: Equatable { CheckResults(repeatElement(s, count: 1).contains(s)) CheckResults(!repeatElement(s, count: 1).contains { $0 != s }) } @inline(never) public func run_SequenceAlgosRange(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: r, n: r.count) benchmarkEquatableSequenceAlgos(s: r, n: r.count) } } @inline(never) public func run_SequenceAlgosArray(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: a, n: a.count) benchmarkEquatableSequenceAlgos(s: a, n: a.count) } } @inline(never) public func run_SequenceAlgosContiguousArray(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: c, n: c.count) benchmarkEquatableSequenceAlgos(s: c, n: c.count) } } @inline(never) public func run_SequenceAlgosAnySequence(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: y, n: n) } } @inline(never) public func run_SequenceAlgosUnfoldSequence(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: s, n: n) } } @inline(never) public func run_SequenceAlgosList(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: l, n: n) benchmarkEquatableSequenceAlgos(s: l, n: n) } } enum List<Element> { case end indirect case node(Element, List<Element>) init<S: BidirectionalCollection>(_ elements: S) where S.Element == Element { self = elements.reversed().reduce(.end) { .node($1,$0) } } }
apache-2.0
opensourcegit/CustomCollectionViews
Pod/Classes/BaseCollectionView.swift
1
4661
// // BaseCollectionView.swift // Pods // // Created by opensourcegit on 18/09/15. // // import Foundation import UIKit public class BaseCollectionView: UICollectionView { var data = [BaseCollectionSectionModel](); public func setCollectionViewData(data:[BaseCollectionSectionModel]){ self.data = data; dispatch_async(dispatch_get_main_queue(), { () -> Void in print("data reload count \(self.data.count)\n") self.reloadData(); }); } override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) self.setup() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup(); } override public func awakeFromNib() { super.awakeFromNib(); self.setup() } func setup(){ self.dataSource = self; self.delegate = self; } } extension BaseCollectionView:UICollectionViewDataSource{ public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ let sectionModel = data[section]; let count = sectionModel.items.count; println("count \(count)"); return count; } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{ let sectionModel = data[indexPath.section]; let cellModel = sectionModel.items[indexPath.item]; let cellIdentifier = cellModel.dynamicType.cellIdentifier(); let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! UICollectionViewCell; if let cell = cell as? ReactiveView{ cell.bindViewModel(cellModel); } return cell } //MARK: optional public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{ return data.count; } // The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: public func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView{ var reusableView : UICollectionReusableView? = nil if kind == UICollectionElementKindSectionHeader { let sectionModel = data[indexPath.section]; let reuseIdentifier = sectionModel.identifer!; reusableView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: reuseIdentifier, forIndexPath: indexPath) as? UICollectionReusableView if let reusableView = reusableView as? ReactiveView { reusableView.bindViewModel(sectionModel); } } return reusableView! } } extension BaseCollectionView:UICollectionViewDelegateFlowLayout{ public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{ let sectionModel:BaseCollectionSectionModel = data[indexPath.section]; let cellModel = sectionModel.items[indexPath.item]; return CellSizer.shared.sizeThatFits(collectionView.bounds.size, viewModel: cellModel, cellClass: cellModel.cellClass()) } // func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets{ // // } // func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat{ // // } // func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat{ // // } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{ return CGSize(width: 100, height: 100); } // func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize{ // // } }
mit
vl4298/mah-income
Mah Income/Mah Income/ApplicationManager.swift
1
361
// // ApplicationManager.swift // Mah Income // // Created by Van Luu on 4/22/17. // Copyright © 2017 Van Luu. All rights reserved. // import Foundation class ApplicationManager { static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "E, d MMM yyyy HH:mm:ss" return formatter }() }
mit
mxcl/swift-package-manager
Sources/PackageModel/Manifest.swift
2
2344
/* This source file is part of the Swift.org open source project Copyright 2015 - 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors ------------------------------------------------------------------------- This file defines the support for loading the Swift-based manifest files. */ import Basic import PackageDescription /** This contains the declarative specification loaded from package manifest files, and the tools for working with the manifest. */ public struct Manifest { /// The standard filename for the manifest. public static var filename = basename + ".swift" /// The standard basename for the manifest. public static var basename = "Package" /// The path of the manifest file. // // FIXME: This doesn't belong here, we want the Manifest to be purely tied // to the repository state, it shouldn't matter where it is. public let path: AbsolutePath /// The repository URL the manifest was loaded from. // // FIXME: This doesn't belong here, we want the Manifest to be purely tied // to the repository state, it shouldn't matter where it is. public let url: String /// The raw package description. public let package: PackageDescription.Package /// The raw product descriptions. public let products: [PackageDescription.Product] /// The version this package was loaded from, if known. public let version: Version? /// The name of the package. public var name: String { return package.name } public init(path: AbsolutePath, url: String, package: PackageDescription.Package, products: [PackageDescription.Product], version: Version?) { self.path = path self.url = url self.package = package self.products = products self.version = version } } extension Manifest { /// Returns JSON representation of this manifest. // Note: Right now we just return the JSON representation of the package, // but this can be expanded to include the details about manifest too. public func jsonString() -> String { return PackageDescription.jsonString(package: package) } }
apache-2.0
shahmishal/swift
test/SourceKit/CursorInfo/cursor_swiftinterface.swift
3
3433
import SomeModule func test() { print(SomeFunc()) let wrapper = XWrapper(x: 43) print(wrapper.x) } // RUN: %empty-directory(%t) // RUN: %empty-directory(%t/modulecache) // // Tests CursorInfo works with modules imported via their .swiftinterface file. // Setup builds a module interface (.swiftinterface) and doc file (.swiftdoc), // for SomeModule (built from the SomeModule.swift input) that is imported in // this file. No .swiftmodule is produced to force it into loading via the // .swiftinterface file. // Setup phase 1: build the module interface (.swiftinterface) and doc (.swiftdoc). // // RUN: %target-swift-frontend -I %t -module-name SomeModule -emit-parseable-module-interface-path %t/SomeModule.swiftinterface -emit-module-doc-path %t/SomeModule.swiftdoc %S/Inputs/SomeModule.swift -emit-module -o /dev/null // Actual test: Check the CusorInfo results of references to symbols in that // module, including the available refactoring actions, and associated doc // comments (from the .swiftdoc file). // // RUN: %sourcekitd-test -req=cursor -cursor-action -pos=1:8 %s -- -I %t -module-cache-path %t/modulecache -target %target-triple %s | %FileCheck %s -check-prefix=CHECK1 // CHECK1: source.lang.swift.ref.module // CHECK1: SomeModule // CHECK1: ACTIONS BEGIN // CHECK1-NEXT: ACTIONS END // RUN: %sourcekitd-test -req=cursor -cursor-action -pos=4:9 %s -- -I %t -module-cache-path %t/modulecache -target %target-triple %s | %FileCheck %s -check-prefix=CHECK2 // CHECK2: source.lang.swift.ref.function.free // CHECK2: SomeFunc() // CHECK2: () -> Int // CHECK2: SomeModule // CHECK2: <CommentParts><Abstract><Para>This is SomeFunc that serves some function</Para></Abstract><ResultDiscussion><Para>42</Para></ResultDiscussion></CommentParts> // CHECK2: ACTIONS BEGIN // CHECK2-NEXT: source.refactoring.kind.rename.global // CHECK2-NEXT: Global Rename // CHECK2-NEXT: symbol without a declaration location cannot be renamed // CHECK2-NEXT: ACTIONS END // RUN: %sourcekitd-test -req=cursor -cursor-action -pos=5:17 %s -- -I %t -module-cache-path %t/modulecache -target %target-triple %s | %FileCheck %s -check-prefix=CHECK3 // CHECK3: source.lang.swift.ref.struct // CHECK3: XWrapper // CHECK3: XWrapper.Type // CHECK3: SomeModule // CHECK3: ACTIONS BEGIN // CHECK3-NEXT: source.refactoring.kind.rename.global // CHECK3-NEXT: Global Rename // CHECK3-NEXT: symbol without a declaration location cannot be renamed // CHECK3-NEXT: ACTIONS END // RUN: %sourcekitd-test -req=cursor -cursor-action -pos=6:9 %s -- -I %t -module-cache-path %t/modulecache -target %target-triple %s | %FileCheck %s -check-prefix=CHECK4 // CHECK4: source.lang.swift.ref.var.local // CHECK4: wrapper // CHECK4: XWrapper // CHECK4: ACTIONS BEGIN // CHECK4-NEXT: source.refactoring.kind.rename.local // CHECK4-NEXT: Local Rename // CHECK4-NEXT: ACTIONS END // RUN: %sourcekitd-test -req=cursor -cursor-action -pos=6:17 %s -- -I %t -module-cache-path %t/modulecache -target %target-triple %s | %FileCheck %s -check-prefix=CHECK5 // CHECK5: source.lang.swift.ref.var.instance // CHECK5: x // CHECK5: Int // CHECK5: SomeModule // CHECK5: <CommentParts><Abstract><Para>This is x, a property of XWrapper</Para></Abstract></CommentParts> // CHECK5: ACTIONS BEGIN // CHECK5-NEXT: source.refactoring.kind.rename.global // CHECK5-NEXT: Global Rename // CHECK5-NEXT: symbol without a declaration location cannot be renamed // CHECK5-NEXT: ACTIONS END
apache-2.0
roambotics/swift
test/AutoDiff/SILOptimizer/property_wrappers.swift
2
3572
// RUN: %target-swift-frontend -emit-sil -verify %s %S/Inputs/nontrivial_loadable_type.swift // REQUIRES: asserts // Test property wrapper differentiation coverage for a variety of property // types: trivial, non-trivial loadable, and address-only. import DifferentiationUnittest // MARK: Property wrappers @propertyWrapper struct SimpleWrapper<Value> { var wrappedValue: Value // stored property } @propertyWrapper struct Wrapper<Value> { private var value: Value var wrappedValue: Value { // computed property get { value } set { value = newValue } } init(wrappedValue: Value) { self.value = wrappedValue } } // `DifferentiableWrapper` conditionally conforms to `Differentiable`. @propertyWrapper struct DifferentiableWrapper<Value> { private var value: Value var wrappedValue: Value { // computed property get { value } set { value = newValue } } init(wrappedValue: Value) { self.value = wrappedValue } } extension DifferentiableWrapper: Differentiable where Value: Differentiable {} // MARK: Types with wrapped properties struct Struct: Differentiable { @Wrapper @SimpleWrapper var trivial: Float = 10 @Wrapper @SimpleWrapper var tracked: Tracked<Float> = 20 @Wrapper @SimpleWrapper var nontrivial: NontrivialLoadable<Float> = 30 // https://github.com/apple/swift/issues/55245 // Semantic member accessors should have empty linear map structs. @DifferentiableWrapper var differentiableWrapped: Float = 40 static func testGetters() { let _: @differentiable(reverse) (Self) -> Float = { $0.trivial } let _: @differentiable(reverse) (Self) -> Tracked<Float> = { $0.tracked } let _: @differentiable(reverse) (Self) -> NontrivialLoadable<Float> = { $0.nontrivial } let _: @differentiable(reverse) (Self) -> Float = { $0.differentiableWrapped } } static func testSetters() { let _: @differentiable(reverse) (inout Self, Float) -> Void = { $0.trivial = $1 } let _: @differentiable(reverse) (inout Self, Tracked<Float>) -> Void = { $0.tracked = $1 } let _: @differentiable(reverse) (inout Self, NontrivialLoadable<Float>) -> Void = { $0.nontrivial = $1 } let _: @differentiable(reverse) (inout Self, Float) -> Void = { $0.differentiableWrapped = $1 } } } struct GenericStruct<T: Differentiable>: Differentiable { @Wrapper @SimpleWrapper var trivial: Float = 10 @Wrapper @SimpleWrapper var tracked: Tracked<Float> = 20 @Wrapper @SimpleWrapper var nontrivial: NontrivialLoadable<Float> = 30 @Wrapper @SimpleWrapper var addressOnly: T // https://github.com/apple/swift/issues/55223 // Test getter pullback for non-trivial loadable property. static func testGetters() { let _: @differentiable(reverse) (Self) -> Float = { $0.trivial } let _: @differentiable(reverse) (Self) -> Tracked<Float> = { $0.tracked } let _: @differentiable(reverse) (Self) -> NontrivialLoadable<Float> = { $0.nontrivial } let _: @differentiable(reverse) (Self) -> T = { $0.addressOnly } } // https://github.com/apple/swift/issues/55224 // Test setter pullback for non-trivial loadable property. static func testSetters() { let _: @differentiable(reverse) (inout Self, Float) -> Void = { $0.trivial = $1 } let _: @differentiable(reverse) (inout Self, Tracked<Float>) -> Void = { $0.tracked = $1 } let _: @differentiable(reverse) (inout Self, NontrivialLoadable<Float>) -> Void = { $0.nontrivial = $1 } let _: @differentiable(reverse) (inout Self, T) -> Void = { $0.addressOnly = $1 } } }
apache-2.0
cohena100/Shimi
Carthage/Checkouts/RxRealm/Example/RxRealm_Tests/RxRealmResultsTests.swift
1
7075
// // RxRealmCollectionsTests.swift // RxRealm // // Created by Marin Todorov on 4/30/16. // Copyright © 2016 CocoaPods. All rights reserved. // import XCTest import RxSwift import RealmSwift import RxRealm import RxTest class RxRealmResultsTests: XCTestCase { fileprivate func realmInMemory(_ name: String) -> Realm { var conf = Realm.Configuration() conf.inMemoryIdentifier = name return try! Realm(configuration: conf) } fileprivate func clearRealm(_ realm: Realm) { try! realm.write { realm.deleteAll() } } func testResultsType() { let expectation1 = expectation(description: "Results<Message> first") let realm = realmInMemory(#function) clearRealm(realm) let bag = DisposeBag() let scheduler = TestScheduler(initialClock: 0) let observer = scheduler.createObserver(Results<Message>.self) let messages$ = Observable.collection(from: realm.objects(Message.self)).shareReplay(1) messages$.scan(0, accumulator: {acc, _ in return acc+1}) .filter { $0 == 4 }.map {_ in ()}.subscribe(onNext: expectation1.fulfill).addDisposableTo(bag) messages$ .subscribe(observer).addDisposableTo(bag) //interact with Realm here delay(0.1) { try! realm.write { realm.add(Message("first")) } } delay(0.2) { try! realm.write { realm.delete(realm.objects(Message.self).first!) } } delay(0.3) { try! realm.write { realm.add(Message("second")) } } scheduler.start() waitForExpectations(timeout: 0.5) {error in //do tests here XCTAssertTrue(error == nil) XCTAssertEqual(observer.events.count, 4) let results = observer.events.last!.value.element! XCTAssertEqual(results.count, 1) XCTAssertEqual(results.first!.text, "second") } } func testResultsTypeChangeset() { let expectation1 = expectation(description: "Results<Message> first") let realm = realmInMemory(#function) clearRealm(realm) let bag = DisposeBag() let scheduler = TestScheduler(initialClock: 0) let observer = scheduler.createObserver(String.self) let messages$ = Observable.changeset(from: realm.objects(Message.self)).shareReplay(1) messages$.scan(0, accumulator: {acc, _ in return acc+1}) .filter { $0 == 3 }.map {_ in ()}.subscribe(onNext: expectation1.fulfill).addDisposableTo(bag) messages$ .map {results, changes in if let changes = changes { return "i:\(changes.inserted) d:\(changes.deleted) u:\(changes.updated)" } else { return "initial" } } .subscribe(observer).addDisposableTo(bag) //interact with Realm here delay(0.1) { try! realm.write { realm.add(Message("first")) } } delay(0.2) { try! realm.write { realm.delete(realm.objects(Message.self).first!) } } scheduler.start() waitForExpectations(timeout: 0.5) {error in //do tests here XCTAssertTrue(error == nil) XCTAssertEqual(observer.events.count, 3) XCTAssertEqual(observer.events[0].value.element!, "initial") XCTAssertEqual(observer.events[1].value.element!, "i:[0] d:[] u:[]") XCTAssertEqual(observer.events[2].value.element!, "i:[] d:[0] u:[]") } } func testResultsEmitsCollectionSynchronously() { let realm = realmInMemory(#function) let bag = DisposeBag() // collection let scheduler = TestScheduler(initialClock: 0) let observer1 = scheduler.createObserver(Results<Message>.self) Observable.collection(from: realm.objects(Message.self), synchronousStart: true) .subscribe(observer1) .addDisposableTo(bag) XCTAssertEqual(observer1.events.count, 1) XCTAssertEqual(observer1.events[0].value.element!.count, 0) } func testResultsEmitsChangesetSynchronously() { let realm = realmInMemory(#function) let bag = DisposeBag() let scheduler = TestScheduler(initialClock: 0) // changeset let observer2 = scheduler.createObserver(Int.self) Observable.changeset(from: realm.objects(Message.self), synchronousStart: true) .map { $0.0.count } .subscribe(observer2) .addDisposableTo(bag) XCTAssertEqual(observer2.events.count, 1) XCTAssertEqual(observer2.events[0].value.element!, 0) } func testResultsEmitsCollectionAsynchronously() { let expectation1 = expectation(description: "Async collection emit") let realm = realmInMemory(#function) let bag = DisposeBag() let scheduler = TestScheduler(initialClock: 0) // test collection let observer = scheduler.createObserver(Results<Message>.self) let messages$ = Observable.collection(from: realm.objects(Message.self), synchronousStart: false) .share() messages$ .subscribe(observer) .addDisposableTo(bag) messages$ .subscribe(onNext: {_ in expectation1.fulfill() }) .addDisposableTo(bag) XCTAssertEqual(observer.events.count, 0) waitForExpectations(timeout: 5) {error in XCTAssertTrue(error == nil) XCTAssertEqual(observer.events.count, 1) XCTAssertEqual(observer.events[0].value.element!.count, 0) } } func testResultsEmitsChangesetAsynchronously() { // test changeset let expectation2 = expectation(description: "Async changeset emit") let realm = realmInMemory(#function) let bag = DisposeBag() let scheduler = TestScheduler(initialClock: 0) let observer2 = scheduler.createObserver(Int.self) let messages2$ = Observable.changeset(from: realm.objects(Message.self), synchronousStart: false) .share() messages2$ .map { $0.0.count } .subscribe(observer2) .addDisposableTo(bag) messages2$ .subscribe(onNext: {_ in expectation2.fulfill() }) .addDisposableTo(bag) XCTAssertEqual(observer2.events.count, 0) waitForExpectations(timeout: 5) {error in XCTAssertTrue(error == nil) XCTAssertEqual(observer2.events.count, 1) XCTAssertEqual(observer2.events[0].value.element!, 0) } } }
mit
crazypoo/PTools
Pods/Appz/Appz/Appz/Apps/Behance.swift
1
1394
// // Behance.swift // Appz // // Created by Mariam AlJamea on 6/17/17. // Copyright © 2017 kitz. All rights reserved. // public extension Applications { public struct Behance: ExternalApplication { public typealias ActionType = Applications.Behance.Action public let scheme = "behance:" public let fallbackURL = "https://www.behance.net/" public let appStoreId = "489667151" public init() {} } } // MARK: - Actions public extension Applications.Behance { public enum Action { case open case userProfile(String) } } extension Applications.Behance.Action: ExternalApplicationAction { public var paths: ActionPaths { switch self { case .open: return ActionPaths( app: Path( pathComponents: ["app"], queryParameters: [:] ), web: Path() ) case .userProfile(let profile): return ActionPaths( app: Path( pathComponents: ["profile", profile], queryParameters: [:] ), web: Path( pathComponents: [profile], queryParameters: [:] ) ) } } }
mit
swift-lang/swift-k
tests/language/working/003-string-array-assignment.swift
2
43
string greetings[] = ["how","are","you"];
apache-2.0
Bleichroder/MaxWall-Controller-on-IOS
MaxWall/MaxWall/Message.swift
1
429
// // Message.swift // MaxWall // // Created by HeHe on 16/6/17. // Copyright © 2016年 HeHe. All rights reserved. // import UIKit class Message { var name: String var content: String var id: String var status: String init?(name: String, content: String, id: String, status: String){ self.name = name self.content = content self.id = id self.status = status } }
apache-2.0
austinfitzpatrick/SwiftVG
SwiftVG/SwiftSVG/Views/SVGVectorImage Categories/SVGVectorImage+ColorReplacement.swift
1
1468
// // SVGVectorImage+ColorReplacement.swift // SwiftVG // // Created by Austin Fitzpatrick on 3/20/15. // Copyright (c) 2015 austinfitzpatrick. All rights reserved. // import UIKit protocol SVGColorReplaceable { func replaceColor(color: UIColor, withColor replacement:UIColor, includeGradients:Bool) } extension SVGGroup: SVGColorReplaceable { func replaceColor(color: UIColor, withColor replacement: UIColor, includeGradients:Bool) { for drawable in drawables { if let group = drawable as? SVGGroup { group.replaceColor(color, withColor: replacement, includeGradients:includeGradients) } else if let path = drawable as? SVGPath { path.replaceColor(color, withColor: replacement, includeGradients:includeGradients) } } } } extension SVGPath: SVGColorReplaceable { func replaceColor(color: UIColor, withColor replacement: UIColor, includeGradients:Bool) { if let fillColor = self.fill?.asColor(){ if fillColor == color { self.fill = replacement } } else if let fillGradient = self.fill?.asGradient() { if includeGradients { for stop in fillGradient.stops { if stop.color == color { fillGradient.removeStop(stop) fillGradient.addStop(stop.offset, color: replacement, opacity: 1.0) } } } } } }
mit
manchan/JinsMeme-Swift-Sample
JinsMemeDemo/ViewController.swift
1
5984
// // ViewController.swift // JinsMemeDemo // // Created by matz on 2015/11/21. // Copyright © 2015年 matz. All rights reserved. // import UIKit final class ViewController: UITableViewController, MEMELibDelegate { var peripherals:NSMutableArray! var dataViewCtl:MMDataViewController! var detailViewCtl:MMDataDetaileViewController! override func viewDidLoad() { super.viewDidLoad() MEMELib.sharedInstance().delegate = self self.peripherals = [] self.title = "MEME Demo" self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Scan", style: UIBarButtonItemStyle.plain, target: self, action: #selector(scanButtonPressed)) } func scanButtonPressed(){ let status:MEMEStatus = MEMELib.sharedInstance().startScanningPeripherals() self.checkMEMEStatus(status) } func memePeripheralFound(_ peripheral: CBPeripheral!, withDeviceAddress address: String!) { print("New Peripheral found \(peripheral.identifier.uuidString) \(address)") self.peripherals.add(peripheral) self.tableView.reloadData() } func memePeripheralConnected(_ peripheral: CBPeripheral!) { print("MEME Device Connected") self.navigationItem.rightBarButtonItem?.isEnabled = false self.tableView.isUserInteractionEnabled = false self.performSegue(withIdentifier: "DataViewSegue", sender: self) // Set Data Mode to Standard Mode MEMELib.sharedInstance().startDataReport() } func memePeripheralDisconnected(_ peripheral: CBPeripheral!) { print("MEME Device Disconnected") self.navigationItem.rightBarButtonItem?.isEnabled = true self.tableView.isUserInteractionEnabled = true self.dismiss(animated: true) { () -> Void in self.dataViewCtl = nil print("MEME Device Disconnected") } } func memeRealTimeModeDataReceived(_ data: MEMERealTimeData!) { guard let _ = self.dataViewCtl else { return } self.dataViewCtl.memeRealTimeModeDataReceived(data) RealtimeData.sharedInstance.memeRealTimeModeDataReceived(data) } func memeAppAuthorized(_ status: MEMEStatus) { self.checkMEMEStatus(status) } func memeCommand(_ response: MEMEResponse) { print("Command Response - eventCode: \(response.eventCode) - commandResult: \(response.commandResult)") switch (response.eventCode) { case 0x02: print("Data Report Started"); break; case 0x04: print("Data Report Stopped"); break; default: break; } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.peripherals.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DeviceCellIdentifier", for: indexPath) let peripheral:CBPeripheral = self.peripherals.object(at: indexPath.row) as! CBPeripheral cell.textLabel?.text = peripheral.identifier.uuidString return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let peripheral:CBPeripheral = self.peripherals.object(at: indexPath.row) as! CBPeripheral let status:MEMEStatus = MEMELib.sharedInstance().connect(peripheral) self.checkMEMEStatus(status) print("Start connecting to MEME Device...") } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "DataViewSegue" { let naviCtl = segue.destination as! UINavigationController self.dataViewCtl = naviCtl.topViewController as! MMDataViewController } } func checkMEMEStatus(_ status:MEMEStatus) { if status == MEME_ERROR_APP_AUTH { let alertController = UIAlertController(title: "App Auth Failed", message: "Invalid Application ID or Client Secret ", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler:nil) alertController.addAction(action) self.present(alertController, animated: true, completion: nil) } else if status == MEME_ERROR_SDK_AUTH{ let alertController = UIAlertController(title: "SDK Auth Failed", message: "Invalid SDK. Please update to the latest SDK.", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler:nil) alertController.addAction(action) self.present(alertController, animated: true, completion: nil) } else if status == MEME_CMD_INVALID { let alertController = UIAlertController(title: "SDK Error", message: "Invalid Command", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler:nil) alertController.addAction(action) self.present(alertController, animated: true, completion: nil) } else if status == MEME_ERROR_BL_OFF { let alertController = UIAlertController(title: "Error", message: "Bluetooth is off.", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler:nil) alertController.addAction(action) self.present(alertController, animated: true, completion: nil) } else if status == MEME_OK { print("Status: MEME_OK") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
AllisonWangJiaoJiao/KnowledgeAccumulation
02-UIViewFormXIB(POP)/UIViewFormXIB(POP)/NibLoadable.swift
1
610
// // NibLoadable.swift // UIViewFormXIB(POP) // // Created by Allison on 2017/4/27. // Copyright © 2017年 Allison. All rights reserved. // import UIKit protocol NibLoadable { } extension NibLoadable where Self : UIView { //在协议里面不允许定义class 只能定义static static func loadFromNib(_ nibname: String? = nil) -> Self {//Self (大写) 当前类对象 //self(小写) 当前对象 let loadName = nibname == nil ? "\(self)" : nibname! return Bundle.main.loadNibNamed(loadName, owner: nil, options: nil)?.first as! Self } }
mit
baberthal/SwiftCoreExt
CoreExtensions/DebugMacros.swift
1
1750
// // DebugMacros.swift // CoreExtensions // // Created by Morgan Lieberthal on 12/5/15. // Copyright © 2015 Morgan Lieberthal. All rights reserved. // import Foundation import Cocoa public func dLog(@autoclosure message: () -> String, filename: String = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, column: UInt = __COLUMN__) { #if DEBUG var path: String! if let fname = NSURL(string: filename) { path = fname.lastPathComponent } else { path = filename } NSLog("[\(path):\(line):\(column)] \(function) -- %@", message()) #endif } public func uLog(error: NSError, filename: String = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, column: UInt = __COLUMN__) { #if DEBUG let alert = NSAlert(error: error) alert.runModal() NSLog("[\(filename):\(line):\(column)] \(function) -- %@", error) #endif } public func aLog(@autoclosure message: () -> String, filename: String = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, column: UInt = __COLUMN__) { var path: String! if let fname = NSURL(string: filename) { path = fname.lastPathComponent } else { path = filename } NSLog("[\(path):\(line):\(column)] \(function) -- %@", message()) } public func eLog(@autoclosure message: () -> String, error: NSError, filename: String = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, column: UInt = __COLUMN__) { var path: String! if let fname = NSURL(string: filename) { path = fname.lastPathComponent } else { path = filename } NSLog("[\(path):\(line):\(column)] \(function) -- %@", message()) NSLog("An error occurred: %@", error) }
mit
yhyuan/WeatherMap
WeatherAroundUs/WeatherAroundUs/UIViewExtension.swift
9
1542
// // UIViewExtension.swift // PaperPlane // // Created by Kedan Li on 15/2/27. // Copyright (c) 2015年 Yu Wang. All rights reserved. // import QuartzCore import UIKit extension UIView { func rotate360Degrees(duration: CFTimeInterval = 1.0, completionDelegate: AnyObject? = nil) { let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotateAnimation.fromValue = 0.0 rotateAnimation.toValue = CGFloat(M_PI * 2.0) rotateAnimation.duration = duration if let delegate: AnyObject = completionDelegate { rotateAnimation.delegate = delegate } self.layer.addAnimation(rotateAnimation, forKey: nil) } func getTheImageOfTheView()->UIImage{ UIGraphicsBeginImageContext(self.bounds.size) self.layer.renderInContext(UIGraphicsGetCurrentContext()) var outputImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return outputImage } func roundCorner(corners: UIRectCorner, radius: CGFloat) { let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSizeMake(radius, radius)) var mask = CAShapeLayer() mask.frame = self.bounds; mask.path = maskPath.CGPath; layer.mask = mask; } func roundCircle(){ let maskPath = UIBezierPath(ovalInRect:self.bounds) let mask = CAShapeLayer() mask.path = maskPath.CGPath layer.mask = mask } }
apache-2.0
archembald/avajo-ios
avajo-ios/ProfileViewController.swift
1
1636
// // ProfileViewController.swift // avajo-ios // // Created by Alejandro Alvarez Martinez on 05/10/2015. // Copyright (c) 2015 Archembald. All rights reserved. // import UIKit class ProfileViewController: UIViewController { @IBOutlet var imgProfilePicture: UIImageView! @IBOutlet var labelUsername: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.imgProfilePicture.layer.masksToBounds = true self.imgProfilePicture.layer.cornerRadius = self.imgProfilePicture.frame.height/2 // Get info from FB let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil) graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in if ((error) != nil){ // Process error println("Error: \(error)") } else { self.labelUsername.text = result.valueForKey("name") as? String // Set pic let fbid = result.valueForKey("id") as? String let url = NSURL(string: "https://graph.facebook.com/"+fbid!+"/picture?type=large") let data = NSData(contentsOfURL: url!) self.imgProfilePicture.image = UIImage(data: data!); } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
agpl-3.0
dadederk/WeatherTV
Weather/Weather/Controllers/Weather/WeatherParserProtocol.swift
1
285
// // WeatherServiceParserProtocol.swift // Weather // // Created by Daniel Devesa Derksen-Staats on 20/02/2016. // Copyright © 2016 Desfici. All rights reserved. // import Foundation protocol WeatherParserProtocol { static func parseWeather(json: AnyObject) -> Weather? }
apache-2.0
wikimedia/wikipedia-ios
Wikipedia/Code/InsertMediaImageInfoView.swift
3
3115
import UIKit final class InsertMediaImageInfoView: UIView { @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var descriptionLabel: UILabel! @IBOutlet private weak var licenseLabel: UILabel! @IBOutlet private weak var licenseView: LicenseView! @IBOutlet private weak var moreInformationButton: UIButton! var moreInformationAction: ((URL) -> Void)? private var keepBackgroundClear = false private var moreInformationURL: URL? { didSet { moreInformationButton.isHidden = moreInformationURL == nil } } func configure(with searchResult: InsertMediaSearchResult, showImageDescription: Bool = true, showLicenseName: Bool = true, showMoreInformationButton: Bool = true, keepBackgroundClear: Bool = false, theme: Theme) { titleLabel.text = searchResult.displayTitle moreInformationURL = searchResult.imageInfo?.filePageURL if showImageDescription, let imageDescription = searchResult.imageInfo?.imageDescription { descriptionLabel.numberOfLines = 5 descriptionLabel.text = imageDescription } else { descriptionLabel.isHidden = true } moreInformationButton.isHidden = !showMoreInformationButton licenseView.licenseCodes = searchResult.imageInfo?.license?.code?.split(separator: "-").compactMap { String($0) } ?? [] licenseView.isHidden = licenseView.licenseCodes.isEmpty if showLicenseName { licenseLabel.text = searchResult.imageInfo?.license?.shortDescription } else { licenseLabel.isHidden = true } updateFonts() setNeedsLayout() self.keepBackgroundClear = keepBackgroundClear apply(theme: theme) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateFonts() } private func updateFonts() { titleLabel.font = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection) descriptionLabel.font = UIFont.wmf_font(.footnote, compatibleWithTraitCollection: traitCollection) licenseLabel.font = UIFont.wmf_font(.semiboldCaption2, compatibleWithTraitCollection: traitCollection) } @IBAction private func showMoreInformation(_ sender: Any) { guard let url = moreInformationURL else { assertionFailure("moreInformationURL should be set by now") return } moreInformationAction?(url) } } extension InsertMediaImageInfoView: Themeable { func apply(theme: Theme) { backgroundColor = keepBackgroundClear ? .clear : theme.colors.paperBackground titleLabel.textColor = theme.colors.primaryText descriptionLabel.textColor = theme.colors.primaryText licenseLabel.textColor = theme.colors.primaryText moreInformationButton.tintColor = theme.colors.link moreInformationButton.backgroundColor = backgroundColor licenseView.tintColor = theme.colors.primaryText } }
mit
P0ed/FireTek
Source/Scenes/Space/HUD/HUDWeaponNode.swift
1
1407
import SpriteKit final class WeaponNode: SKNode { static let cooldownSize = CGSize(width: 32, height: 8) let cooldownNode: CooldownNode let roundsLabel: SKLabelNode override init() { cooldownNode = CooldownNode() roundsLabel = SKLabelNode() roundsLabel.horizontalAlignmentMode = .right roundsLabel.verticalAlignmentMode = .center roundsLabel.fontSize = 6 roundsLabel.fontName = "Menlo" super.init() [cooldownNode, roundsLabel].forEach(addChild) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func layout(size: CGSize) { cooldownNode.position = CGPoint( x: size.width - WeaponNode.cooldownSize.width, y: (size.height - WeaponNode.cooldownSize.height) / 2 ) roundsLabel.position = CGPoint( x: size.width - WeaponNode.cooldownSize.width - 2, y: size.height / 2 ) } } final class CooldownNode: SKNode { let background: SKSpriteNode let progress: SKSpriteNode override init() { background = SKSpriteNode(color: SKColor(white: 0.5, alpha: 0.5), size: WeaponNode.cooldownSize) progress = SKSpriteNode(color: SKColor(white: 0.9, alpha: 0.9), size: WeaponNode.cooldownSize) background.anchorPoint = .zero progress.anchorPoint = .zero super.init() [background, progress].forEach(addChild) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
YevhenHerasymenko/SwiftGroup1
Operations/Operations/MyResultOperation.swift
1
307
// // MyResultOperation.swift // Operations // // Created by Yevhen Herasymenko on 19/07/2016. // Copyright © 2016 Yevhen Herasymenko. All rights reserved. // import UIKit class MyResultOperation: NSOperation { var result: Int? override func main() { print(result) } }
apache-2.0
IvanVorobei/Sparrow
sparrow/modules/request-permissions/managers/presenters/universal/controls/SPRequestPermissionTwiceControl.swift
1
8016
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei (hello@ivanvorobei.by) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class SPRequestPermissionTwiceControl: UIButton, SPRequestPermissionTwiceControlInterface { var permission: SPRequestPermissionType var iconView: SPRequestPermissionIconView! var normalColor: UIColor var selectedColor: UIColor init(permissionType: SPRequestPermissionType, title: String, normalIconImage: UIImage, selectedIconImage: UIImage, normalColor: UIColor, selectedColor: UIColor) { self.permission = permissionType let renderingNormalIconImage = normalIconImage.withRenderingMode(.alwaysTemplate) let renderingSelectedIconImage = selectedIconImage.withRenderingMode(.alwaysTemplate) self.iconView = SPRequestPermissionIconView(iconImage: renderingNormalIconImage, selectedIconImage: renderingSelectedIconImage) self.normalColor = normalColor self.selectedColor = selectedColor super.init(frame: CGRect.zero) self.setTitle(title, for: UIControlState.normal) self.commonInit() //self.iconView.backgroundColor = UIColor.red } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { self.layer.borderWidth = 1 self.addSubview(self.iconView) self.titleLabel?.font = UIFont.init(name: SPRequestPermissionData.fonts.base() + "-Medium", size: 14) if UIScreen.main.bounds.width < 335 { self.titleLabel?.font = UIFont.init(name: SPRequestPermissionData.fonts.base() + "-Medium", size: 12) } self.titleLabel?.minimumScaleFactor = 0.5 self.titleLabel?.adjustsFontSizeToFitWidth = true self.setNormalState(animated: false) } func setNormalState(animated: Bool) { self.layer.borderColor = self.selectedColor.cgColor self.backgroundColor = self.normalColor self.setTitleColor(self.selectedColor, for: UIControlState.normal) self.iconView.setColor(self.selectedColor) self.iconView.setIconImageView(self.iconView.iconImage!) self.setTitleColor(self.selectedColor.withAlphaComponent(0.62), for: UIControlState.highlighted) } func setSelectedState(animated: Bool) { self.layer.borderColor = self.normalColor.cgColor if animated{ UIView.animate(withDuration: 0.4, animations: { self.backgroundColor = self.selectedColor }) } else { self.backgroundColor = self.selectedColor } var colorForTitle = self.normalColor if self.normalColor == UIColor.clear { colorForTitle = UIColor.white } self.setTitleColor(colorForTitle, for: UIControlState.normal) self.setTitleColor(colorForTitle.withAlphaComponent(0.62), for: UIControlState.highlighted) self.iconView.setSelectedState(with: self.normalColor) } internal func addAction(_ target: Any?, action: Selector) { self.addTarget(target, action: action, for: UIControlEvents.touchUpInside) } internal func addAsSubviewTo(_ view: UIView) { view.addSubview(self) } override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = self.frame.height / 2 let sideSize: CGFloat = self.frame.height * 0.45 let xTranslationIconView: CGFloat = self.frame.width * 0.075 iconView.frame = CGRect.init( x: xTranslationIconView, y: (self.frame.height - sideSize) / 2, width: sideSize, height: sideSize ) } } class SPRequestPermissionIconView: UIView { var imageView: UIImageView? var iconImage: UIImage? var selectedIconImage: UIImage? init(iconImage: UIImage, selectedIconImage: UIImage) { super.init(frame: CGRect.zero) self.imageView = UIImageView() self.imageView?.contentMode = .scaleAspectFit self.addSubview(imageView!) self.iconImage = iconImage self.selectedIconImage = selectedIconImage self.setIconImageView(self.iconImage!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setSelectedState(with color: UIColor = .white) { var settingColor = color if settingColor == UIColor.clear { settingColor = UIColor.white } self.setColor(settingColor) self.imageView?.layer.shadowRadius = 0 self.imageView?.layer.shadowOffset = CGSize.init(width: 0, height: 1) let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation") rotationAnimation.fromValue = 0.0 rotationAnimation.toValue = Double.pi * 2 rotationAnimation.duration = 0.18 rotationAnimation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut) self.imageView?.layer.shouldRasterize = true self.imageView?.layer.rasterizationScale = UIScreen.main.scale self.imageView?.layer.add(rotationAnimation, forKey: nil) var blurView = UIView() if #available(iOS 9, *) { blurView = SPBlurView() } blurView.backgroundColor = UIColor.clear self.addSubview(blurView) blurView.frame = CGRect.init(x: 0, y: 0, width: self.frame.height, height: self.frame.height) blurView.center = (self.imageView?.center)! SPAnimation.animate(0.1, animations: { if #available(iOS 9, *) { if let view = blurView as? SPBlurView { view.setBlurRadius(1.2) } } }, options: UIViewAnimationOptions.curveEaseIn, withComplection: { SPAnimation.animate(0.1, animations: { if #available(iOS 9, *) { if let view = blurView as? SPBlurView { view.setBlurRadius(0) } } }, options: UIViewAnimationOptions.curveEaseOut, withComplection: { blurView.removeFromSuperview() }) }) delay(0.05, closure: { self.setIconImageView(self.selectedIconImage!) }) } func setColor(_ color: UIColor) { UIView.transition(with: self.imageView!, duration: 0.2, options: UIViewAnimationOptions.beginFromCurrentState, animations: { self.imageView?.tintColor = color }, completion: nil) } func setIconImageView(_ iconImageView: UIImage) { self.imageView?.image = iconImageView } override func layoutSubviews() { super.layoutSubviews() self.imageView?.frame = self.bounds } }
mit
peferron/algo
EPI/Hash Tables/Find the smallest subarray covering all values/swift/test.swift
1
1028
import Darwin let tests: [(article: [String], search: Set<String>, digest: Range<Int>?)] = [ ( article: [], search: ["abc"], digest: nil ), ( article: ["abc"], search: ["def"], digest: nil ), ( article: ["abc"], search: ["abc"], digest: 0..<1 ), ( article: ["abc", "def", "ghi", "jkl", "mno"], search: ["abc"], digest: 0..<1 ), ( article: ["abc", "def", "ghi", "jkl", "mno"], search: ["jkl", "def"], digest: 1..<4 ), ( article: ["abc", "def", "ghi", "jkl", "mno", "def", "jkl"], search: ["jkl", "def"], digest: 5..<7 ), ] for test in tests { let actual = digest(article: test.article, search: test.search) guard actual == test.digest else { print("For test article \(test.article) and search \(test.search), " + "expected range of digest to be \(test.digest!), but was \(actual!)") exit(1) } }
mit
hyperoslo/CollectionAnimations
Demo/Demo/ViewController.swift
1
3933
import UIKit class ViewController: UIViewController { var data1 = ["First 1", "First 2"] var data2 = ["Second 1", "Second 2"] var items = [String]() lazy var collectionView: UICollectionView = { [unowned self] in var frame = self.view.bounds frame.origin.y += 20 var collectionView = UICollectionView(frame: frame, collectionViewLayout: self.flowLayout) collectionView.delegate = self collectionView.dataSource = self collectionView.bounces = true collectionView.alwaysBounceVertical = true collectionView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth collectionView.backgroundColor = .lightTextColor() collectionView.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CellIdentifier") return collectionView }() lazy var flowLayout: CollectionViewFlowLayout = { var layout = CollectionViewFlowLayout() layout.sectionInset = UIEdgeInsetsMake(2.0, 2.0, 2.0, 2.0) return layout }() lazy var rightButton: UIBarButtonItem = { [unowned self] in let button = UIBarButtonItem( title: "Next", style: .Plain, target: self, action: "next") return button }() lazy var leftButton: UIBarButtonItem = { [unowned self] in let button = UIBarButtonItem( title: "Prev", style: .Plain, target: self, action: "prev") return button }() override func viewDidLoad() { super.viewDidLoad() title = "Items" navigationItem.leftBarButtonItem = self.leftButton navigationItem.leftBarButtonItem?.enabled = false navigationItem.rightBarButtonItem = self.rightButton navigationController?.hidesBarsWhenVerticallyCompact = true items = data1 view.addSubview(self.collectionView) } func prev() { items = data1 flowLayout.animator = FlyAnimator(appearingFrom: .Top, disappearingTo: .Back) reloadData(completion: { [unowned self] in self.navigationItem.leftBarButtonItem?.enabled = false self.navigationItem.rightBarButtonItem?.enabled = true }) } func next() { items = data2 flowLayout.animator = FlyAnimator(appearingFrom: .Back, disappearingTo: .Top) reloadData(completion: { [unowned self] in self.navigationItem.leftBarButtonItem?.enabled = true self.navigationItem.rightBarButtonItem?.enabled = false }) } private func reloadData(completion: (() -> Void)? = nil) { let indexPaths = [ NSIndexPath(forItem: 0, inSection: 0), NSIndexPath(forItem: 1, inSection: 0)] UIView.animateWithDuration(0.8, animations: { _ in self.collectionView.performBatchUpdates({ _ in self.collectionView.reloadItemsAtIndexPaths(indexPaths) }, completion: nil) }, completion: { _ in completion?() }) } } extension ViewController : UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return self.items.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellIdentifier", forIndexPath: indexPath) as! CollectionViewCell cell.setText(self.items[indexPath.row]) cell.layer.borderWidth = 0.5 cell.layer.borderColor = UIColor.lightGrayColor().CGColor cell.layer.cornerRadius = 4 cell.backgroundColor = UIColor.whiteColor() return cell } } extension ViewController : UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let width:CGFloat = self.view.bounds.size.width * 0.98 let height:CGFloat = 150.0 return CGSizeMake(width, height) } }
mit
daisysomus/SideMenuAnimation
SideMenuAnimation/ViewController.swift
1
641
// // ViewController.swift // SideMenuAnimation // // Created by liaojinhua on 2017/2/9. // Copyright © 2017年 Daisy. All rights reserved. // import UIKit class ViewController: UIViewController { weak var rootVC:RootViewController? 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. } @IBAction func menuAction(_ sender: Any) { self.rootVC?.openMenu() } }
apache-2.0
machelix/MVCarouselCollectionView
MVCarouselCollectionView/MVCarouselCellScrollView.swift
1
4098
// MVCarouselCellScrollView.swift // // Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit // 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.ScaleAspectFit } func resetZoom() { if self.imageView.image == nil { return } var imageSize = self.imageView.image!.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.Center if cellSize.width > imageSize.width && cellSize.height > imageSize.height { self.imageView.contentMode = UIViewContentMode.ScaleAspectFit } var cellAspectRatio : CGFloat = self.cellSize.width / self.cellSize.height var imageAspectRatio : CGFloat = imageSize.width / imageSize.height var cellAspectRatioWiderThanImage = cellAspectRatio > imageAspectRatio // Calculate Zoom // If image is taller, then make edge to edge height, else make edge to edge width var zoom = cellAspectRatioWiderThanImage ? cellSize.height / imageSize.height : cellSize.width / imageSize.width self.maximumZoomScale = zoom * CGFloat(zoomToUse()) self.minimumZoomScale = zoom self.zoomScale = zoom // Update content inset var adjustedContentWidth = cellSize.height * imageAspectRatio var horzContentInset = cellAspectRatioWiderThanImage ? 0.5 * (cellSize.width - adjustedContentWidth) : 0.0 var adjustedContentHeight = cellSize.width / imageAspectRatio var 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
64characters/Telephone
TelephoneTests/CallHistoryViewSpy.swift
1
920
// // CallHistoryViewSpy.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone 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. // // Telephone 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. // import UseCases final class CallHistoryViewSpy { private(set) var invokedRecords: [PresentationCallHistoryRecord] = [] } extension CallHistoryViewSpy: CallHistoryView { func show(_ records: [PresentationCallHistoryRecord]) { invokedRecords = records } }
gpl-3.0
remlostime/OOD-Swift
factory/Factory.playground/Contents.swift
1
1497
//: Playground - noun: a place where people can play import Foundation protocol Currency { func symbol() -> String func code() -> String } class US: Currency { func symbol() -> String { return "$" } func code() -> String { return "USD" } } class Euro: Currency { func symbol() -> String { return "€" } func code() -> String { return "EUR" } } class China: Currency { func symbol() -> String { return "¥" } func code() -> String { return "CNY" } } class ErrorCurrency: Currency { func symbol() -> String { return "Error symbol" } func code() -> String { return "Error code" } } enum Country { case USA case China case Euro } class CurrencyFactory { static func getCurrency(_ country: Country) -> Currency { switch country { case .USA: return US() case .China: return China() case .Euro: return Euro() } } } let currency = CurrencyFactory.getCurrency(.China) currency.code() currency.symbol() // Reflection - Get class dynamiclly func classFromString(_ className: String) -> Currency { guard let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else { return ErrorCurrency() } guard let cls = NSClassFromString("\(namespace).\(className)") as? Currency else { return ErrorCurrency() } return cls } let className = "US" let currencyClass = classFromString(className) currencyClass.code() currencyClass.symbol()
gpl-3.0
Venkat1128/ObjCProblemSet
Examples/Lesson 6/House_Swift_main/House_Swift_main/House.swift
1
494
// // House.swift // House_main_Swift // // Created by Gabrielle Miller-Messner on 5/9/16. // Copyright © 2016 Gabrielle Miller-Messner. All rights reserved. // import Foundation class House { var address = "555 Park Ave" let numberOfBedrooms = 3 var hasHotTub = false var hotTub: HotTub? init(address: String) { self.address = address self.hasHotTub = false } init() { self.hasHotTub = true self.hotTub = HotTub() } }
mit
kay-kim/stitch-examples
todo/ios/Pods/FacebookLogin/Sources/Login/LoginButtonDelegate.swift
19
1647
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 /** A delegate for `LoginButton`. */ public protocol LoginButtonDelegate { /** Called when the button was used to login and the process finished. - parameter loginButton: Button that was used to login. - parameter result: The result of the login. */ func loginButtonDidCompleteLogin(_ loginButton: LoginButton, result: LoginResult) /** Called when the button was used to logout. - parameter loginButton: Button that was used to logout. */ func loginButtonDidLogOut(_ loginButton: LoginButton) }
apache-2.0
kotdark/Summflower
Summflower/Summflower/SummflowerSegment.swift
2
3756
// // FloraSegment.swift // Flora // // Created by Sameh Mabrouk on 12/24/14. // Copyright (c) 2014 SMApps. All rights reserved. // /* //SummflowerSegment act as a UITableviewCell for this control. It follows the same configuration as a tableview delegate */ import UIKit class SummflowerSegment: UIButton { var backgroundImage:UIImageView = UIImageView() convenience override init() { self.init(frame: CGRectMake(0, 0, SegmentWidth, SegmentHeight)) } func initWithImage(image:UIImage) -> AnyObject{ self.alpha = SegmentAlpha self.backgroundColor = UIColor.clearColor() self.autoresizingMask = UIViewAutoresizing.FlexibleWidth | .FlexibleHeight self.backgroundImage.image = image self.backgroundImage.frame = self.bounds self.addSubview(self.backgroundImage) //setup shadows self.layer.shadowColor = SegmentShadowColor.CGColor self.layer.shadowOffset = SegmentShadowOffset self.layer.shadowOpacity = SegmentShadowOpacity self.layer.shadowRadius = SegmentShadowRadis self.layer.shouldRasterize = true self.layer.rasterizationScale = SegmentRasterizationScale return self } func rotationWithDuration(duration:NSTimeInterval, angle:Float, completion: ((Bool) -> Void)?){ // Repeat a quarter rotation as many times as needed to complete the full rotation var sign:Float = angle > 0 ? 1 : -1 let numberRepeats:Float = floorf(fabsf(angle) / Float( M_PI_2)) let angelabs:CGFloat = CGFloat(fabs(angle)) let quarterDuration:Float = Float(duration * M_PI_2) / Float(angelabs) let lastRotation = angle - sign * numberRepeats * Float(M_PI_2) let lastDuration:Float = Float( duration) - quarterDuration * numberRepeats self.lastRotationWithDuration(NSTimeInterval(lastDuration), rotation: CGFloat( lastRotation)) self.quarterSpinningBlock(NSTimeInterval(quarterDuration), duration: NSInteger(lastDuration), rotation: NSInteger(lastRotation), numberRepeats: NSInteger(numberRepeats)) return completion!(true) } func quarterSpinningBlock(quarterDuration:NSTimeInterval, duration:NSInteger, rotation:NSInteger, numberRepeats:NSInteger){ if numberRepeats>0 { UIView.animateWithDuration(quarterDuration, delay: 0.0, options: UIViewAnimationOptions.BeginFromCurrentState | UIViewAnimationOptions.CurveLinear, animations: { () -> Void in self.transform = CGAffineTransformRotate(self.transform, CGFloat(M_PI_2)) }) { (Bool) -> Void in if numberRepeats > 0 { self.quarterSpinningBlock(quarterDuration, duration: duration, rotation: rotation, numberRepeats: numberRepeats - 1 ) } else{ self.lastRotationWithDuration(NSTimeInterval(duration), rotation: CGFloat(rotation)) return } } } else{ self.lastRotationWithDuration(NSTimeInterval(duration), rotation: CGFloat(rotation)) } } func lastRotationWithDuration(duration:NSTimeInterval, rotation:CGFloat){ UIView.animateWithDuration(duration, delay: 0.0, options: .BeginFromCurrentState | .CurveEaseOut, animations: { () -> Void in self.transform = CGAffineTransformRotate(self.transform, rotation); }, completion: nil) } }
mit
kay-kim/stitch-examples
todo/ios/Pods/ExtendedJson/ExtendedJson/ExtendedJson/Source/ExtendedJson/BsonArray+ExtendedJson.swift
1
1190
// // BsonArray+ExtendedJson.swift // ExtendedJson // // Created by Jason Flax on 10/4/17. // Copyright © 2017 MongoDB. All rights reserved. // import Foundation extension BSONArray: ExtendedJsonRepresentable { public static func fromExtendedJson(xjson: Any) throws -> ExtendedJsonRepresentable { guard let array = xjson as? [Any], let bsonArray = try? BSONArray(array: array) else { throw BsonError.parseValueFailure(value: xjson, attemptedType: BSONArray.self) } return bsonArray } public var toExtendedJson: Any { return map { $0.toExtendedJson } } public func isEqual(toOther other: ExtendedJsonRepresentable) -> Bool { if let other = other as? BSONArray, other.count == self.count { for i in 0..<other.count { let myExtendedJsonRepresentable = self[i] let otherExtendedJsonRepresentable = other[i] if !myExtendedJsonRepresentable.isEqual(toOther: otherExtendedJsonRepresentable) { return false } } } else { return false } return true } }
apache-2.0
ivasic/Fargo
Fargo/Source/Types/Error.swift
1
2129
// // Error.swift // Fargo // // Created by Ivan Vasic on 01/11/15. // Copyright © 2015 Ivan Vasic. All rights reserved. // import Foundation extension JSON { public enum Error : ErrorType, CustomDebugStringConvertible { case MissingKey(key: JSON.KeyPath.Key, keyPath: JSON.KeyPath) case TypeMismatch(expectedType: String, actualType: String, keyPath: JSON.KeyPath) public init(typeMismatchForType type: String, json: JSON) { self = .TypeMismatch(expectedType: type, actualType: json.objectType(), keyPath: json.keyPath) } public init(missingKey key: JSON.KeyPath.Key, json: JSON) { self = .MissingKey(key: key, keyPath: json.keyPath) } public var debugDescription: String { get { switch self { case .MissingKey(let key, let keyPath): return "MissingKey `\(key)` in keyPath `\(keyPath)`" case .TypeMismatch(let expected, let actual, let keyPath): return "TypeMismatch, expected `\(expected)` got `\(actual)` for keyPath `\(keyPath)`" } } } public func descriptionForJSON(json: JSON) -> String { switch self { case .MissingKey(let key, let keyPath): var string = "MissingKey `\(key)`" if let json = try? json.jsonForKeyPath(keyPath) { string = "\(string) in JSON : `\(json.object)`" } string = "\(string). Full keyPath `\(keyPath)`" return string case .TypeMismatch(let expected, let actual, let keyPath): var string = "TypeMismatch, expected `\(expected)`" if let json = try? json.jsonForKeyPath(keyPath) { string = "\(string) got `(\(json))`" } else { string = "\(string) got `\(actual)`" } string = "\(string). Full keyPath `\(keyPath)`" return string } } } }
mit
rodrigoruiz/SwiftUtilities
SwiftUtilities/Cocoa/UITableView+Extension.swift
1
471
// // UITableView+Extension.swift // SwiftUtilities // // Created by Rodrigo Ruiz on 4/25/17. // Copyright © 2017 Rodrigo Ruiz. All rights reserved. // extension UITableView { public func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withIdentifier: String(describing: T.self), for: indexPath) as? T else { fatalError() } return cell } }
mit
forLoveGitHub/Demo
Demo/Demo/SecondViewController.swift
1
863
// // SecondViewController.swift // Demo // // Created by Marlon on 2016/6/30. // Copyright © 2016年 test. All rights reserved. // import UIKit class SecondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 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 prepare(for segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
xmartlabs/Opera
Example/Example/Controllers/RepositoryCommitsController.swift
1
3513
// RepositoryCommitsController.swift // Example-iOS ( https://github.com/xmartlabs/Example-iOS ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import OperaSwift import RxSwift import RxCocoa class RepositoryCommitsController: RepositoryBaseController { @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! let refreshControl = UIRefreshControl() var disposeBag = DisposeBag() lazy var viewModel: PaginationViewModel<PaginationRequest<Commit>> = { [unowned self] in return PaginationViewModel(paginationRequest: PaginationRequest(route: GithubAPI.Repository.GetCommits(owner: self.owner, repo: self.name))) }() override func viewDidLoad() { super.viewDidLoad() tableView.keyboardDismissMode = .onDrag tableView.addSubview(self.refreshControl) emptyStateLabel.text = "No commits found" let refreshControl = self.refreshControl rx.sentMessage(#selector(RepositoryForksController.viewWillAppear(_:))) .map { _ in false } .bind(to: viewModel.refreshTrigger) .disposed(by: disposeBag) tableView.rx.reachedBottom .bind(to: viewModel.loadNextPageTrigger) .disposed(by: disposeBag) viewModel.loading .drive(activityIndicatorView.rx.isAnimating) .disposed(by: disposeBag) Driver.combineLatest(viewModel.elements.asDriver(), viewModel.firstPageLoading) { elements, loading in return loading ? [] : elements } .asDriver() .drive(tableView.rx.items(cellIdentifier:"Cell")) { _, commit, cell in cell.textLabel?.text = commit.author cell.detailTextLabel?.text = commit.date.shortRepresentation() } .disposed(by: disposeBag) refreshControl.rx.valueChanged .filter { refreshControl.isRefreshing } .map { true } .bind(to: viewModel.refreshTrigger) .disposed(by: disposeBag) viewModel.loading .filter { !$0 && refreshControl.isRefreshing } .drive(onNext: { _ in refreshControl.endRefreshing() }) .disposed(by: disposeBag) viewModel.emptyState .drive(onNext: { [weak self] emptyState in self?.emptyStateLabel.isHidden = !emptyState }) .disposed(by: disposeBag) } }
mit
phatblat/realm-cocoa
plugin/Templates/file_templates/Realm Model Object.xctemplate/Swift/___FILEBASENAME___.swift
11
355
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // import Foundation import RealmSwift class ___FILEBASENAMEASIDENTIFIER___: Object { // Specify properties to ignore (Realm won't persist these) // override static func ignoredProperties() -> [String] { // return [] // } }
apache-2.0
adamhartford/PopDatePicker
PopDatePickerTests/PopDatePickerTests.swift
1
922
// // PopDatePickerTests.swift // PopDatePickerTests // // Created by Adam Hartford on 4/22/15. // Copyright (c) 2015 Adam Hartford. All rights reserved. // import Cocoa import XCTest class PopDatePickerTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
DouKing/WYListView
WYListViewController/ListViewController/WYListView.swift
1
10947
// // WYListViewController.swift // WYListViewController // // Created by iosci on 2016/10/20. // Copyright © 2016年 secoo. All rights reserved. // import UIKit @objc public protocol WYListViewDataSource { func numberOfSections(in listView: WYListView) -> Int func listView(_ listView: WYListView, numberOfRowsInSection section: Int) -> Int func listView(_ listView: WYListView, titleForSection section: Int) -> String? func listView(_ listView: WYListView, titleForRowAtIndexPath indexPath: IndexPath) -> String? @objc optional func listView(_ listView: WYListView, selectRowInSection section: Int) -> NSNumber? //@objc不支持Int? @objc optional func sectionHeight(in listView: WYListView) -> CGFloat @objc optional func listView(_ listView: WYListView, rowHeightAtIndexPath indexPath: IndexPath) -> CGFloat } @objc public protocol WYListViewDelegate { @objc optional func listView(_ listView: WYListView, didSelectRowAtIndexPath indexPath: IndexPath) } open class WYListView: UIViewController { fileprivate let tableViewBaseTag: Int = 2000 fileprivate var currentSection: Int? fileprivate var selectedIndexPaths: [Int : Int] = [:] fileprivate var selectedOffsetYs: [Int : CGFloat] = [:] public var dataSource: WYListViewDataSource? public var delegate: WYListViewDelegate? fileprivate weak var floatView: UIView? @IBOutlet fileprivate weak var segmentView: UICollectionView! { didSet { segmentView.dataSource = self segmentView.delegate = self let nib = UINib(nibName: "WYSegmentCell", bundle: nil) segmentView.register(nib, forCellWithReuseIdentifier: WYSegmentCell.cellId) let floatView = UIView(frame: .zero) floatView.backgroundColor = .red floatView.alpha = 0 self.floatView = floatView segmentView.addSubview(floatView) } } @IBOutlet fileprivate weak var contentView: UICollectionView! { didSet { contentView.dataSource = self contentView.delegate = self let nib = UINib(nibName: "WYContentCell", bundle: nil) contentView.register(nib, forCellWithReuseIdentifier: WYContentCell.cellId) } } deinit { self.endObserveDeviceOrientation() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.observeDeviceOrientation() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.observeDeviceOrientation() } open override func viewDidLoad() { super.viewDidLoad() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + TimeInterval(0.15)) { [unowned self] in self.scrollToLastSection(animated: false) } } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let flowLayout = self.contentView.collectionViewLayout as! UICollectionViewFlowLayout flowLayout.itemSize = self.contentView.bounds.size } open func reloadData(selectRowsAtIndexPaths indexPaths: [IndexPath] = []) { self.currentSection = nil self.selectedIndexPaths = [:] self.selectedOffsetYs = [:] for indexPath in indexPaths { self.select(section: indexPath.section, row: indexPath.row) } self.segmentView.reloadData() self.contentView.reloadData() } private func observeDeviceOrientation() { UIDevice.current.beginGeneratingDeviceOrientationNotifications() NotificationCenter.default.addObserver(self, selector: #selector(handleDeviceOrientationNotification(_:)), name: Notification.Name.UIDeviceOrientationDidChange, object: nil) } private func endObserveDeviceOrientation() { NotificationCenter.default.removeObserver(self, name: Notification.Name.UIDeviceOrientationDidChange, object: nil) UIDevice.current.endGeneratingDeviceOrientationNotifications() } private func changeCollectionViewLayout() { let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = .horizontal flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 flowLayout.itemSize = self.contentView.bounds.size self.contentView.setCollectionViewLayout(flowLayout, animated: true) if let section = self.currentSection { self.scroll(to: section, animated: false) } } fileprivate func select(section: Int, row: Int?) { self.selectedIndexPaths[section] = row } fileprivate func select(section: Int, offsetY: CGFloat?) { self.selectedOffsetYs[section] = offsetY } @objc private func handleDeviceOrientationNotification(_ note: Notification) { self.changeCollectionViewLayout() } } // MARK: - UICollectionViewDelegate, UICollectionViewDataSource - extension WYListView: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let dataSource = self.dataSource else { return 0 } return dataSource.numberOfSections(in: self) } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == self.segmentView { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WYSegmentCell.cellId, for: indexPath) as! WYSegmentCell guard let dataSource = self.dataSource else { return cell } let title = dataSource.listView(self, titleForSection: indexPath.item) cell.setup(withTitle: title) return cell } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WYContentCell.cellId, for: indexPath) as! WYContentCell cell.dataSource = self cell.delegate = self cell.section = indexPath.item cell.reload(animated: false, selectRow: self.selectedIndexPaths[indexPath.item], offsetY: self.selectedOffsetYs[indexPath.item]) return cell } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if collectionView == self.contentView { return self.contentView.bounds.size } let title = self.dataSource?.listView(self, titleForSection: indexPath.item) return CGSize(width: WYSegmentCell.width(withTitle: title), height: collectionView.bounds.size.height) } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.scroll(to: indexPath.item, animated: true) } } extension WYListView: WYContentCellDataSource, WYContentCellDelegate { func numberOfRows(in contentCell: WYContentCell) -> Int { guard let dataSource = self.dataSource else { return 0 } return dataSource.listView(self, numberOfRowsInSection: contentCell.section) } func contentCell(_ cell: WYContentCell, titleForRow row: Int) -> String? { guard let dataSource = self.dataSource else { return nil } return dataSource.listView(self, titleForRowAtIndexPath: IndexPath(row: row, section: cell.section)) } func contentCell(_ cell: WYContentCell, didSelectRow row: Int) { self.select(section: cell.section, row: row) self.delegate?.listView?(self, didSelectRowAtIndexPath: IndexPath(row: row, section: cell.section)) } func contentCell(_ cell: WYContentCell, didScrollTo offsetY: CGFloat) { self.select(section: cell.section, offsetY: offsetY) } } // MARK: - Scroll - extension WYListView { open func scrollToLastSection(animated: Bool, after timeInterval: TimeInterval = 0, completion: (() -> Swift.Void)? = nil) { guard let dataSource = self.dataSource else { return } let number = dataSource.numberOfSections(in: self) if number < 1 { return } self.scroll(to: number - 1, animated: animated, after: timeInterval, completion: completion) } open func scroll(to section: Int, animated: Bool, after timeInterval: TimeInterval = 0, completion: (() -> Swift.Void)? = nil) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + timeInterval) { [unowned self] in guard let dataSource = self.dataSource else { return } let number = dataSource.numberOfSections(in: self) self.currentSection = min(max(section, 0), number - 1) let indexPath = IndexPath(item: self.currentSection!, section: 0) self.segmentView.scrollToItem(at: indexPath, at: .init(rawValue: 0), animated: animated) self.contentView.scrollToItem(at: indexPath, at: .init(rawValue: 0), animated: animated) let layoutAttributes = self.segmentView.collectionViewLayout.initialLayoutAttributesForAppearingItem(at: indexPath) var rect = CGRect.zero if let lab = layoutAttributes { rect = lab.frame } let insert: CGFloat = WYSegmentCell.contentInsert, height: CGFloat = 2 let frame = CGRect(x: rect.origin.x + insert, y: rect.size.height - height, width: rect.size.width - insert * 2, height: height) if animated { UIView.animate(withDuration: 0.15, animations: { [unowned self] in self.floatView?.frame = frame }) { [unowned self] (finished) in self.floatView?.alpha = 1 } } else { self.floatView?.frame = frame self.floatView?.alpha = 1 if completion != nil { completion!() } } } } private func scrollViewDidEndScroll(_ scrollView: UIScrollView) { guard scrollView == self.contentView else { return } let section = scrollView.contentOffset.x / scrollView.bounds.size.width self.scroll(to: Int(section), animated: true) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.scrollViewDidEndScroll(scrollView) } } fileprivate extension WYSegmentCell { static let cellId = "kWYSegmentCellId" } fileprivate extension WYContentCell { static let cellId = "kWYContentCellId" }
mit
RxSwiftCommunity/RxHttpClient
RxHttpClientTests/NSURLSessionTypeTests.swift
1
815
import XCTest @testable import RxHttpClient class NSURLSessionProtocolTests: XCTestCase { var session: URLSessionType = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil) var url: URL = URL(baseUrl: "https://test.com", parameters: ["param": "value"])! override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testCreateDataTaskWithRequest() { let request = URLRequest(url: url) let dataTask = session.dataTaskWithRequest(URLRequest(url: url)) XCTAssertEqual(request.url, dataTask.originalRequest?.url) XCTAssertEqual(request.allHTTPHeaderFields?["header"], dataTask.originalRequest?.allHTTPHeaderFields?["header"]) } }
mit
wishzhouhe/weibo
SinaWeibo/SinaWeibo/Classes/View(视图和控制器)/Discover/WBDiscoverViewController.swift
1
881
// // WBDiscoverViewController.swift // SinaWeibo // // Created by myzj2004 on 2016/11/15. // Copyright © 2016年 myzj2004. All rights reserved. // import UIKit class WBDiscoverViewController: WBBaseViewController { override func viewDidLoad() { super.viewDidLoad() // 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
benjaminsnorris/SharedHelpers
Sources/SwipeTransitionInteractionController.swift
1
5745
/* | _ ____ ____ _ | | |‾| ⚈ |-| ⚈ |‾| | | | | ‾‾‾‾| |‾‾‾‾ | | | ‾ ‾ ‾ */ import UIKit class SwipeTransitionInteractionController: UIPercentDrivenInteractiveTransition { var edge: UIRectEdge var gestureRecognizer: UIPanGestureRecognizer weak var transitionContext: UIViewControllerContextTransitioning? var scrollView: UIScrollView? fileprivate var adjustedInitialLocation = CGPoint.zero fileprivate var initialContentOffset = CGPoint.zero static let velocityThreshold: CGFloat = 50.0 init(edgeForDragging edge: UIRectEdge, gestureRecognizer: UIPanGestureRecognizer, scrollView: UIScrollView? = nil) { self.edge = edge self.gestureRecognizer = gestureRecognizer super.init() self.gestureRecognizer.addTarget(self, action: #selector(gestureRecognizerDidUpdate(_:))) self.scrollView = scrollView if let tableView = scrollView as? UITableView { initialContentOffset = tableView.style == .grouped ? CGPoint(x: 0, y: -44) : .zero } } @available(*, unavailable, message: "Use `init(edgeForDragging:gestureRecognizer:) instead") override init() { fatalError("Use `init(edgeForDragging:gestureRecognizer:) instead") } deinit { gestureRecognizer.removeTarget(self, action: #selector(gestureRecognizerDidUpdate(_:))) } override func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext super.startInteractiveTransition(transitionContext) } func percent(for recognizer: UIPanGestureRecognizer) -> CGFloat { guard let transitionContainerView = transitionContext?.containerView else { return 0 } if let scrollView = scrollView, percentComplete == 0 { switch edge { case .top: if scrollView.contentOffset.y >= initialContentOffset.y { return 0 } case .bottom: if scrollView.contentOffset.y <= initialContentOffset.y { return 0 } case .left: if scrollView.contentOffset.x >= initialContentOffset.x { return 0 } case .right: if scrollView.contentOffset.x <= initialContentOffset.x { return 0 } default: fatalError("edge must be .top, .bottom, .left, or .right. actual=\(edge)") } if adjustedInitialLocation == .zero { adjustedInitialLocation = recognizer.location(in: transitionContainerView) } } scrollView?.contentOffset = initialContentOffset let delta = recognizer.translation(in: transitionContainerView) let width = transitionContainerView.bounds.width let height = transitionContainerView.bounds.height var adjustedPoint = delta if adjustedInitialLocation != .zero { let locationInSourceView = recognizer.location(in: transitionContainerView) adjustedPoint = CGPoint(x: locationInSourceView.x - adjustedInitialLocation.x, y: locationInSourceView.y - adjustedInitialLocation.y) } switch edge { case .top: return adjustedPoint.y > 0 ? adjustedPoint.y / height : 0 case .bottom: return adjustedPoint.y < 0 ? abs(adjustedPoint.y) / height : 0 case .left: return adjustedPoint.x > 0 ? adjustedPoint.x / height : 0 case .right: return adjustedPoint.x < 0 ? abs(adjustedPoint.x) / width : 0 default: fatalError("edge must be .top, .bottom, .left, or .right. actual=\(edge)") } } @objc func gestureRecognizerDidUpdate(_ gestureRecognizer: UIPanGestureRecognizer) { switch gestureRecognizer.state { case .possible, .began: break case .changed: update(percent(for: gestureRecognizer)) case .ended: let velocity = gestureRecognizer.velocity(in: transitionContext?.containerView) var swiped = false switch edge { case .top: swiped = velocity.y > SwipeTransitionInteractionController.velocityThreshold if let scrollView = scrollView, scrollView.contentOffset.y > initialContentOffset.y { swiped = false } case .bottom: swiped = velocity.y < -SwipeTransitionInteractionController.velocityThreshold if let scrollView = scrollView, scrollView.contentOffset.y < initialContentOffset.y { swiped = false } case .left: swiped = velocity.x > SwipeTransitionInteractionController.velocityThreshold if let scrollView = scrollView, scrollView.contentOffset.x > initialContentOffset.x { swiped = false } case .right: swiped = velocity.x < -SwipeTransitionInteractionController.velocityThreshold if let scrollView = scrollView, scrollView.contentOffset.x < initialContentOffset.x { swiped = false } default: break } if swiped || percent(for: gestureRecognizer) >= 0.5 { finish() } else { cancel() } case .cancelled, .failed: cancel() @unknown default: break } } }
mit
ksco/swift-algorithm-club-cn
Bloom Filter/BloomFilter.playground/Contents.swift
1
2168
//: Playground - noun: a place where people can play public class BloomFilter<T> { private var array: [Bool] private var hashFunctions: [T -> Int] public init(size: Int = 1024, hashFunctions: [T -> Int]) { self.array = .init(count: size, repeatedValue: false) self.hashFunctions = hashFunctions } private func computeHashes(value: T) -> [Int] { return hashFunctions.map() { hashFunc in abs(hashFunc(value) % array.count) } } public func insert(element: T) { for hashValue in computeHashes(element) { array[hashValue] = true } } public func insert(values: [T]) { for value in values { insert(value) } } public func query(value: T) -> Bool { let hashValues = computeHashes(value) // Map hashes to indices in the Bloom Filter let results = hashValues.map() { hashValue in array[hashValue] } // All values must be 'true' for the query to return true // This does NOT imply that the value is in the Bloom filter, // only that it may be. If the query returns false, however, // you can be certain that the value was not added. let exists = results.reduce(true, combine: { $0 && $1 }) return exists } public func isEmpty() -> Bool { // As soon as the reduction hits a 'true' value, the && condition will fail. return array.reduce(true) { prev, next in prev && !next } } } /* Two hash functions, adapted from http://www.cse.yorku.ca/~oz/hash.html */ func djb2(x: String) -> Int { var hash = 5381 for char in x.characters { hash = ((hash << 5) &+ hash) &+ char.hashValue } return Int(hash) } func sdbm(x: String) -> Int { var hash = 0 for char in x.characters { hash = char.hashValue &+ (hash << 6) &+ (hash << 16) &- hash } return Int(hash) } /* A simple test */ let bloom = BloomFilter<String>(size: 17, hashFunctions: [djb2, sdbm]) bloom.insert("Hello world!") print(bloom.array) bloom.query("Hello world!") // true bloom.query("Hello WORLD") // false bloom.insert("Bloom Filterz") print(bloom.array) bloom.query("Bloom Filterz") // true bloom.query("Hello WORLD") // true
mit
noehou/myDouYuZB
DYZB/DYZB/Classes/Home/View/RecommendCycleView.swift
1
4217
// // RecommendCycleView.swift // DYZB // // Created by Tommaso on 2016/12/12. // Copyright © 2016年 Tommaso. All rights reserved. // import UIKit private let kCycleCellID = "kCycleCellID" class RecommendCycleView: UIView { //MARK:定义属性 var cycleTimer : Timer? var cycleModels : [CycleModel]?{ didSet { //1、刷新collectionView collectionView.reloadData() //2、设置pageControl个数 pageControl.numberOfPages = cycleModels?.count ?? 0 //3、默认滚动到中间某一个位置 let indexPath = NSIndexPath(item: (cycleModels?.count ?? 0) * 10, section: 0) collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: false) //4、添加定时器 removeCycleTimer() addCycleTimer() } } //MARK:控件属性 @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! //MARK:系统回调函数 override func awakeFromNib() { super.awakeFromNib() //设置该控件不随着父控件的拉伸而拉伸 autoresizingMask = UIViewAutoresizing() //注册cell collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: kCycleCellID) } override func layoutSubviews() { super.layoutSubviews() //设置collectionView的layout let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size // layout.minimumLineSpacing = 0 // layout.minimumInteritemSpacing = 0 // layout.scrollDirection = .horizontal // collectionView.isPagingEnabled = true } } //MARK:-提供一个快速创建view的类方法 extension RecommendCycleView { class func recommendCycleView() -> RecommendCycleView { return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView } } //MARK:-遵守UICollectionView的数据源协议 extension RecommendCycleView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (cycleModels?.count ?? 0) * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionCycleCell cell.cycleModel = cycleModels?[indexPath.item % (cycleModels?.count)!] return cell } } //MARK:-遵守UICollectionView的代理协议 extension RecommendCycleView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { //1、获取滚动的偏移量 let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5 //2、计算pageControl的currentIndex pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeCycleTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { addCycleTimer() } } //MARK:-对定时器的操作方法 extension RecommendCycleView { public func addCycleTimer() { cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true) RunLoop.main.add(cycleTimer!, forMode: .commonModes) } public func removeCycleTimer(){ cycleTimer?.invalidate() cycleTimer = nil } @objc private func scrollToNext() { //1、获取滚动的偏移量 let currentOffsetX = collectionView.contentOffset.x let offsetX = currentOffsetX + collectionView.bounds.width //2、滚动到该位置 collectionView.setContentOffset(CGPoint(x: offsetX,y:0), animated: true) } }
mit
the-grid/Disc
Disc/Models/User.swift
1
1684
import Argo import Ogra import Runes /// A user. public struct User { public let app: UUID? public let avatarUrl: URL? public var emailAddress: String public let id: UUID public var name: String public let scopes: [Scope]? public init( app: UUID? = nil, avatarUrl: URL? = nil, emailAddress: String, id: UUID, name: String, scopes: [Scope]? = nil ) { self.app = app self.avatarUrl = avatarUrl self.emailAddress = emailAddress self.id = id self.name = name self.scopes = scopes } } // Mark: - Decodable extension User: Decodable { public static func decode(_ j: JSON) -> Decoded<User> { return curry(self.init) <^> j <|? "app" <*> j <|? "avatar" <*> j <| "email" <*> j <| "uuid" <*> j <| "name" <*> j <||? "scope" } } // Mark: - Encodable extension User: Encodable { public func encode() -> JSON { return .object([ "app": app.encode(), "avatar": avatarUrl.encode(), "email": emailAddress.encode(), "uuid": id.encode(), "name": name.encode(), "scope": scopes.encode() ]) } } // Mark: - Equatable extension User: Equatable {} public func == (lhs: User, rhs: User) -> Bool { return lhs.app?.uuidString == rhs.app?.uuidString && lhs.avatarUrl?.absoluteString == rhs.avatarUrl?.absoluteString && lhs.emailAddress == rhs.emailAddress && lhs.id == rhs.id && lhs.name == rhs.name && lhs.scopes == rhs.scopes }
mit
bremy11/adar_ece477
MapView/MapViewTests/MapViewTests.swift
1
983
// // MapViewTests.swift // MapViewTests // // Created by Tessie McInerney on 2/7/16. // Copyright © 2016 Tessie McInerney. All rights reserved. // import XCTest @testable import MapView class MapViewTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
gpl-3.0
18775134221/SwiftBase
SwiftTest/SwiftTest/Classes/Main/VC/BaseTabBarVC.swift
2
2733
// // BaseTabBarVC.swift // SwiftTest // // Created by MAC on 2016/12/10. // Copyright © 2016年 MAC. All rights reserved. // import UIKit class BaseTabBarVC: UITabBarController { fileprivate var homeVC: HomeVC? = nil fileprivate var typesVC: TypesVC? = nil fileprivate var shoppingCartVC: ShoppingCartVC? = nil fileprivate var mineVC: MineVC? = nil override func viewDidLoad() { super.viewDidLoad() setupUI() } } extension BaseTabBarVC { fileprivate func setupUI() { setupChildVCs() setupTabBar() } // 设置自定义的TabBar private func setupTabBar() { UITabBar.appearance().tintColor = UIColor.orange let baseTabBar: BaseTabBar = BaseTabBar() baseTabBar.type = .plusDefault // 隐藏系统顶部tabBar的黑线 baseTabBar.shadowImage = UIImage() baseTabBar.backgroundImage = UIImage() baseTabBar.backgroundColor = UIColor(r: 0.62, g: 0.03, b: 0.05) setValue(baseTabBar, forKey: "tabBar") } private func setupChildVCs() { homeVC = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "HomeVC") as? HomeVC addChildVC(homeVC!,"首页","icon_home_normal","icon_home_selected") typesVC = UIStoryboard(name: "Types", bundle: nil).instantiateViewController(withIdentifier: "TypesVC") as? TypesVC addChildVC(typesVC!,"分类","iocn_classification_normal","iocn_classification_selected") shoppingCartVC = UIStoryboard(name: "ShoppingCart", bundle: nil).instantiateViewController(withIdentifier: "ShoppingCartVC") as? ShoppingCartVC addChildVC(shoppingCartVC!,"购物车","icon_shopping-cart_normal","icon_shopping-cart_selected") mineVC = UIStoryboard(name: "Mine", bundle: nil).instantiateViewController(withIdentifier: "MineVC") as? MineVC addChildVC(mineVC!,"我的","icon_personal-center_normal","icon_personal-center_selected") } private func addChildVC(_ vc: UIViewController, _ title: String = "", _ normalImage: String = "",_ selectedImage: String = "") { vc.title = title; vc.tabBarItem.selectedImage = UIImage(named: selectedImage) vc.tabBarItem.image = UIImage(named: normalImage) let baseNaviVC: BaseNavigationVC = BaseNavigationVC(rootViewController: vc) addChildViewController(baseNaviVC) } } extension BaseTabBarVC: UITabBarControllerDelegate { // 选中底部导航按钮回调 override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { } }
apache-2.0
LoopKit/LoopKit
LoopKitUI/UIAlertController.swift
1
2772
// // UIAlertController.swift // LoopKitUI // // Created by Pete Schwamb on 1/22/19. // Copyright © 2019 LoopKit Authors. All rights reserved. // import Foundation extension UIAlertController { /// Convenience method to initialize an alert controller to display an error /// /// - Parameters: /// - error: The error to display /// - title: The title of the alert. If nil, the error description will be used. /// - helpAnchorHandler: An optional closure to be executed when a user taps to open the error's `helpAnchor` /// - url: A URL created from the error's helpAnchor property public convenience init(with error: Error, title: String? = nil, helpAnchorHandler: ((_ url: URL) -> Void)? = nil) { var actions: [UIAlertAction] = [] let errorTitle: String let message: String if let error = error as? LocalizedError { let sentenceFormat = LocalizedString("%@.", comment: "Appends a full-stop to a statement") let messageWithRecovery = [error.failureReason, error.recoverySuggestion].compactMap({ $0 }).map({ String(format: sentenceFormat, $0) }).joined(separator: "\n") if messageWithRecovery.isEmpty { message = error.localizedDescription } else { message = messageWithRecovery } if let helpAnchor = error.helpAnchor, let url = URL(string: helpAnchor), let helpAnchorHandler = helpAnchorHandler { actions.append(UIAlertAction( title: LocalizedString("More Info", comment: "Alert action title to open error help"), style: .default, handler: { (_) in helpAnchorHandler(url) } )) } errorTitle = (error.errorDescription ?? error.localizedDescription).localizedCapitalized } else { // See: https://forums.developer.apple.com/thread/17431 // The compiler automatically emits the code necessary to translate between any ErrorType and NSError. let castedError = error as NSError errorTitle = error.localizedDescription.localizedCapitalized message = castedError.localizedRecoverySuggestion ?? String(describing: error) } self.init(title: title ?? errorTitle, message: message, preferredStyle: .alert) let action = UIAlertAction( title: LocalizedString("com.loudnate.LoopKit.errorAlertActionTitle", value: "OK", comment: "The title of the action used to dismiss an error alert"), style: .default) addAction(action) self.preferredAction = action for action in actions { addAction(action) } } }
mit
wangwugang1314/weiBoSwift
weiBoSwift/weiBoSwiftUITests/weiBoSwiftUITests.swift
1
1241
// // weiBoSwiftUITests.swift // weiBoSwiftUITests // // Created by MAC on 15/11/25. // Copyright © 2015年 MAC. All rights reserved. // import XCTest class weiBoSwiftUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
apache-2.0
LauraSempere/meme-app
Meme/SentMemesCollectionViewController.swift
1
2644
// // SentMemesCollectionViewController.swift // Meme // // Created by Laura Scully on 1/7/2016. // Copyright © 2016 laura.com. All rights reserved. // import UIKit class SentMemesCollectionViewController: UICollectionViewController { @IBOutlet weak var flowLayout:UICollectionViewFlowLayout! var memes:[Meme]! override func viewDidLoad() { super.viewDidLoad() let applicationDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) memes = applicationDelegate.memes let space: CGFloat = 3.0 let width = (view.frame.size.width - (2 * space)) / space let height = (view.frame.size.height - (2 * space)) / space flowLayout.minimumInteritemSpacing = space flowLayout.minimumLineSpacing = space / 10 flowLayout.itemSize = CGSizeMake(width, height) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: #selector(SentMemesCollectionViewController.goToEditMeme)) } override func viewWillAppear(animated: Bool) { self.tabBarController?.tabBar.hidden = false memes = (UIApplication.sharedApplication().delegate as! AppDelegate).memes self.collectionView!.reloadData() } func goToEditMeme(){ let memeEditorVC = storyboard?.instantiateViewControllerWithIdentifier("MemeEditorViewController") as! MemeEditorViewController self.navigationController?.pushViewController(memeEditorVC, animated: true) } // MARK: UICollectionViewDataSource override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return memes.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! SentMemesCollectionViewCell let meme = memes[indexPath.item] cell.image.image = meme.memedImage return cell } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let detailVC = storyboard?.instantiateViewControllerWithIdentifier("MemeDetailViewController") as! MemeDetailViewController let meme = memes[indexPath.item] detailVC.meme = meme detailVC.memeIndex = indexPath.item self.navigationController?.pushViewController(detailVC, animated: true) } }
epl-1.0
ntwf/TheTaleClient
TheTale/Stores/GameInformation/GameInformation.swift
1
1997
// // GameInformation.swift // the-tale // // Created by Mikhail Vospennikov on 14/05/2017. // Copyright © 2017 Mikhail Vospennikov. All rights reserved. // import Foundation struct GameInformation { var accountID: Int var accountName: String var gameVersion: String var staticContent: String var turnDelta: Int var arenaPvP: Int var arenaPvPAccept: Int var arenaPvPLeaveQueue: Int var help: Int var buildingRepair: Int var dropItem: Int } extension GameInformation: JSONDecodable { init?(jsonObject: JSON) { guard let accountID = jsonObject["account_id"] as? Int, let accountName = jsonObject["account_name"] as? String, let gameVersion = jsonObject["game_version"] as? String, let staticContent = jsonObject["static_content"] as? String, let turnDelta = jsonObject["turn_delta"] as? Int, let abilitiesCost = jsonObject["abilities_cost"] as? JSON, let arenaPvP = abilitiesCost["arena_pvp_1x1"] as? Int, let arenaPvPAccept = abilitiesCost["arena_pvp_1x1_accept"] as? Int, let arenaPvPLeaveQueue = abilitiesCost["arena_pvp_1x1_leave_queue"] as? Int, let help = abilitiesCost["help"] as? Int, let buildingRepair = abilitiesCost["building_repair"] as? Int, let dropItem = abilitiesCost["drop_item"] as? Int else { return nil } self.accountID = accountID self.accountName = accountName self.gameVersion = gameVersion self.staticContent = staticContent self.turnDelta = turnDelta self.arenaPvP = arenaPvP self.arenaPvPAccept = arenaPvPAccept self.arenaPvPLeaveQueue = arenaPvPLeaveQueue self.help = help self.buildingRepair = buildingRepair self.dropItem = dropItem } init?() { self.init(jsonObject: [:]) } }
mit
rockgarden/swift_language
Playground/Design-Patterns.playground/Design-Patterns.playground/section-20.swift
1
680
var gameState = GameState() gameState.restoreFromMemento(CheckPoint.restorePreviousState()) gameState.chapter = "Black Mesa Inbound" gameState.weapon = "Crowbar" CheckPoint.saveState(gameState.toMemento()) gameState.chapter = "Anomalous Materials" gameState.weapon = "Glock 17" gameState.restoreFromMemento(CheckPoint.restorePreviousState()) gameState.chapter = "Unforeseen Consequences" gameState.weapon = "MP5" CheckPoint.saveState(gameState.toMemento(), keyName: "gameState2") gameState.chapter = "Office Complex" gameState.weapon = "Crossbow" CheckPoint.saveState(gameState.toMemento()) gameState.restoreFromMemento(CheckPoint.restorePreviousState(keyName: "gameState2"))
mit
irealme/ExpandableTableViewController
DemoExpandableTableViewController/DemoCells/DescriptionTableViewCell.swift
1
667
// // DescriptionTableViewCell.swift // DemoExpandableTableViewController // // Created by Enric Macias Lopez on 8/25/15. // Copyright (c) 2015 Enric Macias Lopez. All rights reserved. // import UIKit class DescriptionTableViewCell: UITableViewCell { // MARK: Properties @IBOutlet weak var descriptionLabel: UILabel! // MARK: Lifecycle override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxCocoa/RxCocoa/CocoaUnits/ControlProperty.swift
10
4956
// // ControlProperty.swift // RxCocoa // // Created by Krunoslav Zaher on 8/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif /// Protocol that enables extension of `ControlProperty`. public protocol ControlPropertyType : ObservableType, ObserverType { /// - returns: `ControlProperty` interface func asControlProperty() -> ControlProperty<E> } /** Unit for `Observable`/`ObservableType` that represents property of UI element. Sequence of values only represents initial control value and user initiated value changes. Programatic value changes won't be reported. It's properties are: - it never fails - `shareReplay(1)` behavior - it's stateful, upon subscription (calling subscribe) last element is immediately replayed if it was produced - it will `Complete` sequence on control being deallocated - it never errors out - it delivers events on `MainScheduler.instance` **The implementation of `ControlProperty` will ensure that sequence of values is being subscribed on main scheduler (`subscribeOn(ConcurrentMainScheduler.instance)` behavior).** **It is implementor's responsibility to make sure that that all other properties enumerated above are satisfied.** **If they aren't, then using this unit communicates wrong properties and could potentially break someone's code.** **In case `values` observable sequence that is being passed into initializer doesn't satisfy all enumerated properties, please don't use this unit.** */ public struct ControlProperty<PropertyType> : ControlPropertyType { public typealias E = PropertyType let _values: Observable<PropertyType> let _valueSink: AnyObserver<PropertyType> /// Initializes control property with a observable sequence that represents property values and observer that enables /// binding values to property. /// /// - parameter values: Observable sequence that represents property values. /// - parameter valueSink: Observer that enables binding values to control property. /// - returns: Control property created with a observable sequence of values and an observer that enables binding values /// to property. public init<V: ObservableType, S: ObserverType>(values: V, valueSink: S) where E == V.E, E == S.E { _values = values.subscribeOn(ConcurrentMainScheduler.instance) _valueSink = valueSink.asObserver() } /// Subscribes an observer to control property values. /// /// - parameter observer: Observer to subscribe to property values. /// - returns: Disposable object that can be used to unsubscribe the observer from receiving control property values. public func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { return _values.subscribe(observer) } /// `ControlEvent` of user initiated value changes. Every time user updates control value change event /// will be emitted from `changed` event. /// /// Programatic changes to control value won't be reported. /// /// It contains all control property values except for first one. /// /// The name only implies that sequence element will be generated once user changes a value and not that /// adjacent sequence values need to be different (e.g. because of interaction between programatic and user updates, /// or for any other reason). public var changed: ControlEvent<PropertyType> { get { return ControlEvent(events: _values.skip(1)) } } /// - returns: `Observable` interface. public func asObservable() -> Observable<E> { return _values } /// - returns: `ControlProperty` interface. public func asControlProperty() -> ControlProperty<E> { return self } /// Binds event to user interface. /// /// - In case next element is received, it is being set to control value. /// - In case error is received, DEBUG buids raise fatal error, RELEASE builds log event to standard output. /// - In case sequence completes, nothing happens. public func on(_ event: Event<E>) { switch event { case .error(let error): bindingErrorToInterface(error) case .next: _valueSink.on(event) case .completed: _valueSink.on(event) } } } extension ControlPropertyType where E == String? { /// Transforms control property of type `String?` into control property of type `String`. public var orEmpty: ControlProperty<String> { let original: ControlProperty<String?> = self.asControlProperty() let values: Observable<String> = original._values.map { $0 ?? "" } let valueSink: AnyObserver<String> = original._valueSink.mapObserver { $0 } return ControlProperty<String>(values: values, valueSink: valueSink) } }
apache-2.0
Karumi/BothamUI
Sources/BothamViewDataSource.swift
1
441
// // BothamDataSource.swift // BothamUI // // Created by Davide Mendolia on 03/12/15. // Copyright © 2015 GoKarumi S.L. All rights reserved. // import Foundation public protocol BothamViewDataSource { associatedtype ItemType var items: [ItemType] { get set } } public extension BothamViewDataSource { public func item(at indexPath: IndexPath) -> ItemType { return items[(indexPath as NSIndexPath).item] } }
apache-2.0
ahoppen/swift
test/Parse/metatype_object_conversion.swift
9
985
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop class C {} struct S {} protocol NonClassProto {} protocol ClassConstrainedProto : class {} func takesAnyObject(_ x: AnyObject) {} func concreteTypes() { takesAnyObject(C.self) takesAnyObject(S.self) // expected-error{{argument type 'S.Type' expected to be an instance of a class or class-constrained type}} takesAnyObject(ClassConstrainedProto.self) // expected-error{{argument type '(any ClassConstrainedProto).Type' expected to be an instance of a class or class-constrained type}} } func existentialMetatypes(nonClass: NonClassProto.Type, classConstrained: ClassConstrainedProto.Type, compo: (NonClassProto & ClassConstrainedProto).Type) { takesAnyObject(nonClass) // expected-error{{argument type 'any NonClassProto.Type' expected to be an instance of a class or class-constrained type}} takesAnyObject(classConstrained) takesAnyObject(compo) }
apache-2.0
ahoppen/swift
test/decl/protocol/special/coding/enum_codable_nonconforming_property.swift
13
19899
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown enum NonCodable : Hashable { func hash(into hasher: inout Hasher) {} static func ==(_ lhs: NonCodable, _ rhs: NonCodable) -> Bool { return true } } struct CodableGeneric<T> : Codable { } // Enums whose properties are not all Codable should fail to synthesize // conformance. enum NonConformingEnum : Codable { // expected-error {{type 'NonConformingEnum' does not conform to protocol 'Decodable'}} // expected-error@-1 {{type 'NonConformingEnum' does not conform to protocol 'Decodable'}} // expected-error@-2 {{type 'NonConformingEnum' does not conform to protocol 'Encodable'}} // expected-error@-3 {{type 'NonConformingEnum' does not conform to protocol 'Encodable'}} case x( w: NonCodable, // expected-note {{cannot automatically synthesize 'Decodable' because 'NonCodable' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because 'NonCodable' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because 'NonCodable' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because 'NonCodable' does not conform to 'Encodable'}} x: Int, y: Double, // FIXME: Remove when conditional conformance lands. // Because conditional conformance is not yet available, Optional, Array, // Set, and Dictionary all conform to Codable even when their generic // parameters do not. // We want to make sure that these cases prevent derived conformance. nonCodableOptional: NonCodable? = nil, // expected-note {{cannot automatically synthesize 'Decodable' because 'NonCodable?' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because 'NonCodable?' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because 'NonCodable?' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because 'NonCodable?' does not conform to 'Encodable'}} nonCodableArray: [NonCodable] = [], // expected-note {{cannot automatically synthesize 'Decodable' because '[NonCodable]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[NonCodable]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[NonCodable]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[NonCodable]' does not conform to 'Encodable'}} nonCodableSet: Set<NonCodable> = [], // expected-note {{cannot automatically synthesize 'Decodable' because 'Set<NonCodable>' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because 'Set<NonCodable>' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because 'Set<NonCodable>' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because 'Set<NonCodable>' does not conform to 'Encodable'}} nonCodableDictionary1: [String : NonCodable] = [:], // expected-note {{cannot automatically synthesize 'Decodable' because '[String : NonCodable]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[String : NonCodable]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[String : NonCodable]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[String : NonCodable]' does not conform to 'Encodable'}} nonCodableDictionary2: [NonCodable : String] = [:], // expected-note {{cannot automatically synthesize 'Decodable' because '[NonCodable : String]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[NonCodable : String]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[NonCodable : String]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[NonCodable : String]' does not conform to 'Encodable'}} nonCodableDictionary3: [NonCodable : NonCodable] = [:], // expected-note {{cannot automatically synthesize 'Decodable' because '[NonCodable : NonCodable]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[NonCodable : NonCodable]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[NonCodable : NonCodable]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[NonCodable : NonCodable]' does not conform to 'Encodable'}} // These conditions should apply recursively, too. nonCodableOptionalOptional: NonCodable?? = nil, // expected-note {{cannot automatically synthesize 'Decodable' because 'NonCodable??' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because 'NonCodable??' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because 'NonCodable??' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because 'NonCodable??' does not conform to 'Encodable'}} nonCodableOptionalArray: [NonCodable]? = nil, // expected-note {{cannot automatically synthesize 'Decodable' because '[NonCodable]?' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[NonCodable]?' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[NonCodable]?' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[NonCodable]?' does not conform to 'Encodable'}} nonCodableOptionalSet: Set<NonCodable>? = nil, // expected-note {{cannot automatically synthesize 'Decodable' because 'Set<NonCodable>?' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because 'Set<NonCodable>?' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because 'Set<NonCodable>?' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because 'Set<NonCodable>?' does not conform to 'Encodable'}} nonCodableOptionalDictionary1: [String : NonCodable]? = nil, // expected-note {{cannot automatically synthesize 'Decodable' because '[String : NonCodable]?' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[String : NonCodable]?' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[String : NonCodable]?' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[String : NonCodable]?' does not conform to 'Encodable'}} nonCodableOptionalDictionary2: [NonCodable : String]? = nil, // expected-note {{cannot automatically synthesize 'Decodable' because '[NonCodable : String]?' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[NonCodable : String]?' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[NonCodable : String]?' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[NonCodable : String]?' does not conform to 'Encodable'}} nonCodableOptionalDictionary3: [NonCodable : NonCodable]? = nil, // expected-note {{cannot automatically synthesize 'Decodable' because '[NonCodable : NonCodable]?' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[NonCodable : NonCodable]?' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[NonCodable : NonCodable]?' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[NonCodable : NonCodable]?' does not conform to 'Encodable'}} nonCodableArrayOptional: [NonCodable?] = [], // expected-note {{cannot automatically synthesize 'Decodable' because '[NonCodable?]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[NonCodable?]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[NonCodable?]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[NonCodable?]' does not conform to 'Encodable'}} nonCodableArrayArray: [[NonCodable]] = [], // expected-note {{cannot automatically synthesize 'Decodable' because '[[NonCodable]]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[[NonCodable]]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[[NonCodable]]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[[NonCodable]]' does not conform to 'Encodable'}} nonCodableArraySet: [Set<NonCodable>] = [], // expected-note {{cannot automatically synthesize 'Decodable' because '[Set<NonCodable>]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[Set<NonCodable>]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[Set<NonCodable>]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[Set<NonCodable>]' does not conform to 'Encodable'}} nonCodableArrayDictionary1: [[String : NonCodable]] = [], // expected-note {{cannot automatically synthesize 'Decodable' because '[[String : NonCodable]]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[[String : NonCodable]]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[[String : NonCodable]]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[[String : NonCodable]]' does not conform to 'Encodable'}} nonCodableArrayDictionary2: [[NonCodable : String]] = [], // expected-note {{cannot automatically synthesize 'Decodable' because '[[NonCodable : String]]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[[NonCodable : String]]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[[NonCodable : String]]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[[NonCodable : String]]' does not conform to 'Encodable'}} nonCodableArrayDictionary3: [[NonCodable : NonCodable]] = [], // expected-note {{cannot automatically synthesize 'Decodable' because '[[NonCodable : NonCodable]]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[[NonCodable : NonCodable]]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[[NonCodable : NonCodable]]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[[NonCodable : NonCodable]]' does not conform to 'Encodable'}} nonCodableDictionaryOptional1: [String : NonCodable?] = [:], // expected-note {{cannot automatically synthesize 'Decodable' because '[String : NonCodable?]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[String : NonCodable?]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[String : NonCodable?]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[String : NonCodable?]' does not conform to 'Encodable'}} nonCodableDictionaryOptional2: [NonCodable : NonCodable?] = [:], // expected-note {{cannot automatically synthesize 'Decodable' because '[NonCodable : NonCodable?]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[NonCodable : NonCodable?]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[NonCodable : NonCodable?]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[NonCodable : NonCodable?]' does not conform to 'Encodable'}} nonCodableDictionaryArray1: [String : [NonCodable]] = [:], // expected-note {{cannot automatically synthesize 'Decodable' because '[String : [NonCodable]]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[String : [NonCodable]]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[String : [NonCodable]]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[String : [NonCodable]]' does not conform to 'Encodable'}} nonCodableDictionaryArray2: [NonCodable : [NonCodable]] = [:], // expected-note {{cannot automatically synthesize 'Decodable' because '[NonCodable : [NonCodable]]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[NonCodable : [NonCodable]]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[NonCodable : [NonCodable]]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[NonCodable : [NonCodable]]' does not conform to 'Encodable'}} nonCodableDictionarySet1: [String : Set<NonCodable>] = [:], // expected-note {{cannot automatically synthesize 'Decodable' because '[String : Set<NonCodable>]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[String : Set<NonCodable>]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[String : Set<NonCodable>]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[String : Set<NonCodable>]' does not conform to 'Encodable'}} nonCodableDictionarySet2: [NonCodable : Set<NonCodable>] = [:], // expected-note {{cannot automatically synthesize 'Decodable' because '[NonCodable : Set<NonCodable>]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[NonCodable : Set<NonCodable>]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[NonCodable : Set<NonCodable>]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[NonCodable : Set<NonCodable>]' does not conform to 'Encodable'}} nonCodableDictionaryDictionary1: [String : [String : NonCodable]] = [:], // expected-note {{cannot automatically synthesize 'Decodable' because '[String : [String : NonCodable]]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[String : [String : NonCodable]]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[String : [String : NonCodable]]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[String : [String : NonCodable]]' does not conform to 'Encodable'}} nonCodableDictionaryDictionary2: [NonCodable : [String : NonCodable]] = [:], // expected-note {{cannot automatically synthesize 'Decodable' because '[NonCodable : [String : NonCodable]]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[NonCodable : [String : NonCodable]]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[NonCodable : [String : NonCodable]]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[NonCodable : [String : NonCodable]]' does not conform to 'Encodable'}} nonCodableDictionaryDictionary3: [String : [NonCodable : NonCodable]] = [:], // expected-note {{cannot automatically synthesize 'Decodable' because '[String : [NonCodable : NonCodable]]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[String : [NonCodable : NonCodable]]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[String : [NonCodable : NonCodable]]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[String : [NonCodable : NonCodable]]' does not conform to 'Encodable'}} nonCodableDictionaryDictionary4: [NonCodable : [NonCodable : NonCodable]] = [:], // expected-note {{cannot automatically synthesize 'Decodable' because '[NonCodable : [NonCodable : NonCodable]]' does not conform to 'Decodable'}} // expected-note@-1 {{cannot automatically synthesize 'Decodable' because '[NonCodable : [NonCodable : NonCodable]]' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because '[NonCodable : [NonCodable : NonCodable]]' does not conform to 'Encodable'}} // expected-note@-3 {{cannot automatically synthesize 'Encodable' because '[NonCodable : [NonCodable : NonCodable]]' does not conform to 'Encodable'}} // However, arbitrary generic types which _do_ conform to Codable should be // valid. codableGenericThing1: CodableGeneric<NonCodable>? = nil, codableGenericThing2: CodableGeneric<NonCodable?>? = nil, codableGenericThing3: CodableGeneric<[NonCodable]>? = nil, codableGenericThing4: CodableGeneric<Set<NonCodable>>? = nil, codableGenericThing5: CodableGeneric<[String : NonCodable]>? = nil, codableGenericThing6: CodableGeneric<[NonCodable : String]>? = nil, codableGenericThing7: CodableGeneric<[NonCodable : NonCodable]>? = nil) } // They should not receive Codable methods. let _ = NonConformingEnum.init(from:) // expected-error {{'NonConformingEnum' cannot be constructed because it has no accessible initializers}} let _ = NonConformingEnum.encode(to:) // expected-error {{type 'NonConformingEnum' has no member 'encode(to:)'}} // They should not get a CodingKeys type. let _ = NonConformingEnum.XCodingKeys.self // expected-error {{'XCodingKeys' is inaccessible due to 'private' protection level}}
apache-2.0
hirohisa/RxSwift
RxSwift/RxSwift/Observables/Implementations/Filter.swift
15
1793
// // Filter.swift // Rx // // Created by Krunoslav Zaher on 2/17/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Where_<O : ObserverType>: Sink<O>, ObserverType { typealias Element = O.Element typealias Parent = Where<Element> let parent: Parent init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func on(event: Event<Element>) { switch event { case .Next(let boxedValue): let value = boxedValue.value _ = self.parent.predicate(value).recoverWith { e in trySendError(observer, e) self.dispose() return failure(e) }.flatMap { satisfies -> RxResult<Void> in if satisfies { trySend(observer, event) } return SuccessResult } case .Completed: fallthrough case .Error: trySend(observer, event) self.dispose() } } } class Where<Element> : Producer<Element> { typealias Predicate = (Element) -> RxResult<Bool> let source: Observable<Element> let predicate: Predicate init(source: Observable<Element>, predicate: Predicate) { self.source = source self.predicate = predicate } override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = Where_(parent: self, observer: observer, cancel: cancel) setSink(sink) return source.subscribeSafe(sink) } }
mit
RMizin/PigeonMessenger-project
FalconMessenger/ChatsControllers/IncomingVoiceMessageCell.swift
1
2615
// // IncomingVoiceMessageCell.swift // Pigeon-project // // Created by Roman Mizin on 11/26/17. // Copyright © 2017 Roman Mizin. All rights reserved. // import UIKit import AVFoundation class IncomingVoiceMessageCell: BaseVoiceMessageCell { override func setupViews() { super.setupViews() bubbleView.addSubview(playerView) bubbleView.addSubview(nameLabel) bubbleView.addSubview(timeLabel) bubbleView.frame.origin = BaseMessageCell.incomingBubbleOrigin bubbleView.frame.size.width = 150 timeLabel.backgroundColor = .clear timeLabel.textColor = UIColor.darkGray.withAlphaComponent(0.7) playerView.timerLabel.textColor = ThemeManager.currentTheme().incomingBubbleTextColor bubbleView.tintColor = ThemeManager.currentTheme().incomingBubbleTintColor } override func prepareForReuse() { super.prepareForReuse() bubbleView.tintColor = ThemeManager.currentTheme().incomingBubbleTintColor playerView.timerLabel.textColor = ThemeManager.currentTheme().incomingBubbleTextColor } func setupData(message: Message, isGroupChat: Bool) { if isGroupChat { nameLabel.text = message.senderName ?? "" nameLabel.sizeToFit() bubbleView.frame.size.height = frame.size.height.rounded() playerView.frame = CGRect(x: 10, y: 20, width: bubbleView.frame.width-20, height: bubbleView.frame.height-BaseMessageCell.messageTimeHeight-15).integral if nameLabel.frame.size.width >= BaseMessageCell.incomingGroupMessageAuthorNameLabelMaxWidth { nameLabel.frame.size.width = playerView.frame.size.width - 24 } } else { bubbleView.frame.size.height = frame.size.height.rounded() playerView.frame = CGRect(x: 7, y: 14, width: bubbleView.frame.width-17, height: bubbleView.frame.height-BaseMessageCell.messageTimeHeight-19).integral } timeLabel.frame.origin = CGPoint(x: bubbleView.frame.width-timeLabel.frame.width-1, y: bubbleView.frame.height-timeLabel.frame.height-5) timeLabel.text = message.convertedTimestamp guard message.voiceEncodedString != nil else { return } playerView.timerLabel.text = message.voiceDuration playerView.startingTime = message.voiceStartTime.value ?? 0 playerView.seconds = message.voiceStartTime.value ?? 0 if let isCrooked = message.isCrooked.value, isCrooked { bubbleView.image = ThemeManager.currentTheme().incomingBubble } else { bubbleView.image = ThemeManager.currentTheme().incomingPartialBubble } } }
gpl-3.0
chrislzm/TimeAnalytics
Time Analytics/TANetClient.swift
1
5958
// // TANetClient.swift // Time Analytics // // Singleton network client interface for Time Analytics. Used by TANetClientConvenience methods to make requests of the Moves REST API. // // Created by Chris Leung on 5/14/17. // Copyright © 2017 Chris Leung. All rights reserved. // import Foundation class TANetClient { // MARK: Shared Instance static let sharedInstance = TANetClient() // MARK: Properties var session = URLSession.shared // MARK: Session Variables // A copy of all these session variables are stored in UserDefaults, and loaded by the AppDelegate when the app is opened // Moves session variables var movesAuthCode:String? var movesAccessToken:String? var movesAccessTokenExpiration:Date? var movesRefreshToken:String? var movesUserId:UInt64? var movesUserFirstDate:String? var movesLatestUpdate:Date? // RescueTime session variable var rescueTimeApiKey:String? // Internal session variables var lastCheckedForNewData:Date? // MARK: Methods // Shared HTTP Method for all HTTP requests func taskForHTTPMethod(_ apiScheme:String, _ httpMethod:String, _ apiHost: String, _ apiMethod: String, apiParameters: [String:String]?, valuesForHTTPHeader: [(String, String)]?, httpBody: String?, completionHandler: @escaping (_ result: AnyObject?, _ error: NSError?) -> Void) -> URLSessionDataTask { /* 1. Build the URL */ let request = NSMutableURLRequest(url: urlFromParameters(apiScheme, apiHost, apiMethod, apiParameters)) /* 2. Configure the request */ request.httpMethod = httpMethod // Add other HTTP Header fields and values, if any if let valuesForHTTPHeader = valuesForHTTPHeader { for (value,headerField) in valuesForHTTPHeader { request.addValue(value, forHTTPHeaderField: headerField) } } // Add http request body, if any if let httpBody = httpBody { request.httpBody = httpBody.data(using: String.Encoding.utf8) } /* 3. Make the request */ let task = session.dataTask(with: request as URLRequest) { (data, response, error) in func sendError(_ error: String) { let userInfo = [NSLocalizedDescriptionKey : error] completionHandler(nil, NSError(domain: "taskForGETMethod", code: 1, userInfo: userInfo)) } /* GUARD: Was there an error? */ guard (error == nil) else { sendError("There was an error with your request: \(String(describing: error))") return } /* GUARD: Did we get a status code from the response? */ guard let statusCode = (response as? HTTPURLResponse)?.statusCode else { sendError("Your request did not return a valid response (no status code).") return } /* GUARD: Did we get a successful 2XX response? */ guard statusCode >= 200 && statusCode <= 299 else { var errorString = "Your request returned a status code other than 2xx. Status code returned: \(statusCode).\n" // If we received some response, also include it in the error message if let errorResponse = response { errorString += "Error response receieved: \(errorResponse)\n" } // If we received some data, also include it in the error message if let errorData = data { let (parsedErrorData,_) = self.convertData(errorData) if let validParsedErrorData = parsedErrorData { errorString += "Error data received: \(validParsedErrorData)\n" } } sendError(errorString) return } /* GUARD: Was there any data returned? */ guard let data = data else { sendError("No data was returned by the request!") return } /* 4. Attempt to parse the data */ let (parseResult,error) = self.convertData(data) /* 5. Send the result to the completion handler */ completionHandler(parseResult,error) } /* 6. Start the request */ task.resume() return task } // MARK: Private helper methods // Creates a URL from parameters private func urlFromParameters(_ apiScheme:String, _ host:String, _ method:String, _ parameters: [String:String]?) -> URL { var components = URLComponents() components.scheme = apiScheme components.host = host components.path = method if let parameters = parameters { components.queryItems = [URLQueryItem]() for (key, value) in parameters { let queryItem = URLQueryItem(name: key, value: value) components.queryItems!.append(queryItem) } } return components.url! } // Attemps to convert raw JSON into a usable Foundation object. Returns an error if unsuccessful. private func convertData(_ data: Data) -> (AnyObject?,NSError?) { var parsedResult: AnyObject? = nil do { parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject } catch { let userInfo = [NSLocalizedDescriptionKey : "Could not parse the data as JSON: '\(data)'"] let error = NSError(domain: "NetClient.convertData", code: 1, userInfo: userInfo) return(nil,error) } return(parsedResult,nil) } }
mit
kolyasev/YaftDB
Example/Tests/Tests.swift
1
795
import UIKit import XCTest import YaftDB class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. let db = Cache(path: "") } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
artsy/eigen
ios/Artsy/View_Controllers/Live_Auctions/LiveAuctionStateManagerSpec.swift
1
5321
import Quick import Nimble import Interstellar @testable import Artsy class LiveAuctionStateManagerSpec: QuickSpec { override func spec() { var subject: LiveAuctionStateManager! var sale: LiveSale! let stubbedJWT = StubbedCredentials.registered.jwt beforeEach { OHHTTPStubs.stubJSONResponse(forHost: "metaphysics*.artsy.net", withResponse: [:]) // Not sure why ^ is needed, might be worth looking // Follow up to ^ it's needed because app state, including staging/prod flags, leak between test runs. sale = testLiveSale() let creds = BiddingCredentials(bidders: [], paddleNumber: "", userID: "") subject = LiveAuctionStateManager(host: "http://localhost", sale: sale, saleArtworks: [], jwt: stubbedJWT, bidderCredentials: creds, socketCommunicatorCreator: test_socketCommunicatorCreator(), stateReconcilerCreator: test_stateReconcilerCreator()) } it("sets its saleID and bidders upon initialization") { expect(subject.bidderCredentials.bidders).to( beEmpty() ) expect(subject.sale) === sale } it("creates an appropriate socket communicator") { expect(mostRecentSocketCommunicator?.host) == "http://localhost" expect(mostRecentSocketCommunicator?.jwt.string) == stubbedJWT.string expect(mostRecentSocketCommunicator?.causalitySaleID) == "some-random-string-of-nc72bjzj7" } it("invokes the state reconciler when new snapshot data avaialble") { let state = ["hi there!"] mostRecentSocketCommunicator?.updatedAuctionState.update(state as AnyObject) expect(mostRecentStateReconciler?.mostRecentState as? [String]) == state } it("invokes current lot updates") { let currentLot = ["hi there!"] mostRecentSocketCommunicator?.currentLotUpdate.update(currentLot as AnyObject) expect(mostRecentStateReconciler?.mostRecentCurrentLotUpdate as? [String]) == currentLot } it("invokes lot event updates") { let lotEvent = ["hi there!"] mostRecentSocketCommunicator?.lotUpdateBroadcasts.update(lotEvent as AnyObject) expect(mostRecentStateReconciler?.mostRecentEventBroadcast as? [String]) == lotEvent } it("invokes sale-on-hold updates") { let event: [String : Any] = [ "type": "SaleOnHold", "isOnHold": true, "userMessage": "some custom message" ] mostRecentSocketCommunicator?.saleOnHoldSignal.update(event as AnyObject) let result = subject.saleOnHoldSignal.peek() expect(result?.isOnHold).to( beTruthy() ) expect(result?.message) == "some custom message" } } } func test_socketCommunicatorCreator() -> LiveAuctionStateManager.SocketCommunicatorCreator { return { host, saleID, jwt in return Test_SocketCommunicator(host: host, causalitySaleID: saleID, jwt: jwt) } } func test_stateReconcilerCreator() -> LiveAuctionStateManager.StateReconcilerCreator { return { saleArtworks in return Test_StateRecociler() } } var mostRecentSocketCommunicator: Test_SocketCommunicator? class Test_SocketCommunicator: LiveAuctionSocketCommunicatorType { let host: String let causalitySaleID: String let jwt: JWT init(host: String, causalitySaleID: String, jwt: JWT) { self.host = host self.causalitySaleID = causalitySaleID self.jwt = jwt mostRecentSocketCommunicator = self } let updatedAuctionState = Observable<AnyObject>() let lotUpdateBroadcasts = Observable<AnyObject>() let currentLotUpdate = Observable<AnyObject>() let postEventResponses = Observable<AnyObject>() let socketConnectionSignal = Observable<Bool>() let operatorConnectedSignal = Observable<AnyObject>() let saleOnHoldSignal = Observable<AnyObject>() func bidOnLot(_ lotID: String, amountCents: UInt64, bidderCredentials: BiddingCredentials, bidUUID: String) {} func leaveMaxBidOnLot(_ lotID: String, amountCents: UInt64, bidderCredentials: BiddingCredentials, bidUUID: String) {} } var mostRecentStateReconciler: Test_StateRecociler? class Test_StateRecociler: LiveAuctionStateReconcilerType { var mostRecentState: AnyObject? var mostRecentEventBroadcast: AnyObject? var mostRecentCurrentLotUpdate: AnyObject? var mostRecentEvent: AnyObject? var debugAllEventsSignal = Observable<LotEventJSON>() init() { mostRecentStateReconciler = self } func updateState(_ state: AnyObject) { mostRecentState = state } func processNewEvents(_ event: AnyObject) { mostRecentEvent = event } func processLotEventBroadcast(_ broadcast: AnyObject) { mostRecentEventBroadcast = broadcast } func processCurrentLotUpdate(_ update: AnyObject) { mostRecentCurrentLotUpdate = update } var newLotsSignal: Observable<[LiveAuctionLotViewModelType]> { return Observable() } var currentLotSignal: Observable<LiveAuctionLotViewModelType?> { return Observable() } var saleSignal: Observable<LiveAuctionViewModelType> { return Observable() } }
mit
1aurabrown/eidolon
Kiosk/Bid Fulfillment/PlacingBidViewController.swift
1
8060
import UIKit class PlacingBidViewController: UIViewController { @IBOutlet weak var titleLabel: ARSerifLabel! @IBOutlet var bidDetailsPreviewView: BidDetailsPreviewView! @IBOutlet weak var outbidNoticeLabel: ARSerifLabel! @IBOutlet weak var spinner: Spinner! @IBOutlet weak var bidConfirmationImageView: UIImageView! let placeBidNetworkModel = PlaceBidNetworkModel() var registerNetworkModel: RegistrationNetworkModel? var foundHighestBidder = false var pollInterval = NSTimeInterval(1) var maxPollRequests = 6 var pollRequests = 0 @IBOutlet weak var backToAuctionButton: ActionButton! // for comparisons at the end var bidderPositions:[BidderPosition]? var mostRecentSaleArtwork:SaleArtwork? override func viewDidLoad() { super.viewDidLoad() outbidNoticeLabel.hidden = true backToAuctionButton.hidden = true let auctionID = self.fulfillmentNav().auctionID! let bidDetails = self.fulfillmentNav().bidDetails bidDetailsPreviewView.bidDetails = bidDetails RACSignal.empty().then { if self.registerNetworkModel == nil { return RACSignal.empty() } return self.registerNetworkModel?.registerSignal().doError { (error) -> Void in // TODO: Display Registration Error } } .then { self.placeBidNetworkModel.fulfillmentNav = self.fulfillmentNav() return self.placeBidNetworkModel.bidSignal(auctionID, bidDetails:bidDetails).doError { (error) -> Void in // TODO: Display Bid Placement Error // If you just registered, we can still push the bidder details VC and display your info } } .then { [weak self] (_) in if self == nil { return RACSignal.empty() } return self!.waitForBidResolution().doError { (error) -> Void in // TODO: Display error or message. Possible that the user will receive texts about result of their bid // We can still display your bidder info to you } } .subscribeNext { [weak self] (_) -> Void in self?.finishUp() return } } func checkForMaxBid() -> RACSignal { return self.getMyBidderPositions().doNext { [weak self] (newBidderPositions) -> Void in let newBidderPositions = newBidderPositions as? [BidderPosition] self?.bidderPositions = newBidderPositions } } func waitForBidResolution () -> RACSignal { // We delay to give the server some time to do the auction // 0.5 may be a tad excessive, but on the whole the networking for // register / bidding is probably about 2-3 seconds, so another 0.5 // isn't gonna hurt so much. return self.pollForUpdatedSaleArtwork().then { [weak self] (_) in return self == nil ? RACSignal.empty() : self!.checkForMaxBid() } } func finishUp() { self.spinner.hidden = true if let topBidderID = mostRecentSaleArtwork?.saleHighestBid?.id { for position in bidderPositions! { if position.highestBid?.id == topBidderID { foundHighestBidder = true } } } if (foundHighestBidder) { isHighestBidder() } else { isLowestBidder() } // Update the bid details sale artwork to our mostRecentSaleArtwork if let mostRecentSaleArtwork = self.mostRecentSaleArtwork { let bidDetails = self.fulfillmentNav().bidDetails bidDetails.saleArtwork?.updateWithValues(mostRecentSaleArtwork) } let showBidderDetails = hasCreatedAUser() || !foundHighestBidder let delayTime = foundHighestBidder ? 3.0 : 7.0 if showBidderDetails { delayToMainThread(delayTime) { self.performSegue(.PushtoBidConfirmed) } } else { backToAuctionButton.hidden = false } } func hasCreatedAUser() -> Bool { return registerNetworkModel != nil } func isHighestBidder() { titleLabel.text = "Bid Confirmed" bidConfirmationImageView.image = UIImage(named: "BidHighestBidder") } func isLowestBidder() { titleLabel.text = "Higher bid needed" titleLabel.textColor = UIColor.artsyRed() outbidNoticeLabel.hidden = false bidConfirmationImageView.image = UIImage(named: "BidNotHighestBidder") } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue == .PushtoBidConfirmed { let registrationConfirmationVC = segue.destinationViewController as YourBiddingDetailsViewController registrationConfirmationVC.titleText = titleLabel.text registrationConfirmationVC.titleColor = titleLabel.textColor registrationConfirmationVC.confirmationImage = bidConfirmationImageView.image let highestBidCopy = "You will be asked for your Bidder Number and PIN next time you bid instead of entering all your information." let notHighestBidderCopy = "Use your Bidder Number and PIN next time you bid." registrationConfirmationVC.bodyCopy = foundHighestBidder ? highestBidCopy : notHighestBidderCopy } } func pollForUpdatedSaleArtwork() -> RACSignal { func getUpdatedSaleArtwork() -> RACSignal { let nav = self.fulfillmentNav() let artworkID = nav.bidDetails.saleArtwork!.artwork.id; let endpoint: ArtsyAPI = ArtsyAPI.AuctionInfoForArtwork(auctionID: nav.auctionID, artworkID: artworkID) return nav.loggedInProvider!.request(endpoint, method: .GET, parameters:endpoint.defaultParameters).filterSuccessfulStatusCodes().mapJSON().mapToObject(SaleArtwork.self) } let beginningBidCents = self.fulfillmentNav().bidDetails.saleArtwork?.saleHighestBid?.amountCents ?? 0 let updatedSaleArtworkSignal = getUpdatedSaleArtwork().flattenMap { [weak self] (saleObject) -> RACStream! in self?.pollRequests++ println("Polling \(self?.pollRequests) of \(self?.maxPollRequests) for updated sale artwork") let saleArtwork = saleObject as? SaleArtwork let updatedBidCents = saleArtwork?.saleHighestBid?.amountCents ?? 0 // TODO: handle the case where the user was already the highest bidder if updatedBidCents != beginningBidCents { // This is an updated model – hooray! self?.mostRecentSaleArtwork = saleArtwork return RACSignal.empty() } else { if (self?.pollRequests ?? 0) >= (self?.maxPollRequests ?? 0) { // We have exceeded our max number of polls, fail. return RACSignal.error(nil) } else { // We didn't get an updated value, so let's try again. return RACSignal.empty().delay(self?.pollInterval ?? 1).then({ () -> RACSignal! in return self?.pollForUpdatedSaleArtwork() }) } } } return RACSignal.empty().delay(pollInterval).then { updatedSaleArtworkSignal } } func getMyBidderPositions() -> RACSignal { let nav = self.fulfillmentNav() let artworkID = nav.bidDetails.saleArtwork!.artwork.id; let endpoint: ArtsyAPI = ArtsyAPI.MyBidPositionsForAuctionArtwork(auctionID: nav.auctionID, artworkID: artworkID) return nav.loggedInProvider!.request(endpoint, method: .GET, parameters:endpoint.defaultParameters).filterSuccessfulStatusCodes().mapJSON().mapToObjectArray(BidderPosition.self) } @IBAction func backToAuctionTapped(sender: AnyObject) { fulfillmentContainer()?.closeFulfillmentModal() } }
mit
alexfish/stylize
Stylize.playground/section-1.swift
1
395
// Playground - noun: a place where people can play import Stylize let foregroundStyle = Stylize.foreground(UIColor.red) let kernStyle = Stylize.kern(5) let style = Stylize.compose(foregroundStyle, kernStyle) let label = UILabel(frame: CGRect(x: 0, y: 0, width: 400, height: 50)) let string = NSAttributedString(string: "Hello World") label.attributedText = style(string)
mit
jarocht/iOS-Bootcamp-Summer2015
HW9/GoogleMapsDemo/GoogleMapsDemo/Location.swift
1
481
// // Location.swift // GoogleMapsDemo // // Created by X Code User on 7/21/15. // Copyright (c) 2015 Jonathan Engelsma. All rights reserved. // import Foundation class Location { var company: String var phone: String var lat: Double var long: Double init (company: String, phone: String, Latitude: Double, Longitude: Double){ self.company = company self.phone = phone self.lat = Latitude self.long = Longitude } }
gpl-2.0
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/NSView+RxTests.swift
20
1100
// // NSView+RxTests.swift // Tests // // Created by Krunoslav Zaher on 12/6/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import RxCocoa import Cocoa import XCTest final class NSViewTests : RxTest { } extension NSViewTests { func testHidden_True() { let subject = NSView(frame: CGRect.zero) Observable.just(true).subscribe(subject.rx.isHidden).dispose() XCTAssertTrue(subject.isHidden == true) } func testHidden_False() { let subject = NSView(frame: CGRect.zero) Observable.just(false).subscribe(subject.rx.isHidden).dispose() XCTAssertTrue(subject.isHidden == false) } } extension NSViewTests { func testAlpha_0() { let subject = NSView(frame: CGRect.zero) Observable.just(0).subscribe(subject.rx.alpha).dispose() XCTAssertTrue(subject.alphaValue == 0.0) } func testAlpha_1() { let subject = NSView(frame: CGRect.zero) Observable.just(1).subscribe(subject.rx.alpha).dispose() XCTAssertTrue(subject.alphaValue == 1.0) } }
mit
dn-m/Collections
Collections/SortedDictionary.swift
1
4768
// // SortedDictionary.swift // Collections // // Created by James Bean on 12/23/16. // // /// Ordered dictionary which has sorted `keys`. public struct SortedDictionary<Key, Value>: DictionaryProtocol where Key: Hashable & Comparable { /// Backing dictionary. /// // FIXME: Make `private` in Swift 4 internal var unsorted: [Key: Value] = [:] // MARK: - Instance Properties /// Values contained herein, in order sorted by their associated keys. public var values: LazyMapRandomAccessCollection<SortedArray<Key>,Value> { return keys.lazy.map { self.unsorted[$0]! } } /// Sorted keys. public var keys: SortedArray<Key> = [] // MARK: - Initializers /// Create an empty `SortedOrderedDictionary`. public init() { } // MARK: - Subscripts /// - returns: Value for the given `key`, if available. Otherwise, `nil`. public subscript(key: Key) -> Value? { get { return unsorted[key] } set { guard let newValue = newValue else { unsorted.removeValue(forKey: key) keys.remove(key) return } let oldValue = unsorted.updateValue(newValue, forKey: key) if oldValue == nil { keys.insert(key) } } } // MARK: - Instance Methods /// Insert the given `value` for the given `key`. Order will be maintained. public mutating func insert(_ value: Value, key: Key) { keys.insert(key) unsorted[key] = value } /// Insert the contents of another `SortedDictionary` value. public mutating func insertContents(of sortedDictionary: SortedDictionary<Key, Value>) { sortedDictionary.forEach { insert($0.1, key: $0.0) } } /// - returns: Value at the given `index`, if present. Otherwise, `nil`. public func value(at index: Int) -> Value? { if index >= keys.count { return nil } return unsorted[keys[index]] } } extension SortedDictionary: Collection { // MARK: - `Collection` /// Index after the given `index`. public func index(after index: Int) -> Int { assert(index < endIndex, "Cannot decrement index to \(index - 1)") return index + 1 } /// Start index. public var startIndex: Int { return 0 } /// End index. public var endIndex: Int { return keys.count } /// Count. public var count: Int { return keys.count } } extension SortedDictionary: BidirectionalCollection { /// Index before the given `index`. public func index(before index: Int) -> Int { assert(index > 0, "Cannot decrement index to \(index - 1)") return index - 1 } } extension SortedDictionary: RandomAccessCollection { /// - Returns: Element at the given `index`. public subscript (index: Int) -> (Key, Value) { let key = keys[index] let value = unsorted[key]! return (key, value) } } extension SortedDictionary { public func min() -> (Key,Value)? { guard let firstKey = keys.first else { return nil } return (firstKey, unsorted[firstKey]!) } public func max() -> (Key,Value)? { guard let lastKey = keys.last else { return nil } return (lastKey, unsorted[lastKey]!) } public func sorted() -> [(Key,Value)] { return Array(self) } } extension SortedDictionary: ExpressibleByDictionaryLiteral { // MARK: - `ExpressibleByDictionaryLiteral` /// Create a `SortedDictionary` with a `DictionaryLiteral`. public init(dictionaryLiteral elements: (Key, Value)...) { self.init() elements.forEach { (k, v) in insert(v, key: k) } } } /// - returns: `true` if all values contained in both `SortedDictionary` values are /// equivalent. Otherwise, `false`. public func == <K, V: Equatable> (lhs: SortedDictionary<K,V>, rhs: SortedDictionary<K,V>) -> Bool { guard lhs.keys == rhs.keys else { return false } for key in lhs.keys { if rhs.unsorted[key] == nil || rhs.unsorted[key]! != lhs.unsorted[key]! { return false } } for key in rhs.keys { if lhs.unsorted[key] == nil || lhs.unsorted[key]! != rhs.unsorted[key]! { return false } } return true } /// - returns: `SortedOrderedDictionary` with values of two `SortedOrderedDictionary` values. public func + <Value, Key> ( lhs: SortedDictionary<Value, Key>, rhs: SortedDictionary<Value, Key> ) -> SortedDictionary<Value, Key> where Key: Hashable, Key: Comparable { var result = lhs rhs.forEach { result.insert($0.1, key: $0.0) } return result }
mit
doertydoerk/SlideToUnlock
SlideToUnlock/AppDelegate.swift
1
2089
// // AppDelegate.swift // SlideToUnlock // // Created by Dirk Gerretz on 08/03/2017. // Copyright © 2017 [code2 app];. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
PJayRushton/iOS-CollectionView-Demo
InterestsCollectionViewDemo/JSON+Extras.swift
1
4629
import Foundation public struct JSONParser { public static func JSONObjectWithData(data:NSData) throws -> JSONObject { let obj:Any = try NSJSONSerialization.JSONObjectWithData(data, options: []) return try JSONObject.JSONValue(obj) } public static func JSONObjectArrayWithData(data:NSData) throws -> [JSONObject] { let object:AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: []) guard let ra = object as? [JSONObject] else { throw JSONError.TypeMismatch(expected: [JSONObject].self, actual: object.dynamicType) } return ra } private init() { } // No need to instatiate one of these. } public protocol JSONCollectionType { func jsonData() throws -> NSData } extension JSONCollectionType { public func jsonData() throws -> NSData { guard let jsonCollection = self as? AnyObject else { throw JSONError.TypeMismatchWithKey(key:"", expected: AnyObject.self, actual: self.dynamicType) // shouldn't happen } return try NSJSONSerialization.dataWithJSONObject(jsonCollection, options: []) } } public protocol JSONObjectConvertible : JSONValueType { typealias ConvertibleType = Self init(json:JSONObject) throws } extension JSONObjectConvertible { public static func JSONValue(object: Any) throws -> ConvertibleType { guard let json = object as? JSONObject else { throw JSONError.TypeMismatch(expected: JSONObject.self, actual: object.dynamicType) } guard let value = try self.init(json: json) as? ConvertibleType else { throw JSONError.TypeMismatch(expected: ConvertibleType.self, actual: object.dynamicType) } return value } } extension Dictionary : JSONCollectionType {} extension Array : JSONCollectionType {} public typealias JSONObjectArray = [JSONObject] extension NSDate : JSONValueType { public static func JSONValue(object: Any) throws -> NSDate { guard let dateString = object as? String else { throw JSONError.TypeMismatch(expected: String.self, actual: object.dynamicType) } guard let date = NSDate.fromISO8601String(dateString) else { throw JSONError.TypeMismatch(expected: "ISO8601 date string", actual: dateString) } return date } } public extension NSDate { static private let ISO8601MillisecondFormatter:NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; let tz = NSTimeZone(abbreviation:"GMT") formatter.timeZone = tz return formatter }() static private let ISO8601SecondFormatter:NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"; let tz = NSTimeZone(abbreviation:"GMT") formatter.timeZone = tz return formatter }() static private let formatters = [ISO8601MillisecondFormatter, ISO8601SecondFormatter] static func fromISO8601String(dateString:String) -> NSDate? { for formatter in formatters { if let date = formatter.dateFromString(dateString) { return date } } return .None } } infix operator <| { associativity left precedence 150 } public func <| <A: JSONValueType>(dictionary: JSONObject, key: String) throws -> A { return try dictionary.JSONValueForKey(key) } public func <| <A: JSONValueType>(dictionary: JSONObject, key: String) throws -> A? { return try dictionary.JSONValueForKey(key) } public func <| <A: JSONValueType>(dictionary: JSONObject, key: String) throws -> [A] { return try dictionary.JSONValueForKey(key) } public func <| <A: JSONValueType>(dictionary: JSONObject, key: String) throws -> [A]? { return try dictionary.JSONValueForKey(key) } public func <| <A: RawRepresentable where A.RawValue: JSONValueType>(dictionary: JSONObject, key: String) throws -> A { return try dictionary.JSONValueForKey(key) } public func <| <A: RawRepresentable where A.RawValue: JSONValueType>(dictionary: JSONObject, key: String) throws -> A? { return try dictionary.JSONValueForKey(key) } public func <| <A: RawRepresentable where A.RawValue: JSONValueType>(dictionary: JSONObject, key: String) throws -> [A] { return try dictionary.JSONValueForKey(key) } public func <| <A: RawRepresentable where A.RawValue: JSONValueType>(dictionary: JSONObject, key: String) throws -> [A]? { return try dictionary.JSONValueForKey(key) }
mit
gyro-n/PaymentsIos
GyronPayments/Classes/UI/CardViewController.swift
1
11336
// // CardViewController.swift // Pods // // Created by David Ye on 2017/07/21. // Copyright © 2016 gyron. All rights reserved. // // import UIKit import PromiseKit public protocol CardViewControllerDelegate: class { func created(card: SimpleTransactionToken) func createError(error: Error) } open class CardViewController: UIViewController, UITextFieldDelegate { var sdkOptions: Options? var sdk: SDK? var customerId: String? var isDummy: Bool? var cardNumber: String? var cardBrand: String? public weak var delegate: CardViewControllerDelegate? public var customTitle: String? @IBOutlet weak var cardNumberTextField: UITextField? @IBOutlet weak var expiryMonthTextField: UITextField? @IBOutlet weak var expiryYearTextField: UITextField? @IBOutlet weak var cvvTextField: UITextField? @IBOutlet weak var cardHolderNameTextField: UITextField? @IBOutlet weak var nicknameTextField: UITextField? @IBOutlet weak var activityIndicator: UIActivityIndicatorView? @IBOutlet weak var cardImage: UIImageView? @IBOutlet weak var navigationBar: UINavigationBar? @IBOutlet weak var emailTextField: UITextField? @IBAction func handleBarButtonCancelClick(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } @IBAction func handleDoneClick(_ sender: UIBarButtonItem) { /*self.showActivityIndicator(isShown: true) let cardData = TransactionTokenCardRequestData(cardholder: self.cardHolderNameTextField!.text!, cardNumber: self.cardNumberTextField!.text!, expMonth: self.expiryMonthTextField!.text!, expYear: self.expiryYearTextField!.text!, cvv: self.cvvTextField!.text!) let data = CardCreateRequestData(cardData: cardData, name: self.nicknameTextField!.text!) let clientId = self.clientId ?? UUID().uuidString self.sdk?.cardResource?.create(clientId: clientId, data: data, callback: nil).then(execute: { c -> Void in self.delegate?.created(card: c) self.showActivityIndicator(isShown: false) self.dismiss(animated: true, completion: nil) }).catch(execute: { e in self.delegate?.createError(error: e) print(e.localizedDescription) let f = e as! WrappedError switch (f) { case .ResponseError(let d): self.showAlert(title: "Card Creation Processing Error", message: ErrorUtils.convertErrorArrayToString(values: d.errors)) } self.showActivityIndicator(isShown: false) })*/ let cardNumber = self.cardNumberTextField!.text! if (self.isDummy ?? false) { self.delegate?.created(card: SimpleTransactionToken(id: UUID().uuidString, type: TransactionTokenType.recurring, cardholder: self.cardHolderNameTextField!.text!, expMonth: Int(self.expiryMonthTextField!.text!)!, expYear: Int(self.expiryYearTextField!.text!)!, lastFour: cardNumber.substring(from: cardNumber.index(cardNumber.endIndex, offsetBy: -4)), brand: self.cardBrand ?? "visa")) self.dismiss(animated: true, completion: nil) self.navigationController?.popViewController(animated: true) } else { let type: TransactionTokenType = TransactionTokenType.recurring let usageLimit: String = transactionTokenTypeList[2].first!.value let cardData = TransactionTokenCardRequestData(cardholder: self.cardHolderNameTextField!.text!, cardNumber: self.cardNumberTextField!.text!, expMonth: self.expiryMonthTextField!.text!, expYear: self.expiryYearTextField!.text!, cvv: self.cvvTextField!.text!) let requestData = TransactionTokenCreateRequestData(paymentType: "card", email: self.emailTextField!.text!, type: type, usageLimit: usageLimit, data: cardData) self.createTransactionToken(createParams: requestData).then(execute: { t -> Void in let cd = t.data as! TransactionTokenCardData let simpleToken = SimpleTransactionToken(id: t.id, type: t.type, cardholder: cd.cardholder, expMonth: cd.expMonth, expYear: cd.expYear, lastFour: cd.lastFour, brand: cd.brand) self.delegate?.created(card: simpleToken) self.showActivityIndicator(isShown: false) self.dismiss(animated: true, completion: nil) }).catch(execute: { e in self.delegate?.createError(error: e) print(e.localizedDescription) let f = e as! WrappedError switch (f) { case .ResponseError(let d): self.showAlert(title: "Transaction Token Processing Error", message: ErrorUtils.convertErrorArrayToString(values: d.errors)) } self.showActivityIndicator(isShown: false) }) } } @IBAction func cardNumberChanged(_ sender: UITextField) { self.setCardStateAndImage() } func getCardImage(forState cardState: CardState) -> UIImage? { switch cardState { case .identified(let cardType): switch cardType { case .amex: return UIImage(named: "amex", in: self.getBundle(), compatibleWith: nil) case .diners: return UIImage(named: "diners_club", in: self.getBundle(), compatibleWith: nil) case .discover: return UIImage(named: "discover", in: self.getBundle(), compatibleWith: nil) case .jcb: return UIImage(named: "jcb", in: self.getBundle(), compatibleWith: nil) case .masterCard: return UIImage(named: "mastercard", in: self.getBundle(), compatibleWith: nil) case .unionPay: return UIImage(named: "union_pay", in: self.getBundle(), compatibleWith: nil) case .visa: return UIImage(named: "visa", in: self.getBundle(), compatibleWith: nil) } case .indeterminate: return UIImage(named: "credit_card", in: self.getBundle(), compatibleWith: nil) case .invalid: return UIImage(named: "credit_card", in: self.getBundle(), compatibleWith: nil) } } func getCardBrand(forState cardState: CardState) -> String? { switch cardState { case .identified(let cardType): switch cardType { case .amex: return "amex" case .diners: return "diners" case .discover: return "discover" case .jcb: return "jcb" case .masterCard: return "master_card" case .unionPay: return "union_pay" case .visa: return "visa" } case .indeterminate: return "unknown" case .invalid: return nil } } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.customTitle = "Other Card Details" } convenience public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, sdkOptions: Options, customerId: String, customTitle: String?, isDummy: Bool?, cardNumber: String?) { self.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.sdkOptions = sdkOptions self.sdk = SDK(options: sdkOptions) self.customerId = customerId self.isDummy = isDummy if let ct = customTitle { self.customTitle = ct } self.cardNumber = cardNumber } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // self.navigationBar!.topItem?.title = self.customTitle self.cardImage!.image = UIImage(named: "credit_card", in: self.getBundle(), compatibleWith: nil) self.cardNumberTextField?.returnKeyType = UIReturnKeyType.done self.cardHolderNameTextField?.returnKeyType = UIReturnKeyType.done self.expiryMonthTextField?.returnKeyType = UIReturnKeyType.done self.expiryYearTextField?.returnKeyType = UIReturnKeyType.done self.cvvTextField?.returnKeyType = UIReturnKeyType.done // Load the card number if any self.cardNumberTextField?.text = self.cardNumber self.setCardStateAndImage() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationBar?.isHidden = false self.navigationBar?.topItem?.title = self.customTitle self.title = self.customTitle self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(handleDoneClick)) } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) //This will hide the keyboard } public func textFieldDidEndEditing(_ textField: UITextField) { textField.resignFirstResponder() } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func showAlert(title: String, message: String) -> Void { let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alertController, animated: true, completion: nil) } func showActivityIndicator(isShown: Bool) -> Void { if (isShown) { activityIndicator?.startAnimating() } else { activityIndicator?.stopAnimating() } } func getBundle() -> Bundle? { let bundleURL = self.nibBundle!.resourceURL?.appendingPathComponent(bundleName) return Bundle(url: bundleURL!) } func createTransactionToken(createParams: TransactionTokenCreateRequestData) -> Promise<TransactionToken> { return self.sdk!.transactionTokenResource!.create(data: createParams, callback: nil) } func setCardStateAndImage() -> Void { let cs = CardState(fromPrefix: self.cardNumberTextField!.text!) self.cardBrand = getCardBrand(forState: cs) self.cardImage!.image = self.getCardImage(forState: cs) } /* // 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. } */ }
mit
radex/swift-compiler-crashes
crashes-fuzzing/22977-swift-mangle-mangler-mangletype.swift
11
213
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<T where B:a{let c{""[1 func let d=a
mit
radex/swift-compiler-crashes
crashes-duplicates/15794-swift-parser-skipsingle.swift
11
292
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum b { var b { { case { protocol c { struct A { class case , let { { { { { { { [ [ [ [ { ( { { { { { { { { { { { { { d )
mit
radex/swift-compiler-crashes
crashes-fuzzing/08293-swift-typebase-isequal.swift
11
254
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import CoreData func a { var d[] var d{ class B{ protocol b{ { } func a typealias e:a
mit
moldedbits/firebase-chat-example
Firebase-Chat-Research/Constants.swift
1
465
// // Constants.swift // Firebase-Chat-Research // // Created by Amit kumar Swami on 18/03/16. // Copyright © 2016 moldedbits. All rights reserved. // import Foundation struct Constants { static let FIREBASE_BASE_URL = "https://unlazechatresearch.firebaseio.com" static let BASE_URL = "https://floating-depths-76594.herokuapp.com" } struct StoryBoardIdentifier { static let showChats = "showChats" static let showMessages = "showMessages" }
mit
sabarishsekar/MyLogging
MyLogging/MainViewController.swift
1
2036
// // MainViewController.swift // MyLogging // // Created by Sabarish on 9/15/17. // Copyright © 2017 IBM. All rights reserved. // import UIKit @objc public protocol LoginDelegate: class { func submitBtnTapped() } public class MainViewController: UIViewController { @IBOutlet public weak var companyName: UILabel! @IBOutlet public weak var userName: UILabel! @IBOutlet public weak var password: UILabel! @IBOutlet public weak var usernameTextField: UITextField! @IBOutlet public weak var passwordTextField: UITextField! @IBOutlet weak var btnSubmit: UIButton! public weak var delegate: LoginDelegate? public override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. print("MainViewController: viewDidLoad method executed...") } public override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // public class func createLoginViewControllerWithDelegate(dgt: LoginDelegate) -> MainViewController { // let frameworkBundle = Bundle(identifier: "com.ibm.mylogging.login") // let frameworkStoryboard = UIStoryboard(name: "Login", bundle: frameworkBundle) // let loginVC: MainViewController? = frameworkStoryboard.instantiateViewController(withIdentifier: "mainViewController") as? MainViewController // loginVC?.delegate = dgt // return loginVC! // } @IBAction func btnSubmitEvent(_ sender: Any) { print("Submit btn tapped") self.delegate?.submitBtnTapped() } /* // 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. } */ }
mit