repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lancy98/HamburgerMenu | refs/heads/master | HamburgerMenu/HamburgerMenu/SlideMenuViewController.swift | mit | 1 | //
// SlideMenuViewController.swift
// DynamicTrayDemo
//
// Created by Lancy on 27/05/15.
// Copyright (c) 2015 Lancy. All rights reserved.
//
import UIKit
protocol DynamicTrayMenuDataSource : class {
func trayViewController() -> UIViewController
func mainViewController() -> UIViewController
}
class SlideMenuViewController: UIViewController {
weak var dataSource: DynamicTrayMenuDataSource? {
didSet {
if let inDataSource = dataSource {
let mainVC = inDataSource.mainViewController()
mainViewController = mainVC
addViewController(mainVC, toView: view)
view.sendSubviewToBack(mainVC.view)
if let tView = trayView {
let trayVC = inDataSource.trayViewController()
trayViewController = trayVC
addViewController(trayVC, toView: trayView!)
}
}
}
}
private var trayViewController: UIViewController?
private var mainViewController: UIViewController?
private var trayView: UIVisualEffectView?
private var trayLeftEdgeConstraint: NSLayoutConstraint?
private var animator: UIDynamicAnimator?
private var gravity: UIGravityBehavior?
private var attachment: UIAttachmentBehavior?
private let widthFactor = CGFloat(0.4) // 40% width of the view
private let minThresholdFactor = CGFloat(0.2)
private var overlayView: UIView?
private var trayWidth: CGFloat {
return CGFloat(view.frame.width * widthFactor);
}
private var isGravityRight = false
// check if the hamburger menu is being showed
var isShowingTray: Bool {
return isGravityRight
}
func showTray() {
tray(true)
}
func hideTray() {
tray(false)
}
func updateMainViewController(viewController: UIViewController) {
if let mainVC = mainViewController {
mainVC.willMoveToParentViewController(nil)
mainVC.view.removeFromSuperview()
mainVC.removeFromParentViewController()
}
addViewController(viewController, toView: view)
}
private func tray(show: Bool) {
let pushBehavior = UIPushBehavior(items: [trayView!], mode: .Instantaneous)
pushBehavior.angle = show ? CGFloat(M_PI) : 0
pushBehavior.magnitude = UI_USER_INTERFACE_IDIOM() == .Pad ? 1500 : 200
isGravityRight = show
upadateGravity(isGravityRight)
animator!.addBehavior(pushBehavior);
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
setUpTrayView()
setUpGestureRecognizers()
animator = UIDynamicAnimator(referenceView: view)
setUpBehaviors()
if trayViewController == nil && dataSource != nil {
let trayVC = dataSource!.trayViewController()
trayViewController = trayVC
addViewController(trayVC, toView: trayView!)
}
}
private func addViewController(viewController: UIViewController, toView: UIView) {
addChildViewController(viewController)
viewController.view.setTranslatesAutoresizingMaskIntoConstraints(false)
toView.addSubview(viewController.view)
viewController.didMoveToParentViewController(self)
toView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options:
NSLayoutFormatOptions(0), metrics: nil, views: ["view": viewController.view]))
toView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options:
NSLayoutFormatOptions(0), metrics: nil, views: ["view": viewController.view]))
}
private func setUpBehaviors() {
// Collision behaviour
let collisionBehavior = UICollisionBehavior(items: [trayView!])
let rightInset = view.frame.width - trayWidth
let edgeInset = UIEdgeInsetsMake(0, -trayWidth, 0, rightInset)
collisionBehavior.setTranslatesReferenceBoundsIntoBoundaryWithInsets(edgeInset)
animator!.addBehavior(collisionBehavior)
// Gravity behaviour
gravity = UIGravityBehavior(items: [trayView!])
animator!.addBehavior(gravity)
upadateGravity(isGravityRight)
}
private func upadateGravity(isRight: Bool) {
let angle = isRight ? 0 : M_PI
gravity!.setAngle(CGFloat(angle), magnitude: 1.0)
// Add the overlay if gravity is right
if isRight {
addOverlayView()
} else {
removeOverlayView()
}
}
private func addOverlayView() {
if overlayView == nil {
// Create overlay view.
overlayView = UIView.new()
overlayView!.backgroundColor = UIColor.blackColor()
overlayView!.alpha = 0.0
overlayView!.setTranslatesAutoresizingMaskIntoConstraints(false)
mainViewController!.view.addSubview(overlayView!)
// Fill the parent.
mainViewController!.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options:
NSLayoutFormatOptions(0), metrics: nil, views: ["view": overlayView!]))
mainViewController!.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options:
NSLayoutFormatOptions(0), metrics: nil, views: ["view": overlayView!]))
// Add Tap Gesture
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("overlayTapped:"))
overlayView!.addGestureRecognizer(tapGesture)
// animate with alpha
UIView.animateWithDuration(0.4) {
self.overlayView!.alpha = 0.4
}
}
}
private func removeOverlayView() {
if overlayView != nil {
UIView.animateWithDuration(0.4, animations: {
self.overlayView!.alpha = 0.0
}, completion: { completed in
self.overlayView!.removeFromSuperview()
self.overlayView = nil
})
}
}
func overlayTapped(tapGesture: UITapGestureRecognizer) {
tray(false) // hide the tray.
}
private func setUpTrayView() {
// Adding blur view
let blurEffect = UIBlurEffect(style: .ExtraLight)
trayView = UIVisualEffectView(effect: blurEffect)
trayView!.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(trayView!)
// Add constraints to blur view
view.addConstraint(NSLayoutConstraint(item: trayView!, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 0.4, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: trayView!, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: trayView!, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 0.0))
trayLeftEdgeConstraint = NSLayoutConstraint(item: trayView!, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1.0, constant:-trayWidth)
view.addConstraint(trayLeftEdgeConstraint!)
view.layoutIfNeeded()
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
private func setUpGestureRecognizers() {
// Edge pan.
let edgePan = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("pan:"))
edgePan.edges = .Left
view.addGestureRecognizer(edgePan)
// Pan.
let pan = UIPanGestureRecognizer (target: self, action: Selector("pan:"))
trayView!.addGestureRecognizer(pan)
}
func pan(gesture: UIPanGestureRecognizer) {
let currentPoint = gesture.locationInView(view)
let xOnlyPoint = CGPointMake(currentPoint.x, view.center.y)
switch(gesture.state) {
case .Began:
attachment = UIAttachmentBehavior(item: trayView!, attachedToAnchor: xOnlyPoint)
animator!.addBehavior(attachment)
case .Changed:
attachment!.anchorPoint = xOnlyPoint
case .Cancelled, .Ended:
animator!.removeBehavior(attachment)
attachment = nil
let velocity = gesture.velocityInView(view)
let velocityThreshold = CGFloat(500)
if abs(velocity.x) > velocityThreshold {
isGravityRight = velocity.x > 0
upadateGravity(isGravityRight)
} else {
isGravityRight = (trayView!.frame.origin.x + trayView!.frame.width) > (view.frame.width * minThresholdFactor)
upadateGravity(isGravityRight)
}
default:
if attachment != nil {
animator!.removeBehavior(attachment)
attachment = nil
}
}
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
animator!.removeAllBehaviors()
if (trayView!.frame.origin.x + trayView!.frame.width) > (view.center.x * minThresholdFactor) {
trayLeftEdgeConstraint?.constant = 0
isGravityRight = true
} else {
trayLeftEdgeConstraint?.constant = -(size.width * widthFactor)
isGravityRight = false
}
coordinator.animateAlongsideTransition({ context in
self.view.layoutIfNeeded()
}, completion: { context in
self.setUpBehaviors()
})
}
} | a792d8f919bec31174c01d99b257ab06 | 35.476534 | 175 | 0.619915 | false | false | false | false |
chitaranjan/Album | refs/heads/master | DKImagePickerController/DKImageResource.swift | apache-2.0 | 5 | //
// DKImageResource.swift
// DKImagePickerController
//
// Created by ZhangAo on 15/8/11.
// Copyright (c) 2015年 ZhangAo. All rights reserved.
//
import UIKit
public extension Bundle {
class func imagePickerControllerBundle() -> Bundle {
let assetPath = Bundle(for: DKImageResource.self).resourcePath!
return Bundle(path: (assetPath as NSString).appendingPathComponent("DKImagePickerController.bundle"))!
}
}
public class DKImageResource {
private class func imageForResource(_ name: String) -> UIImage {
let bundle = Bundle.imagePickerControllerBundle()
let imagePath = bundle.path(forResource: name, ofType: "png", inDirectory: "Images")
let image = UIImage(contentsOfFile: imagePath!)
return image!
}
private class func stretchImgFromMiddle(_ image: UIImage) -> UIImage {
let centerX = image.size.width / 2
let centerY = image.size.height / 2
return image.resizableImage(withCapInsets: UIEdgeInsets(top: centerY, left: centerX, bottom: centerY, right: centerX))
}
class func checkedImage() -> UIImage {
return stretchImgFromMiddle(imageForResource("checked_background"))
}
class func blueTickImage() -> UIImage {
return imageForResource("tick_blue")
}
class func cameraImage() -> UIImage {
return imageForResource("camera")
}
class func videoCameraIcon() -> UIImage {
return imageForResource("video_camera")
}
class func emptyAlbumIcon() -> UIImage {
return stretchImgFromMiddle(imageForResource("empty_album"))
}
}
public class DKImageLocalizedString {
public class func localizedStringForKey(_ key: String) -> String {
return NSLocalizedString(key, tableName: "DKImagePickerController", bundle:Bundle.imagePickerControllerBundle(), value: "", comment: "")
}
}
public func DKImageLocalizedStringWithKey(_ key: String) -> String {
return DKImageLocalizedString.localizedStringForKey(key)
}
| be914c2e232c18a2d9fab697026981fe | 28.5 | 144 | 0.694915 | false | false | false | false |
zorn/RGBWell | refs/heads/master | RGBWell/MainWindowController.swift | mit | 1 | import Cocoa
class MainWindowController: NSWindowController {
@IBOutlet weak var redSlider: NSSlider!
@IBOutlet weak var greenSlider: NSSlider!
@IBOutlet weak var blueSlider: NSSlider!
@IBOutlet weak var colorWell: NSColorWell!
var red = 0.0
var green = 0.0
var blue = 0.0
var alpha = 1.0
override func windowDidLoad() {
super.windowDidLoad()
redSlider.doubleValue = red
greenSlider.doubleValue = green
blueSlider.doubleValue = blue
updateColor()
}
override var windowNibName: String? {
return "MainWindowController"
}
@IBAction func adjustRed(sender: NSSlider) {
println("R slider's value \(sender.doubleValue)")
red = sender.doubleValue
updateColor()
}
@IBAction func adjustGreen(sender: NSSlider) {
println("G slider's value \(sender.doubleValue)")
green = sender.doubleValue
updateColor()
}
@IBAction func adjustBlue(sender: NSSlider) {
println("B slider's value \(sender.doubleValue)")
blue = sender.doubleValue
updateColor()
}
func updateColor() {
let newColor = NSColor(calibratedRed: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha))
colorWell.color = newColor
}
}
| dfc6a090511fd2d61ca9dbaa82e06c3f | 26.32 | 126 | 0.623719 | false | false | false | false |
darina/omim | refs/heads/master | iphone/Maps/UI/Ads/RemoveAdsViewController.swift | apache-2.0 | 4 | import SafariServices
@objc protocol RemoveAdsViewControllerDelegate: AnyObject {
func didCompleteSubscribtion(_ viewController: RemoveAdsViewController)
func didCancelSubscribtion(_ viewController: RemoveAdsViewController)
}
@objc class RemoveAdsViewController: MWMViewController {
typealias VC = RemoveAdsViewController
private let transitioning = FadeTransitioning<RemoveAdsPresentationController>()
@IBOutlet weak var loadingView: UIView!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView! {
didSet {
loadingIndicator.color = .blackPrimaryText()
}
}
@IBOutlet weak var payButton: UIButton!
@IBOutlet weak var monthButton: UIButton!
@IBOutlet weak var weekButton: UIButton!
@IBOutlet weak var whySupportButton: UIButton!
@IBOutlet weak var saveLabel: UILabel!
@IBOutlet weak var productsLoadingIndicator: UIActivityIndicatorView!
@IBOutlet weak var whySupportView: UIView!
@IBOutlet weak var optionsView: UIView!
@IBOutlet weak var moreOptionsButton: UIButton! {
didSet {
moreOptionsButton.setTitle(L("options_dropdown_title").uppercased(), for: .normal)
}
}
@IBOutlet weak var moreOptionsButtonImage: UIImageView!
@IBOutlet weak var titleLabel: UILabel! {
didSet {
titleLabel.text = L("remove_ads_title").uppercased()
}
}
@IBOutlet weak var whySupportLabel: UILabel! {
didSet {
whySupportLabel.text = L("why_support").uppercased()
}
}
@IBOutlet weak var optionsHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var whySupportConstraint: NSLayoutConstraint!
@objc weak var delegate: RemoveAdsViewControllerDelegate?
var subscriptions: [ISubscription]?
private static func formatPrice(_ price: NSDecimalNumber?, locale: Locale?) -> String {
guard let price = price else { return "" }
guard let locale = locale else { return "\(price)" }
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = locale
return formatter.string(from: price) ?? ""
}
private static func calculateDiscount(_ price: NSDecimalNumber?,
weeklyPrice: NSDecimalNumber?,
period: SubscriptionPeriod) -> NSDecimalNumber? {
guard let price = price, let weeklyPrice = weeklyPrice else { return nil }
switch period {
case .week:
return 0
case .month:
return weeklyPrice.multiplying(by: 52).subtracting(price.multiplying(by: 12))
case .year:
return weeklyPrice.multiplying(by: 52).subtracting(price)
case .unknown:
return nil
}
}
override func viewDidLoad() {
super.viewDidLoad()
InAppPurchase.adsRemovalSubscriptionManager.addListener(self)
InAppPurchase.adsRemovalSubscriptionManager.getAvailableSubscriptions { subscriptions, error in
self.subscriptions = subscriptions
self.productsLoadingIndicator.stopAnimating()
guard let subscriptions = subscriptions else {
MWMAlertViewController.activeAlert().presentInfoAlert(L("bookmarks_convert_error_title"), text: L("purchase_error_subtitle"))
self.delegate?.didCancelSubscribtion(self)
return
}
self.saveLabel.isHidden = false
self.optionsView.isHidden = false
self.payButton.isEnabled = true
assert(subscriptions.count == 3)
let weeklyPrice = subscriptions[0].price
let monthlyPrice = subscriptions[1].price
let yearlyPrice = subscriptions[2].price
let yearlyDiscount = VC.calculateDiscount(yearlyPrice,
weeklyPrice: weeklyPrice,
period: subscriptions[2].period)
let monthlyDiscount = VC.calculateDiscount(monthlyPrice,
weeklyPrice: weeklyPrice,
period: subscriptions[1].period)
let locale = subscriptions[0].priceLocale
self.payButton.setTitle(String(coreFormat: L("paybtn_title"),
arguments: [VC.formatPrice(yearlyPrice, locale: locale)]), for: .normal)
self.saveLabel.text = String(coreFormat: L("paybtn_subtitle"),
arguments: [VC.formatPrice(yearlyDiscount, locale: locale)])
self.monthButton.setTitle(String(coreFormat: L("options_dropdown_item1"),
arguments: [VC.formatPrice(monthlyPrice, locale: locale),
VC.formatPrice(monthlyDiscount, locale: locale)]), for: .normal)
self.weekButton.setTitle(String(coreFormat: L("options_dropdown_item2"),
arguments: [VC.formatPrice(weeklyPrice, locale: locale)]), for: .normal)
Statistics.logEvent(kStatInappShow, withParameters: [kStatVendor: MWMPurchaseManager.adsRemovalVendorId(),
kStatProduct: subscriptions[2].productId,
kStatPurchase: MWMPurchaseManager.adsRemovalServerId(),
kStatInappTrial: false],
with: .realtime)
}
}
override var prefersStatusBarHidden: Bool {
return true
}
deinit {
InAppPurchase.adsRemovalSubscriptionManager.removeListener(self)
}
@IBAction func onClose(_ sender: Any) {
Statistics.logEvent(kStatInappCancel, withParameters: [kStatPurchase: MWMPurchaseManager.adsRemovalServerId()])
delegate?.didCancelSubscribtion(self)
}
@IBAction func onPay(_ sender: UIButton) {
subscribe(subscriptions?[2])
}
@IBAction func onMonth(_ sender: UIButton) {
subscribe(subscriptions?[1])
}
@IBAction func onWeek(_ sender: UIButton) {
subscribe(subscriptions?[0])
}
@IBAction func onMoreOptions(_ sender: UIButton) {
view.layoutIfNeeded()
UIView.animate(withDuration: kDefaultAnimationDuration) {
self.moreOptionsButtonImage.transform = CGAffineTransform(rotationAngle: -CGFloat.pi + 0.01)
self.optionsHeightConstraint.constant = 109
self.view.layoutIfNeeded()
}
}
@IBAction func onWhySupport(_ sender: UIButton) {
whySupportView.isHidden = false
whySupportView.alpha = 0
whySupportConstraint.priority = .defaultHigh
UIView.animate(withDuration: kDefaultAnimationDuration) {
self.whySupportView.alpha = 1
self.whySupportButton.alpha = 0
}
}
@IBAction func onTerms(_ sender: UIButton) {
guard let url = URL(string: User.termsOfUseLink()) else { return }
let safari = SFSafariViewController(url: url)
present(safari, animated: true, completion: nil)
}
@IBAction func onPrivacy(_ sender: UIButton) {
guard let url = URL(string: User.privacyPolicyLink()) else { return }
let safari = SFSafariViewController(url: url)
present(safari, animated: true, completion: nil)
}
private func subscribe(_ subscription: ISubscription?) {
guard let subscription = subscription else {
MWMAlertViewController.activeAlert().presentInfoAlert(L("bookmarks_convert_error_title"),
text: L("purchase_error_subtitle"))
delegate?.didCancelSubscribtion(self)
return
}
Statistics.logEvent(kStatInappSelect, withParameters: [kStatProduct: subscription.productId,
kStatPurchase: MWMPurchaseManager.adsRemovalServerId(),
kStatInappTrial: false])
Statistics.logEvent(kStatInappPay, withParameters: [kStatPurchase: MWMPurchaseManager.adsRemovalServerId(),
kStatInappTrial: false],
with: .realtime)
showPurchaseProgress()
InAppPurchase.adsRemovalSubscriptionManager.subscribe(to: subscription)
}
private func showPurchaseProgress() {
loadingView.isHidden = false
loadingView.alpha = 0
UIView.animate(withDuration: kDefaultAnimationDuration) {
self.loadingView.alpha = 1
}
}
private func hidePurchaseProgress() {
UIView.animate(withDuration: kDefaultAnimationDuration, animations: {
self.loadingView.alpha = 0
}) { _ in
self.loadingView.isHidden = true
}
}
override var transitioningDelegate: UIViewControllerTransitioningDelegate? {
get { return transitioning }
set {}
}
override var modalPresentationStyle: UIModalPresentationStyle {
get { return .custom }
set {}
}
}
extension RemoveAdsViewController: SubscriptionManagerListener {
func didFailToValidate() {}
func didValidate(_ isValid: Bool) {}
func didSubscribe(_ subscription: ISubscription) {
MWMPurchaseManager.setAdsDisabled(true)
hidePurchaseProgress()
delegate?.didCompleteSubscribtion(self)
}
func didDefer(_ subscription: ISubscription) {
hidePurchaseProgress()
delegate?.didCompleteSubscribtion(self)
}
func didFailToSubscribe(_ subscription: ISubscription, error: Error?) {
if let error = error as NSError?, error.code != SKError.paymentCancelled.rawValue {
MWMAlertViewController.activeAlert().presentInfoAlert(L("bookmarks_convert_error_title"),
text: L("purchase_error_subtitle"))
}
hidePurchaseProgress()
}
}
| ba1a9b9a7dabdafcd4e853262c1a0247 | 37.360324 | 133 | 0.659103 | false | false | false | false |
cliqz-oss/browser-ios | refs/heads/development | ClientTests/MockProfile.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@testable import Client
import Foundation
import Account
import ReadingList
import Shared
import Storage
import Sync
import XCTest
import Deferred
public class MockSyncManager: SyncManager {
public var isSyncing = false
public var lastSyncFinishTime: Timestamp? = nil
public var syncDisplayState: SyncDisplayState?
public func hasSyncedHistory() -> Deferred<Maybe<Bool>> {
return deferMaybe(true)
}
public func syncClients() -> SyncResult { return deferMaybe(.Completed) }
public func syncClientsThenTabs() -> SyncResult { return deferMaybe(.Completed) }
public func syncHistory() -> SyncResult { return deferMaybe(.Completed) }
public func syncLogins() -> SyncResult { return deferMaybe(.Completed) }
public func syncEverything() -> Success {
return succeed()
}
public func beginTimedSyncs() {}
public func endTimedSyncs() {}
public func applicationDidBecomeActive() {
self.beginTimedSyncs()
}
public func applicationDidEnterBackground() {
self.endTimedSyncs()
}
public func onNewProfile() {
}
public func onAddedAccount() -> Success {
return succeed()
}
public func onRemovedAccount(account: FirefoxAccount?) -> Success {
return succeed()
}
public func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
return deferMaybe(true)
}
}
public class MockTabQueue: TabQueue {
public func addToQueue(tab: ShareItem) -> Success {
return succeed()
}
public func getQueuedTabs() -> Deferred<Maybe<Cursor<ShareItem>>> {
return deferMaybe(ArrayCursor<ShareItem>(data: []))
}
public func clearQueuedTabs() -> Success {
return succeed()
}
}
public class MockProfile: Profile {
private let name: String = "mockaccount"
func localName() -> String {
return name
}
func shutdown() {
}
private var dbCreated = false
lazy var db: BrowserDB = {
self.dbCreated = true
return BrowserDB(filename: "mock.db", files: self.files)
}()
/**
* Favicons, history, and bookmarks are all stored in one intermeshed
* collection of tables.
*/
// Cliqz: added ExtendedBrowserHistory protocol to history to get extra data for telemetry signals
private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory, ResettableSyncStorage, ExtendedBrowserHistory> = {
return SQLiteHistory(db: self.db, prefs: MockProfilePrefs())
}()
var favicons: Favicons {
return self.places
}
lazy var queue: TabQueue = {
return MockTabQueue()
}()
// Cliqz: added ExtendedBrowserHistory protocol to history to get extra data for telemetry signals
var history: protocol<BrowserHistory, SyncableHistory, ResettableSyncStorage, ExtendedBrowserHistory> {
return self.places
}
lazy var syncManager: SyncManager = {
return MockSyncManager()
}()
lazy var certStore: CertStore = {
return CertStore()
}()
lazy var bookmarks: protocol<BookmarksModelFactorySource, SyncableBookmarks, LocalItemSource, MirrorItemSource, ShareToDestination> = {
// Make sure the rest of our tables are initialized before we try to read them!
// This expression is for side-effects only.
let p = self.places
return MergedSQLiteBookmarks(db: self.db)
}()
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs, files: self.files)
}()
lazy var prefs: Prefs = {
return MockProfilePrefs()
}()
lazy var files: FileAccessor = {
return ProfileFileAccessor(profile: self)
}()
lazy var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath as String)
}()
lazy var recentlyClosedTabs: ClosedTabsStore = {
return ClosedTabsStore(prefs: self.prefs)
}()
internal lazy var remoteClientsAndTabs: RemoteClientsAndTabs = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
private lazy var syncCommands: SyncCommands = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
lazy var logins: protocol<BrowserLogins, SyncableLogins, ResettableSyncStorage> = {
return MockLogins(files: self.files)
}()
let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration()
var account: FirefoxAccount? = nil
func hasAccount() -> Bool {
return account != nil
}
func hasSyncableAccount() -> Bool {
return account?.actionNeeded == FxAActionNeeded.none
}
func getAccount() -> FirefoxAccount? {
return account
}
func setAccount(account: FirefoxAccount) {
self.account = account
self.syncManager.onAddedAccount()
}
func removeAccount() {
let old = self.account
self.account = nil
self.syncManager.onRemovedAccount(old)
}
func getClients() -> Deferred<Maybe<[RemoteClient]>> {
return deferMaybe([])
}
func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return deferMaybe([])
}
func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return deferMaybe([])
}
func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return deferMaybe(0)
}
func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) {
}
}
| dabb925c58c2eaa3bdb6bbdaae3fec3f | 27.575 | 139 | 0.665267 | false | false | false | false |
akisute/ParaMangar | refs/heads/master | ParaMangar/Sample3ViewController.swift | mit | 1 | //
// Sample3ViewController.swift
// ParaMangar
//
// Created by Ono Masashi on 2015/03/11.
// Copyright (c) 2015年 akisute. All rights reserved.
//
import UIKit
import ParaMangarLib
class Sample3ViewController: UIViewController {
@IBOutlet var targetView: UIView!
@IBOutlet var animatingView: UIView!
@IBOutlet var imageView: UIImageView!
@IBOutlet var render1SecButton: UIButton!
var animator: ParaMangar?
@IBAction func onRender1SecButton(sender: UIButton) {
let duration = 1.0
self.animator = ParaMangar.renderViewForDuration(self.targetView, duration: duration, block: {
UIView.animateWithDuration(duration/2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.allZeros, animations: { () -> Void in
self.animatingView.transform = CGAffineTransformMakeScale(2.0, 2.0)
}, completion: nil)
UIView.animateWithDuration(duration/2, delay: duration/2, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.allZeros, animations: { () -> Void in
self.animatingView.transform = CGAffineTransformIdentity
}, completion: nil)
}).toImage(duration, completion: { image in
self.animator = nil
self.render1SecButton.setTitle("Completed!", forState: UIControlState.Normal)
self.imageView.image = image
})
}
}
| 94ebef68c1051b51d5aea20faf6650e9 | 39.135135 | 196 | 0.680808 | false | false | false | false |
e78l/swift-corelibs-foundation | refs/heads/master | Foundation/Measurement.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if DEPLOYMENT_RUNTIME_SWIFT
import CoreFoundation
#else
@_exported import Foundation // Clang module
import _SwiftCoreFoundationOverlayShims
#endif
/// A `Measurement` is a model type that holds a `Double` value associated with a `Unit`.
///
/// Measurements support a large set of operators, including `+`, `-`, `*`, `/`, and a full set of comparison operators.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public struct Measurement<UnitType : Unit> : ReferenceConvertible, Comparable, Equatable {
public typealias ReferenceType = NSMeasurement
/// The unit component of the `Measurement`.
public let unit: UnitType
/// The value component of the `Measurement`.
public var value: Double
/// Create a `Measurement` given a specified value and unit.
public init(value: Double, unit: UnitType) {
self.value = value
self.unit = unit
}
public func hash(into hasher: inout Hasher) {
// Warning: The canonicalization performed here needs to be kept in
// perfect sync with the definition of == below. The floating point
// values that are compared there must match exactly with the values fed
// to the hasher here, or hashing would break.
if let dimension = unit as? Dimension {
// We don't need to feed the base unit to the hasher here; all
// dimensional measurements of the same type share the same unit.
hasher.combine(dimension.converter.baseUnitValue(fromValue: value))
} else {
hasher.combine(unit)
hasher.combine(value)
}
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return "\(value) \(unit.symbol)"
}
public var debugDescription: String {
return "\(value) \(unit.symbol)"
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "value", value: value))
c.append((label: "unit", value: unit.symbol))
return Mirror(self, children: c, displayStyle: .struct)
}
}
/// When a `Measurement` contains a `Dimension` unit, it gains the ability to convert between the kinds of units in that dimension.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement where UnitType : Dimension {
/// Returns a new measurement created by converting to the specified unit.
///
/// - parameter otherUnit: A unit of the same `Dimension`.
/// - returns: A converted measurement.
public func converted(to otherUnit: UnitType) -> Measurement<UnitType> {
if unit.isEqual(otherUnit) {
return Measurement(value: value, unit: otherUnit)
} else {
let valueInTermsOfBase = unit.converter.baseUnitValue(fromValue: value)
if otherUnit.isEqual(type(of: unit).baseUnit()) {
return Measurement(value: valueInTermsOfBase, unit: otherUnit)
} else {
let otherValueFromTermsOfBase = otherUnit.converter.value(fromBaseUnitValue: valueInTermsOfBase)
return Measurement(value: otherValueFromTermsOfBase, unit: otherUnit)
}
}
}
/// Converts the measurement to the specified unit.
///
/// - parameter otherUnit: A unit of the same `Dimension`.
public mutating func convert(to otherUnit: UnitType) {
self = converted(to: otherUnit)
}
/// Add two measurements of the same Dimension.
///
/// If the `unit` of the `lhs` and `rhs` are `isEqual`, then this returns the result of adding the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit.
/// - returns: The result of adding the two measurements.
public static func +(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value + rhs.value, unit: lhs.unit)
} else {
let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value)
return Measurement(value: lhsValueInTermsOfBase + rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit())
}
}
/// Subtract two measurements of the same Dimension.
///
/// If the `unit` of the `lhs` and `rhs` are `==`, then this returns the result of subtracting the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit.
/// - returns: The result of adding the two measurements.
public static func -(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit == rhs.unit {
return Measurement(value: lhs.value - rhs.value, unit: lhs.unit)
} else {
let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value)
return Measurement(value: lhsValueInTermsOfBase - rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit())
}
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement {
/// Add two measurements of the same Unit.
/// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
/// - returns: A measurement of value `lhs.value + rhs.value` and unit `lhs.unit`.
public static func +(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value + rhs.value, unit: lhs.unit)
} else {
fatalError("Attempt to add measurements with non-equal units")
}
}
/// Subtract two measurements of the same Unit.
/// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
/// - returns: A measurement of value `lhs.value - rhs.value` and unit `lhs.unit`.
public static func -(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value - rhs.value, unit: lhs.unit)
} else {
fatalError("Attempt to subtract measurements with non-equal units")
}
}
/// Multiply a measurement by a scalar value.
/// - returns: A measurement of value `lhs.value * rhs` with the same unit as `lhs`.
public static func *(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
return Measurement(value: lhs.value * rhs, unit: lhs.unit)
}
/// Multiply a scalar value by a measurement.
/// - returns: A measurement of value `lhs * rhs.value` with the same unit as `rhs`.
public static func *(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
return Measurement(value: lhs * rhs.value, unit: rhs.unit)
}
/// Divide a measurement by a scalar value.
/// - returns: A measurement of value `lhs.value / rhs` with the same unit as `lhs`.
public static func /(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
return Measurement(value: lhs.value / rhs, unit: lhs.unit)
}
/// Divide a scalar value by a measurement.
/// - returns: A measurement of value `lhs / rhs.value` with the same unit as `rhs`.
public static func /(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
return Measurement(value: lhs / rhs.value, unit: rhs.unit)
}
/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value == rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if the measurements are equal.
public static func ==<LeftHandSideType, RightHandSideType>(_ lhs: Measurement<LeftHandSideType>, _ rhs: Measurement<RightHandSideType>) -> Bool {
// Warning: This defines an equivalence relation that needs to be kept
// in perfect sync with the hash(into:) definition above. The floating
// point values that are fed to the hasher there must match exactly with
// the values compared here, or hashing would break.
if lhs.unit == rhs.unit {
return lhs.value == rhs.value
} else {
if let lhsDimensionalUnit = lhs.unit as? Dimension,
let rhsDimensionalUnit = rhs.unit as? Dimension {
if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() {
let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value)
return lhsValueInTermsOfBase == rhsValueInTermsOfBase
}
}
return false
}
}
/// Compare two measurements of the same `Unit`.
/// - returns: `true` if the measurements can be compared and the `lhs` is less than the `rhs` converted value.
public static func <<LeftHandSideType, RightHandSideType>(lhs: Measurement<LeftHandSideType>, rhs: Measurement<RightHandSideType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value < rhs.value
} else {
if let lhsDimensionalUnit = lhs.unit as? Dimension,
let rhsDimensionalUnit = rhs.unit as? Dimension {
if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() {
let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value)
return lhsValueInTermsOfBase < rhsValueInTermsOfBase
}
}
fatalError("Attempt to compare measurements with non-equal dimensions")
}
}
}
// Implementation note: similar to NSArray, NSDictionary, etc., NSMeasurement's import as an ObjC generic type is suppressed by the importer. Eventually we will need a more general purpose mechanism to correctly import generic types.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSMeasurement {
return NSMeasurement(doubleValue: value, unit: unit)
}
public static func _forceBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) {
result = Measurement(value: source.doubleValue, unit: source.unit as! UnitType)
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) -> Bool {
if let u = source.unit as? UnitType {
result = Measurement(value: source.doubleValue, unit: u)
return true
} else {
return false
}
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSMeasurement?) -> Measurement {
let u = source!.unit as! UnitType
return Measurement(value: source!.doubleValue, unit: u)
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension NSMeasurement : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
#if DEPLOYMENT_RUNTIME_SWIFT
return AnyHashable(Measurement._unconditionallyBridgeFromObjectiveC(self))
#else
return AnyHashable(self as Measurement)
#endif
}
}
// This workaround is required for the time being, because Swift doesn't support covariance for Measurement (26607639)
/* MeasurementFormatter is unavailable:
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension MeasurementFormatter {
public func string<UnitType>(from measurement: Measurement<UnitType>) -> String {
if let result = string(for: measurement) {
return result
} else {
return ""
}
}
}
*/
// @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
// extension Unit : Codable {
// public convenience init(from decoder: Decoder) throws {
// let container = try decoder.singleValueContainer()
// let symbol = try container.decode(String.self)
// self.init(symbol: symbol)
// }
// public func encode(to encoder: Encoder) throws {
// var container = encoder.singleValueContainer()
// try container.encode(self.symbol)
// }
// }
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : Codable {
private enum CodingKeys : Int, CodingKey {
case value
case unit
}
private enum UnitCodingKeys : Int, CodingKey {
case symbol
case converter
}
private enum LinearConverterCodingKeys : Int, CodingKey {
case coefficient
case constant
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let value = try container.decode(Double.self, forKey: .value)
let unitContainer = try container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit)
let symbol = try unitContainer.decode(String.self, forKey: .symbol)
let unit: UnitType
if UnitType.self is Dimension.Type {
let converterContainer = try unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter)
let coefficient = try converterContainer.decode(Double.self, forKey: .coefficient)
let constant = try converterContainer.decode(Double.self, forKey: .constant)
let unitMetaType = (UnitType.self as! Dimension.Type)
unit = (unitMetaType.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient, constant: constant)) as! UnitType)
} else {
unit = UnitType(symbol: symbol)
}
self.init(value: value, unit: unit)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.value, forKey: .value)
var unitContainer = container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit)
try unitContainer.encode(self.unit.symbol, forKey: .symbol)
if UnitType.self is Dimension.Type {
guard type(of: (self.unit as! Dimension).converter) is UnitConverterLinear.Type else {
preconditionFailure("Cannot encode a Measurement whose UnitType has a non-linear unit converter.")
}
let converter = (self.unit as! Dimension).converter as! UnitConverterLinear
var converterContainer = unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter)
try converterContainer.encode(converter.coefficient, forKey: .coefficient)
try converterContainer.encode(converter.constant, forKey: .constant)
}
}
}
| 2f571dcf862eff5d1e901e5bb245ac8c | 45.344828 | 280 | 0.657924 | false | false | false | false |
proversity-org/edx-app-ios | refs/heads/master | Source/OEXAnalytics+AppReview.swift | apache-2.0 | 1 | //
// OEXAnalytics+AppReview.swift
// edX
//
// Created by Danial Zahid on 3/8/17.
// Copyright © 2017 edX. All rights reserved.
//
import UIKit
private let viewRatingDisplayName = "AppReviews: View Rating"
private let dismissRatingDisplayName = "AppReviews: Dismiss Rating"
private let submitRatingDisplayName = "AppReviews: Submit Rating"
private let sendFeedbackDisplayName = "AppReviews: Send Feedback"
private let maybeLaterDisplayName = "AppReviews: Maybe Later"
private let rateTheAppDisplayName = "AppReviews: Rate The App"
extension OEXAnalytics {
private func additionalParams(selectedRating: Int? = nil) -> [String: String] {
var params = [key_app_version : Bundle.main.oex_buildVersionString()]
if let rating = selectedRating{
params[key_rating] = String(rating)
}
return params
}
private func appReviewEvent(name: String, displayName: String) -> OEXAnalyticsEvent {
let event = OEXAnalyticsEvent()
event.name = name
event.displayName = displayName
event.category = AnalyticsCategory.AppReviews.rawValue
return event
}
func trackAppReviewScreen() {
self.trackScreen(withName: AnalyticsScreenName.AppReviews.rawValue, courseID: nil, value: nil, additionalInfo: additionalParams(selectedRating: nil))
self.trackEvent(appReviewEvent(name: AnalyticsEventName.ViewRating.rawValue, displayName: viewRatingDisplayName), forComponent: nil, withInfo: additionalParams())
}
func trackDismissRating() {
self.trackEvent(appReviewEvent(name: AnalyticsEventName.DismissRating.rawValue, displayName: dismissRatingDisplayName), forComponent: nil, withInfo: additionalParams())
}
func trackSubmitRating(rating: Int) {
self.trackEvent(appReviewEvent(name: AnalyticsEventName.SubmitRating.rawValue, displayName: submitRatingDisplayName), forComponent: nil, withInfo: additionalParams(selectedRating: rating))
}
func trackSendFeedback(rating: Int) {
self.trackEvent(appReviewEvent(name: AnalyticsEventName.SendFeedback.rawValue, displayName: sendFeedbackDisplayName), forComponent: nil, withInfo: additionalParams(selectedRating: rating))
}
func trackMaybeLater(rating: Int) {
self.trackEvent(appReviewEvent(name: AnalyticsEventName.MaybeLater.rawValue, displayName: maybeLaterDisplayName), forComponent: nil, withInfo: additionalParams(selectedRating: rating))
}
func trackRateTheApp(rating: Int) {
self.trackEvent(appReviewEvent(name: AnalyticsEventName.RateTheApp.rawValue, displayName: rateTheAppDisplayName), forComponent: nil, withInfo: additionalParams(selectedRating: rating))
}
}
| a3ac026cb5180da2d7c572371809fdc8 | 43.868852 | 196 | 0.739861 | false | false | false | false |
eure/ReceptionApp | refs/heads/master | iOS/ReceptionApp/Screens/ConfirmOtherViewController.swift | mit | 1 | //
// ConfirmOtherViewController.swift
// ReceptionApp
//
// Created by Hiroshi Kimura on 8/27/15.
// Copyright © 2016 eureka, Inc.
//
// 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
// MARK: - ConfirmOtherViewController
final class ConfirmOtherViewController: BaseConfirmViewController {
// MARK: Internal
@IBOutlet private(set) dynamic weak var companyNameView: UIView!
@IBOutlet private(set) dynamic weak var purposeView: UIView!
var transaction: OtherTransaction?
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = Configuration.Color.backgroundColor
self.companyNameView.backgroundColor = Configuration.Color.backgroundColor
self.purposeView.backgroundColor = Configuration.Color.backgroundColor
self.icons.forEach { $0.tintColor = Configuration.Color.imageTintColor }
self.messageLabel.textColor = Configuration.Color.textColor
self.messageLabel.font = Configuration.Font.baseBoldFont(size: 18)
self.messageLabel.text = "ConfirmOtherViewController.label.confirm".l10n
if let visitor = transaction?.visitor {
self.companyNameLabel.attributedText = NSAttributedString.baseAttributedString(
visitor.companyName,
color: Configuration.Color.textColor,
size: 32
)
if visitor.companyName.isEmpty {
self.companyNameHeight.constant = 0
self.companyNameBottom.constant = 0
}
}
self.textView.attributedText = NSAttributedString.baseAttributedString(
self.transaction?.visitor?.purpose ?? "",
color: Configuration.Color.textColor,
size: 36
)
}
// MARK: BaseConfirmViewController
override dynamic func handleSubmitButton(sender: AnyObject) {
guard let transaction = self.transaction else {
return
}
super.handleSubmitButton(sender)
let controller = CompletionViewController.viewControllerFromStoryboard()
Container.VisitorService.sendVisitor(transaction: transaction) { _ in }
self.navigationController?.pushViewController(controller, animated: true)
}
// MARK: Private
@IBOutlet private dynamic weak var companyNameLabel: UILabel!
@IBOutlet private dynamic weak var textView: UITextView!
@IBOutlet private dynamic var icons: [UIImageView]!
@IBOutlet private dynamic weak var companyNameHeight: NSLayoutConstraint!
@IBOutlet private dynamic weak var companyNameBottom: NSLayoutConstraint!
}
| 94f2e0e7ffd2c0ab011adb5c7b368da1 | 35.733333 | 91 | 0.682914 | false | true | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureAuthentication/Sources/FeatureAuthenticationDomain/WalletAuthentication/Services/WalletRecovery/Validation/SeedPhraseValidator.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Foundation
import HDWalletKit
public protocol SeedPhraseValidatorAPI {
func validate(phrase: String) -> AnyPublisher<MnemonicValidationScore, Never>
}
public final class SeedPhraseValidator: SeedPhraseValidatorAPI {
// MARK: - Type
private enum Constant {
static let seedPhraseLength: Int = 12
}
// MARK: - Properties
private let words: Set<String>
// MARK: - Setup
public init(words: Set<String> = Set(WordList.default.words)) {
self.words = words
}
// MARK: - API
public func validate(phrase: String) -> AnyPublisher<MnemonicValidationScore, Never> {
if phrase.isEmpty {
return .just(.none)
}
/// Make an array of the individual words
let components = phrase
.components(separatedBy: .whitespacesAndNewlines)
.filter { !$0.isEmpty }
if components.count < Constant.seedPhraseLength {
return .just(.incomplete)
}
if components.count > Constant.seedPhraseLength {
return .just(.excess)
}
/// Separate out the words that are duplicates
let duplicates = Set(components.duplicates ?? [])
/// The total number of duplicates entered
let duplicatesCount = duplicates
.map { duplicate in
components.filter { $0 == duplicate }.count
}
.reduce(0, +)
/// Make a set for all the individual entries
let set = Set(phrase.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty && !duplicates.contains($0) })
guard !set.isEmpty || duplicatesCount > 0 else {
return .just(.none)
}
/// Are all the words entered thus far valid words
let entriesAreValid = set.isSubset(of: words) && duplicates.isSubset(of: words)
if entriesAreValid {
return .just(.valid)
}
/// Combine the `set` and `duplicates` to form a `Set<String>` of all
/// words that are not included in the `WordList`
let difference = set.union(duplicates).subtracting(words)
/// Find the `NSRange` value for each word or incomplete word that is not
/// included in the `WordList`
let ranges = difference.map { delta -> [NSRange] in
phrase.ranges(of: delta)
}
.flatMap { $0 }
return .just(.invalid(ranges))
}
}
// MARK: - Convenience
extension String {
/// A convenience function for getting an array of `NSRange` values
/// for a particular substring.
fileprivate func ranges(of substring: String) -> [NSRange] {
var ranges: [Range<Index>] = []
enumerateSubstrings(in: startIndex..<endIndex, options: .byWords) { word, value, _, _ in
if let word = word, word == substring {
ranges.append(value)
}
}
return ranges.map { NSRange($0, in: self) }
}
}
extension Array where Element: Hashable {
public var duplicates: [Element]? {
let dictionary = Dictionary(grouping: self, by: { $0 })
let pairs = dictionary.filter { $1.count > 1 }
let duplicates = Array(pairs.keys)
return !duplicates.isEmpty ? duplicates : nil
}
}
| 4e620e870afb8db2611416bbaabf35a0 | 29.472727 | 129 | 0.604415 | false | false | false | false |
AnthonyMDev/BRYXBanner | refs/heads/master | Pod/Classes/Banner.swift | mit | 1 | //
// Banner.swift
//
// Created by Harlan Haskins on 7/27/15.
// Copyright (c) 2015 Bryx. All rights reserved.
//
import UIKit
private enum BannerState {
case Showing, Hidden, Gone
}
/// A level of 'springiness' for Banners.
///
/// - None: The banner will slide in and not bounce.
/// - Slight: The banner will bounce a little.
/// - Heavy: The banner will bounce a lot.
public enum BannerSpringiness {
case None, Slight, Heavy
private var springValues: (damping: CGFloat, velocity: CGFloat) {
switch self {
case .None: return (damping: 1.0, velocity: 1.0)
case .Slight: return (damping: 0.7, velocity: 1.5)
case .Heavy: return (damping: 0.6, velocity: 2.0)
}
}
}
/// Banner is a dropdown notification view that presents above the main view controller, but below the status bar.
public class Banner: UIView {
private class func topWindow() -> UIWindow? {
for window in UIApplication.sharedApplication().windows.reverse() {
if window.windowLevel == UIWindowLevelNormal && !window.hidden && window.frame != CGRectZero { return window }
}
return nil
}
private let contentView = UIView()
private let labelView = UIView()
private let backgroundView = UIView()
/// How long the slide down animation should last.
public var animationDuration: NSTimeInterval = 0.4
/// The preferred style of the status bar during display of the banner. Defaults to `.LightContent`.
///
/// If the banner's `adjustsStatusBarStyle` is false, this property does nothing.
public var preferredStatusBarStyle = UIStatusBarStyle.LightContent
/// Whether or not this banner should adjust the status bar style during its presentation. Defaults to `false`.
public var adjustsStatusBarStyle = false
/// How 'springy' the banner should display. Defaults to `.Slight`
public var springiness = BannerSpringiness.Slight
/// The color of the text as well as the image tint color if `shouldTintImage` is `true`.
public var textColor = UIColor.whiteColor() {
didSet {
resetTintColor()
}
}
/// Whether or not the banner should show a shadow when presented.
public var hasShadows = true {
didSet {
resetShadows()
}
}
/// The color of the background view. Defaults to `nil`.
override public var backgroundColor: UIColor? {
get { return backgroundView.backgroundColor }
set { backgroundView.backgroundColor = newValue }
}
/// The opacity of the background view. Defaults to 0.95.
override public var alpha: CGFloat {
get { return backgroundView.alpha }
set { backgroundView.alpha = newValue }
}
/// A block to call when the uer taps on the banner.
public var didTapBlock: (() -> ())?
/// A block to call after the banner has finished dismissing and is off screen.
public var didDismissBlock: (() -> ())?
/// Whether or not the banner should dismiss itself when the user taps. Defaults to `true`.
public var dismissesOnTap = true
/// Whether or not the banner should dismiss itself when the user swipes up. Defaults to `true`.
public var dismissesOnSwipe = true
/// Whether or not the banner should tint the associated image to the provided `textColor`. Defaults to `true`.
public var shouldTintImage = true {
didSet {
resetTintColor()
}
}
/// The label that displays the banner's title.
public let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
/// The label that displays the banner's subtitle.
public let detailLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
/// The image on the left of the banner.
let image: UIImage?
/// The image view that displays the `image`.
public let imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .ScaleAspectFit
return imageView
}()
private var bannerState = BannerState.Hidden {
didSet {
if bannerState != oldValue {
forceUpdates()
}
}
}
/// A Banner with the provided `title`, `subtitle`, and optional `image`, ready to be presented with `show()`.
///
/// - parameter title: The title of the banner. Optional. Defaults to nil.
/// - parameter subtitle: The subtitle of the banner. Optional. Defaults to nil.
/// - parameter image: The image on the left of the banner. Optional. Defaults to nil.
/// - parameter backgroundColor: The color of the banner's background view. Defaults to `UIColor.blackColor()`.
/// - parameter didTapBlock: An action to be called when the user taps on the banner. Optional. Defaults to `nil`.
public required init(title: String? = nil, subtitle: String? = nil, image: UIImage? = nil, backgroundColor: UIColor = UIColor.blackColor(), didTapBlock: (() -> ())? = nil) {
self.didTapBlock = didTapBlock
self.image = image
super.init(frame: CGRectZero)
resetShadows()
addGestureRecognizers()
initializeSubviews()
resetTintColor()
titleLabel.text = title
detailLabel.text = subtitle
backgroundView.backgroundColor = backgroundColor
backgroundView.alpha = 0.95
}
private func forceUpdates() {
guard let superview = superview, showingConstraint = showingConstraint, hiddenConstraint = hiddenConstraint else { return }
switch bannerState {
case .Hidden:
superview.removeConstraint(showingConstraint)
superview.addConstraint(hiddenConstraint)
case .Showing:
superview.removeConstraint(hiddenConstraint)
superview.addConstraint(showingConstraint)
case .Gone:
superview.removeConstraint(hiddenConstraint)
superview.removeConstraint(showingConstraint)
superview.removeConstraints(commonConstraints)
}
setNeedsLayout()
setNeedsUpdateConstraints()
layoutIfNeeded()
updateConstraintsIfNeeded()
}
internal func didTap(recognizer: UITapGestureRecognizer) {
if dismissesOnTap {
dismiss()
}
didTapBlock?()
}
internal func didSwipe(recognizer: UISwipeGestureRecognizer) {
if dismissesOnSwipe {
dismiss()
}
}
private func addGestureRecognizers() {
addGestureRecognizer(UITapGestureRecognizer(target: self, action: "didTap:"))
let swipe = UISwipeGestureRecognizer(target: self, action: "didSwipe:")
swipe.direction = .Up
addGestureRecognizer(swipe)
}
private func resetTintColor() {
titleLabel.textColor = textColor
detailLabel.textColor = textColor
imageView.image = shouldTintImage ? image?.imageWithRenderingMode(.AlwaysTemplate) : image
imageView.tintColor = shouldTintImage ? textColor : nil
}
private func resetShadows() {
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOpacity = self.hasShadows ? 0.5 : 0.0
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowRadius = 4
}
private var contentTopOffsetConstraint: NSLayoutConstraint!
private var minimumHeightConstraint: NSLayoutConstraint!
private func initializeSubviews() {
let views = [
"backgroundView": backgroundView,
"contentView": contentView,
"imageView": imageView,
"labelView": labelView,
"titleLabel": titleLabel,
"detailLabel": detailLabel
]
translatesAutoresizingMaskIntoConstraints = false
addSubview(backgroundView)
minimumHeightConstraint = backgroundView.constraintWithAttribute(.Height, .GreaterThanOrEqual, to: 80)
addConstraint(minimumHeightConstraint) // Arbitrary, but looks nice.
addConstraints(backgroundView.constraintsEqualToSuperview())
backgroundView.backgroundColor = backgroundColor
backgroundView.addSubview(contentView)
labelView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(labelView)
labelView.addSubview(titleLabel)
labelView.addSubview(detailLabel)
backgroundView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("H:|[contentView]|", views: views))
backgroundView.addConstraint(contentView.constraintWithAttribute(.Bottom, .Equal, to: .Bottom, of: backgroundView))
contentTopOffsetConstraint = contentView.constraintWithAttribute(.Top, .Equal, to: .Top, of: backgroundView)
backgroundView.addConstraint(contentTopOffsetConstraint)
let leftConstraintText: String
if image == nil {
leftConstraintText = "|"
} else {
contentView.addSubview(imageView)
contentView.addConstraint(imageView.constraintWithAttribute(.Leading, .Equal, to: contentView, constant: 15.0))
contentView.addConstraint(imageView.constraintWithAttribute(.CenterY, .Equal, to: contentView))
imageView.addConstraint(imageView.constraintWithAttribute(.Width, .Equal, to: 25.0))
imageView.addConstraint(imageView.constraintWithAttribute(.Height, .Equal, to: .Width))
leftConstraintText = "[imageView]"
}
let constraintFormat = "H:\(leftConstraintText)-(15)-[labelView]-(8)-|"
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat(constraintFormat, views: views))
contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("V:|-(>=1)-[labelView]-(>=1)-|", views: views))
backgroundView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("H:|[contentView]-(<=1)-[labelView]", options: .AlignAllCenterY, views: views))
for view in [titleLabel, detailLabel] {
let constraintFormat = "H:|[label]-(8)-|"
contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat(constraintFormat, options: .DirectionLeadingToTrailing, metrics: nil, views: ["label": view]))
}
labelView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("V:|-(10)-[titleLabel][detailLabel]-(10)-|", views: views))
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var showingConstraint: NSLayoutConstraint?
private var hiddenConstraint: NSLayoutConstraint?
private var commonConstraints = [NSLayoutConstraint]()
override public func didMoveToSuperview() {
super.didMoveToSuperview()
guard let superview = superview where bannerState != .Gone else { return }
commonConstraints = self.constraintsWithAttributes([.Leading, .Trailing], .Equal, to: superview)
superview.addConstraints(commonConstraints)
showingConstraint = self.constraintWithAttribute(.Top, .Equal, to: .Top, of: superview)
let yOffset: CGFloat = -7.0 // Offset the bottom constraint to make room for the shadow to animate off screen.
hiddenConstraint = self.constraintWithAttribute(.Bottom, .Equal, to: .Top, of: superview, constant: yOffset)
}
public override func layoutSubviews() {
super.layoutSubviews()
adjustHeightOffset()
}
private func adjustHeightOffset() {
guard let superview = superview else { return }
if superview === Banner.topWindow() {
let statusBarSize = UIApplication.sharedApplication().statusBarFrame.size
let heightOffset = min(statusBarSize.height, statusBarSize.width) // Arbitrary, but looks nice.
contentTopOffsetConstraint.constant = heightOffset
minimumHeightConstraint.constant = statusBarSize.height > 0 ? 80 : 40
} else {
contentTopOffsetConstraint.constant = 0
minimumHeightConstraint.constant = 0
}
}
/// Shows the banner. If a view is specified, the banner will be displayed at the top of that view, otherwise at top of the top window. If a `duration` is specified, the banner dismisses itself automatically after that duration elapses.
/// - parameter view: A view the banner will be shown in. Optional. Defaults to 'nil', which in turn means it will be shown in the top window. duration A time interval, after which the banner will dismiss itself. Optional. Defaults to `nil`.
public func show(view: UIView? = Banner.topWindow(), duration: NSTimeInterval? = nil) {
guard let view = view else {
print("[Banner]: Could not find view. Aborting.")
return
}
view.addSubview(self)
forceUpdates()
let (damping, velocity) = self.springiness.springValues
let oldStatusBarStyle = UIApplication.sharedApplication().statusBarStyle
if adjustsStatusBarStyle {
UIApplication.sharedApplication().setStatusBarStyle(preferredStatusBarStyle, animated: true)
}
UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .AllowUserInteraction, animations: {
self.bannerState = .Showing
}, completion: { finished in
guard let duration = duration else { return }
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(duration * NSTimeInterval(NSEC_PER_SEC))), dispatch_get_main_queue()) {
self.dismiss(self.adjustsStatusBarStyle ? oldStatusBarStyle : nil)
}
})
}
/// Dismisses the banner.
public func dismiss(oldStatusBarStyle: UIStatusBarStyle? = nil) {
let (damping, velocity) = self.springiness.springValues
UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .AllowUserInteraction, animations: {
self.bannerState = .Hidden
if let oldStatusBarStyle = oldStatusBarStyle {
UIApplication.sharedApplication().setStatusBarStyle(oldStatusBarStyle, animated: true)
}
}, completion: { finished in
self.bannerState = .Gone
self.removeFromSuperview()
self.didDismissBlock?()
})
}
}
extension NSLayoutConstraint {
class func defaultConstraintsWithVisualFormat(format: String, options: NSLayoutFormatOptions = .DirectionLeadingToTrailing, metrics: [String: AnyObject]? = nil, views: [String: AnyObject] = [:]) -> [NSLayoutConstraint] {
return NSLayoutConstraint.constraintsWithVisualFormat(format, options: options, metrics: metrics, views: views)
}
}
extension UIView {
func constraintsEqualToSuperview(edgeInsets: UIEdgeInsets = UIEdgeInsetsZero) -> [NSLayoutConstraint] {
self.translatesAutoresizingMaskIntoConstraints = false
var constraints = [NSLayoutConstraint]()
if let superview = self.superview {
constraints.append(self.constraintWithAttribute(.Leading, .Equal, to: superview, constant: edgeInsets.left))
constraints.append(self.constraintWithAttribute(.Trailing, .Equal, to: superview, constant: edgeInsets.right))
constraints.append(self.constraintWithAttribute(.Top, .Equal, to: superview, constant: edgeInsets.top))
constraints.append(self.constraintWithAttribute(.Bottom, .Equal, to: superview, constant: edgeInsets.bottom))
}
return constraints
}
func constraintWithAttribute(attribute: NSLayoutAttribute, _ relation: NSLayoutRelation, to constant: CGFloat, multiplier: CGFloat = 1.0) -> NSLayoutConstraint {
self.translatesAutoresizingMaskIntoConstraints = false
return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: nil, attribute: .NotAnAttribute, multiplier: multiplier, constant: constant)
}
func constraintWithAttribute(attribute: NSLayoutAttribute, _ relation: NSLayoutRelation, to otherAttribute: NSLayoutAttribute, of item: AnyObject? = nil, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> NSLayoutConstraint {
self.translatesAutoresizingMaskIntoConstraints = false
return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: item ?? self, attribute: otherAttribute, multiplier: multiplier, constant: constant)
}
func constraintWithAttribute(attribute: NSLayoutAttribute, _ relation: NSLayoutRelation, to item: AnyObject, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> NSLayoutConstraint {
self.translatesAutoresizingMaskIntoConstraints = false
return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: item, attribute: attribute, multiplier: multiplier, constant: constant)
}
func constraintsWithAttributes(attributes: [NSLayoutAttribute], _ relation: NSLayoutRelation, to item: AnyObject, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> [NSLayoutConstraint] {
return attributes.map { self.constraintWithAttribute($0, relation, to: item, multiplier: multiplier, constant: constant) }
}
} | 1b3faa9d0f89e4d269775d3c971cca5a | 46.537037 | 245 | 0.681823 | false | false | false | false |
noppefoxwolf/TVUploader-iOS | refs/heads/master | Example/Pods/SwiftTask/SwiftTask/_StateMachine.swift | mit | 1 | //
// _StateMachine.swift
// SwiftTask
//
// Created by Yasuhiro Inami on 2015/01/21.
// Copyright (c) 2015年 Yasuhiro Inami. All rights reserved.
//
import Foundation
///
/// fast, naive event-handler-manager in replace of ReactKit/SwiftState (dynamic but slow),
/// introduced from SwiftTask 2.6.0
///
/// see also: https://github.com/ReactKit/SwiftTask/pull/22
///
internal class _StateMachine<Progress, Value, Error>
{
internal typealias ErrorInfo = Task<Progress, Value, Error>.ErrorInfo
internal typealias ProgressTupleHandler = Task<Progress, Value, Error>._ProgressTupleHandler
internal let weakified: Bool
internal let state: _Atomic<TaskState>
internal let progress: _Atomic<Progress?> = _Atomic(nil) // NOTE: always nil if `weakified = true`
internal let value: _Atomic<Value?> = _Atomic(nil)
internal let errorInfo: _Atomic<ErrorInfo?> = _Atomic(nil)
internal let configuration = TaskConfiguration()
/// wrapper closure for `_initClosure` to invoke only once when started `.Running`,
/// and will be set to `nil` afterward
internal var initResumeClosure: _Atomic<(Void -> Void)?> = _Atomic(nil)
private lazy var _progressTupleHandlers = _Handlers<ProgressTupleHandler>()
private lazy var _completionHandlers = _Handlers<Void -> Void>()
private var _lock = _RecursiveLock()
internal init(weakified: Bool, paused: Bool)
{
self.weakified = weakified
self.state = _Atomic(paused ? .Paused : .Running)
}
internal func addProgressTupleHandler(inout token: _HandlerToken?, _ progressTupleHandler: ProgressTupleHandler) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
if self.state.rawValue == .Running || self.state.rawValue == .Paused {
token = self._progressTupleHandlers.append(progressTupleHandler)
return token != nil
}
else {
return false
}
}
internal func removeProgressTupleHandler(handlerToken: _HandlerToken?) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
if let handlerToken = handlerToken {
let removedHandler = self._progressTupleHandlers.remove(handlerToken)
return removedHandler != nil
}
else {
return false
}
}
internal func addCompletionHandler(inout token: _HandlerToken?, _ completionHandler: Void -> Void) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
if self.state.rawValue == .Running || self.state.rawValue == .Paused {
token = self._completionHandlers.append(completionHandler)
return token != nil
}
else {
return false
}
}
internal func removeCompletionHandler(handlerToken: _HandlerToken?) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
if let handlerToken = handlerToken {
let removedHandler = self._completionHandlers.remove(handlerToken)
return removedHandler != nil
}
else {
return false
}
}
internal func handleProgress(progress: Progress)
{
self._lock.lock()
defer { self._lock.unlock() }
if self.state.rawValue == .Running {
let oldProgress = self.progress.rawValue
// NOTE: if `weakified = false`, don't store progressValue for less memory footprint
if !self.weakified {
self.progress.rawValue = progress
}
for handler in self._progressTupleHandlers {
handler(oldProgress: oldProgress, newProgress: progress)
}
}
}
internal func handleFulfill(value: Value)
{
self._lock.lock()
defer { self._lock.unlock() }
let newState = self.state.updateIf { $0 == .Running ? .Fulfilled : nil }
if let _ = newState {
self.value.rawValue = value
self._finish()
}
}
internal func handleRejectInfo(errorInfo: ErrorInfo)
{
self._lock.lock()
defer { self._lock.unlock() }
let toState = errorInfo.isCancelled ? TaskState.Cancelled : .Rejected
let newState = self.state.updateIf { $0 == .Running || $0 == .Paused ? toState : nil }
if let _ = newState {
self.errorInfo.rawValue = errorInfo
self._finish()
}
}
internal func handlePause() -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
let newState = self.state.updateIf { $0 == .Running ? .Paused : nil }
if let _ = newState {
self.configuration.pause?()
return true
}
else {
return false
}
}
internal func handleResume() -> Bool
{
self._lock.lock()
if let initResumeClosure = self.initResumeClosure.update({ _ in nil }) {
self.state.rawValue = .Running
self._lock.unlock()
//
// NOTE:
// Don't use `_lock` here so that dispatch_async'ed `handleProgress` inside `initResumeClosure()`
// will be safely called even when current thread goes into sleep.
//
initResumeClosure()
//
// Comment-Out:
// Don't call `configuration.resume()` when lazy starting.
// This prevents inapropriate starting of upstream in ReactKit.
//
//self.configuration.resume?()
return true
}
else {
let resumed = _handleResume()
self._lock.unlock()
return resumed
}
}
private func _handleResume() -> Bool
{
let newState = self.state.updateIf { $0 == .Paused ? .Running : nil }
if let _ = newState {
self.configuration.resume?()
return true
}
else {
return false
}
}
internal func handleCancel(error: Error? = nil) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
let newState = self.state.updateIf { $0 == .Running || $0 == .Paused ? .Cancelled : nil }
if let _ = newState {
self.errorInfo.rawValue = ErrorInfo(error: error, isCancelled: true)
self._finish()
return true
}
else {
return false
}
}
private func _finish()
{
for handler in self._completionHandlers {
handler()
}
self._progressTupleHandlers.removeAll()
self._completionHandlers.removeAll()
self.configuration.finish()
self.initResumeClosure.rawValue = nil
self.progress.rawValue = nil
}
}
//--------------------------------------------------
// MARK: - Utility
//--------------------------------------------------
internal struct _HandlerToken
{
internal let key: Int
}
internal struct _Handlers<T>: SequenceType
{
internal typealias KeyValue = (key: Int, value: T)
private var currentKey: Int = 0
private var elements = [KeyValue]()
internal mutating func append(value: T) -> _HandlerToken
{
self.currentKey = self.currentKey &+ 1
self.elements += [(key: self.currentKey, value: value)]
return _HandlerToken(key: self.currentKey)
}
internal mutating func remove(token: _HandlerToken) -> T?
{
for i in 0..<self.elements.count {
if self.elements[i].key == token.key {
return self.elements.removeAtIndex(i).value
}
}
return nil
}
internal mutating func removeAll(keepCapacity: Bool = false)
{
self.elements.removeAll(keepCapacity: keepCapacity)
}
internal func generate() -> AnyGenerator<T>
{
return AnyGenerator(self.elements.map { $0.value }.generate())
}
} | e50c1accf858261f422804687696aeb8 | 28.365248 | 124 | 0.550725 | false | false | false | false |
yysskk/SwipeMenuViewController | refs/heads/master | Sources/Classes/SwipeMenuViewController.swift | mit | 1 | import UIKit
open class SwipeMenuViewController: UIViewController, SwipeMenuViewDelegate, SwipeMenuViewDataSource {
open var swipeMenuView: SwipeMenuView!
open override func viewDidLoad() {
super.viewDidLoad()
swipeMenuView = SwipeMenuView(frame: view.frame)
swipeMenuView.delegate = self
swipeMenuView.dataSource = self
view.addSubview(swipeMenuView)
}
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// potentially nil.
// https://forums.developer.apple.com/thread/94426
swipeMenuView?.willChangeOrientation()
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
addSwipeMenuViewConstraints()
}
private func addSwipeMenuViewConstraints() {
swipeMenuView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *), view.hasSafeAreaInsets, swipeMenuView.options.tabView.isSafeAreaEnabled {
NSLayoutConstraint.activate([
swipeMenuView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
swipeMenuView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
swipeMenuView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
swipeMenuView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
} else {
NSLayoutConstraint.activate([
swipeMenuView.topAnchor.constraint(equalTo: topLayoutGuide.topAnchor),
swipeMenuView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
swipeMenuView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
swipeMenuView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}
// MARK: - SwipeMenuViewDelegate
open func swipeMenuView(_ swipeMenuView: SwipeMenuView, viewWillSetupAt currentIndex: Int) { }
open func swipeMenuView(_ swipeMenuView: SwipeMenuView, viewDidSetupAt currentIndex: Int) { }
open func swipeMenuView(_ swipeMenuView: SwipeMenuView, willChangeIndexFrom fromIndex: Int, to toIndex: Int) { }
open func swipeMenuView(_ swipeMenuView: SwipeMenuView, didChangeIndexFrom fromIndex: Int, to toIndex: Int) { }
// MARK: - SwipeMenuViewDataSource
open func numberOfPages(in swipeMenuView: SwipeMenuView) -> Int {
return children.count
}
open func swipeMenuView(_ swipeMenuView: SwipeMenuView, titleForPageAt index: Int) -> String {
return children[index].title ?? ""
}
open func swipeMenuView(_ swipeMenuView: SwipeMenuView, viewControllerForPageAt index: Int) -> UIViewController {
let vc = children[index]
vc.didMove(toParent: self)
return vc
}
}
| 18409b6630569874d328d76b102de1d7 | 40.614286 | 117 | 0.700309 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/SILGen/switch_abstraction.swift | apache-2.0 | 22 |
// RUN: %target-swift-emit-silgen -module-name switch_abstraction -parse-stdlib %s | %FileCheck %s
struct A {}
enum Optionable<T> {
case Summn(T)
case Nuttn
}
// CHECK-LABEL: sil hidden [ossa] @$s18switch_abstraction18enum_reabstraction1x1ayAA10OptionableOyAA1AVAHcG_AHtF : $@convention(thin) (@guaranteed Optionable<(A) -> A>, A) -> ()
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Optionable<(A) -> A>,
// CHECK: switch_enum [[ARG]] : $Optionable<(A) -> A>, case #Optionable.Summn!enumelt: [[DEST:bb[0-9]+]]
//
// CHECK: [[DEST]]([[ARG:%.*]] :
// CHECK: [[ORIG:%.*]] = copy_value [[ARG]]
// CHECK: [[CONV:%.*]] = convert_function [[ORIG]]
// CHECK: [[REABSTRACT:%.*]] = function_ref @$s{{.*}}TR :
// CHECK: [[SUBST:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[CONV]])
func enum_reabstraction(x: Optionable<(A) -> A>, a: A) {
switch x {
case .Summn(var f):
f(a)
case .Nuttn:
()
}
}
enum Wacky<A, B> {
case Foo(A)
case Bar((B) -> A)
}
// CHECK-LABEL: sil hidden [ossa] @$s18switch_abstraction45enum_addr_only_to_loadable_with_reabstraction{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T> (@in_guaranteed Wacky<T, A>, A) -> @out T {
// CHECK: switch_enum_addr [[ENUM:%.*]] : $*Wacky<T, A>, {{.*}} case #Wacky.Bar!enumelt: [[DEST:bb[0-9]+]]
// CHECK: [[DEST]]:
// CHECK: [[ORIG_ADDR:%.*]] = unchecked_take_enum_data_addr [[ENUM]] : $*Wacky<T, A>, #Wacky.Bar
// CHECK: [[ORIG:%.*]] = load [take] [[ORIG_ADDR]]
// CHECK: [[CONV:%.*]] = convert_function [[ORIG]]
// CHECK: [[REABSTRACT:%.*]] = function_ref @$s{{.*}}TR :
// CHECK: [[SUBST:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]<T>([[CONV]])
func enum_addr_only_to_loadable_with_reabstraction<T>(x: Wacky<T, A>, a: A)
-> T
{
switch x {
case .Foo(var b):
return b
case .Bar(var f):
return f(a)
}
}
func hello() {}
func goodbye(_: Any) {}
// CHECK-LABEL: sil hidden [ossa] @$s18switch_abstraction34requires_address_and_reabstractionyyF : $@convention(thin) () -> () {
// CHECK: [[FN:%.*]] = function_ref @$s18switch_abstraction5helloyyF : $@convention(thin) () -> ()
// CHECK: [[THICK:%.*]] = thin_to_thick_function [[FN]]
// CHECK: [[BOX:%.*]] = alloc_stack
// CHECK: [[THUNK:%.*]] = function_ref @$sIeg_ytIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out ()
// CHECK: [[ABSTRACT:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[THICK]])
// CHECK: [[CONV:%.*]] = convert_function [[ABSTRACT]]
// CHECK: store [[CONV]] to [init] [[BOX]]
func requires_address_and_reabstraction() {
switch hello {
case let a as Any: goodbye(a)
}
}
| 89cc4f9608a44a87c8302fb4399aaf5a | 37.279412 | 191 | 0.592778 | false | false | false | false |
Ticketmaster/Task | refs/heads/master | Example-iOS/Example-iOS/Models/KeyValueObserver.swift | mit | 1 | //
// KeyValueObserver.swift
// Example-iOS
//
// Created by Prachi Gauriar on 7/6/2016.
// Copyright © 2016 Ticketmaster Entertainment, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/// Instances of `KeyValueObserver` make it easy to use KVO without manually registering for
/// change notifications or overriding `observeValueForKeyPath(_:ofObject:change:context:)`.
/// Upon creating a `KeyValueObserver` object, it automatically starts observing the key path
/// specified and executes its change block whenever a change is observed. When the instance
/// is deallocated, it automatically stops observing the specified key path.
class KeyValueObserver<ObservedType: NSObject> : NSObject {
/// The object being observed.
private let object: ObservedType
/// The key path being observed.
private let keyPath: String
/// The block to invoke whenever a change is observed.
private let changeBlock: (ObservedType) -> ()
/// A private context variable for use when registering and deregistering from KVO
private var context = 0
/// Initializes a newly created `KeyValueObserver` instance with the specified object,
/// key path, key-value observing options, and change block. Upon completion of this
/// method, the new instance will be observing change notifications for the specified
/// object and key path.
///
/// - parameter object: The object to observe
/// - parameter keyPath: The key path to observe
/// - parameter options: The key-value observing options to use when registering for
/// change notifications
/// - parameter changeBlock: The block to invoke whenever a change is observed
init(object: ObservedType,
keyPath: String,
options: NSKeyValueObservingOptions = .initial,
changeBlock: @escaping (ObservedType) -> ()) {
self.object = object
self.keyPath = keyPath
self.changeBlock = changeBlock
super.init()
object.addObserver(self, forKeyPath: keyPath, options: options, context: &context)
}
deinit {
object.removeObserver(self, forKeyPath: keyPath, context: &context)
}
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
changeBlock(self.object)
}
}
| 3e53cf626d73d3f1147ada031e00ef07 | 41.321429 | 93 | 0.70211 | false | false | false | false |
Daemon-Devarshi/MedicationSchedulerSwift3.0 | refs/heads/master | Medication/ViewControllers/AddNewForms/AddNewMedicationViewController.swift | mit | 1 | //
// AddNewMedicationViewController.swift
// Medication
//
// Created by Devarshi Kulshreshtha on 8/20/16.
// Copyright © 2016 Devarshi. All rights reserved.
//
import UIKit
import CoreData
import EventKit
class AddNewMedicationViewController: FormBaseViewController {
//MARK: Constants declarations
static let pushSegueIdentifier = "PushAddNewMedicationViewController"
//MARK: Var declarations
// Pickers
fileprivate var timePicker: UIDatePicker!
fileprivate var unitPicker: UIPickerView!
fileprivate var priorityPicker: UIPickerView!
// Values displayed in pickers
fileprivate var pirorityModes: [PriorityMode] = [.high, .medium, .low]
fileprivate var units: [Units] = [.pills, .ml]
fileprivate var eventStore: EKEventStore?
fileprivate var selectedMedicine: Medicine?
fileprivate var selectedPriority: PriorityMode?
fileprivate var selectedUnit: Units?
fileprivate var scheduleTime: Date?
var patient: Patient! {
didSet {
managedObjectContext = patient.managedObjectContext
}
}
//MARK: Outlets declarations
@IBOutlet weak var medicineField: UITextField!
@IBOutlet weak var scheduleMedicationField: UITextField!
@IBOutlet weak var dosageField: UITextField!
@IBOutlet weak var selectUnitField: UITextField!
@IBOutlet weak var selectPriorityField: UITextField!
//MARK: Overriden methods
override func viewDidLoad() {
super.viewDidLoad()
configureDatePicker()
configurePickerViews()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let segueIdentifier = segue.identifier {
if segueIdentifier == MedicinesTableViewController.pushSegueIdentifier {
// passing managedObjectContext to PatientsTableViewController
let medicinesTableViewController = segue.destination as! MedicinesTableViewController
medicinesTableViewController.managedObjectContext = managedObjectContext
medicinesTableViewController.medicineSelectionHandler = { [weak self](selectedMedicine) in
// weak used to break retain cycle
guard let _self = self else {
return
}
_self.medicineField.text = selectedMedicine.name
_self.selectedMedicine = selectedMedicine
}
}
}
}
}
//MARK:- Implementing UIPickerViewDataSource, UIPickerViewDelegate protocols
extension AddNewMedicationViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == unitPicker {
return units.count
}
else if pickerView == priorityPicker{
return pirorityModes.count
}
return 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
var title: String?
if pickerView == unitPicker {
title = units[row].description
}
else if pickerView == priorityPicker{
title = pirorityModes[row].description
}
return title
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == unitPicker {
let value = units[row]
selectedUnit = value
selectUnitField.text = value.description
}
else if pickerView == priorityPicker {
let value = pirorityModes[row]
selectedPriority = value
selectPriorityField.text = value.description
}
}
}
//MARK:- Utility methods
extension AddNewMedicationViewController {
// Scheduling reminders
fileprivate func scheduleReminder() {
if let eventStore = eventStore {
let reminder = EKReminder(eventStore: eventStore)
let notes = "\(selectedMedicine!.name!) \(dosageField.text!) \(selectedUnit!.description)"
reminder.title = "Provide \(notes) to \(patient.fullName!)"
reminder.notes = notes
reminder.calendar = eventStore.defaultCalendarForNewReminders()
let alarm = EKAlarm(absoluteDate: scheduleTime!)
reminder.addAlarm(alarm)
reminder.priority = selectedPriority!.rawValue
let recurrenceRule = EKRecurrenceRule(recurrenceWith: .daily, interval: 1, end: nil)
reminder.recurrenceRules = [recurrenceRule]
// setting dueDateComponents for recurring events
let gregorian = NSCalendar(identifier:NSCalendar.Identifier.gregorian)
let dailyComponents = gregorian?.components([.year, .month, .day, .hour, .minute, .second, .timeZone], from: scheduleTime!)
reminder.dueDateComponents = dailyComponents
do {
try eventStore.save(reminder, commit: true)
displaySingleButtonActionAlert(withTitle: "Success!", message: "Medication successfully scheduled.") {[weak self] in
// weak used to break retain cycle
guard let _self = self else {
return
}
_ = _self.navigationController?.popViewController(animated: true)
}
} catch {
let error = error as NSError
print("\(error), \(error.userInfo)")
displaySingleButtonActionAlert(withTitle: "Error!", message: error.localizedDescription)
}
}
}
// Configuring date picker
fileprivate func configureDatePicker() {
timePicker = UIDatePicker(frame: CGRect.zero)
timePicker.datePickerMode = .time
timePicker.backgroundColor = UIColor.white
timePicker.addTarget(self, action: #selector(AddNewMedicationViewController.medicationScheduleChanged), for: .valueChanged)
scheduleMedicationField.inputView = timePicker
}
// Configuring all picker views
fileprivate func configurePickerViews() {
// configuring unitPicker
unitPicker = UIPickerView()
unitPicker.delegate = self
unitPicker.dataSource = self
selectUnitField.inputView = unitPicker
// configuring priorityPicker
priorityPicker = UIPickerView()
priorityPicker.delegate = self
priorityPicker.dataSource = self
selectPriorityField.inputView = priorityPicker
}
}
//MARK:- User actions and text field delegate
extension AddNewMedicationViewController {
override func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// to disable text editing on fields which have input view associated with them
if textField == scheduleMedicationField || textField == selectPriorityField || textField == selectUnitField {
return false
}
return true
}
func medicationScheduleChanged(_ sender:UIDatePicker) {
scheduleTime = sender.date.fullMinuteTime()
scheduleMedicationField.text = scheduleTime!.displayTime()
}
@IBAction func scheduleMedication(_ sender: AnyObject) {
// validations
guard let dosage = dosageField.text else {
displaySingleButtonActionAlert(withTitle: "Error!", message: "Please enter all details.")
return
}
guard let selectedMedicine = selectedMedicine, let selectedPriority = selectedPriority, let selectedUnit = selectedUnit, let scheduleTime = scheduleTime else {
displaySingleButtonActionAlert(withTitle: "Error!", message: "Please enter all details.")
return
}
// Create medication and assign values to its attributes
let medication = Medication.createMedication(withPatient: patient, inManagedObjectContext: managedObjectContext)
medication.dosage = NSNumber(value: Int32(dosage)!)
medication.unit = NSNumber(value: Int32(selectedUnit.rawValue))
medication.priority = NSNumber(value: Int32(selectedPriority.rawValue))
medication.scheduleTime = scheduleTime as NSDate
medication.medicine = selectedMedicine
medication.patient = patient
// saving in local db + creating reminder
do {
try managedObjectContext.save()
// scheduling the reminder
if eventStore == nil {
eventStore = EKEventStore()
eventStore!.requestAccess(
to: .reminder, completion: {[weak self](granted, error) in
guard let _self = self else {
return
}
// Background to main thread
DispatchQueue.main.async(execute: {
if !granted {
print("Access to store not granted")
print(error!.localizedDescription)
_self.displaySingleButtonActionAlert(withTitle: "Permission Declined!", message: "Reminder could not be scheduled.")
} else {
print("Access granted")
_self.scheduleReminder()
}
})
})
}
else {
scheduleReminder()
}
} catch {
let error = error as NSError
print("\(error), \(error.userInfo)")
displaySingleButtonActionAlert(withTitle: "Error!", message: error.localizedDescription)
}
}
}
| d062dbe116fc92478cbe7852fba1e93f | 38.115385 | 168 | 0.612291 | false | false | false | false |
a1exb1/ABToolKit-pod | refs/heads/master | Pod/Classes/Autolayout/AutoLayoutHelper.swift | mit | 1 | //
// UIViewExtensions.swift
//
//
// Created by Shagun Madhikarmi on 09/10/2014.
// Copyright (c) 2014 madhikarma. All rights reserved.
//
import Foundation
import UIKit
/**
Extension of UIView for AutoLayout helper methods
*/
public extension UIView {
// Mark: - Fill
public func fillSuperView(edges: UIEdgeInsets) -> [NSLayoutConstraint] {
var topConstraint: NSLayoutConstraint = self.addTopConstraint(toView: self.superview, relation: .Equal, constant: edges.top)
var leftConstraint: NSLayoutConstraint = self.addLeftConstraint(toView: self.superview, relation: .Equal, constant: edges.left)
var bottomConstraint: NSLayoutConstraint = self.addBottomConstraint(toView: self.superview, relation: .Equal, constant: edges.bottom)
var rightConstraint: NSLayoutConstraint = self.addRightConstraint(toView: self.superview, relation: .Equal, constant: edges.right)
return [topConstraint, leftConstraint, bottomConstraint, rightConstraint]
}
// MARK: - Left Constraints
public func addLeftConstraint(toView view: UIView?, attribute: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
let constraint: NSLayoutConstraint = self.createConstraint(attribute: .Left, toView: view, attribute: attribute, relation: relation, constant: constant)
self.superview?.addConstraint(constraint)
return constraint
}
public func addLeftConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
return self.addLeftConstraint(toView: view, attribute: .Left, relation: relation, constant: constant)
}
// MARK: - Right Constraints
public func addRightConstraint(toView view: UIView?, attribute: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
let constraint: NSLayoutConstraint = self.createConstraint(attribute: .Right, toView: view, attribute: attribute, relation: relation, constant: constant)
self.superview?.addConstraint(constraint)
return constraint
}
public func addRightConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
return self.addRightConstraint(toView: view, attribute: .Right, relation: relation, constant: constant)
}
// MARK: - Top Constraints
public func addTopConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
return self.addTopConstraint(toView: view, attribute: .Top, relation: relation, constant: constant)
}
public func addTopConstraint(toView view: UIView?, attribute: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
let constraint: NSLayoutConstraint = self.createConstraint(attribute: .Top, toView: view, attribute: attribute, relation: relation, constant: constant)
self.superview?.addConstraint(constraint)
return constraint
}
public func addTopMarginConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
return self.addTopMarginConstraint(toView: view, attribute: .TopMargin, relation: relation, constant: constant)
}
public func addTopMarginConstraint(toView view: UIView?, attribute: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
let constraint: NSLayoutConstraint = self.createConstraint(attribute: .TopMargin, toView: view, attribute: attribute, relation: relation, constant: constant)
self.superview?.addConstraint(constraint)
return constraint
}
// MARK: - Bottom Constraints
public func addBottomConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
return self.addBottomConstraint(toView: view, attribute: .Bottom, relation: relation, constant: constant)
}
public func addBottomConstraint(toView view: UIView?, attribute: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
let constraint: NSLayoutConstraint = self.createConstraint(attribute: .Bottom, toView: view, attribute: attribute, relation: relation, constant: constant)
self.superview?.addConstraint(constraint)
return constraint
}
public func addBottomMarginConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
let constraint: NSLayoutConstraint = self.createConstraint(attribute: .BottomMargin, toView: view, attribute: .Bottom, relation: relation, constant: constant)
self.superview?.addConstraint(constraint)
return constraint
}
public func addBottomMarginConstraint(toView view: UIView?, attribute: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
return self.addBottomConstraint(toView: view, attribute: .BottomMargin, relation: relation, constant: constant)
}
// MARK: - Center X Constraint
public func addCenterXConstraint(toView view: UIView?) -> NSLayoutConstraint {
return self.addCenterXConstraint(toView: view, relation: .Equal, constant: 0)
}
public func addCenterXConstraint(toView view: UIView?, constant: CGFloat) -> NSLayoutConstraint {
return self.addCenterXConstraint(toView: view, relation: .Equal, constant: constant)
}
public func addCenterXConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
let constraint: NSLayoutConstraint = self.createConstraint(attribute: .CenterX, toView: view, attribute: .CenterX, relation: relation, constant: constant)
self.superview?.addConstraint(constraint)
return constraint
}
// MARK: - Center Y Constraint
public func addCenterYConstraint(toView view: UIView?) -> NSLayoutConstraint {
return self.addCenterYConstraint(toView: view, relation: .Equal, constant: 0)
}
public func addCenterYConstraint(toView view: UIView?, constant: CGFloat) -> NSLayoutConstraint {
return self.addCenterYConstraint(toView: view, relation: .Equal, constant: constant)
}
public func addCenterYConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
let constraint: NSLayoutConstraint = self.createConstraint(attribute: .CenterY, toView: view, attribute: .CenterY, relation: relation, constant: constant)
self.superview?.addConstraint(constraint)
return constraint
}
// MARK: - Width Constraints
public func addWidthConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
let constraint: NSLayoutConstraint = self.createConstraint(attribute: .Width, toView: view, attribute: .Width, relation: relation, constant: constant)
self.superview?.addConstraint(constraint)
return constraint
}
public func addWidthConstraint(relation relation1: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
return self.addWidthConstraint(toView: nil, relation: relation1, constant: constant)
}
// MARK: - Height Constraints
public func addHeightConstraint(toView view: UIView?, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
let constraint: NSLayoutConstraint = self.createConstraint(attribute: .Height, toView: view, attribute: .Height, relation: relation, constant: constant)
self.superview?.addConstraint(constraint)
return constraint
}
public func addHeightConstraint(relation relation1: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
return self.addHeightConstraint(toView: nil, relation: relation1, constant: constant)
}
// MARK: - Private
private func createConstraint(attribute attr1: NSLayoutAttribute, toView: UIView?, attribute attr2: NSLayoutAttribute, relation: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
let constraint = NSLayoutConstraint(
item: self,
attribute: attr1,
relatedBy: relation,
toItem: toView,
attribute: attr2,
multiplier: 1.0,
constant: constant)
return constraint
}
} | 9cf322c486a5015519d20d5b91e65ddf | 41.255924 | 193 | 0.692428 | false | false | false | false |
bosr/Zewo | refs/heads/master | Modules/Mapper/Tests/Mapper/MappableValueTests.swift | mit | 1 | import XCTest
@testable import Mapper
class MappableValueTests: XCTestCase {
static var allTests: [(String, (MappableValueTests) -> () throws -> Void)] {
return [
("testNestedMappable", testNestedMappable),
("testNestedInvalidMappable", testNestedInvalidMappable),
("testNestedOptionalMappable", testNestedOptionalMappable),
("testNestedOptionalInvalidMappable", testNestedOptionalInvalidMappable),
("testArrayOfMappables", testArrayOfMappables),
("testArrayOfInvalidMappables", testArrayOfInvalidMappables),
("testInvalidArrayOfMappables", testInvalidArrayOfMappables),
("testArrayOfPartiallyInvalidMappables", testArrayOfPartiallyInvalidMappables),
("testExistingOptionalArrayOfMappables", testExistingOptionalArrayOfMappables),
("testOptionalArrayOfMappables", testOptionalArrayOfMappables),
("testOptionalArrayOfInvalidMappables", testOptionalArrayOfInvalidMappables),
("testOptionalArrayOfPartiallyInvalidMappables", testOptionalArrayOfPartiallyInvalidMappables)
]
}
func testNestedMappable() {
struct Test: Mappable {
let nest: Nested
init(mapper: Mapper) throws {
try self.nest = mapper.map(from: "nest")
}
}
struct Nested: Mappable {
let string: String
init(mapper: Mapper) throws {
try self.string = mapper.map(from: "string")
}
}
let structuredData: StructuredData = [
"nest": ["string": "hello"]
]
let test = try! Test(mapper: Mapper(structuredData: structuredData))
XCTAssertEqual(test.nest.string, "hello")
}
func testNestedInvalidMappable() {
struct Nested: Mappable {
let string: String
init(mapper: Mapper) throws {
try self.string = mapper.map(from: "string")
}
}
struct Test: Mappable {
let nested: Nested
init(mapper: Mapper) throws {
try self.nested = mapper.map(from: "nest")
}
}
let structuredData: StructuredData = ["nest": ["strong": "er"]]
let test = try? Test(mapper: Mapper(structuredData: structuredData))
XCTAssertNil(test)
}
func testNestedOptionalMappable() {
struct Nested: Mappable {
let string: String
init(mapper: Mapper) throws {
try self.string = mapper.map(from: "string")
}
}
struct Test: Mappable {
let nested: Nested?
init(mapper: Mapper) throws {
self.nested = mapper.map(optionalFrom: "nest")
}
}
let structuredData: StructuredData = ["nest": ["string": "zewo"]]
let test = try! Test(mapper: Mapper(structuredData: structuredData))
XCTAssertEqual(test.nested!.string, "zewo")
}
func testNestedOptionalInvalidMappable() {
struct Nested: Mappable {
let string: String
init(mapper: Mapper) throws {
try self.string = mapper.map(from: "string")
}
}
struct Test: Mappable {
let nested: Nested?
init(mapper: Mapper) throws {
self.nested = mapper.map(optionalFrom: "nest")
}
}
let structuredData: StructuredData = ["nest": ["strong": "er"]]
let test = try! Test(mapper: Mapper(structuredData: structuredData))
XCTAssertNil(test.nested)
}
func testArrayOfMappables() {
struct Nested: Mappable {
let string: String
init(mapper: Mapper) throws {
try self.string = mapper.map(from: "string")
}
}
struct Test: Mappable {
let nested: [Nested]
init(mapper: Mapper) throws {
try self.nested = mapper.map(arrayFrom: "nested")
}
}
let test = try! Test(mapper: Mapper(structuredData: ["nested": [["string": "fire"], ["string": "sun"]]]))
XCTAssertEqual(test.nested.count, 2)
XCTAssertEqual(test.nested[1].string, "sun")
}
func testArrayOfInvalidMappables() {
struct Nested: Mappable {
let string: String
init(mapper: Mapper) throws {
try self.string = mapper.map(from: "string")
}
}
struct Test: Mappable {
let nested: [Nested]
init(mapper: Mapper) throws {
try self.nested = mapper.map(arrayFrom: "nested")
}
}
let test = try! Test(mapper: Mapper(structuredData: ["nested": [["string": 1], ["string": 1]]]))
XCTAssertTrue(test.nested.isEmpty)
}
func testInvalidArrayOfMappables() {
struct Nested: Mappable {
let string: String
init(mapper: Mapper) throws {
try self.string = mapper.map(from: "string")
}
}
struct Test: Mappable {
let nested: [Nested]
init(mapper: Mapper) throws {
try self.nested = mapper.map(arrayFrom: "nested")
}
}
let test = try? Test(mapper: Mapper(structuredData: ["hested": [["strong": "fire"], ["strong": "sun"]]]))
XCTAssertNil(test)
}
func testArrayOfPartiallyInvalidMappables() {
struct Nested: Mappable {
let string: String
init(mapper: Mapper) throws {
try self.string = mapper.map(from: "string")
}
}
struct Test: Mappable {
let nested: [Nested]
init(mapper: Mapper) throws {
try self.nested = mapper.map(arrayFrom: "nested")
}
}
let test = try! Test(mapper: Mapper(structuredData: ["nested": [["string": 1], ["string": "fire"]]]))
XCTAssertEqual(test.nested.count, 1)
}
func testExistingOptionalArrayOfMappables() {
struct Nested: Mappable {
let string: String
init(mapper: Mapper) throws {
try self.string = mapper.map(from: "string")
}
}
struct Test: Mappable {
let nested: [Nested]?
init(mapper: Mapper) throws {
self.nested = mapper.map(optionalArrayFrom: "nested")
}
}
let test = try! Test(mapper: Mapper(structuredData: ["nested": [["string": "ring"], ["string": "fire"]]]))
XCTAssertEqual(test.nested!.count, 2)
}
func testOptionalArrayOfMappables() {
struct Nested: Mappable {
let string: String
init(mapper: Mapper) throws {
try self.string = mapper.map(from: "string")
}
}
struct Test: Mappable {
let nested: [Nested]?
init(mapper: Mapper) throws {
self.nested = mapper.map(optionalArrayFrom: "nested")
}
}
let test = try! Test(mapper: Mapper(structuredData: []))
XCTAssertNil(test.nested)
}
func testOptionalArrayOfInvalidMappables() {
struct Nested: Mappable {
let string: String
init(mapper: Mapper) throws {
try self.string = mapper.map(from: "string")
}
}
struct Test: Mappable {
let nested: [Nested]?
init(mapper: Mapper) throws {
self.nested = mapper.map(optionalArrayFrom: "nested")
}
}
let test = try! Test(mapper: Mapper(structuredData: ["nested": [["strong": 3], ["strong": 5]]]))
XCTAssertTrue(test.nested!.isEmpty)
}
func testOptionalArrayOfPartiallyInvalidMappables() {
struct Nested: Mappable {
let string: String
init(mapper: Mapper) throws {
try self.string = mapper.map(from: "string")
}
}
struct Test: Mappable {
let nested: [Nested]?
init(mapper: Mapper) throws {
self.nested = mapper.map(optionalArrayFrom: "nested")
}
}
let test = try! Test(mapper: Mapper(structuredData: ["nested": [["string": 1], ["string": "fire"]]]))
XCTAssertEqual(test.nested!.count, 1)
}
}
| 3fe59afd30e2a08342c29a21545ace6a | 35.271552 | 114 | 0.55104 | false | true | false | false |
vermont42/Conjugar | refs/heads/master | Conjugar/TestAnalyticsService.swift | agpl-3.0 | 1 | //
// TestAnalyticsService.swift
// Conjugar
//
// Created by Joshua Adams on 11/25/18.
// Copyright © 2018 Josh Adams. All rights reserved.
//
import Foundation
class TestAnalyticsService: AnalyticsServiceable {
private var fire: (String) -> ()
init(fire: @escaping (String) -> () = { analytic in print(analytic) }) {
self.fire = fire
}
func recordEvent(_ eventName: String, parameters: [String: String]?, metrics: [String: Double]?) {
var analytic = eventName
if let parameters = parameters {
analytic += " "
for (key, value) in parameters {
analytic += key + ": " + value + " "
}
}
fire(analytic)
}
}
| 7187910b0c47709ea1e1a80d959a6985 | 22.857143 | 100 | 0.618263 | false | true | false | false |
BoltApp/bolt-ios | refs/heads/master | 125-iOSTips-master/Demo/47.给App的某个功能添加快捷方式/Pods/Swifter/Sources/MimeTypes.swift | apache-2.0 | 5 | //
// MimeTypes.swift
// Swifter
//
// Created by Daniel Große on 16.02.18.
//
import Foundation
internal let DEFAULT_MIME_TYPE = "application/octet-stream"
internal let mimeTypes = [
"html": "text/html",
"htm": "text/html",
"shtml": "text/html",
"css": "text/css",
"xml": "text/xml",
"gif": "image/gif",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "application/javascript",
"atom": "application/atom+xml",
"rss": "application/rss+xml",
"mml": "text/mathml",
"txt": "text/plain",
"jad": "text/vnd.sun.j2me.app-descriptor",
"wml": "text/vnd.wap.wml",
"htc": "text/x-component",
"png": "image/png",
"tif": "image/tiff",
"tiff": "image/tiff",
"wbmp": "image/vnd.wap.wbmp",
"ico": "image/x-icon",
"jng": "image/x-jng",
"bmp": "image/x-ms-bmp",
"svg": "image/svg+xml",
"svgz": "image/svg+xml",
"webp": "image/webp",
"woff": "application/font-woff",
"jar": "application/java-archive",
"war": "application/java-archive",
"ear": "application/java-archive",
"json": "application/json",
"hqx": "application/mac-binhex40",
"doc": "application/msword",
"pdf": "application/pdf",
"ps": "application/postscript",
"eps": "application/postscript",
"ai": "application/postscript",
"rtf": "application/rtf",
"m3u8": "application/vnd.apple.mpegurl",
"xls": "application/vnd.ms-excel",
"eot": "application/vnd.ms-fontobject",
"ppt": "application/vnd.ms-powerpoint",
"wmlc": "application/vnd.wap.wmlc",
"kml": "application/vnd.google-earth.kml+xml",
"kmz": "application/vnd.google-earth.kmz",
"7z": "application/x-7z-compressed",
"cco": "application/x-cocoa",
"jardiff": "application/x-java-archive-diff",
"jnlp": "application/x-java-jnlp-file",
"run": "application/x-makeself",
"pl": "application/x-perl",
"pm": "application/x-perl",
"prc": "application/x-pilot",
"pdb": "application/x-pilot",
"rar": "application/x-rar-compressed",
"rpm": "application/x-redhat-package-manager",
"sea": "application/x-sea",
"swf": "application/x-shockwave-flash",
"sit": "application/x-stuffit",
"tcl": "application/x-tcl",
"tk": "application/x-tcl",
"der": "application/x-x509-ca-cert",
"pem": "application/x-x509-ca-cert",
"crt": "application/x-x509-ca-cert",
"xpi": "application/x-xpinstall",
"xhtml": "application/xhtml+xml",
"xspf": "application/xspf+xml",
"zip": "application/zip",
"bin": "application/octet-stream",
"exe": "application/octet-stream",
"dll": "application/octet-stream",
"deb": "application/octet-stream",
"dmg": "application/octet-stream",
"iso": "application/octet-stream",
"img": "application/octet-stream",
"msi": "application/octet-stream",
"msp": "application/octet-stream",
"msm": "application/octet-stream",
"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"mid": "audio/midi",
"midi": "audio/midi",
"kar": "audio/midi",
"mp3": "audio/mpeg",
"ogg": "audio/ogg",
"m4a": "audio/x-m4a",
"ra": "audio/x-realaudio",
"3gpp": "video/3gpp",
"3gp": "video/3gpp",
"ts": "video/mp2t",
"mp4": "video/mp4",
"mpeg": "video/mpeg",
"mpg": "video/mpeg",
"mov": "video/quicktime",
"webm": "video/webm",
"flv": "video/x-flv",
"m4v": "video/x-m4v",
"mng": "video/x-mng",
"asx": "video/x-ms-asf",
"asf": "video/x-ms-asf",
"wmv": "video/x-ms-wmv",
"avi": "video/x-msvideo"
]
internal func MimeType(ext: String?) -> String {
if ext != nil && mimeTypes.contains(where: { $0.0 == ext!.lowercased() }) {
return mimeTypes[ext!.lowercased()]!
}
return DEFAULT_MIME_TYPE
}
extension NSURL {
public func mimeType() -> String {
return MimeType(ext: self.pathExtension)
}
}
extension NSString {
public func mimeType() -> String {
return MimeType(ext: self.pathExtension)
}
}
extension String {
public func mimeType() -> String {
return (NSString(string: self)).mimeType()
}
}
| 94cba8d2d4c920298af254fab9a61421 | 29.286713 | 88 | 0.601709 | false | false | false | false |
akkakks/firefox-ios | refs/heads/master | Storage/Storage/SQLitePasswords.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
private class PasswordsTable<T>: GenericTable<Password> {
override var name: String { return "logins" }
override var version: Int { return 1 }
override var rows: String { return "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"hostname TEXT NOT NULL, " +
"httpRealm TEXT NOT NULL, " +
"formSubmitUrl TEXT NOT NULL, " +
"usernameField TEXT NOT NULL, " +
"passwordField TEXT NOT NULL, " +
"guid TEXT NOT NULL UNIQUE, " +
"timeCreated REAL NOT NULL, " +
"timeLastUsed REAL NOT NULL, " +
"timePasswordChanged REAL NOT NULL, " +
"username TEXT NOT NULL, " +
"password TEXT NOT NULL" }
override func getInsertAndArgs(inout item: Password) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
if item.guid == nil {
item.guid = NSUUID().UUIDString
}
args.append(item.hostname)
args.append(item.httpRealm)
args.append(item.formSubmitUrl)
args.append(item.usernameField)
args.append(item.passwordField)
args.append(item.guid)
args.append(item.timeCreated)
args.append(item.timeLastUsed)
args.append(item.timePasswordChanged)
args.append(item.username)
args.append(item.password)
return ("INSERT INTO \(name) (hostname, httpRealm, formSubmitUrl, usernameField, passwordField, guid, timeCreated, timeLastUsed, timePasswordChanged, username, password) VALUES (?,?,?,?,?,?,?,?,?,?,?)", args)
}
override func getUpdateAndArgs(inout item: Password) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
args.append(item.httpRealm)
args.append(item.formSubmitUrl)
args.append(item.usernameField)
args.append(item.passwordField)
args.append(item.timeCreated)
args.append(item.timeLastUsed)
args.append(item.timePasswordChanged)
args.append(item.password)
args.append(item.hostname)
args.append(item.username)
return ("UPDATE \(name) SET httpRealm = ?, formSubmitUrl = ?, usernameField = ?, passwordField = ?, timeCreated = ?, timeLastUsed = ?, timePasswordChanged = ?, password = ?) WHERE hostname = ? AND username = ?", args)
}
override func getDeleteAndArgs(inout item: Password?) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
if let pw = item {
args.append(pw.hostname)
args.append(pw.username)
return ("DELETE FROM \(name) WHERE hostname = ? AND username = ?", args)
}
return ("DELETE FROM \(name)", args)
}
override var factory: ((row: SDRow) -> Password)? {
return { row -> Password in
let site = Site(url: row["hostname"] as! String, title: "")
let pw = Password(site: site, username: row["username"] as! String, password: row["password"] as! String)
pw.httpRealm = row["httpRealm"] as! String
pw.formSubmitUrl = row["formSubmitUrl"] as! String
pw.usernameField = row["usernameField"] as! String
pw.passwordField = row["passwordField"] as! String
pw.guid = row["guid"] as? String
pw.timeCreated = NSDate(timeIntervalSince1970: row["timeCreated"] as! Double)
pw.timeLastUsed = NSDate(timeIntervalSince1970: row["timeLastUsed"] as! Double)
pw.timePasswordChanged = NSDate(timeIntervalSince1970: row["timePasswordChanged"] as! Double)
return pw
}
}
override func getQueryAndArgs(options: QueryOptions?) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
if let filter: AnyObject = options?.filter {
args.append(filter)
return ("SELECT * FROM \(name) WHERE hostname = ?", args)
}
return ("SELECT * FROM \(name)", args)
}
}
public class SQLitePasswords : Passwords {
private let table = PasswordsTable<Password>()
private let db: BrowserDB
public init(files: FileAccessor) {
self.db = BrowserDB(files: files)!
db.createOrUpdate(table)
}
public func get(options: QueryOptions, complete: (cursor: Cursor) -> Void) {
var err: NSError? = nil
let cursor = db.query(&err, callback: { (connection, err) -> Cursor in
return self.table.query(connection, options: options)
})
dispatch_async(dispatch_get_main_queue()) { _ in
complete(cursor: cursor)
}
}
public func add(password: Password, complete: (success: Bool) -> Void) {
var err: NSError? = nil
let inserted = db.insert(&err, callback: { (connection, inout err: NSError?) -> Int in
return self.table.insert(connection, item: password, err: &err)
})
dispatch_async(dispatch_get_main_queue()) { _ in
complete(success: inserted > -1)
return
}
}
public func remove(password: Password, complete: (success: Bool) -> Void) {
var err: NSError? = nil
let deleted = db.delete(&err, callback: { (connection, inout err: NSError?) -> Int in
return self.table.delete(connection, item: password, err: &err)
})
dispatch_async(dispatch_get_main_queue()) { _ in
complete(success: deleted > -1)
}
}
public func removeAll(complete: (success: Bool) -> Void) {
var err: NSError? = nil
let deleted = db.delete(&err, callback: { (connection, inout err: NSError?) -> Int in
return self.table.delete(connection, item: nil, err: &err)
})
dispatch_async(dispatch_get_main_queue()) { _ in
complete(success: deleted > -1)
}
}
} | d8cf42263caa8376a91fcbfc9cfcadfd | 39.489796 | 225 | 0.604436 | false | false | false | false |
amraboelela/swift-corelibs-foundation | refs/heads/master | Foundation/NSStringAPI.swift | apache-2.0 | 6 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Exposing the API of NSString on Swift's String
//
//===----------------------------------------------------------------------===//
// Important Note
// ==============
//
// This file is shared between two projects:
//
// 1. https://github.com/apple/swift/tree/master/stdlib/public/SDK/Foundation
// 2. https://github.com/apple/swift-corelibs-foundation/tree/master/Foundation
//
// If you change this file, you must update it in both places.
#if !DEPLOYMENT_RUNTIME_SWIFT
@_exported import Foundation // Clang module
#endif
// Open Issues
// ===========
//
// Property Lists need to be properly bridged
//
func _toNSArray<T, U : AnyObject>(_ a: [T], f: (T) -> U) -> NSArray {
let result = NSMutableArray(capacity: a.count)
for s in a {
result.add(f(s))
}
return result
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// We only need this for UnsafeMutablePointer, but there's not currently a way
// to write that constraint.
extension Optional {
/// Invokes `body` with `nil` if `self` is `nil`; otherwise, passes the
/// address of `object` to `body`.
///
/// This is intended for use with Foundation APIs that return an Objective-C
/// type via out-parameter where it is important to be able to *ignore* that
/// parameter by passing `nil`. (For some APIs, this may allow the
/// implementation to avoid some work.)
///
/// In most cases it would be simpler to just write this code inline, but if
/// `body` is complicated than that results in unnecessarily repeated code.
internal func _withNilOrAddress<NSType : AnyObject, ResultType>(
of object: inout NSType?,
_ body:
(AutoreleasingUnsafeMutablePointer<NSType?>?) -> ResultType
) -> ResultType {
return self == nil ? body(nil) : body(&object)
}
}
#endif
extension String {
//===--- Class Methods --------------------------------------------------===//
//===--------------------------------------------------------------------===//
// @property (class) const NSStringEncoding *availableStringEncodings;
/// An array of the encodings that strings support in the application's
/// environment.
public static var availableStringEncodings: [Encoding] {
var result = [Encoding]()
var p = NSString.availableStringEncodings
while p.pointee != 0 {
result.append(Encoding(rawValue: p.pointee))
p += 1
}
return result
}
// @property (class) NSStringEncoding defaultCStringEncoding;
/// The C-string encoding assumed for any method accepting a C string as an
/// argument.
public static var defaultCStringEncoding: Encoding {
return Encoding(rawValue: NSString.defaultCStringEncoding)
}
// + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
/// Returns a human-readable string giving the name of the specified encoding.
///
/// - Parameter encoding: A string encoding. For possible values, see
/// `String.Encoding`.
/// - Returns: A human-readable string giving the name of `encoding` in the
/// current locale.
public static func localizedName(
of encoding: Encoding
) -> String {
return NSString.localizedName(of: encoding.rawValue)
}
// + (instancetype)localizedStringWithFormat:(NSString *)format, ...
/// Returns a string created by using a given format string as a
/// template into which the remaining argument values are substituted
/// according to the user's default locale.
public static func localizedStringWithFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
return String(format: format, locale: Locale.current,
arguments: arguments)
}
//===--------------------------------------------------------------------===//
// NSString factory functions that have a corresponding constructor
// are omitted.
//
// + (instancetype)string
//
// + (instancetype)
// stringWithCharacters:(const unichar *)chars length:(NSUInteger)length
//
// + (instancetype)stringWithFormat:(NSString *)format, ...
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithCString:(const char *)cString
// encoding:(NSStringEncoding)enc
//===--------------------------------------------------------------------===//
//===--- Adds nothing for String beyond what String(s) does -------------===//
// + (instancetype)stringWithString:(NSString *)aString
//===--------------------------------------------------------------------===//
// + (instancetype)stringWithUTF8String:(const char *)bytes
/// Creates a string by copying the data from a given
/// C array of UTF8-encoded bytes.
public init?(utf8String bytes: UnsafePointer<CChar>) {
if let ns = NSString(utf8String: bytes) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
}
extension String {
//===--- Already provided by String's core ------------------------------===//
// - (instancetype)init
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithBytes:(const void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
/// Creates a new string equivalent to the given bytes interpreted in the
/// specified encoding.
///
/// - Parameters:
/// - bytes: A sequence of bytes to interpret using `encoding`.
/// - encoding: The ecoding to use to interpret `bytes`.
public init? <S: Sequence>(bytes: S, encoding: Encoding)
where S.Iterator.Element == UInt8 {
let byteArray = Array(bytes)
if let ns = NSString(
bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// - (instancetype)
// initWithBytesNoCopy:(void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
// freeWhenDone:(BOOL)flag
/// Creates a new string that contains the specified number of bytes from the
/// given buffer, interpreted in the specified encoding, and optionally
/// frees the buffer.
///
/// - Warning: This initializer is not memory-safe!
public init?(
bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int,
encoding: Encoding, freeWhenDone flag: Bool
) {
if let ns = NSString(
bytesNoCopy: bytes, length: length, encoding: encoding.rawValue,
freeWhenDone: flag) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// - (instancetype)
// initWithCharacters:(const unichar *)characters
// length:(NSUInteger)length
/// Creates a new string that contains the specified number of characters
/// from the given C array of Unicode characters.
public init(
utf16CodeUnits: UnsafePointer<unichar>,
count: Int
) {
self = String._unconditionallyBridgeFromObjectiveC(NSString(characters: utf16CodeUnits, length: count))
}
// - (instancetype)
// initWithCharactersNoCopy:(unichar *)characters
// length:(NSUInteger)length
// freeWhenDone:(BOOL)flag
/// Creates a new string that contains the specified number of characters
/// from the given C array of UTF-16 code units.
public init(
utf16CodeUnitsNoCopy: UnsafePointer<unichar>,
count: Int,
freeWhenDone flag: Bool
) {
self = String._unconditionallyBridgeFromObjectiveC(NSString(
charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy),
length: count,
freeWhenDone: flag))
}
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
/// Produces a string created by reading data from the file at a
/// given path interpreted using a given encoding.
public init(
contentsOfFile path: String,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from the file at
/// a given path and returns by reference the encoding used to
/// interpret the file.
public init(
contentsOfFile path: String,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOfFile: path, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
public init(
contentsOfFile path: String
) throws {
let ns = try NSString(contentsOfFile: path, usedEncoding: nil)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError**)error
/// Produces a string created by reading data from a given URL
/// interpreted using a given encoding. Errors are written into the
/// inout `error` argument.
public init(
contentsOf url: URL,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOf: url, encoding: enc.rawValue)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from a given URL
/// and returns by reference the encoding used to interpret the
/// data. Errors are written into the inout `error` argument.
public init(
contentsOf url: URL,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
public init(
contentsOf url: URL
) throws {
let ns = try NSString(contentsOf: url, usedEncoding: nil)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithCString:(const char *)nullTerminatedCString
// encoding:(NSStringEncoding)encoding
/// Produces a string containing the bytes in a given C array,
/// interpreted according to a given encoding.
public init?(
cString: UnsafePointer<CChar>,
encoding enc: Encoding
) {
if let ns = NSString(cString: cString, encoding: enc.rawValue) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// FIXME: handle optional locale with default arguments
// - (instancetype)
// initWithData:(NSData *)data
// encoding:(NSStringEncoding)encoding
/// Returns a `String` initialized by converting given `data` into
/// Unicode characters using a given `encoding`.
public init?(data: Data, encoding: Encoding) {
guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil }
self = String._unconditionallyBridgeFromObjectiveC(s)
}
// - (instancetype)initWithFormat:(NSString *)format, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted.
public init(format: String, _ arguments: CVarArg...) {
self = String(format: format, arguments: arguments)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to the user's default locale.
public init(format: String, arguments: [CVarArg]) {
self = String(format: format, locale: nil, arguments: arguments)
}
// - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: Locale?, _ args: CVarArg...) {
self = String(format: format, locale: locale, arguments: args)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// locale:(id)locale
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: Locale?, arguments: [CVarArg]) {
#if DEPLOYMENT_RUNTIME_SWIFT
self = withVaList(arguments) {
String._unconditionallyBridgeFromObjectiveC(
NSString(format: format, locale: locale?._bridgeToObjectiveC(), arguments: $0)
)
}
#else
self = withVaList(arguments) {
NSString(format: format, locale: locale, arguments: $0) as String
}
#endif
}
}
extension StringProtocol where Index == String.Index {
//===--- Bridging Helpers -----------------------------------------------===//
//===--------------------------------------------------------------------===//
/// The corresponding `NSString` - a convenience for bridging code.
// FIXME(strings): There is probably a better way to bridge Self to NSString
var _ns: NSString {
return self._ephemeralString._bridgeToObjectiveC()
}
// self can be a Substring so we need to subtract/add this offset when
// passing _ns to the Foundation APIs. Will be 0 if self is String.
@_inlineable
@_versioned
internal var _substringOffset: Int {
return self.startIndex.encodedOffset
}
/// Return an `Index` corresponding to the given offset in our UTF-16
/// representation.
func _index(_ utf16Index: Int) -> Index {
return Index(encodedOffset: utf16Index + _substringOffset)
}
@_inlineable
@_versioned
internal func _toRelativeNSRange(_ r: Range<String.Index>) -> NSRange {
return NSRange(
location: r.lowerBound.encodedOffset - _substringOffset,
length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset)
}
/// Return a `Range<Index>` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _range(_ r: NSRange) -> Range<Index> {
return _index(r.location)..<_index(r.location + r.length)
}
/// Return a `Range<Index>?` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _optionalRange(_ r: NSRange) -> Range<Index>? {
if r.location == NSNotFound {
return nil
}
return _range(r)
}
/// Invoke `body` on an `Int` buffer. If `index` was converted from
/// non-`nil`, convert the buffer to an `Index` and write it into the
/// memory referred to by `index`
func _withOptionalOutParameter<Result>(
_ index: UnsafeMutablePointer<Index>?,
_ body: (UnsafeMutablePointer<Int>?) -> Result
) -> Result {
var utf16Index: Int = 0
let result = (index != nil ? body(&utf16Index) : body(nil))
index?.pointee = _index(utf16Index)
return result
}
/// Invoke `body` on an `NSRange` buffer. If `range` was converted
/// from non-`nil`, convert the buffer to a `Range<Index>` and write
/// it into the memory referred to by `range`
func _withOptionalOutParameter<Result>(
_ range: UnsafeMutablePointer<Range<Index>>?,
_ body: (UnsafeMutablePointer<NSRange>?) -> Result
) -> Result {
var nsRange = NSRange(location: 0, length: 0)
let result = (range != nil ? body(&nsRange) : body(nil))
range?.pointee = self._range(nsRange)
return result
}
//===--- Instance Methods/Properties-------------------------------------===//
//===--------------------------------------------------------------------===//
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// @property BOOL boolValue;
// - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
/// Returns a Boolean value that indicates whether the string can be
/// converted to the specified encoding without loss of information.
///
/// - Parameter encoding: A string encoding.
/// - Returns: `true` if the string can be encoded in `encoding` without loss
/// of information; otherwise, `false`.
public func canBeConverted(to encoding: String.Encoding) -> Bool {
return _ns.canBeConverted(to: encoding.rawValue)
}
// @property NSString* capitalizedString
/// A copy of the string with each word changed to its corresponding
/// capitalized spelling.
///
/// This property performs the canonical (non-localized) mapping. It is
/// suitable for programming operations that require stable results not
/// depending on the current locale.
///
/// A capitalized string is a string with the first character in each word
/// changed to its corresponding uppercase value, and all remaining
/// characters set to their corresponding lowercase values. A "word" is any
/// sequence of characters delimited by spaces, tabs, or line terminators.
/// Some common word delimiting punctuation isn't considered, so this
/// property may not generally produce the desired results for multiword
/// strings. See the `getLineStart(_:end:contentsEnd:for:)` method for
/// additional information.
///
/// Case transformations aren’t guaranteed to be symmetrical or to produce
/// strings of the same lengths as the originals.
public var capitalized: String {
return _ns.capitalized as String
}
// @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0);
/// A capitalized representation of the string that is produced
/// using the current locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedCapitalized: String {
return _ns.localizedCapitalized
}
// - (NSString *)capitalizedStringWithLocale:(Locale *)locale
/// Returns a capitalized representation of the string
/// using the specified locale.
public func capitalized(with locale: Locale?) -> String {
return _ns.capitalized(with: locale) as String
}
// - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
/// Returns the result of invoking `compare:options:` with
/// `NSCaseInsensitiveSearch` as the only option.
public func caseInsensitiveCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.caseInsensitiveCompare(aString._ephemeralString)
}
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// - (unichar)characterAtIndex:(NSUInteger)index
//
// We have a different meaning for "Character" in Swift, and we are
// trying not to expose error-prone UTF-16 integer indexes
// - (NSString *)
// commonPrefixWithString:(NSString *)aString
// options:(StringCompareOptions)mask
/// Returns a string containing characters this string and the
/// given string have in common, starting from the beginning of each
/// up to the first characters that aren't equivalent.
public func commonPrefix<
T : StringProtocol
>(with aString: T, options: String.CompareOptions = []) -> String {
return _ns.commonPrefix(with: aString._ephemeralString, options: options)
}
// - (NSComparisonResult)
// compare:(NSString *)aString
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range locale:(id)locale
/// Compares the string using the specified options and
/// returns the lexical ordering for the range.
public func compare<T : StringProtocol>(
_ aString: T,
options mask: String.CompareOptions = [],
range: Range<Index>? = nil,
locale: Locale? = nil
) -> ComparisonResult {
// According to Ali Ozer, there may be some real advantage to
// dispatching to the minimal selector for the supplied options.
// So let's do that; the switch should compile away anyhow.
let aString = aString._ephemeralString
return locale != nil ? _ns.compare(
aString,
options: mask,
range: _toRelativeNSRange(
range ?? startIndex..<endIndex
),
locale: locale?._bridgeToObjectiveC()
)
: range != nil ? _ns.compare(
aString,
options: mask,
range: _toRelativeNSRange(range!)
)
: !mask.isEmpty ? _ns.compare(aString, options: mask)
: _ns.compare(aString)
}
// - (NSUInteger)
// completePathIntoString:(NSString **)outputName
// caseSensitive:(BOOL)flag
// matchesIntoArray:(NSArray **)outputArray
// filterTypes:(NSArray *)filterTypes
/// Interprets the string as a path in the file system and
/// attempts to perform filename completion, returning a numeric
/// value that indicates whether a match was possible, and by
/// reference the longest path that matches the string.
///
/// - Returns: The actual number of matching paths.
public func completePath(
into outputName: UnsafeMutablePointer<String>? = nil,
caseSensitive: Bool,
matchesInto outputArray: UnsafeMutablePointer<[String]>? = nil,
filterTypes: [String]? = nil
) -> Int {
#if DEPLOYMENT_RUNTIME_SWIFT
var outputNamePlaceholder: String?
var outputArrayPlaceholder = [String]()
let res = self._ns.completePath(
into: &outputNamePlaceholder,
caseSensitive: caseSensitive,
matchesInto: &outputArrayPlaceholder,
filterTypes: filterTypes
)
if let n = outputNamePlaceholder {
outputName?.pointee = n
} else {
outputName?.pointee = ""
}
outputArray?.pointee = outputArrayPlaceholder
return res
#else // DEPLOYMENT_RUNTIME_SWIFT
var nsMatches: NSArray?
var nsOutputName: NSString?
let result: Int = outputName._withNilOrAddress(of: &nsOutputName) {
outputName in outputArray._withNilOrAddress(of: &nsMatches) {
outputArray in
// FIXME: completePath(...) is incorrectly annotated as requiring
// non-optional output parameters. rdar://problem/25494184
let outputNonOptionalName = unsafeBitCast(
outputName, to: AutoreleasingUnsafeMutablePointer<NSString?>.self)
let outputNonOptionalArray = unsafeBitCast(
outputArray, to: AutoreleasingUnsafeMutablePointer<NSArray?>.self)
return self._ns.completePath(
into: outputNonOptionalName,
caseSensitive: caseSensitive,
matchesInto: outputNonOptionalArray,
filterTypes: filterTypes
)
}
}
if let matches = nsMatches {
// Since this function is effectively a bridge thunk, use the
// bridge thunk semantics for the NSArray conversion
outputArray?.pointee = matches as! [String]
}
if let n = nsOutputName {
outputName?.pointee = n as String
}
return result
#endif // DEPLOYMENT_RUNTIME_SWIFT
}
// - (NSArray *)
// componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
/// Returns an array containing substrings from the string
/// that have been divided by characters in the given set.
public func components(separatedBy separator: CharacterSet) -> [String] {
return _ns.components(separatedBy: separator)
}
// - (NSArray *)componentsSeparatedByString:(NSString *)separator
/// Returns an array containing substrings from the string that have been
/// divided by the given separator.
///
/// The substrings in the resulting array appear in the same order as the
/// original string. Adjacent occurrences of the separator string produce
/// empty strings in the result. Similarly, if the string begins or ends
/// with the separator, the first or last substring, respectively, is empty.
/// The following example shows this behavior:
///
/// let list1 = "Karin, Carrie, David"
/// let items1 = list1.components(separatedBy: ", ")
/// // ["Karin", "Carrie", "David"]
///
/// // Beginning with the separator:
/// let list2 = ", Norman, Stanley, Fletcher"
/// let items2 = list2.components(separatedBy: ", ")
/// // ["", "Norman", "Stanley", "Fletcher"
///
/// If the list has no separators, the array contains only the original
/// string itself.
///
/// let name = "Karin"
/// let list = name.components(separatedBy: ", ")
/// // ["Karin"]
///
/// - Parameter separator: The separator string.
/// - Returns: An array containing substrings that have been divided from the
/// string using `separator`.
// FIXME(strings): now when String conforms to Collection, this can be
// replaced by split(separator:maxSplits:omittingEmptySubsequences:)
public func components<
T : StringProtocol
>(separatedBy separator: T) -> [String] {
return _ns.components(separatedBy: separator._ephemeralString)
}
// - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the string as a C string
/// using a given encoding.
public func cString(using encoding: String.Encoding) -> [CChar]? {
return withExtendedLifetime(_ns) {
(s: NSString) -> [CChar]? in
_persistCString(s.cString(using: encoding.rawValue))
}
}
// - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
//
// - (NSData *)
// dataUsingEncoding:(NSStringEncoding)encoding
// allowLossyConversion:(BOOL)flag
/// Returns a `Data` containing a representation of
/// the `String` encoded using a given encoding.
public func data(
using encoding: String.Encoding,
allowLossyConversion: Bool = false
) -> Data? {
return _ns.data(
using: encoding.rawValue,
allowLossyConversion: allowLossyConversion)
}
// @property NSString* decomposedStringWithCanonicalMapping;
/// A string created by normalizing the string's contents using Form D.
public var decomposedStringWithCanonicalMapping: String {
return _ns.decomposedStringWithCanonicalMapping
}
// @property NSString* decomposedStringWithCompatibilityMapping;
/// A string created by normalizing the string's contents using Form KD.
public var decomposedStringWithCompatibilityMapping: String {
return _ns.decomposedStringWithCompatibilityMapping
}
//===--- Importing Foundation should not affect String printing ---------===//
// Therefore, we're not exposing this:
//
// @property NSString* description
//===--- Omitted for consistency with API review results 5/20/2014 -----===//
// @property double doubleValue;
// - (void)
// enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block
/// Enumerates all the lines in a string.
public func enumerateLines(
invoking body: @escaping (_ line: String, _ stop: inout Bool) -> Void
) {
_ns.enumerateLines {
(line: String, stop: UnsafeMutablePointer<ObjCBool>)
in
var stop_ = false
body(line, &stop_)
if stop_ {
stop.pointee = true
}
}
}
// @property NSStringEncoding fastestEncoding;
/// The fastest encoding to which the string can be converted without loss
/// of information.
public var fastestEncoding: String.Encoding {
return String.Encoding(rawValue: _ns.fastestEncoding)
}
// - (BOOL)
// getCString:(char *)buffer
// maxLength:(NSUInteger)maxBufferCount
// encoding:(NSStringEncoding)encoding
/// Converts the `String`'s content to a given encoding and
/// stores them in a buffer.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
public func getCString(
_ buffer: inout [CChar], maxLength: Int, encoding: String.Encoding
) -> Bool {
return _ns.getCString(&buffer,
maxLength: Swift.min(buffer.count, maxLength),
encoding: encoding.rawValue)
}
// - (NSUInteger)hash
/// An unsigned integer that can be used as a hash table address.
public var hash: Int {
return _ns.hash
}
// - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the number of bytes required to store the
/// `String` in a given encoding.
public func lengthOfBytes(using encoding: String.Encoding) -> Int {
return _ns.lengthOfBytes(using: encoding.rawValue)
}
// - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString
/// Compares the string and the given string using a case-insensitive,
/// localized, comparison.
public
func localizedCaseInsensitiveCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.localizedCaseInsensitiveCompare(aString._ephemeralString)
}
// - (NSComparisonResult)localizedCompare:(NSString *)aString
/// Compares the string and the given string using a localized comparison.
public func localizedCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.localizedCompare(aString._ephemeralString)
}
/// Compares the string and the given string as sorted by the Finder.
public func localizedStandardCompare<
T : StringProtocol
>(_ string: T) -> ComparisonResult {
return _ns.localizedStandardCompare(string._ephemeralString)
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property long long longLongValue
// @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0);
/// A lowercase version of the string that is produced using the current
/// locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedLowercase: String {
return _ns.localizedLowercase
}
// - (NSString *)lowercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to lowercase, taking into account the specified
/// locale.
public func lowercased(with locale: Locale?) -> String {
return _ns.lowercased(with: locale)
}
// - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the maximum number of bytes needed to store the
/// `String` in a given encoding.
public
func maximumLengthOfBytes(using encoding: String.Encoding) -> Int {
return _ns.maximumLengthOfBytes(using: encoding.rawValue)
}
// @property NSString* precomposedStringWithCanonicalMapping;
/// A string created by normalizing the string's contents using Form C.
public var precomposedStringWithCanonicalMapping: String {
return _ns.precomposedStringWithCanonicalMapping
}
// @property NSString * precomposedStringWithCompatibilityMapping;
/// A string created by normalizing the string's contents using Form KC.
public var precomposedStringWithCompatibilityMapping: String {
return _ns.precomposedStringWithCompatibilityMapping
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (id)propertyList
/// Parses the `String` as a text representation of a
/// property list, returning an NSString, NSData, NSArray, or
/// NSDictionary object, according to the topmost element.
public func propertyList() -> Any {
return _ns.propertyList()
}
// - (NSDictionary *)propertyListFromStringsFileFormat
/// Returns a dictionary object initialized with the keys and
/// values found in the `String`.
public func propertyListFromStringsFileFormat() -> [String : String] {
return _ns.propertyListFromStringsFileFormat() as! [String : String]? ?? [:]
}
#endif
// - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Returns a Boolean value indicating whether the string contains the given
/// string, taking the current locale into account.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@available(OSX 10.11, iOS 9.0, *)
public func localizedStandardContains<
T : StringProtocol
>(_ string: T) -> Bool {
return _ns.localizedStandardContains(string._ephemeralString)
}
// @property NSStringEncoding smallestEncoding;
/// The smallest encoding to which the string can be converted without
/// loss of information.
public var smallestEncoding: String.Encoding {
return String.Encoding(rawValue: _ns.smallestEncoding)
}
// - (NSString *)
// stringByAddingPercentEncodingWithAllowedCharacters:
// (NSCharacterSet *)allowedCharacters
/// Returns a new string created by replacing all characters in the string
/// not in the specified set with percent encoded characters.
public func addingPercentEncoding(
withAllowedCharacters allowedCharacters: CharacterSet
) -> String? {
// FIXME: the documentation states that this method can return nil if the
// transformation is not possible, without going into further details. The
// implementation can only return nil if malloc() returns nil, so in
// practice this is not possible. Still, to be consistent with
// documentation, we declare the method as returning an optional String.
//
// <rdar://problem/17901698> Docs for -[NSString
// stringByAddingPercentEncodingWithAllowedCharacters] don't precisely
// describe when return value is nil
return _ns.addingPercentEncoding(withAllowedCharacters:
allowedCharacters
)
}
// - (NSString *)stringByAppendingFormat:(NSString *)format, ...
/// Returns a string created by appending a string constructed from a given
/// format string and the following arguments.
public func appendingFormat<
T : StringProtocol
>(
_ format: T, _ arguments: CVarArg...
) -> String {
return _ns.appending(
String(format: format._ephemeralString, arguments: arguments))
}
// - (NSString *)stringByAppendingString:(NSString *)aString
/// Returns a new string created by appending the given string.
// FIXME(strings): shouldn't it be deprecated in favor of `+`?
public func appending<
T : StringProtocol
>(_ aString: T) -> String {
return _ns.appending(aString._ephemeralString)
}
/// Returns a string with the given character folding options
/// applied.
public func folding(
options: String.CompareOptions = [], locale: Locale?
) -> String {
return _ns.folding(options: options, locale: locale)
}
// - (NSString *)stringByPaddingToLength:(NSUInteger)newLength
// withString:(NSString *)padString
// startingAtIndex:(NSUInteger)padIndex
/// Returns a new string formed from the `String` by either
/// removing characters from the end, or by appending as many
/// occurrences as necessary of a given pad string.
public func padding<
T : StringProtocol
>(
toLength newLength: Int,
withPad padString: T,
startingAt padIndex: Int
) -> String {
return _ns.padding(
toLength: newLength,
withPad: padString._ephemeralString,
startingAt: padIndex)
}
// @property NSString* stringByRemovingPercentEncoding;
/// A new string made from the string by replacing all percent encoded
/// sequences with the matching UTF-8 characters.
public var removingPercentEncoding: String? {
return _ns.removingPercentEncoding
}
// - (NSString *)
// stringByReplacingCharactersInRange:(NSRange)range
// withString:(NSString *)replacement
/// Returns a new string in which the characters in a
/// specified range of the `String` are replaced by a given string.
public func replacingCharacters<
T : StringProtocol, R : RangeExpression
>(in range: R, with replacement: T) -> String where R.Bound == Index {
return _ns.replacingCharacters(
in: _toRelativeNSRange(range.relative(to: self)),
with: replacement._ephemeralString)
}
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
//
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
// options:(StringCompareOptions)options
// range:(NSRange)searchRange
/// Returns a new string in which all occurrences of a target
/// string in a specified range of the string are replaced by
/// another given string.
public func replacingOccurrences<
Target : StringProtocol,
Replacement : StringProtocol
>(
of target: Target,
with replacement: Replacement,
options: String.CompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
let target = target._ephemeralString
let replacement = replacement._ephemeralString
return (searchRange != nil) || (!options.isEmpty)
? _ns.replacingOccurrences(
of: target,
with: replacement,
options: options,
range: _toRelativeNSRange(
searchRange ?? startIndex..<endIndex
)
)
: _ns.replacingOccurrences(of: target, with: replacement)
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (NSString *)
// stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a new string made by replacing in the `String`
/// all percent escapes with the matching characters as determined
/// by a given encoding.
@available(swift, deprecated: 3.0, obsoleted: 4.0,
message: "Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding.")
public func replacingPercentEscapes(
using encoding: String.Encoding
) -> String? {
return _ns.replacingPercentEscapes(using: encoding.rawValue)
}
#endif
// - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
/// Returns a new string made by removing from both ends of
/// the `String` characters contained in a given character set.
public func trimmingCharacters(in set: CharacterSet) -> String {
return _ns.trimmingCharacters(in: set)
}
// @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0);
/// An uppercase version of the string that is produced using the current
/// locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedUppercase: String {
return _ns.localizedUppercase as String
}
// - (NSString *)uppercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to uppercase, taking into account the specified
/// locale.
public func uppercased(with locale: Locale?) -> String {
return _ns.uppercased(with: locale)
}
//===--- Omitted due to redundancy with "utf8" property -----------------===//
// - (const char *)UTF8String
// - (BOOL)
// writeToFile:(NSString *)path
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to a file at a given
/// path using a given encoding.
public func write<
T : StringProtocol
>(
toFile path: T, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
try _ns.write(
toFile: path._ephemeralString,
atomically: useAuxiliaryFile,
encoding: enc.rawValue)
}
// - (BOOL)
// writeToURL:(NSURL *)url
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to the URL specified
/// by url using the specified encoding.
public func write(
to url: URL, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
try _ns.write(
to: url, atomically: useAuxiliaryFile, encoding: enc.rawValue)
}
// - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0);
#if !DEPLOYMENT_RUNTIME_SWIFT
/// Perform string transliteration.
@available(OSX 10.11, iOS 9.0, *)
public func applyingTransform(
_ transform: StringTransform, reverse: Bool
) -> String? {
return _ns.applyingTransform(transform, reverse: reverse)
}
// - (void)
// enumerateLinguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(LinguisticTaggerOptions)opts
// orthography:(Orthography *)orthography
// usingBlock:(
// void (^)(
// NSString *tag, NSRange tokenRange,
// NSRange sentenceRange, BOOL *stop)
// )block
/// Performs linguistic analysis on the specified string by
/// enumerating the specific range of the string, providing the
/// Block with the located tags.
public func enumerateLinguisticTags<
T : StringProtocol, R : RangeExpression
>(
in range: R,
scheme tagScheme: T,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
invoking body:
(String, Range<Index>, Range<Index>, inout Bool) -> Void
) where R.Bound == Index {
let range = range.relative(to: self)
_ns.enumerateLinguisticTags(
in: _toRelativeNSRange(range),
scheme: tagScheme._ephemeralString,
options: opts,
orthography: orthography != nil ? orthography! : nil
) {
var stop_ = false
body($0, self._range($1), self._range($2), &stop_)
if stop_ {
$3.pointee = true
}
}
}
#endif
// - (void)
// enumerateSubstringsInRange:(NSRange)range
// options:(NSStringEnumerationOptions)opts
// usingBlock:(
// void (^)(
// NSString *substring,
// NSRange substringRange,
// NSRange enclosingRange,
// BOOL *stop)
// )block
/// Enumerates the substrings of the specified type in the specified range of
/// the string.
///
/// Mutation of a string value while enumerating its substrings is not
/// supported. If you need to mutate a string from within `body`, convert
/// your string to an `NSMutableString` instance and then call the
/// `enumerateSubstrings(in:options:using:)` method.
///
/// - Parameters:
/// - range: The range within the string to enumerate substrings.
/// - opts: Options specifying types of substrings and enumeration styles.
/// If `opts` is omitted or empty, `body` is called a single time with
/// the range of the string specified by `range`.
/// - body: The closure executed for each substring in the enumeration. The
/// closure takes four arguments:
/// - The enumerated substring. If `substringNotRequired` is included in
/// `opts`, this parameter is `nil` for every execution of the
/// closure.
/// - The range of the enumerated substring in the string that
/// `enumerate(in:options:_:)` was called on.
/// - The range that includes the substring as well as any separator or
/// filler characters that follow. For instance, for lines,
/// `enclosingRange` contains the line terminators. The enclosing
/// range for the first string enumerated also contains any characters
/// that occur before the string. Consecutive enclosing ranges are
/// guaranteed not to overlap, and every single character in the
/// enumerated range is included in one and only one enclosing range.
/// - An `inout` Boolean value that the closure can use to stop the
/// enumeration by setting `stop = true`.
public func enumerateSubstrings<
R : RangeExpression
>(
in range: R,
options opts: String.EnumerationOptions = [],
_ body: @escaping (
_ substring: String?, _ substringRange: Range<Index>,
_ enclosingRange: Range<Index>, inout Bool
) -> Void
) where R.Bound == Index {
_ns.enumerateSubstrings(
in: _toRelativeNSRange(range.relative(to: self)), options: opts) {
var stop_ = false
body($0,
self._range($1),
self._range($2),
&stop_)
if stop_ {
UnsafeMutablePointer($3).pointee = true
}
}
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property float floatValue;
// - (BOOL)
// getBytes:(void *)buffer
// maxLength:(NSUInteger)maxBufferCount
// usedLength:(NSUInteger*)usedBufferCount
// encoding:(NSStringEncoding)encoding
// options:(StringEncodingConversionOptions)options
// range:(NSRange)range
// remainingRange:(NSRangePointer)leftover
/// Writes the given `range` of characters into `buffer` in a given
/// `encoding`, without any allocations. Does not NULL-terminate.
///
/// - Parameter buffer: A buffer into which to store the bytes from
/// the receiver. The returned bytes are not NUL-terminated.
///
/// - Parameter maxBufferCount: The maximum number of bytes to write
/// to buffer.
///
/// - Parameter usedBufferCount: The number of bytes used from
/// buffer. Pass `nil` if you do not need this value.
///
/// - Parameter encoding: The encoding to use for the returned bytes.
///
/// - Parameter options: A mask to specify options to use for
/// converting the receiver's contents to `encoding` (if conversion
/// is necessary).
///
/// - Parameter range: The range of characters in the receiver to get.
///
/// - Parameter leftover: The remaining range. Pass `nil` If you do
/// not need this value.
///
/// - Returns: `true` iff some characters were converted.
///
/// - Note: Conversion stops when the buffer fills or when the
/// conversion isn't possible due to the chosen encoding.
///
/// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes.
public func getBytes<
R : RangeExpression
>(
_ buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: String.Encoding,
options: String.EncodingConversionOptions = [],
range: R,
remaining leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool where R.Bound == Index {
return _withOptionalOutParameter(leftover) {
self._ns.getBytes(
&buffer,
maxLength: Swift.min(buffer.count, maxBufferCount),
usedLength: usedBufferCount,
encoding: encoding.rawValue,
options: options,
range: _toRelativeNSRange(range.relative(to: self)),
remaining: $0)
}
}
// - (void)
// getLineStart:(NSUInteger *)startIndex
// end:(NSUInteger *)lineEndIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first line and
/// the end of the last line touched by the given range.
public func getLineStart<
R : RangeExpression
>(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: R
) where R.Bound == Index {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getLineStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toRelativeNSRange(range.relative(to: self)))
}
}
}
}
// - (void)
// getParagraphStart:(NSUInteger *)startIndex
// end:(NSUInteger *)endIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first paragraph
/// and the end of the last paragraph touched by the given range.
public func getParagraphStart<
R : RangeExpression
>(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: R
) where R.Bound == Index {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getParagraphStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toRelativeNSRange(range.relative(to: self)))
}
}
}
}
//===--- Already provided by core Swift ---------------------------------===//
// - (instancetype)initWithString:(NSString *)aString
//===--- Initializers that can fail dropped for factory functions -------===//
// - (instancetype)initWithUTF8String:(const char *)bytes
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property NSInteger integerValue;
// @property Int intValue;
//===--- Omitted by apparent agreement during API review 5/20/2014 ------===//
// @property BOOL absolutePath;
// - (BOOL)isEqualToString:(NSString *)aString
// - (NSRange)lineRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the line or lines
/// containing a given range.
public func lineRange<
R : RangeExpression
>(for aRange: R) -> Range<Index> where R.Bound == Index {
return _range(_ns.lineRange(
for: _toRelativeNSRange(aRange.relative(to: self))))
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (NSArray *)
// linguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(LinguisticTaggerOptions)opts
// orthography:(Orthography *)orthography
// tokenRanges:(NSArray**)tokenRanges
/// Returns an array of linguistic tags for the specified
/// range and requested tags within the receiving string.
public func linguisticTags<
T : StringProtocol, R : RangeExpression
>(
in range: R,
scheme tagScheme: T,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil // FIXME:Can this be nil?
) -> [String] where R.Bound == Index {
var nsTokenRanges: NSArray?
let result = tokenRanges._withNilOrAddress(of: &nsTokenRanges) {
self._ns.linguisticTags(
in: _toRelativeNSRange(range.relative(to: self)),
scheme: tagScheme._ephemeralString,
options: opts,
orthography: orthography,
tokenRanges: $0) as NSArray
}
if let nsTokenRanges = nsTokenRanges {
tokenRanges?.pointee = (nsTokenRanges as [AnyObject]).map {
self._range($0.rangeValue)
}
}
return result as! [String]
}
// - (NSRange)paragraphRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the
/// paragraph or paragraphs containing a given range.
public func paragraphRange<
R : RangeExpression
>(for aRange: R) -> Range<Index> where R.Bound == Index {
return _range(
_ns.paragraphRange(for: _toRelativeNSRange(aRange.relative(to: self))))
}
#endif
// - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(StringCompareOptions)mask
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(StringCompareOptions)mask
// range:(NSRange)aRange
/// Finds and returns the range in the `String` of the first
/// character from a given character set found in a given range with
/// given options.
public func rangeOfCharacter(
from aSet: CharacterSet,
options mask: String.CompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
return _optionalRange(
_ns.rangeOfCharacter(
from: aSet,
options: mask,
range: _toRelativeNSRange(
aRange ?? startIndex..<endIndex
)
)
)
}
// - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex
/// Returns the range in the `String` of the composed
/// character sequence located at a given index.
public
func rangeOfComposedCharacterSequence(at anIndex: Index) -> Range<Index> {
return _range(
_ns.rangeOfComposedCharacterSequence(at: anIndex.encodedOffset))
}
// - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range
/// Returns the range in the string of the composed character
/// sequences for a given range.
public func rangeOfComposedCharacterSequences<
R : RangeExpression
>(
for range: R
) -> Range<Index> where R.Bound == Index {
// Theoretically, this will be the identity function. In practice
// I think users will be able to observe differences in the input
// and output ranges due (if nothing else) to locale changes
return _range(
_ns.rangeOfComposedCharacterSequences(
for: _toRelativeNSRange(range.relative(to: self))))
}
// - (NSRange)rangeOfString:(NSString *)aString
//
// - (NSRange)
// rangeOfString:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(StringCompareOptions)mask
// range:(NSRange)aRange
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(StringCompareOptions)mask
// range:(NSRange)searchRange
// locale:(Locale *)locale
/// Finds and returns the range of the first occurrence of a
/// given string within a given range of the `String`, subject to
/// given options, using the specified locale, if any.
public func range<
T : StringProtocol
>(
of aString: T,
options mask: String.CompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: Locale? = nil
) -> Range<Index>? {
let aString = aString._ephemeralString
return _optionalRange(
locale != nil ? _ns.range(
of: aString,
options: mask,
range: _toRelativeNSRange(
searchRange ?? startIndex..<endIndex
),
locale: locale
)
: searchRange != nil ? _ns.range(
of: aString, options: mask, range: _toRelativeNSRange(searchRange!)
)
: !mask.isEmpty ? _ns.range(of: aString, options: mask)
: _ns.range(of: aString)
)
}
// - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Finds and returns the range of the first occurrence of a given string,
/// taking the current locale into account. Returns `nil` if the string was
/// not found.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@available(OSX 10.11, iOS 9.0, *)
public func localizedStandardRange<
T : StringProtocol
>(of string: T) -> Range<Index>? {
return _optionalRange(
_ns.localizedStandardRange(of: string._ephemeralString))
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (NSString *)
// stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the `String` using a given
/// encoding to determine the percent escapes necessary to convert
/// the `String` into a legal URL string.
@available(swift, deprecated: 3.0, obsoleted: 4.0,
message: "Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.")
public func addingPercentEscapes(
using encoding: String.Encoding
) -> String? {
return _ns.addingPercentEscapes(using: encoding.rawValue)
}
#endif
//===--- From the 10.10 release notes; not in public documentation ------===//
// No need to make these unavailable on earlier OSes, since they can
// forward trivially to rangeOfString.
/// Returns `true` iff `other` is non-empty and contained within
/// `self` by case-sensitive, non-literal search.
///
/// Equivalent to `self.rangeOfString(other) != nil`
public func contains<T : StringProtocol>(_ other: T) -> Bool {
let r = self.range(of: other) != nil
if #available(OSX 10.10, iOS 8.0, *) {
_sanityCheck(r == _ns.contains(other._ephemeralString))
}
return r
}
/// Returns a Boolean value indicating whether the given string is non-empty
/// and contained within this string by case-insensitive, non-literal
/// search, taking into account the current locale.
///
/// Locale-independent case-insensitive operation, and other needs, can be
/// achieved by calling `range(of:options:range:locale:)`.
///
/// Equivalent to:
///
/// range(of: other, options: .caseInsensitiveSearch,
/// locale: Locale.current) != nil
public func localizedCaseInsensitiveContains<
T : StringProtocol
>(_ other: T) -> Bool {
let r = self.range(
of: other, options: .caseInsensitive, locale: Locale.current
) != nil
if #available(OSX 10.10, iOS 8.0, *) {
_sanityCheck(r ==
_ns.localizedCaseInsensitiveContains(other._ephemeralString))
}
return r
}
}
// Deprecated slicing
extension StringProtocol where Index == String.Index {
// - (NSString *)substringFromIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` from the one at a given index to the end.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript with a 'partial range from' operator.")
public func substring(from index: Index) -> String {
return _ns.substring(from: index.encodedOffset)
}
// - (NSString *)substringToIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` up to, but not including, the one at a given index.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript with a 'partial range upto' operator.")
public func substring(to index: Index) -> String {
return _ns.substring(to: index.encodedOffset)
}
// - (NSString *)substringWithRange:(NSRange)aRange
/// Returns a string object containing the characters of the
/// `String` that lie within a given range.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript.")
public func substring(with aRange: Range<Index>) -> String {
return _ns.substring(with: _toRelativeNSRange(aRange))
}
}
extension StringProtocol {
// - (const char *)fileSystemRepresentation
/// Returns a file system-specific representation of the `String`.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public var fileSystemRepresentation: [CChar] {
fatalError("unavailable function can't be called")
}
// - (BOOL)
// getFileSystemRepresentation:(char *)buffer
// maxLength:(NSUInteger)maxLength
/// Interprets the `String` as a system-independent path and
/// fills a buffer with a C-string in a format and encoding suitable
/// for use with file-system calls.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public func getFileSystemRepresentation(
_ buffer: inout [CChar], maxLength: Int) -> Bool {
fatalError("unavailable function can't be called")
}
//===--- Kept for consistency with API review results 5/20/2014 ---------===//
// We decided to keep pathWithComponents, so keeping this too
// @property NSString lastPathComponent;
/// Returns the last path component of the `String`.
@available(*, unavailable, message: "Use lastPathComponent on URL instead.")
public var lastPathComponent: String {
fatalError("unavailable function can't be called")
}
//===--- Renamed by agreement during API review 5/20/2014 ---------------===//
// @property NSUInteger length;
/// Returns the number of Unicode characters in the `String`.
@available(*, unavailable,
message: "Take the count of a UTF-16 view instead, i.e. str.utf16.count")
public var utf16Count: Int {
fatalError("unavailable function can't be called")
}
// @property NSArray* pathComponents
/// Returns an array of NSString objects containing, in
/// order, each path component of the `String`.
@available(*, unavailable, message: "Use pathComponents on URL instead.")
public var pathComponents: [String] {
fatalError("unavailable function can't be called")
}
// @property NSString* pathExtension;
/// Interprets the `String` as a path and returns the
/// `String`'s extension, if any.
@available(*, unavailable, message: "Use pathExtension on URL instead.")
public var pathExtension: String {
fatalError("unavailable function can't be called")
}
// @property NSString *stringByAbbreviatingWithTildeInPath;
/// Returns a new string that replaces the current home
/// directory portion of the current path with a tilde (`~`)
/// character.
@available(*, unavailable, message: "Use abbreviatingWithTildeInPath on NSString instead.")
public var abbreviatingWithTildeInPath: String {
fatalError("unavailable function can't be called")
}
// - (NSString *)stringByAppendingPathComponent:(NSString *)aString
/// Returns a new string made by appending to the `String` a given string.
@available(*, unavailable, message: "Use appendingPathComponent on URL instead.")
public func appendingPathComponent(_ aString: String) -> String {
fatalError("unavailable function can't be called")
}
// - (NSString *)stringByAppendingPathExtension:(NSString *)ext
/// Returns a new string made by appending to the `String` an
/// extension separator followed by a given extension.
@available(*, unavailable, message: "Use appendingPathExtension on URL instead.")
public func appendingPathExtension(_ ext: String) -> String? {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByDeletingLastPathComponent;
/// Returns a new string made by deleting the last path
/// component from the `String`, along with any final path
/// separator.
@available(*, unavailable, message: "Use deletingLastPathComponent on URL instead.")
public var deletingLastPathComponent: String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByDeletingPathExtension;
/// Returns a new string made by deleting the extension (if
/// any, and only the last) from the `String`.
@available(*, unavailable, message: "Use deletingPathExtension on URL instead.")
public var deletingPathExtension: String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByExpandingTildeInPath;
/// Returns a new string made by expanding the initial
/// component of the `String` to its full path value.
@available(*, unavailable, message: "Use expandingTildeInPath on NSString instead.")
public var expandingTildeInPath: String {
fatalError("unavailable function can't be called")
}
// - (NSString *)
// stringByFoldingWithOptions:(StringCompareOptions)options
// locale:(Locale *)locale
@available(*, unavailable, renamed: "folding(options:locale:)")
public func folding(
_ options: String.CompareOptions = [], locale: Locale?
) -> String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByResolvingSymlinksInPath;
/// Returns a new string made from the `String` by resolving
/// all symbolic links and standardizing path.
@available(*, unavailable, message: "Use resolvingSymlinksInPath on URL instead.")
public var resolvingSymlinksInPath: String {
fatalError("unavailable property")
}
// @property NSString* stringByStandardizingPath;
/// Returns a new string made by removing extraneous path
/// components from the `String`.
@available(*, unavailable, message: "Use standardizingPath on URL instead.")
public var standardizingPath: String {
fatalError("unavailable function can't be called")
}
// - (NSArray *)stringsByAppendingPaths:(NSArray *)paths
/// Returns an array of strings made by separately appending
/// to the `String` each string in a given array.
@available(*, unavailable, message: "Map over paths with appendingPathComponent instead.")
public func strings(byAppendingPaths paths: [String]) -> [String] {
fatalError("unavailable function can't be called")
}
}
// Pre-Swift-3 method names
extension String {
@available(*, unavailable, renamed: "localizedName(of:)")
public static func localizedNameOfStringEncoding(
_ encoding: String.Encoding
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.")
public static func pathWithComponents(_ components: [String]) -> String {
fatalError("unavailable function can't be called")
}
// + (NSString *)pathWithComponents:(NSArray *)components
/// Returns a string built from the strings in a given array
/// by concatenating them with a path separator between each pair.
@available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.")
public static func path(withComponents components: [String]) -> String {
fatalError("unavailable function can't be called")
}
}
extension StringProtocol {
@available(*, unavailable, renamed: "canBeConverted(to:)")
public func canBeConvertedToEncoding(_ encoding: String.Encoding) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "capitalizedString(with:)")
public func capitalizedStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "commonPrefix(with:options:)")
public func commonPrefixWith(
_ aString: String, options: String.CompareOptions) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "completePath(into:outputName:caseSensitive:matchesInto:filterTypes:)")
public func completePathInto(
_ outputName: UnsafeMutablePointer<String>? = nil,
caseSensitive: Bool,
matchesInto matchesIntoArray: UnsafeMutablePointer<[String]>? = nil,
filterTypes: [String]? = nil
) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "components(separatedBy:)")
public func componentsSeparatedByCharactersIn(
_ separator: CharacterSet
) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "components(separatedBy:)")
public func componentsSeparatedBy(_ separator: String) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "cString(usingEncoding:)")
public func cStringUsingEncoding(_ encoding: String.Encoding) -> [CChar]? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "data(usingEncoding:allowLossyConversion:)")
public func dataUsingEncoding(
_ encoding: String.Encoding,
allowLossyConversion: Bool = false
) -> Data? {
fatalError("unavailable function can't be called")
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@available(*, unavailable, renamed: "enumerateLinguisticTags(in:scheme:options:orthography:_:)")
public func enumerateLinguisticTagsIn(
_ range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options,
orthography: NSOrthography?,
_ body:
(String, Range<Index>, Range<Index>, inout Bool) -> Void
) {
fatalError("unavailable function can't be called")
}
#endif
@available(*, unavailable, renamed: "enumerateSubstrings(in:options:_:)")
public func enumerateSubstringsIn(
_ range: Range<Index>,
options opts: String.EnumerationOptions = [],
_ body: (
_ substring: String?, _ substringRange: Range<Index>,
_ enclosingRange: Range<Index>, inout Bool
) -> Void
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)")
public func getBytes(
_ buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: String.Encoding,
options: String.EncodingConversionOptions = [],
range: Range<Index>,
remainingRange leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getLineStart(_:end:contentsEnd:for:)")
public func getLineStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getParagraphStart(_:end:contentsEnd:for:)")
public func getParagraphStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lengthOfBytes(using:)")
public func lengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lineRange(for:)")
public func lineRangeFor(_ aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@available(*, unavailable, renamed: "linguisticTags(in:scheme:options:orthography:tokenRanges:)")
public func linguisticTagsIn(
_ range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil
) -> [String] {
fatalError("unavailable function can't be called")
}
#endif
@available(*, unavailable, renamed: "lowercased(with:)")
public func lowercaseStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "maximumLengthOfBytes(using:)")
public
func maximumLengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "paragraphRange(for:)")
public func paragraphRangeFor(_ aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfCharacter(from:options:range:)")
public func rangeOfCharacterFrom(
_ aSet: CharacterSet,
options mask: String.CompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfComposedCharacterSequence(at:)")
public
func rangeOfComposedCharacterSequenceAt(_ anIndex: Index) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfComposedCharacterSequences(for:)")
public func rangeOfComposedCharacterSequencesFor(
_ range: Range<Index>
) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "range(of:options:range:locale:)")
public func rangeOf(
_ aString: String,
options mask: String.CompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: Locale? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "localizedStandardRange(of:)")
public func localizedStandardRangeOf(_ string: String) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "addingPercentEncoding(withAllowedCharacters:)")
public func addingPercentEncodingWithAllowedCharacters(
_ allowedCharacters: CharacterSet
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "addingPercentEscapes(using:)")
public func addingPercentEscapesUsingEncoding(
_ encoding: String.Encoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "appendingFormat")
public func stringByAppendingFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "padding(toLength:with:startingAt:)")
public func byPaddingToLength(
_ newLength: Int, withString padString: String, startingAt padIndex: Int
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingCharacters(in:with:)")
public func replacingCharactersIn(
_ range: Range<Index>, withString replacement: String
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingOccurrences(of:with:options:range:)")
public func replacingOccurrencesOf(
_ target: String,
withString replacement: String,
options: String.CompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingPercentEscapes(usingEncoding:)")
public func replacingPercentEscapesUsingEncoding(
_ encoding: String.Encoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "trimmingCharacters(in:)")
public func byTrimmingCharactersIn(_ set: CharacterSet) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "strings(byAppendingPaths:)")
public func stringsByAppendingPaths(_ paths: [String]) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(from:)")
public func substringFrom(_ index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(to:)")
public func substringTo(_ index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(with:)")
public func substringWith(_ aRange: Range<Index>) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "uppercased(with:)")
public func uppercaseStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "write(toFile:atomically:encoding:)")
public func writeToFile(
_ path: String, atomically useAuxiliaryFile:Bool,
encoding enc: String.Encoding
) throws {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "write(to:atomically:encoding:)")
public func writeToURL(
_ url: URL, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
fatalError("unavailable function can't be called")
}
}
| cd2f8482f020caa0257460170e873d8c | 34.422581 | 279 | 0.677014 | false | false | false | false |
starhoshi/pi-chan | refs/heads/master | pi-chan/ViewControllers/Posts/Cell/PostTableViewCell.swift | mit | 1 | //
// PostTableViewCell.swift
// pi-chan
//
// Created by Kensuke Hoshikawa on 2016/04/06.
// Copyright © 2016年 star__hoshi. All rights reserved.
//
import UIKit
import Kingfisher
import Font_Awesome_Swift
import SwiftDate
import NSDate_TimeAgo
import MGSwipeTableCell
class PostTableViewCell: MGSwipeTableCell {
@IBOutlet weak var contentsView: UIView!
@IBOutlet weak var circleThumbnail: UIImageView!
@IBOutlet weak var circleUpdateThumbnail: UIImageView!
@IBOutlet weak var wip: UILabel!
@IBOutlet weak var category: UILabel!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var createdBy: UILabel!
@IBOutlet weak var starIcon: UILabel!
@IBOutlet weak var starCount: UILabel!
@IBOutlet weak var eyeIcon: UILabel!
@IBOutlet weak var eyeCount: UILabel!
@IBOutlet weak var commentsIcon: UILabel!
@IBOutlet weak var commentsCount: UILabel!
@IBOutlet weak var checkIcon: UILabel!
@IBOutlet weak var checkCount: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
starIcon.setFAIcon(.FAStar, iconSize: 14)
eyeIcon.setFAIcon(.FAEye, iconSize: 14)
commentsIcon.setFAIcon(.FAComments, iconSize: 14)
checkIcon.setFAIcon(.FACheckSquareO, iconSize: 14)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setItems(post:Post){
category.text = post.category
title.text = post.name
starIcon.textColor = post.star ? UIColor.esaGreen() : UIColor.esaFontBlue()
eyeIcon.textColor = post.watch ? UIColor.esaGreen() : UIColor.esaFontBlue()
starCount.text = String(post.stargazersCount)
eyeCount.text = String(post.watchersCount)
commentsCount.text = String(post.commentsCount)
checkCount.text = "\(post.doneTasksCount)/\(post.tasksCount)"
wip.hidden = !post.wip
contentsView.alpha = post.wip ? 0.5 : 1.0
setCreatedBy(post)
setThumbnail(post)
}
func setThumbnail(post:Post){
circleThumbnail.toCircle().kf_setImageWithURL(post.createdBy.icon)
circleUpdateThumbnail.hidden = post.createdBy.screenName == post.updatedBy.screenName ? true:false
circleUpdateThumbnail.toCircle().kf_setImageWithURL(post.updatedBy.icon)
}
func setCreatedBy(post:Post){
var createdByText = ""
if post.updatedAt == post.createdAt {
createdByText += "Created by \(post.createdBy.screenName) | "
createdByText += post.createdAt.toDateFromISO8601()!.timeAgo()
} else {
createdByText += "Updated by \(post.updatedBy.screenName) | "
createdByText += post.updatedAt.toDateFromISO8601()!.timeAgo()
}
createdBy.text = createdByText
}
}
| 3d5184f092249eb03c4954287d6cfbae | 33.115385 | 102 | 0.726419 | false | false | false | false |
pyanfield/ataturk_olympic | refs/heads/master | swift_programming_extensions.playground/section-1.swift | mit | 1 | // Playground - noun: a place where people can play
import UIKit
// 2.20
// 扩展就是向一个已有的类、结构体或枚举类型添加新功能(functionality)。
// 扩展和 Objective-C 中的分类(categories)类似。(不过与Objective-C不同的是,Swift 的扩展没有名字。)
// Swift 中的扩展可以:
// 添加计算型属性和计算静态属性
// 定义实例方法和类型方法
// 提供新的构造器
// 定义下标
// 定义和使用新的嵌套类型
// 使一个已有类型符合某个协议
// 声明一个扩展使用关键字extension:
// extension SomeType: SomeProtocol, AnotherProctocol {
// // 协议实现写到这里
// }
extension Double {
var km: Double { return self * 1_000.0 }
var m : Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
println("One inch is \(oneInch) meters")
let threeFeet = 3.ft
println("Three feet is \(threeFeet) meters")
// 扩展可以添加新的计算属性,但是不可以添加存储属性,也不可以向已有属性添加属性观测器(property observers)。
// 扩展能向类中添加新的便利构造器,但是它们不能向类中添加新的指定构造器或析构函数。指定构造器和析构函数必须总是由原始的类实现来提供。
struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
}
let defaultRect = Rect()
let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0),
size: Size(width: 5.0, height: 5.0))
extension Rect {
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
let centerRect = Rect(center: Point(x: 4.0, y: 4.0),
size: Size(width: 3.0, height: 3.0))
// 扩展方法 Methods
extension Int{
// 传入的时一个没有参数没有返回值的函数
func repetitions(task: () -> ()){
for i in 0..<self{
task()
}
}
// 结构体和枚举类型中修改self或其属性的方法必须将该实例方法标注为mutating,正如来自原始实现的修改方法一样。
mutating func square(){
self = self * self
}
subscript(digitIndex: Int) -> Int{
var decimalBase = 1
for _ in 1...digitIndex{
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
3.repetitions{
println("Test repetition function on Int")
}
var three = 3
three.square()
println(three)
println(12345678[5])
// 扩展添加嵌套类型
extension Character {
enum Kind {
case Vowel, Consonant, Other
}
var kind: Kind {
switch String(self).lowercaseString {
case "a", "e", "i", "o", "u":
return .Vowel
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
return .Consonant
default:
return .Other
}
}
}
func printLetterKinds(word: String) {
println("'\(word)' is made up of the following kinds of letters:")
for character in word {
switch character.kind {
case .Vowel:
print("vowel ")
case .Consonant:
print("consonant ")
case .Other:
print("other ")
}
}
print("\n")
}
printLetterKinds("Hello")
| 46bd0c979b6ea6fb37e15b845c68f3b1 | 21.781955 | 73 | 0.568647 | false | false | false | false |
rsaenzi/MyCurrencyConverterApp | refs/heads/master | MyCurrencyConverterApp/MyCurrencyConverterAppTests/App/AccessControllers/ApiAccess/Test_ApiRequest.swift | mit | 1 | //
// Test_ApiRequest.swift
// MyCurrencyConverterApp
//
// Created by Rigoberto Sáenz Imbacuán on 8/7/16.
// Copyright © 2016 Rigoberto Sáenz Imbacuán [https://www.linkedin.com/in/rsaenzi]. All rights reserved.
//
import XCTest
@testable import MyCurrencyConverterApp
class Test_ApiRequest: XCTestCase {
func test_getUniqueInstance() {
// Only the first call should receive a valid instance...
let _ = CurrencyConverter.app.control.apiRequest
// After the first call ge must get nil...
for _ in 0...10 {
XCTAssertNil(ApiRequest.getUniqueInstance())
}
}
func test_endpointGetExchangeRates(){
// Make the request
CurrencyConverter.app.control.apiRequest.endpointGetExchangeRates({ (response) in
// Must inform the success of the data parsing
XCTAssert(response.responseCode == eResponseCodeGetExchangeRates.Success_200)
XCTAssert(response.responseMessage == "Success!")
}) { (httpCode, nsError, errorDescription) in
// Data can no be fetched...
XCTFail()
}
}
}
| d6c5b4c26729fc66aa9695d6230be06d | 28.439024 | 105 | 0.610605 | false | true | false | false |
24/ios-o2o-c | refs/heads/master | gxc/Order/OrderDetailViewController.swift | mit | 1 |
import Foundation
import UIKit
class OrderDetailViewController: UIViewController,UIWebViewDelegate {
var leftView = UIView()
var rightView = UIView()
var leftBtn = UIButton()
var rightBtn = UIButton()
var contentView = UIView()
var scrollView = UIScrollView()
var containerView: UIView!
var buyBtn = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "bar_back.png"), style: UIBarButtonItemStyle.Done, target: self, action: Selector("NavigationControllerBack"))
self.navigationItem.title = "订单详情"
self.navigationController?.navigationBar.barTintColor = UIColor(fromHexString: "#008FD7")
var navigationBar = self.navigationController?.navigationBar
/*navigation 不遮住View*/
self.automaticallyAdjustsScrollViewInsets = false
self.edgesForExtendedLayout = UIRectEdge()
/*self view*/
self.view.backgroundColor = UIColor.whiteColor()
navigationBar?.tintColor = UIColor.whiteColor()
var containerSize = CGSize(width: self.view.bounds.width, height: 540)
containerView = UIView(frame: CGRect(origin: CGPoint(x: 0, y:0), size:containerSize))
scrollView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
scrollView.contentSize = containerSize
scrollView.addSubview(containerView)
self.view.addSubview(scrollView)
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("User_Order_Detail:"), name: GXNotifaction_User_Order_Detail, object: nil)
GxApiCall().OrderDetail(GXViewState.userInfo.Token!, orderId: NSString(format: "%.0f",GXViewState.ShopOrderDetail.OrderId!))
let superview: UIView = containerView
var mySegcon = UISegmentedControl(items: ["订单详情","衣物列表"])
mySegcon.selectedSegmentIndex = 0
mySegcon.backgroundColor = UIColor.whiteColor()
mySegcon.tintColor = UIColor(fromHexString: "#008FD7")
containerView.addSubview(mySegcon)
mySegcon.addTarget(self, action: "segconChanged:", forControlEvents: UIControlEvents.ValueChanged)
mySegcon.snp_makeConstraints { make in
make.top.equalTo(superview.snp_top).offset(5)
make.centerX.equalTo(superview.snp_centerX)
make.width.equalTo(200)
make.height.equalTo(35)
}
containerView.addSubview(contentView)
contentView.snp_makeConstraints { make in
make.top.equalTo(mySegcon.snp_bottom).offset(10)
make.left.equalTo(superview.snp_left)
make.width.equalTo(superview)
make.height.equalTo(380)
}
}
func segconChanged(segcon: UISegmentedControl)
{
var leftView = OrderDetailLeftViewController()
var rightView = OrderDetailRightViewController()
removeSubView()
switch segcon.selectedSegmentIndex
{
case 0:
segcon.selectedSegmentIndex = 0
buyBtn.hidden = false
contentView.addSubview(leftView.view)
case 1:
segcon.selectedSegmentIndex = 1
buyBtn.hidden = true
contentView.addSubview(rightView.view)
default:
break;
}
}
func removeSubView()
{
let views = contentView.subviews
for s in views
{
s.removeFromSuperview()
}
}
func User_Order_Detail(notif :NSNotification)
{
let superview: UIView = self.view
removeSubView()
MBProgressHUD.hideHUDForView(self.view, animated: true)
var shopOrderDetail = notif.userInfo?["GXNotifaction_User_Order_Detail"] as GX_OrderDetail
GXViewState.OrderDetail = shopOrderDetail
var orderDetail = shopOrderDetail.shopDetail!
var leftView = OrderDetailLeftViewController()
contentView.addSubview(leftView.view)
//预约送衣服和 评论订单
if(orderDetail.CanCancle!)
{
buyBtn.setTitle("取消订单", forState: UIControlState.Normal)
buyBtn.addTarget(self, action: Selector("CancelOrder"), forControlEvents: UIControlEvents.TouchUpInside)
}
else if(orderDetail.CanSend!)
{
buyBtn.setTitle("预约送衣", forState: UIControlState.Normal)
buyBtn.addTarget(self, action: Selector("SendOrder"), forControlEvents: UIControlEvents.TouchUpInside)
}
else if(orderDetail.CanComment!)
{
buyBtn.setTitle("评论订单", forState: UIControlState.Normal)
buyBtn.addTarget(self, action: Selector("CommonOrder"), forControlEvents: UIControlEvents.TouchUpInside)
}
if(!orderDetail.IsPay! && orderDetail.NoPayAmount > 0 && (orderDetail.Status! == 3 || orderDetail.Status! == 4 || orderDetail.Status! == 5 || orderDetail.Status! == 6))
{
buyBtn.setTitle("去支付", forState: UIControlState.Normal)
buyBtn.addTarget(self, action: Selector("PayGo"), forControlEvents: UIControlEvents.TouchUpInside)
}
buyBtn.backgroundColor = UIColor(fromHexString: "#E61D4C")
self.view.addSubview(buyBtn)
buyBtn.snp_makeConstraints { make in
make.top.equalTo(self.contentView.snp_bottom)
make.left.equalTo(0).offset(5)
make.right.equalTo(self.contentView).offset(-5)
make.height.equalTo(40)
}
buyBtn.layer.cornerRadius = 4
if(buyBtn.titleLabel?.text == nil || buyBtn.titleLabel?.text == "" )
{
buyBtn.removeFromSuperview()
}
}
func CancelOrder()
{
self.navigationController?.pushViewController(CancelOrderViewController(), animated: true)
}
func SendOrder()
{
//预约送衣服
self.navigationController?.pushViewController(SendOrderViewController(), animated: true)
}
func CommonOrder()
{
//评论订单
self.navigationController?.pushViewController(CommonOrderViewController(), animated: true)
}
func PayGo()
{
self.navigationController?.pushViewController(PayViewController(), animated: true)
}
override func viewDidAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("User_Order_Detail:"), name: GXNotifaction_User_Order_Detail, object: nil)
GxApiCall().OrderDetail(GXViewState.userInfo.Token!, orderId: NSString(format: "%.0f",GXViewState.ShopOrderDetail.OrderId!))
}
func NavigationControllerBack()
{
self.navigationController?.popViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 7dfbc45c2f3fbcbfef1183b0fe0b1206 | 28.390438 | 199 | 0.619086 | false | false | false | false |
fuji2013/FJSImageViewController | refs/heads/master | FJSImageViewController/FJSImageViewController.swift | mit | 1 | //
// FJSImageViewController.swift
// FJSImageViewController
//
// Created by hf on 2015/12/20.
// Copyright © 2015年 swift-studing.com. All rights reserved.
//
import UIKit
public class FJSImageViewController: UIViewController {
/** image to display */
public var image: UIImage?
/** Options to specify how a view adjusts its content when its size changes */
public var contentMode: UIViewContentMode = .ScaleToFill
/** Position and size of image */
public var imageViewFrame: CGRect?
private var isDirty = false;
private let imageView = UIImageView(image: nil)
private var beforePoint = CGPointMake(0.0, 0.0)
private var currentScale = CGFloat(1.0)
public override func viewDidLoad() {
super.viewDidLoad()
configureImageView()
setupGesture()
}
internal func handleGesture(gesture: UIGestureRecognizer){
if let tapGesture = gesture as? UITapGestureRecognizer{
tap(tapGesture)
}else if let pinchGesture = gesture as? UIPinchGestureRecognizer{
pinch(pinchGesture)
}else if let panGesture = gesture as? UIPanGestureRecognizer{
pan(panGesture)
}
}
private func configureImageView(){
self.imageView.image = image
self.imageView.contentMode = contentMode
self.imageView.frame = imageViewFrame ?? self.view.bounds
self.imageView.userInteractionEnabled = true
self.view.addSubview(self.imageView)
}
private func setupGesture(){
let pinchGesture = UIPinchGestureRecognizer(target: self, action: "handleGesture:")
self.view.addGestureRecognizer(pinchGesture)
let tapGesture = UITapGestureRecognizer(target: self, action: "handleGesture:")
self.view.addGestureRecognizer(tapGesture)
let panGesture = UIPanGestureRecognizer(target: self, action: "handleGesture:")
self.view.addGestureRecognizer(panGesture)
}
private func pan(gesture:UIPanGestureRecognizer){
isDirty = true
var translation = gesture.translationInView(self.view)
if abs(self.beforePoint.x) > 0.0 || abs(self.beforePoint.y) > 0.0{
translation = CGPointMake(self.beforePoint.x + translation.x, self.beforePoint.y + translation.y)
}
switch gesture.state{
case .Changed:
let scaleTransform = CGAffineTransformMakeScale(self.currentScale, self.currentScale)
let translationTransform = CGAffineTransformMakeTranslation(translation.x, translation.y)
self.imageView.transform = CGAffineTransformConcat(scaleTransform, translationTransform)
case .Ended , .Cancelled:
self.beforePoint = translation
default:
break
}
}
private func tap(gesture:UITapGestureRecognizer){
if isDirty{
isDirty = false
UIView.animateWithDuration(0.2){
self.beforePoint = CGPointMake(0.0, 0.0)
self.imageView.transform = CGAffineTransformIdentity
}
}else{
self.dismissViewControllerAnimated(false, completion: nil)
}
}
private func pinch(gesture:UIPinchGestureRecognizer){
var scale = gesture.scale
scale = self.currentScale + (scale - 1.0)
switch gesture.state{
case .Changed:
isDirty = true
let scaleTransform = CGAffineTransformMakeScale(scale, scale)
let transitionTransform = CGAffineTransformMakeTranslation(self.beforePoint.x, self.beforePoint.y)
self.imageView.transform = CGAffineTransformConcat(scaleTransform, transitionTransform)
case .Ended , .Cancelled:
self.currentScale = scale
default:
break
}
}
}
| 7fd682c9480746c9a09b04d8790b8b70 | 34.706422 | 110 | 0.647225 | false | false | false | false |
ProfileCreator/ProfileCreator | refs/heads/master | ProfileCreator/ProfileCreator/Profile Editor OutlineView/PropertyListEditor Source/Items/PropertyListType.swift | mit | 1 | //
// PropertyListType.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Foundation
// MARK: - Property List Types
/// `PropertyListType` is a simple enum that contains cases for each property list type. These are
/// primarily useful when you need the type of a `PropertyListItem` for use in an arbitrary boolean
/// expression. For example,
///
/// ```
/// extension PropertyListItem {
/// var isScalar: Bool {
/// return propertyListType != .ArrayType && propertyListType != .DictionaryType
/// }
/// }
/// ```
///
/// This type of concise expression isn’t possible with `PropertyListItem` because each of its enum
/// cases has an associated value.
enum PropertyListType {
case array
case boolean
case data
case date
case dictionary
case number
case string
}
extension PropertyListType {
/// Returns the `PropertyListType` instance that corresponds to the specified index of the
/// type pop-up menu, or `nil` if the index doesn’t have a known type correspondence.
/// - parameter index: The index of the type pop-up menu whose type is being returned.
init?(typePopUpMenuItemIndex index: Int) {
switch index {
case 0:
self = .array
case 1:
self = .dictionary
case 3:
self = .boolean
case 4:
self = .data
case 5:
self = .date
case 6:
self = .number
case 7:
self = .string
default:
return nil
}
}
/// Returns the index of the type pop-up menu that the instance corresponds to.
var typePopUpMenuItemIndex: Int {
switch self {
case .array:
return 0
case .dictionary:
return 1
case .boolean:
return 3
case .data:
return 4
case .date:
return 5
case .number:
return 6
case .string:
return 7
}
}
}
| 58adf62419a6d69e11d1ad786c990225 | 24.414634 | 99 | 0.582054 | false | false | false | false |
weby/Stencil | refs/heads/master | Tests/ParserSpec.swift | bsd-2-clause | 1 | import Spectre
import Stencil
func testTokenParser() {
describe("TokenParser") {
$0.it("can parse a text token") {
let parser = TokenParser(tokens: [
Token.Text(value: "Hello World")
], namespace: Namespace())
let nodes = try parser.parse()
let node = nodes.first as? TextNode
try expect(nodes.count) == 1
try expect(node?.text) == "Hello World"
}
$0.it("can parse a variable token") {
let parser = TokenParser(tokens: [
Token.Variable(value: "'name'")
], namespace: Namespace())
let nodes = try parser.parse()
let node = nodes.first as? VariableNode
try expect(nodes.count) == 1
let result = try node?.render(Context())
try expect(result) == "name"
}
$0.it("can parse a comment token") {
let parser = TokenParser(tokens: [
Token.Comment(value: "Secret stuff!")
], namespace: Namespace())
let nodes = try parser.parse()
try expect(nodes.count) == 0
}
$0.it("can parse a tag token") {
let namespace = Namespace()
namespace.registerSimpleTag("known") { _ in
return ""
}
let parser = TokenParser(tokens: [
Token.Block(value: "known"),
], namespace: namespace)
let nodes = try parser.parse()
try expect(nodes.count) == 1
}
$0.it("errors when parsing an unknown tag") {
let parser = TokenParser(tokens: [
Token.Block(value: "unknown"),
], namespace: Namespace())
try expect(try parser.parse()).toThrow(TemplateSyntaxError("Unknown template tag 'unknown'"))
}
}
}
| da1ea64a656faffc74e676a0c30cef1d | 25.209677 | 99 | 0.588923 | false | false | false | false |
LYM-mg/DemoTest | refs/heads/master | 其他功能/CoreData练习/coreData01简单使用/coreData01/ViewController.swift | mit | 1 | //
// ViewController.swift
// coreData
//
// Created by i-Techsys.com on 17/1/10.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
fileprivate lazy var tableView: UITableView = UITableView(frame: self.view.frame)
@IBOutlet weak var textField: UITextField!
var peoples = [NSManagedObject]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
view.addSubview(tableView)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(ViewController.addClick))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(ViewController.saveClick))
peoples = getPerson()
}
@objc func addClick() {
let alertVC = UIAlertController(title: "新建联系人", message: nil, preferredStyle: .alert)
alertVC.addTextField { (textfield) in
textfield.placeholder = "请输入名字"
}
alertVC.addTextField { (textfield) in
textfield.placeholder = "请输入年龄"
textfield.keyboardType = UIKeyboardType.numberPad
}
// 确定
let sureAction = UIAlertAction(title: "确定", style: .default, handler: {(_ action: UIAlertAction) -> Void in
// let age = Int(arc4random_uniform(100))
// self.storePerson(name: self.textField.text ?? "默认文字", age: age)
let text = alertVC.textFields?.first?.text
let ageText = alertVC.textFields?.last?.text
self.storePerson(name: text ?? "明明就是你", age: Int(ageText ?? "0")!)
self.tableView.reloadData()
})
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
alertVC.addAction(sureAction)
alertVC.addAction(cancelAction)
present(alertVC, animated: true, completion: nil)
}
@objc func saveClick() {
let _ = getPerson()
}
}
// MARK: - coreData
extension ViewController {
/// 获取托管对象内容总管
func getContext () -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
/// 保存一条数据
func storePerson(name:String, age: Int){
let managerContext = getContext()
// 定义一个entity,这个entity一定要在Xcdatamoded做好定义
let entity = NSEntityDescription.entity(forEntityName: "Person", in: managerContext)
let person = NSManagedObject(entity: entity!, insertInto: managerContext) as! Person
person.setValue(name, forKey: "name")
person.setValue(age, forKey: "age")
peoples.append(person)
try? managerContext.save()
}
/// 获取某一entity的所有数据
func getPerson() -> [NSManagedObject]{
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
let searchResults = try? getContext().fetch(fetchRequest)
print("numbers of \(searchResults!.count)")
for p in (searchResults as! [NSManagedObject]){
print("name: \(p.value(forKey: "name")!) age: \(p.value(forKey: "age")!)")
}
return searchResults as! [NSManagedObject]
}
}
// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return peoples.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cellID")
if cell == nil {
cell = UITableViewCell(style: .value1, reuseIdentifier: "cellID")
}
let person = peoples[indexPath.row]
cell?.textLabel?.text = person.value(forKey: "name") as? String
cell?.detailTextLabel?.text = String(describing: person.value(forKey: "age")!)
return cell!
}
}
| 7fc6647251011a9a8f88b53307872b62 | 34.432203 | 151 | 0.640517 | false | false | false | false |
aleufms/JeraUtils | refs/heads/master | JeraUtils/Base/ReactiveHelper.swift | mit | 1 | //
// ReactiveHelper.swift
// Glambox
//
// Created by Alessandro Nakamuta on 1/28/16.
// Copyright © 2016 Glambox. All rights reserved.
//
import RxSwift
import Kingfisher
public extension ObservableType where E == NSURL? {
public func downloadImage(placeholder placeholder: UIImage? = nil) -> Observable<UIImage?> {
return flatMapLatest { imageURL -> Observable<UIImage?> in
if let imageURL = imageURL {
return Observable<UIImage?>.create({ (observer) -> Disposable in
observer.onNext(placeholder)
let retrieveImageTask = KingfisherManager.sharedManager.retrieveImageWithURL(imageURL, optionsInfo: [.Transition(ImageTransition.Fade(1))], progressBlock: nil, completionHandler: { (image, error, cacheType, imageURL) in
if let error = error{
observer.onError(error)
}
if let image = image{
observer.onNext(image)
observer.onCompleted()
}
})
return AnonymousDisposable {
retrieveImageTask.cancel()
}
})
}
return Observable.just(placeholder)
}
}
}
public extension ObservableType {
public func delay(time: NSTimeInterval, scheduler: SchedulerType = MainScheduler.instance) -> Observable<E> {
return self.flatMap { element in
Observable<Int>.timer(time, scheduler: scheduler)
.map { _ in
return element
}
}
}
} | dff2d238eb5cb72365b2a3a3c4427fc1 | 34.55102 | 239 | 0.532453 | false | false | false | false |
eldesperado/SpareTimeAlarmApp | refs/heads/master | SpareTimeMusicApp/NTSwitch.swift | mit | 1 | //
// NTSwitch.swift
// SpareTimeAlarmApp
//
// Created by Pham Nguyen Nhat Trung on 8/5/15.
// Copyright (c) 2015 Pham Nguyen Nhat Trung. All rights reserved.
//
import Foundation
import UIKit
class NTSwitch: SevenSwitch {
override init() {
super.init()
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
onTintColor = UIColor.untAzulColor()
borderColor = UIColor(white: 1, alpha: 0.41)
shadowColor = UIColor.untTransparentColor()
thumbTintColor = UIColor.untTransparentColor()
onThumbTintColor = UIColor.whiteColor()
}
}
| a0a57a2933a887ddbb8efc0ce77e87a7 | 19.09375 | 67 | 0.670295 | false | false | false | false |
gizmosachin/ColorSlider | refs/heads/master | Sources/ColorSlider.swift | mit | 1 | //
// ColorSlider.swift
//
// Created by Sachin Patel on 1/11/15.
//
// The MIT License (MIT)
//
// Copyright (c) 2015-Present Sachin Patel (http://gizmosachin.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
/// The orientation in which the `ColorSlider` is drawn.
public enum Orientation {
/// The horizontal orientation.
case horizontal
/// The vertical orientation.
case vertical
}
///
/// ColorSlider is a customizable color picker with live preview.
///
/// Inspired by Snapchat, ColorSlider lets you drag to select black, white, or any color in between.
/// Customize `ColorSlider` and its preview via a simple API, and receive callbacks via `UIControlEvents`.
///
/// Use the convenience initializer to create a `.vertical` ColorSlider with a live preview that appears to the `.left` of it:
/// ```swift
/// let colorSlider = ColorSlider(orientation: .vertical, previewSide: .left)
/// ```
///
/// You can create a custom preview view using the `ColorSliderPreviewing` protocol, or by subclassing `DefaultPreviewView`.
/// To pass in a custom preview view, simply use the default initializer instead:
/// ```swift
/// let myPreviewView = MyPreviewView()
/// let colorSlider = ColorSlider(orientation: .vertical, previewView: myPreviewView)
/// ```
///
/// ColorSlider is a `UIControl` subclass and fully supports the following `UIControlEvents`:
/// * `.valueChanged`
/// * `.touchDown`
/// * `.touchUpInside`
/// * `.touchUpOutside`
/// * `.touchCancel`
///
/// Once adding your class as a target, you can get callbacks via the `color` property:
/// ```swift
/// colorSlider.addTarget(self, action: #selector(ViewController.changedColor(_:)), forControlEvents: .valueChanged)
///
/// func changedColor(_ slider: ColorSlider) {
/// var color = slider.color
/// // ...
/// }
/// ```
///
/// Customize the appearance of ColorSlider by setting properties on the `gradientView`:
/// ```swift
/// // Add a border
/// colorSlider.gradientView.layer.borderWidth = 2.0
/// colorSlider.gradientView.layer.borderColor = UIColor.white
///
/// // Disable rounded corners
/// colorSlider.gradientView.automaticallyAdjustsCornerRadius = false
/// ```
///
/// ColorSlider uses the [HSB](https://en.wikipedia.org/wiki/HSL_and_HSV) color standard internally.
/// You can set the `saturation` of your ColorSlider's `gradientView` to change the saturation of colors on the slider.
/// See the `GradientView` and `HSBColor` for more details on how colors are calculated.
///
public class ColorSlider: UIControl {
/// The selected color.
public var color: UIColor {
get {
return UIColor(hsbColor: internalColor)
}
set {
internalColor = HSBColor(color: newValue)
previewView?.colorChanged(to: color)
previewView?.transition(to: .inactive)
sendActions(for: .valueChanged)
}
}
/// The background gradient view.
public let gradientView: GradientView
/// The preview view, passed in the required initializer.
public let previewView: PreviewView?
/// The layout orientation of the slider, as defined in the required initializer.
internal let orientation: Orientation
/// The internal HSBColor representation of `color`.
internal var internalColor: HSBColor
@available(*, unavailable)
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) and storyboards are unsupported, use init(orientation:) instead.")
}
// MARK: - Init
/// - parameter orientation: The orientation of the ColorSlider.
/// - parameter side: The side of the ColorSlider on which to anchor the live preview.
public convenience init(orientation: Orientation = .vertical, previewSide side: DefaultPreviewView.Side = .left) {
// Check to ensure the side is valid for the given orientation
switch orientation {
case .horizontal:
assert(side == .top || side == .bottom, "The preview must be on the top or bottom for orientation \(orientation).")
case .vertical:
assert(side == .left || side == .right, "The preview must be on the left or right for orientation \(orientation).")
}
// Create the preview view
let previewView = DefaultPreviewView(side: side)
self.init(orientation: orientation, previewView: previewView)
}
/// - parameter orientation: The orientation of the ColorSlider.
/// - parameter previewView: An optional preview view that stays anchored to the slider. See ColorSliderPreviewing.
required public init(orientation: Orientation, previewView: PreviewView?) {
self.orientation = orientation
self.previewView = previewView
gradientView = GradientView(orientation: orientation)
internalColor = HSBColor(hue: 0, saturation: gradientView.saturation, brightness: 1)
super.init(frame: .zero)
addSubview(gradientView)
if let currentPreviewView = previewView {
currentPreviewView.isUserInteractionEnabled = false
addSubview(currentPreviewView)
}
}
}
/// :nodoc:
// MARK: - Layout
extension ColorSlider {
public override func layoutSubviews() {
super.layoutSubviews()
gradientView.frame = bounds
if let preview = previewView {
switch orientation {
// Initial layout pass, set preview center as needed
case .horizontal where preview.center.y != bounds.midY,
.vertical where preview.center.x != bounds.midX:
if internalColor.hue == 0 {
// Initially set preview center to the top or left
centerPreview(at: .zero)
} else {
// Set preview center from `internalColor`
let sliderProgress = gradientView.calculateSliderProgress(for: internalColor)
centerPreview(at: CGPoint(x: sliderProgress * bounds.width, y: sliderProgress * bounds.height))
}
// Adjust preview view size if needed
case .horizontal where autoresizesSubviews:
preview.bounds.size = CGSize(width: 25, height: bounds.height + 10)
case .vertical where autoresizesSubviews:
preview.bounds.size = CGSize(width: bounds.width + 10, height: 25)
default:
break
}
}
}
/// Center the preview view at a particular point, given the orientation.
///
/// * If orientation is `.horizontal`, the preview is centered at `(point.x, bounds.midY)`.
/// * If orientation is `.vertical`, the preview is centered at `(bounds.midX, point.y)`.
///
/// The `x` and `y` values of `point` are constrained to the bounds of the slider.
/// - parameter point: The desired point at which to center the `previewView`.
internal func centerPreview(at point: CGPoint) {
switch orientation {
case .horizontal:
let boundedTouchX = (0..<bounds.width).clamp(point.x)
previewView?.center = CGPoint(x: boundedTouchX, y: bounds.midY)
case .vertical:
let boundedTouchY = (0..<bounds.height).clamp(point.y)
previewView?.center = CGPoint(x: bounds.midX, y: boundedTouchY)
}
}
}
/// :nodoc:
// MARK: - UIControlEvents
extension ColorSlider {
/// Begins tracking a touch when the user starts dragging.
public override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
super.beginTracking(touch, with: event)
// Reset saturation to default value
internalColor.saturation = gradientView.saturation
update(touch: touch, touchInside: true)
let touchLocation = touch.location(in: self)
centerPreview(at: touchLocation)
previewView?.transition(to: .active)
sendActions(for: .touchDown)
sendActions(for: .valueChanged)
return true
}
/// Continues tracking a touch as the user drags.
public override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
super.continueTracking(touch, with: event)
update(touch: touch, touchInside: isTouchInside)
if isTouchInside {
let touchLocation = touch.location(in: self)
centerPreview(at: touchLocation)
} else {
previewView?.transition(to: .activeFixed)
}
sendActions(for: .valueChanged)
return true
}
/// Ends tracking a touch when the user finishes dragging.
public override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
guard let endTouch = touch else { return }
update(touch: endTouch, touchInside: isTouchInside)
previewView?.transition(to: .inactive)
sendActions(for: isTouchInside ? .touchUpInside : .touchUpOutside)
}
/// Cancels tracking a touch when the user cancels dragging.
public override func cancelTracking(with event: UIEvent?) {
sendActions(for: .touchCancel)
}
}
/// :nodoc:
/// MARK: - Internal Calculations
fileprivate extension ColorSlider {
/// Updates the internal color and preview view when a touch event occurs.
/// - parameter touch: The touch that triggered the update.
/// - parameter touchInside: Whether the touch that triggered the update was inside the control when the event occurred.
func update(touch: UITouch, touchInside: Bool) {
internalColor = gradientView.color(from: internalColor, after: touch, insideSlider: touchInside)
previewView?.colorChanged(to: color)
}
}
/// :nodoc:
/// MARK: - Increase Tappable Area
extension ColorSlider {
/// Increase the tappable area of `ColorSlider` to a minimum of 44 points on either edge.
override public func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// If hidden, don't customize behavior
guard !isHidden else { return super.hitTest(point, with: event) }
// Determine the delta between the width / height and 44, the iOS HIG minimum tap target size.
// If a side is already longer than 44, add 10 points of padding to either side of the slider along that axis.
let minimumSideLength: CGFloat = 44
let padding: CGFloat = -20
let dx: CGFloat = min(bounds.width - minimumSideLength, padding)
let dy: CGFloat = min(bounds.height - minimumSideLength, padding)
// If an increased tappable area is needed, respond appropriately
let increasedTapAreaNeeded = (dx < 0 || dy < 0)
let expandedBounds = bounds.insetBy(dx: dx / 2, dy: dy / 2)
if increasedTapAreaNeeded && expandedBounds.contains(point) {
for subview in subviews.reversed() {
let convertedPoint = subview.convert(point, from: self)
if let hitTestView = subview.hitTest(convertedPoint, with: event) {
return hitTestView
}
}
return self
} else {
return super.hitTest(point, with: event)
}
}
}
| deca3652035aa5d8b7d405ec3f9b722b | 34.929936 | 126 | 0.719996 | false | false | false | false |
etoledom/Heyou | refs/heads/master | Heyou/Classes/Scenes/AlertController.swift | mit | 1 | import UIKit
typealias Layout = NSLayoutConstraint.Attribute
open class Heyou: UIViewController {
///Array of UI Elements to show
let elements: [Element]
var animator = HYModalAlertAnimator()
private let alertView: AlertView
private weak var presentingVC: UIViewController?
// MARK: - ViewController life cycle
public init(elements: [Element]) {
self.elements = elements
alertView = AlertView(elements: elements)
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
elements = []
alertView = AlertView(elements: elements)
super.init(coder: aDecoder)
}
override open func viewDidLoad() {
super.viewDidLoad()
configureAlertView()
configureBackground()
}
func configureBackground() {
view.backgroundColor = UIColor.black.withAlphaComponent(0.4)
let tap = UITapGestureRecognizer(target: self, action: #selector(self.onTap))
tap.delegate = self
view.addGestureRecognizer(tap)
}
func configureAlertView() {
view.addSubview(alertView)
NSLayoutConstraint.activate([
view.centerXAnchor.constraint(equalTo: alertView.centerXAnchor),
view.centerYAnchor.constraint(equalTo: alertView.centerYAnchor)
])
}
func dismiss(completion: (() -> Void)? = nil) {
presentingViewController?.dismiss(animated: true, completion: completion)
}
@objc func onTap(_ tap: UITapGestureRecognizer) {
dismiss()
}
/// Make the alert be presendted by the given view controller. Use this method to use the custom presentation animation.
///
/// - Parameter viewController: View Controller that will present this alert.
open func show(onViewController viewController: UIViewController) {
presentingVC = viewController
viewController.definesPresentationContext = true
self.transitioningDelegate = self
animator.presenting = true
modalPresentationStyle = UIModalPresentationStyle.overFullScreen
presentingVC?.present(self, animated: true, completion: nil)
}
open func show() {
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
show(onViewController: topController)
}
}
}
extension Heyou: HYPresentationAnimatable {
var topView: UIView {
return alertView
}
var backgroundView: UIView {
return view
}
}
extension Heyou: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return animator
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
animator.presenting = false
return animator
}
}
extension Heyou: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return !alertView.frame.contains(touch.location(in: view))
}
}
| 61b2790b5bfe9d5e721f4dc7a67c34d9 | 30.867925 | 177 | 0.690053 | false | false | false | false |
OSzhou/MyTestDemo | refs/heads/master | 17_SwiftTestCode/TestCode/OtherPro/MeetupChildViewController.swift | apache-2.0 | 1 | //
// MeetupChildViewController.swift
// TestCode
//
// Created by Zhouheng on 2020/7/15.
// Copyright © 2020 tataUFO. All rights reserved.
//
import UIKit
class MeetupChildViewController: HFBaseTableViewController {
let headerH: CGFloat = 88 + 52.5 + 50
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: CGFloat(arc4random_uniform(255)) / 255.0, green: CGFloat(arc4random_uniform(255)) / 255.0, blue: CGFloat(arc4random_uniform(255)) / 255.0, alpha: 1.0)
self.createUI()
self.getData()
}
func getData() {
}
func createUI() {
addTableview(superview: view, style: .plain) { [weak self] (tableview) in
guard let self = self else { return }
tableview.frame = CGRect(x: 0, y: 0, width: Constants.ScreenWidth, height: Constants.ScreenHeight - self.headerH)
tableview.dataSource = self
tableview.delegate = self
tableview.backgroundColor = UIColor.clear
tableview.tableHeaderView = self.headerView
// tableview.register(MeetupPassOrRejectTableViewCell.self, forCellReuseIdentifier: MeetupPassOrRejectTableViewCell.identifier())
tableview.register(MeetupWaitingTableViewCell.self, forCellReuseIdentifier: MeetupWaitingTableViewCell.identifier())
}
}
/// MARK: --- lazy loading
lazy var headerView: MeetupTableViewHeader = {
let view = MeetupTableViewHeader(frame: CGRect(x: 0, y: 0, width: Constants.ScreenWidth, height: 50))
return view
}()
}
extension MeetupChildViewController {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MeetupWaitingTableViewCell.identifier()) as! MeetupWaitingTableViewCell
// let cell = tableView.dequeueReusableCell(withIdentifier: MeetupPassOrRejectTableViewCell.identifier()) as! MeetupPassOrRejectTableViewCell
cell.backgroundColor = UIColor.clear
cell.selectionStyle = UITableViewCell.SelectionStyle.none
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 77
}
}
| 0bd2efdc13448d6c5b8558db566546c1 | 33.657895 | 194 | 0.653379 | false | false | false | false |
CoderJChen/SWWB | refs/heads/master | CJWB/CJWB/Classes/Profile/Tools/Emotion/CJEmotionVC.swift | apache-2.0 | 1 | //
// CJEmotionVC.swift
// CJWB
//
// Created by 星驿ios on 2017/9/13.
// Copyright © 2017年 CJ. All rights reserved.
//
import UIKit
private let EmoticonCell = "EmoticonCell"
class CJEmotionVC: UIViewController {
var emotionCallBack : ( _ emotion :CJEmotionModel) -> ()
fileprivate lazy var collectionView : UICollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: CJEmotionCollectionViewLayout())
fileprivate lazy var toolBar : UIToolbar = UIToolbar()
fileprivate lazy var manager = CJEmotionManger()
init(emotionCallBack : @escaping ( _ emotion :CJEmotionModel) -> ()){
self.emotionCallBack = emotionCallBack
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
// Do any additional setup after loading the view.
}
}
extension CJEmotionVC{
fileprivate func setUpUI(){
view.addSubview(collectionView)
view.addSubview(toolBar)
collectionView.backgroundColor = UIColor.purple
toolBar.backgroundColor = UIColor.darkGray
collectionView.translatesAutoresizingMaskIntoConstraints = false
toolBar.translatesAutoresizingMaskIntoConstraints = false
let views = ["tBar" : toolBar,"cView" : collectionView] as [String : Any]
let cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[tBar]-0-|", options: [], metrics: nil, views: views)
view.addConstraints(cons)
prepareForCollectionView()
prepareForToolBar()
}
fileprivate func prepareForCollectionView(){
collectionView.register(CJEmotionCell.self, forCellWithReuseIdentifier: EmoticonCell)
collectionView.dataSource = self
collectionView.delegate = self
}
fileprivate func prepareForToolBar(){
let titles = ["最近","默认","emoji","浪小花"]
var index = 0
var tempItems = [UIBarButtonItem]()
for title in titles {
let item = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(CJEmotionVC.itemClick(item:)))
item.tag = index
index += 1
tempItems.append(item)
tempItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil))
}
tempItems.removeLast()
toolBar.items = tempItems
toolBar.tintColor = UIColor.orange
}
@objc fileprivate func itemClick(item : UIBarButtonItem){
let tag = item.tag
let indexPath = NSIndexPath(item: 0, section: tag)
collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: true)
}
}
extension CJEmotionVC : UICollectionViewDataSource, UICollectionViewDelegate{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return manager.packages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonCell, for: indexPath) as! CJEmotionCell
let package = manager.packages[indexPath.section]
let emotion = package.emotions[indexPath.item]
cell.emotion = emotion
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let package = manager.packages[section]
return package.emotions.count
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let packege = manager.packages[indexPath.section]
let emotion = packege.emotions[indexPath.item]
emotionCallBack(emotion)
}
fileprivate func insertRecentlyEmotion(emotion : CJEmotionModel){
if emotion.isRemove || emotion.isEmpty {
return
}
if (manager.packages.first?.emotions.contains(emotion))! {
let index = (manager.packages.first?.emotions.index(of: emotion))
manager.packages.first?.emotions.remove(at: index!)
}else{
manager.packages.first?.emotions.remove(at: 19)
}
manager.packages.first?.emotions.insert(emotion, at: 0)
}
}
class CJEmotionCollectionViewLayout: UICollectionViewFlowLayout {
override func prepare() {
super.prepare()
let itemWH = UIScreen.main.bounds.width / 7
itemSize = CGSize(width: itemWH, height: itemWH)
minimumLineSpacing = 0
minimumInteritemSpacing = 0
scrollDirection = .horizontal
collectionView?.isPagingEnabled = true
collectionView?.showsVerticalScrollIndicator = false
collectionView?.showsHorizontalScrollIndicator = false
let insetMargin = ((collectionView?.bounds.height)! - 3*itemWH) / 2
collectionView?.contentInset = UIEdgeInsetsMake(insetMargin, 0, insetMargin, 0)
}
}
| 515c46d02b4edf56dbf352e172961912 | 35.173611 | 180 | 0.661547 | false | false | false | false |
srxboys/RXExtenstion | refs/heads/master | RXExtenstion/Swift3x/RXModel.swift | mit | 1 | //
// RXModel.swift
// RXSwiftExtention
//
// Created by srx on 2017/3/25.
// Copyright © 2017年 https://github.com/srxboys. All rights reserved.
//
/*
* 数据模型 基类
*
* 详见:https://github.com/srxboys/RXSwiftExtention
*
* 有个小小的改动,以前所有dict都是公共区域写的,为了让OC 用类方法,放到了 RXModel的大括号里面
* 再看RXPrintInterface.swift里面,我就没有动,就变成了不是类方法也不是实例方法的,就不提供给OC调用
*/
import UIKit
class RXModel: NSObject {
override func setValue(_ value: Any?, forUndefinedKey key: String) {
//不存在的
NSLog("error 不存在的key" + key)
}
/*
* 所有返回的类型,一定要和 定义的类型匹配否则必崩溃 *****
*/
// MARK: --- String-----
/// 根据字典key获取内容为 字符串类型
public class func dictForKeyString(_ dict:[String:Any], key : String) ->String {
let valueStatus = dictForKey(dict, key: key)
if(!valueStatus.isValue) {
return ""
}
let value = valueStatus.object
if value is String {
var count : Int = 0
#if OS_OBJECT_SWIFT3
count = (value as! String).characters.count
#else
//swift4
count = (value as! String).count
#endif
if( count > 0 && (value as! String) != "<null>") {
return value as! String
}
else {
return ""
}
}
else if(value is [String:Any]) { return "" }
else if(value is [Any]) { return "" }
else {
let valueString = "\(value)"
var valueStringCount = 0
#if OS_OBJECT_SWIFT3
valueStringCount = valueString.characters.count;
#else
//swift4
valueStringCount = valueString.count;
#endif
if valueStringCount <= 0 { return "" }
}
return "\(value)"
}
/// 根据字典key获取内容为 数值类型
public class func dictForKeyInt(_ dict:[String:Any], key : String) ->Int {
let value = dictForKeyString(dict, key: key)
if(!value.isEmpty) {
return Int(value)!
}
return 0
}
// MARK: --- Bool -----
/// 根据字典key获取内容为 布尔类型
public class func dictForKeyBool(_ dict:[String:Any], key : String) ->Bool {
let value = dictForKeyInt(dict, key: key)
if(value > 0) { return true }
return false
}
// MARK: --- CGFloat -----
/// 根据字典key获取内容为 CGFloat
public class func dictForKeyCGFloat(_ dict:[String:Any], key : String) ->CGFloat {
let value = dictForKeyString(dict, key: key)
if(!value.isEmpty) {
return CGFloat(Float(value)!)
}
return 0
}
// MARK: --- Float -----
/// 根据字典key获取内容为 Float
public class func dictForKeyFloat(_ dict:[String:Any], key : String) ->Float {
let value = dictForKeyString(dict, key: key)
if(!value.isEmpty) {
return Float(value)!
}
return 0
}
// MARK: --- Dictionary -----
/// 根据字典key获取内容为字典 返回值 [值,是否有值]
public class func dictForKeyDict(_ dict:[String:Any], key : String) ->(object:[String:Any], isValue:Bool) {
let valueStatus = dictForKey(dict, key: key)
if(!valueStatus.isValue) {
return ([String:Any](), false)
}
let value = valueStatus.object
if value is [String:Any] {
return (value as! [String:Any], true)
}
return ([String:Any](), false)
}
// MARK: --- Any -----
/// 根据字典key获取内容为任意类型 返回值 [值,是否有值]
public class func dictForKey(_ dict:[String:Any], key:String) -> (object:Any, isValue:Bool) {
guard dict.index(forKey: key) != nil else {
return ("", false)
}
let anyValue = dict[key]
guard anyValue != nil else {
return ("", false)
}
if anyValue is Int {
return (String(anyValue as! Int), true)
}
if anyValue is String {
return (anyValue as! String, true)
}
return (anyValue!, true)
}
}
| 87d34ed5b82afb844abeeb7a9cd832dc | 24.993506 | 111 | 0.530352 | false | false | false | false |
cfraz89/RxSwift | refs/heads/master | RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesAPI.swift | mit | 1 | //
// GitHubSearchRepositoriesAPI.swift
// RxExample
//
// Created by Krunoslav Zaher on 10/18/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !RX_NO_MODULE
import RxSwift
#endif
import struct Foundation.URL
import struct Foundation.Data
import struct Foundation.URLRequest
import struct Foundation.NSRange
import class Foundation.HTTPURLResponse
import class Foundation.URLSession
import class Foundation.NSRegularExpression
import class Foundation.JSONSerialization
import class Foundation.NSString
/**
Parsed GitHub respository.
*/
struct Repository: CustomDebugStringConvertible {
var name: String
var url: String
init(name: String, url: String) {
self.name = name
self.url = url
}
}
extension Repository {
var debugDescription: String {
return "\(name) | \(url)"
}
}
/**
ServiceState state.
*/
enum ServiceState {
case online
case offline
}
/**
Raw response from GitHub API
*/
enum SearchRepositoryResponse {
/**
New repositories just fetched
*/
case repositories(repositories: [Repository], nextURL: URL?)
/**
In case there was some problem fetching data from service, this will be returned.
It really doesn't matter if that is a failure in network layer, parsing error or something else.
In case data can't be read and parsed properly, something is wrong with server response.
*/
case serviceOffline
/**
This example uses unauthenticated GitHub API. That API does have throttling policy and you won't
be able to make more then 10 requests per minute.
That is actually an awesome scenario to demonstrate complex retries using alert views and combination of timers.
Just search like mad, and everything will be handled right.
*/
case limitExceeded
}
/**
This is the final result of loading. Crème de la crème.
*/
struct RepositoriesState {
/**
List of parsed repositories ready to be shown in the UI.
*/
let repositories: [Repository]
/**
Current network state.
*/
let serviceState: ServiceState?
/**
Limit exceeded
*/
let limitExceeded: Bool
static let empty = RepositoriesState(repositories: [], serviceState: nil, limitExceeded: false)
}
class GitHubSearchRepositoriesAPI {
// *****************************************************************************************
// !!! This is defined for simplicity sake, using singletons isn't advised !!!
// !!! This is just a simple way to move services to one location so you can see Rx code !!!
// *****************************************************************************************
static let sharedAPI = GitHubSearchRepositoriesAPI(wireframe: DefaultWireframe(), reachabilityService: try! DefaultReachabilityService())
let activityIndicator = ActivityIndicator()
// Why would network service have wireframe service? It's here to abstract promting user
// Do we really want to make this example project factory/fascade/service competition? :)
private let _wireframe: Wireframe
fileprivate let _reachabilityService: ReachabilityService
private init(wireframe: Wireframe, reachabilityService: ReachabilityService) {
_wireframe = wireframe
_reachabilityService = reachabilityService
}
}
// MARK: Pagination
extension GitHubSearchRepositoriesAPI {
/**
Public fascade for search.
*/
func search(_ query: String, loadNextPageTrigger: Observable<Void>) -> Observable<RepositoriesState> {
let escapedQuery = query.URLEscaped
let url = URL(string: "https://api.github.com/search/repositories?q=\(escapedQuery)")!
return recursivelySearch([], loadNextURL: url, loadNextPageTrigger: loadNextPageTrigger)
// Here we go again
.startWith(RepositoriesState.empty)
}
private func recursivelySearch(_ loadedSoFar: [Repository], loadNextURL: URL, loadNextPageTrigger: Observable<Void>) -> Observable<RepositoriesState> {
return loadSearchURL(loadNextURL).flatMap { searchResponse -> Observable<RepositoriesState> in
switch searchResponse {
/**
If service is offline, that's ok, that means that this isn't the last thing we've heard from that API.
It will retry until either battery drains, you become angry and close the app or evil machine comes back
from the future, steals your device and Googles Sarah Connor's address.
*/
case .serviceOffline:
return Observable.just(RepositoriesState(repositories: loadedSoFar, serviceState: .offline, limitExceeded: false))
case .limitExceeded:
return Observable.just(RepositoriesState(repositories: loadedSoFar, serviceState: .online, limitExceeded: true))
case let .repositories(newPageRepositories, maybeNextURL):
var loadedRepositories = loadedSoFar
loadedRepositories.append(contentsOf: newPageRepositories)
let appenedRepositories = RepositoriesState(repositories: loadedRepositories, serviceState: .online, limitExceeded: false)
// if next page can't be loaded, just return what was loaded, and stop
guard let nextURL = maybeNextURL else {
return Observable.just(appenedRepositories)
}
return Observable.concat([
// return loaded immediately
Observable.just(appenedRepositories),
// wait until next page can be loaded
Observable.never().takeUntil(loadNextPageTrigger),
// load next page
self.recursivelySearch(loadedRepositories, loadNextURL: nextURL, loadNextPageTrigger: loadNextPageTrigger)
])
}
}
}
private func loadSearchURL(_ searchURL: URL) -> Observable<SearchRepositoryResponse> {
return URLSession.shared
.rx.response(request: URLRequest(url: searchURL))
.retry(3)
.trackActivity(self.activityIndicator)
.observeOn(Dependencies.sharedDependencies.backgroundWorkScheduler)
.map { httpResponse, data -> SearchRepositoryResponse in
if httpResponse.statusCode == 403 {
return .limitExceeded
}
let jsonRoot = try GitHubSearchRepositoriesAPI.parseJSON(httpResponse, data: data)
guard let json = jsonRoot as? [String: AnyObject] else {
throw exampleError("Casting to dictionary failed")
}
let repositories = try GitHubSearchRepositoriesAPI.parseRepositories(json)
let nextURL = try GitHubSearchRepositoriesAPI.parseNextURL(httpResponse)
return .repositories(repositories: repositories, nextURL: nextURL)
}
.retryOnBecomesReachable(.serviceOffline, reachabilityService: _reachabilityService)
}
}
// MARK: Parsing the response
extension GitHubSearchRepositoriesAPI {
private static let parseLinksPattern = "\\s*,?\\s*<([^\\>]*)>\\s*;\\s*rel=\"([^\"]*)\""
private static let linksRegex = try! NSRegularExpression(pattern: parseLinksPattern, options: [.allowCommentsAndWhitespace])
fileprivate static func parseLinks(_ links: String) throws -> [String: String] {
let length = (links as NSString).length
let matches = GitHubSearchRepositoriesAPI.linksRegex.matches(in: links, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: length))
var result: [String: String] = [:]
for m in matches {
let matches = (1 ..< m.numberOfRanges).map { rangeIndex -> String in
let range = m.rangeAt(rangeIndex)
let startIndex = links.characters.index(links.startIndex, offsetBy: range.location)
let endIndex = links.characters.index(links.startIndex, offsetBy: range.location + range.length)
let stringRange = startIndex ..< endIndex
return links.substring(with: stringRange)
}
if matches.count != 2 {
throw exampleError("Error parsing links")
}
result[matches[1]] = matches[0]
}
return result
}
fileprivate static func parseNextURL(_ httpResponse: HTTPURLResponse) throws -> URL? {
guard let serializedLinks = httpResponse.allHeaderFields["Link"] as? String else {
return nil
}
let links = try GitHubSearchRepositoriesAPI.parseLinks(serializedLinks)
guard let nextPageURL = links["next"] else {
return nil
}
guard let nextUrl = URL(string: nextPageURL) else {
throw exampleError("Error parsing next url `\(nextPageURL)`")
}
return nextUrl
}
fileprivate static func parseJSON(_ httpResponse: HTTPURLResponse, data: Data) throws -> AnyObject {
if !(200 ..< 300 ~= httpResponse.statusCode) {
throw exampleError("Call failed")
}
return try JSONSerialization.jsonObject(with: data, options: []) as AnyObject
}
fileprivate static func parseRepositories(_ json: [String: AnyObject]) throws -> [Repository] {
guard let items = json["items"] as? [[String: AnyObject]] else {
throw exampleError("Can't find items")
}
return try items.map { item in
guard let name = item["name"] as? String,
let url = item["url"] as? String else {
throw exampleError("Can't parse repository")
}
return Repository(name: name, url: url)
}
}
}
| 20b9eadc81899eedec1b4343cf5bc850 | 35.208791 | 172 | 0.639049 | false | false | false | false |
Za1006/TIY-Assignments | refs/heads/master | HeroTracker/HeroTracker/HeroTableViewController.swift | cc0-1.0 | 1 | //
// HeroTableViewController.swift
// HeroTracker
//
// Created by Elizabeth Yeh on 10/12/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
class HeroTableViewController: UITableViewController
{
var heroes = Array<Hero>()
override func viewDidLoad()
{
super.viewDidLoad()
title = "S.H.I.E.L.D. Hero Tracker"
loadHeroes()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
@IBOutlet weak var HeroCell: UITableViewCell!
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return heroes.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("HeroCell", forIndexPath: indexPath)
// Configure the cell...
let aHero = heroes[indexPath.row]
cell.textLabel?.text = aHero.name
cell.detailTextLabel?.text = aHero.homeWorld
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let selectedHero = heroes[indexPath.row]
let detailVC = storyboard?.instantiateViewControllerWithIdentifier("HeroDetailViewController") as! HeroDetailViewController
detailVC.hero = selectedHero
navigationController?.pushViewController(detailVC, animated: true)
}
// instead of doing the segue use the func above by creating a viewController but not connecting it to the TableViewController
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: Navigation
private func loadHeroes()
{
do
{
let filePath = NSBundle.mainBundle().pathForResource("heroes", ofType: "json")
let dataFromFile = NSData(contentsOfFile: filePath!)
let heroData: NSArray! = try NSJSONSerialization.JSONObjectWithData(dataFromFile!, options:[]) as! NSArray
for heroDictionary in heroData
{
let aHero = Hero(dictionary: heroDictionary as! NSDictionary)
heroes.append(aHero)
}
heroes.sortInPlace({ $0.name < $1.name})
}
catch let error as NSError
{
print(error)
}
}
}
| ff7923f351c5460571766aa18259bfcb | 31.664179 | 157 | 0.659813 | false | false | false | false |
GraphQLSwift/Graphiti | refs/heads/main | Sources/Graphiti/Value/Value.swift | mit | 1 | public final class Value<EnumType: Encodable & RawRepresentable> where EnumType.RawValue == String {
let value: EnumType
var description: String?
var deprecationReason: String?
init(
value: EnumType
) {
self.value = value
}
}
public extension Value {
convenience init(_ value: EnumType) {
self.init(value: value)
}
@discardableResult
func description(_ description: String) -> Self {
self.description = description
return self
}
@discardableResult
func deprecationReason(_ deprecationReason: String) -> Self {
self.deprecationReason = deprecationReason
return self
}
}
| 4a54250b96ef358f465d8515d4d6038f | 22.62069 | 100 | 0.645255 | false | false | false | false |
chengxianghe/MissGe | refs/heads/master | MissGe/MissGe/Class/Project/Request/Home/MLLikeRequest.swift | mit | 1 | //
// MLLikeRequest.swift
// MissLi
//
// Created by chengxianghe on 16/7/26.
// Copyright © 2016年 cn. All rights reserved.
//
import UIKit
//http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=post&a=likeit&pid=40298
class MLLikeCommentRequest: MLBaseRequest {
var pid = ""
//c=post&a=likeit&pid=40298
override func requestParameters() -> [String : Any]? {
let dict = ["c":"post","a":"likeit","pid":"\(pid)"]
return dict
}
override func requestHandleResult() {
print("requestHandleResult -- \(self.classForCoder)")
}
override func requestVerifyResult() -> Bool {
guard let dict = self.responseObject as? NSDictionary else {
return false
}
return (dict["result"] as? String) == "200"
}
}
//http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=article&a=likeit&aid=7992
class MLLikeArticleRequest: MLBaseRequest {
var aid = ""
//c=post&a=likeit&pid=40298
override func requestParameters() -> [String : Any]? {
let dict = ["c":"article","a":"likeit","aid":"\(aid)"]
return dict
}
override func requestHandleResult() {
print("requestHandleResult -- \(self.classForCoder)")
}
override func requestVerifyResult() -> Bool {
guard let dict = self.responseObject as? NSDictionary else {
return false
}
return (dict["result"] as? String) == "200"
}
}
| c33d34347b58227326b77d0870e5bf8d | 27.982456 | 160 | 0.62046 | false | false | false | false |
milot/BoxFinder | refs/heads/master | BoxFinder/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// BoxFinder
//
// Created by Milot Shala on 4/7/17.
// Copyright © 2017 Milot Shala. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
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:.
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.boxId == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| bbb105279942d31f186452e6ba37ccbd | 50.885246 | 279 | 0.796209 | false | false | false | false |
NoryCao/zhuishushenqi | refs/heads/master | zhuishushenqi/NewVersion/Reader/ZSVerticalViewController.swift | mit | 1 | //
// ZSVerticalViewController.swift
// zhuishushenqi
//
// Created by caony on 2019/7/9.
// Copyright © 2019 QS. All rights reserved.
//
import UIKit
class ZSVerticalViewController: BaseViewController, ZSReaderVCProtocol {
fileprivate var pageVC:PageViewController = PageViewController()
weak var toolBar:ZSReaderToolbar?
weak var dataSource:UIPageViewControllerDataSource?
weak var delegate:UIPageViewControllerDelegate?
var nextPageHandler: ZSReaderPageHandler?
var lastPageHandler: ZSReaderPageHandler?
lazy var tableView:UITableView = {
let tableView = UITableView(frame: .zero, style: .grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.sectionHeaderHeight = 0.01
tableView.sectionFooterHeight = 0.01
if #available(iOS 11, *) {
tableView.contentInsetAdjustmentBehavior = .never
}
tableView.register(ZSShelfTableViewCell.self, forCellReuseIdentifier: "\(ZSShelfTableViewCell.self)")
tableView.qs_registerHeaderFooterClass(ZSBookShelfHeaderView.self)
let blurEffect = UIBlurEffect(style: .extraLight)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
tableView.backgroundView = blurEffectView
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func bind(toolBar: ZSReaderToolbar) {
self.toolBar = toolBar
}
func destroy() {
pageVC.destroy()
}
func changeBg(style: ZSReaderStyle) {
pageVC.bgView.image = style.backgroundImage
}
func jumpPage(page: ZSBookPage,_ animated:Bool, _ direction:UIPageViewController.NavigationDirection = .forward) {
pageVC.newPage = page
tableView.beginUpdates()
tableView.reloadSection(UInt(page.chapterIndex), with: UITableView.RowAnimation.automatic)
tableView.endUpdates()
}
private func setupGesture() {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction(tap:)))
tap.numberOfTouchesRequired = 1
tap.numberOfTapsRequired = 1
view.addGestureRecognizer(tap)
}
@objc
private func tapAction(tap:UITapGestureRecognizer) {
toolBar?.show(inView: view, true)
}
}
extension ZSVerticalViewController:UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
}
}
| 9a4732f8f2736c1bd638ba55265f9a62 | 30.574713 | 118 | 0.684019 | false | false | false | false |
tylerlutz/SwiftPlaygrounds | refs/heads/master | Numbers.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
//Integers
var myBankAccount: Int = -500
//Unsigned Int value has to be zero or greater
var myAge: UInt = 22
//Use Int64 for numebrs larger then 2,147,483,647
var bigNumber: Int64 = 2147483647
//Double up to 15 decimal points
var anotherBankAccount: Double = 55.5
//Float up to 6 decimal points
var someVal: Float = 5.5
//Have to cast someVal to a double
var sum = anotherBankAccount * Double(someVal) | d5b729b579cb7bfe5bac91a634233cfa | 21.619048 | 52 | 0.742616 | false | false | false | false |
AbdulBasitBashir/learn-ios9-hybrid-apps | refs/heads/master | step0_remote_website/step0_remote_website/ViewController.swift | mit | 4 | //
// ViewController.swift
// step0_remote_website
//
// Created by Zia Khan on 29/07/2015.
// Copyright © 2015 Panacloud. All rights reserved.
//
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
/* Now instantiate the web view */
webView = WKWebView(frame: view.bounds, configuration: configuration)
if let theWebView = webView{
/* Load a web page into our web view */
let url = NSURL(string: "http://www.apple.com")
let urlRequest = NSURLRequest(URL: url!)
theWebView.loadRequest(urlRequest)
theWebView.navigationDelegate = self
view.addSubview(theWebView)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 9933bfba8c523d67204dd87df41a67b3 | 26.425532 | 80 | 0.626067 | false | true | false | false |
raymondshadow/SwiftDemo | refs/heads/master | SwiftApp/StudyNote/StudyNote/Promise/SNPromise.swift | apache-2.0 | 1 | //
// RNPromise.swift
// StudyNote
//
// Created by wuyp on 2019/11/21.
// Copyright © 2019 Raymond. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
typealias YAOPromiseInputAction = (PublishSubject<Any?>, Any?) -> Void
typealias YAOPromiseCatchAction = (Error) -> Void
typealias YAOPromiseFinallyAction = (Any?) -> Void
class SNPromise {
private var inputsPool: [YAOPromiseInputAction] = []
private var catchsPool: [YAOPromiseCatchAction] = []
private var finallyAction: YAOPromiseFinallyAction = {_ in }
private var execResult: Any?
private var subject = PublishSubject<Any?>()
private var bag = DisposeBag()
init() {
registerInputActionHandle()
}
private func registerInputActionHandle() {
subject = PublishSubject<Any?>()
bag = DisposeBag()
subject.subscribeOn(MainScheduler.instance).subscribe(onNext: {[weak self] (value) in
self?.resolveItemAction(value: value)
}, onError: {[weak self] (err) in
self?.rejectItemAction(err: err)
}, onCompleted: {[weak self] in
self?.execCompleted()
}).disposed(by: bag)
}
}
// MARK: - public
extension SNPromise {
@discardableResult
func then(_ handle: @escaping YAOPromiseInputAction) -> SNPromise {
inputsPool.append(handle)
if inputsPool.count == 1 {
handle(subject, nil)
}
return self
}
@discardableResult
func `catch`(_ action: @escaping YAOPromiseCatchAction) -> SNPromise {
catchsPool.append(action)
return self
}
func `finally`(_ action: @escaping YAOPromiseFinallyAction) {
finallyAction = action
}
}
// MARK: - private handle each action
extension SNPromise {
private func resolveItemAction(value: Any? = nil) {
execResult = value
registerInputActionHandle()
if inputsPool.count > 0 {
_ = inputsPool.removeFirst()
}
guard inputsPool.count > 0 else {
execCompleted()
return
}
inputsPool[0](subject, value)
}
private func rejectItemAction(err: Error) {
catchsPool.forEach { action in
action(err)
}
execCompleted()
}
private func execCompleted() {
inputsPool.removeAll()
catchsPool.removeAll()
registerInputActionHandle()
finallyAction(execResult)
}
}
| e77e900453606ee0e7809ab04b760167 | 24.76 | 93 | 0.595497 | false | false | false | false |
timd/ProiOSTableCollectionViews | refs/heads/master | Ch09/InCellCV/InCellCV/ViewController.swift | mit | 1 | //
// ViewController.swift
// InCellCV
//
// Created by Tim on 07/11/15.
// Copyright © 2015 Tim Duckett. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var collectionView: UICollectionView!
var cvData = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController {
func setupData() {
for index in 0...100 {
cvData.append(index)
}
}
func addButtonToCell(cell: UICollectionViewCell) {
guard cell.contentView.viewWithTag(1000) != nil else {
return
}
let button = UIButton(type: UIButtonType.RoundedRect)
button.tag = 1000
button.setTitle("Tap me!", forState: UIControlState.Normal)
button.sizeToFit()
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: "didTapButtonInCell:", forControlEvents: UIControlEvents.TouchUpInside)
let vConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.CenterX, relatedBy:
NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)
let hConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -10)
cell.contentView.addSubview(button)
cell.contentView.addConstraints([vConstraint, hConstraint])
}
func didTapButtonInCell(sender: UIButton) {
let cell = sender.superview!.superview as! UICollectionViewCell
let indexPathAtTap = collectionView.indexPathForCell(cell)
let alert = UIAlertController(title: "Something happened!", message: "A button was tapped in item \(indexPathAtTap!.row)", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}
}
extension ViewController: UICollectionViewDataSource {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cvData.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellIdentifier", forIndexPath: indexPath)
if let label = cell.contentView.viewWithTag(1000) as? UILabel {
label.text = "Item \(cvData[indexPath.row])"
}
addButtonToCell(cell)
cell.layer.borderColor = UIColor.blackColor().CGColor
cell.layer.borderWidth = 1.0
return cell
}
}
| 1e8218624845b39cf84595a86d002362 | 31.413462 | 225 | 0.661821 | false | false | false | false |
justinhester/hacking-with-swift | refs/heads/master | src/Project17/Project17/GameViewController.swift | gpl-3.0 | 1 | //
// GameViewController.swift
// Project17
//
// Created by Justin Lawrence Hester on 2/6/16.
// Copyright (c) 2016 Justin Lawrence Hester. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| 3a3b9591041cb16f2446e2877c352cb0 | 25.943396 | 94 | 0.607143 | false | false | false | false |
jamalping/XPUtil | refs/heads/master | XPUtil/UIKit/CellIdentfierable.swift | mit | 1 | //
// CellidentfierCompatible.swift
// XPUtilExample
//
// Created by Apple on 2018/12/18.
// Copyright © 2018年 xyj. All rights reserved.
//
import UIKit
// MARK: - TableViewCell、CollectionViewCell,遵循Cell标志协议,实现为默认实现
extension UITableViewCell: CellidentfierCompatible {}
extension UICollectionViewCell: CellidentfierCompatible{}
extension UITableViewHeaderFooterView: CellidentfierCompatible{}
// MARK: - Cell标志协议
public protocol CellidentfierCompatible {
associatedtype CompatibleType
var cell: CompatibleType { get }
var identier: String { get }
}
public struct CellIdentier<Base> {
let base: Base
}
public extension CellidentfierCompatible {
static var cell: CellIdentier<Self.Type>{
return CellIdentier.init(base: self.self)
}
var cell: CellIdentier<Self> {
return CellIdentier.init(base: self)
}
var identier: String {
return "\(cell.base)"
}
static var identier: String {
return "\(cell.base)"
}
}
// MARK: - TableViewCell、CollectionViewCell,遵循Cell标志协议,实现为默认实现
extension UITableViewCell: Cellidentfierable {}
extension UICollectionViewCell: Cellidentfierable{}
extension UITableViewHeaderFooterView: Cellidentfierable{}
// MARK: - Cell标志协议
protocol Cellidentfierable {
static var cellIdentfier: String { get }
}
extension Cellidentfierable where Self: UITableViewCell {
static var cellIdentfier: String {
return "\(self)"
}
var cellIdentfier: String {
return Self.cellIdentfier
}
}
extension Cellidentfierable where Self: UICollectionViewCell {
static var cellIdentfier: String {
return "\(self)"
}
var cellIdentfier: String {
return Self.cellIdentfier
}
}
extension Cellidentfierable where Self: UITableViewHeaderFooterView {
static var cellIdentfier: String {
return "\(self)"
}
var cellIdentfier: String {
return Self.cellIdentfier
}
}
/// 注册cell
protocol CellRegistable {}
extension UITableView: CellRegistable {}
extension UICollectionView: CellRegistable {}
extension CellRegistable where Self: UITableView {
func registerCells<T: UITableViewCell>(_ cellClasses: [T.Type]) {
cellClasses.forEach {
self.registerSingleCell($0)
}
}
func registerSingleCell<T: UITableViewCell>(_ cellClass: T.Type) {
let className = "\(cellClass)"
/// 存在nib文件
if let resourcePath = Bundle.main.resourcePath, FileManager.default.fileExists(atPath: resourcePath + "/\(className).nib") {
let nib = UINib(nibName: className, bundle: nil)
self.register(nib, forCellReuseIdentifier: cellClass.cellIdentfier)
}else {
self.register(cellClass, forCellReuseIdentifier: cellClass.cellIdentfier)
}
}
}
extension CellRegistable where Self: UICollectionView {
func registerCells<T: UICollectionViewCell>(_ cellClasses: [T.Type]) {
cellClasses.forEach {
self.registerSingleCell($0)
}
}
func registerSingleCell<T: UICollectionViewCell>(_ cellClass: T.Type) {
let className = "\(cellClass)"
/// 存在nib文件
if let resourcePath = Bundle.main.resourcePath, FileManager.default.fileExists(atPath: resourcePath + "/\(className).nib") {
let nib = UINib(nibName: className, bundle: nil)
self.register(nib, forCellWithReuseIdentifier: cellClass.cellIdentfier)
}else {
self.register(cellClass, forCellWithReuseIdentifier: cellClass.cellIdentfier)
}
}
}
| 6d48d61986ffdc37c4e6fa2377dc2828 | 24.567376 | 132 | 0.680721 | false | false | false | false |
LeoMobileDeveloper/MDTable | refs/heads/master | MDTableExample/Extension.swift | mit | 1 | //
// Extension.swift
// MDTableExample
//
// Created by Leo on 2017/7/6.
// Copyright © 2017年 Leo Huang. All rights reserved.
//
import Foundation
import UIKit
import CoreGraphics
extension UIView {
func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
extension Int{
func asLocalizedPlayCount()->String{
if self < 100000 {
return "\(self)"
}else if self < 100000000{
return "\(self/10000)万"
}else{
return "\(self/100000000)亿"
}
}
}
extension UIColor{
static var theme:UIColor{
get{
return UIColor(red: 210.0 / 255.0, green: 62.0 / 255.0, blue: 57.0 / 255.0, alpha: 1.0)
}
}
}
struct ImageConst{
static let bytesPerPixel = 4
static let bitsPerComponent = 8
}
//解压缩来提高效率
extension UIImage{
func decodedImage()->UIImage?{
guard let cgImage = self.cgImage else{
return nil
}
guard let colorspace = cgImage.colorSpace else {
return nil
}
let width = cgImage.width
let height = cgImage.height
let bytesPerRow = ImageConst.bytesPerPixel * width
let ctx = CGContext(data: nil,
width: width,
height: height,
bitsPerComponent: ImageConst.bitsPerComponent,
bytesPerRow: bytesPerRow,
space: colorspace,
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)
guard let context = ctx else {
return nil
}
let rect = CGRect(x: 0, y: 0, width: width, height: height)
context.draw(cgImage, in: rect)
guard let drawedImage = context.makeImage() else{
return nil
}
let result = UIImage(cgImage: drawedImage, scale:self.scale , orientation: self.imageOrientation)
return result
}
}
extension UIImageView{
func asyncSetImage(_ image:UIImage?){
DispatchQueue.global(qos: .userInteractive).async {
let decodeImage = image?.decodedImage()
DispatchQueue.main.async {
self.image = decodeImage
}
}
}
}
extension UIButton{
func asyncSetImage(_ image:UIImage,for state:UIControlState){
DispatchQueue.global(qos: .userInteractive).async {
let decodeImage = image.decodedImage()
DispatchQueue.main.async {
self.setImage(decodeImage, for: state)
}
}
}
}
extension UIView{
var x:CGFloat{
get{
return self.frame.origin.x
}
set{
var frame = self.frame
frame.origin.x = newValue
self.frame = frame
}
}
var y:CGFloat{
get{
return self.frame.origin.y
}
set{
var frame = self.frame
frame.origin.y = newValue
self.frame = frame
}
}
var maxX:CGFloat{
get{
return self.frame.origin.x + self.frame.width
}
}
var maxY:CGFloat{
get{
return self.frame.origin.y + self.frame.height
}
}
func added(to superView:UIView)->Self{
superView.addSubview(self)
return self
}
}
extension UILabel{
static func title()->UILabel{
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12)
label.textColor = UIColor(red: 51.0 / 255.0, green: 51.0 / 255.0, blue: 51.0 / 255.0, alpha: 1.0)
label.textAlignment = .left
return label
}
static func subTitle()->UILabel{
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12)
label.textColor = UIColor(red: 85.0 / 255.0, green: 85.0 / 255.0, blue: 85.0 / 255.0, alpha: 1.0)
label.textAlignment = .left
return label
}
}
extension UIButton{
func setBackgroundColor(_ color: UIColor, for state: UIControlState){
let rect = CGRect(x: 0, y: 0, width: 1000, height: 1000)
UIGraphicsBeginImageContext(rect.size)
let ctx = UIGraphicsGetCurrentContext()
ctx?.setFillColor(color.cgColor)
ctx?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
self.setImage(image, for: state)
}
}
extension Date{
static var dayOfToday:String{
get{
let formatter = DateFormatter()
formatter.dateFormat = "dd"
let date = Date()
let day = formatter.string(from: date)
return day
}
}
}
| cdea45d99c4f597121b969a39ad1518d | 26.364641 | 137 | 0.555219 | false | false | false | false |
rheinfabrik/Dobby | refs/heads/master | DobbyTests/MatcherSpec.swift | apache-2.0 | 2 | import Quick
import Nimble
import Dobby
class MatcherSpec: QuickSpec {
override func spec() {
describe("Matching") {
context("a matching function") {
let matcher: Dobby.Matcher<Int> = matches { $0 == 0 }
it("succeeds if the matching function returns true") {
expect(matcher.matches(0)).to(beTrue())
}
it("fails if the matching function returns false") {
expect(matcher.matches(1)).to(beFalse())
}
}
context("anything") {
let matcher: Dobby.Matcher<Int> = any()
it("always succeeds") {
expect(matcher.matches(0)).to(beTrue())
expect(matcher.matches(1)).to(beTrue())
}
}
context("anything but whatever (not)") {
let matcher: Dobby.Matcher<Int> = not(0)
it("succeeds if the given matcher is not matched") {
expect(matcher.matches(1)).to(beTrue())
}
it("fails if the given matcher is matched") {
expect(matcher.matches(0)).to(beFalse())
}
}
context("nothing") {
let matcher: Dobby.Matcher<Int?> = none()
it("succeeds if the actual value equals nil") {
expect(matcher.matches(nil)).to(beTrue())
}
it("fails if the actual value does not equal nil") {
expect(matcher.matches(0)).to(beFalse())
}
}
context("something") {
let matcher: Dobby.Matcher<Int?> = some(0)
it("succeeds if the given matcher is matched") {
expect(matcher.matches(0)).to(beTrue())
}
it("fails if the given matcher is not matched") {
expect(matcher.matches(nil)).to(beFalse())
expect(matcher.matches(1)).to(beFalse())
}
}
context("a value") {
let matcher: Dobby.Matcher<Int> = equals(0)
it("succeeds if the actual value equals the expected value") {
expect(matcher.matches(0)).to(beTrue())
}
it("fails if the actual value does not equal the expected value") {
expect(matcher.matches(1)).to(beFalse())
}
}
context("a 2-tuple") {
let matcher: Dobby.Matcher<(Int, Int)> = equals((0, 1))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1)).to(beFalse())
expect(matcher.matches(0, 0)).to(beFalse())
}
}
context("a 3-tuple") {
let matcher: Dobby.Matcher<(Int, Int, Int)> = equals((0, 1, 2))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1, 2)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1, 2)).to(beFalse())
expect(matcher.matches(0, 0, 2)).to(beFalse())
expect(matcher.matches(0, 1, 1)).to(beFalse())
}
}
context("a 4-tuple") {
let matcher: Dobby.Matcher<(Int, Int, Int, Int)> = equals((0, 1, 2, 3))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1, 2, 3)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1, 2, 3)).to(beFalse())
expect(matcher.matches(0, 0, 2, 3)).to(beFalse())
expect(matcher.matches(0, 1, 1, 3)).to(beFalse())
expect(matcher.matches(0, 1, 2, 2)).to(beFalse())
}
}
context("a 5-tuple") {
let matcher: Dobby.Matcher<(Int, Int, Int, Int, Int)> = equals((0, 1, 2, 3, 4))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1, 2, 3, 4)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1, 2, 3, 4)).to(beFalse())
expect(matcher.matches(0, 0, 2, 3, 4)).to(beFalse())
expect(matcher.matches(0, 1, 1, 3, 4)).to(beFalse())
expect(matcher.matches(0, 1, 2, 2, 4)).to(beFalse())
expect(matcher.matches(0, 1, 2, 3, 3)).to(beFalse())
}
}
context("an array") {
let matcher: Dobby.Matcher<[Int]> = equals([0, 1, 2])
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches([0, 1, 2])).to(beTrue())
}
it("fails if the amount of actual values differs from the amount of expected values") {
expect(matcher.matches([0, 1])).to(beFalse())
expect(matcher.matches([0, 1, 2, 3])).to(beFalse())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches([1, 1, 2])).to(beFalse())
expect(matcher.matches([0, 0, 2])).to(beFalse())
expect(matcher.matches([0, 1, 1])).to(beFalse())
}
}
context("a dictionary") {
let matcher: Dobby.Matcher<[Int: Int]> = equals([0: 0, 1: 1, 2: 2])
it("succeeds if all actual pairs equal the expected pairs") {
expect(matcher.matches([0: 0, 1: 1, 2: 2])).to(beTrue())
}
it("fails if the amount of actual pairs differs from the amount of expected pairs") {
expect(matcher.matches([0: 0, 1: 1])).to(beFalse())
expect(matcher.matches([0: 0, 1: 1, 2: 2, 3: 3])).to(beFalse())
}
it("fails if any actual pair does not equal the expected pair") {
expect(matcher.matches([0: 1, 1: 1, 2: 2])).to(beFalse())
expect(matcher.matches([0: 0, 1: 0, 2: 2])).to(beFalse())
expect(matcher.matches([0: 0, 1: 1, 2: 1])).to(beFalse())
}
}
context("a 2-tuple of matchers") {
let matcher: Dobby.Matcher<(Int, Int)> = matches((equals(0), equals(1)))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1)).to(beFalse())
expect(matcher.matches(0, 0)).to(beFalse())
}
}
context("a 3-tuple of matchers") {
let matcher: Dobby.Matcher<(Int, Int, Int)> = matches((equals(0), equals(1), equals(2)))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1, 2)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1, 2)).to(beFalse())
expect(matcher.matches(0, 0, 2)).to(beFalse())
expect(matcher.matches(0, 1, 1)).to(beFalse())
}
}
context("a 4-tuple of matchers") {
let matcher: Dobby.Matcher<(Int, Int, Int, Int)> = matches((equals(0), equals(1), equals(2), equals(3)))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1, 2, 3)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1, 2, 3)).to(beFalse())
expect(matcher.matches(0, 0, 2, 3)).to(beFalse())
expect(matcher.matches(0, 1, 1, 3)).to(beFalse())
expect(matcher.matches(0, 1, 2, 2)).to(beFalse())
}
}
context("a 5-tuple of matchers") {
let matcher: Dobby.Matcher<(Int, Int, Int, Int, Int)> = matches((equals(0), equals(1), equals(2), equals(3), equals(4)))
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches(0, 1, 2, 3, 4)).to(beTrue())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches(1, 1, 2, 3, 4)).to(beFalse())
expect(matcher.matches(0, 0, 2, 3, 4)).to(beFalse())
expect(matcher.matches(0, 1, 1, 3, 4)).to(beFalse())
expect(matcher.matches(0, 1, 2, 2, 4)).to(beFalse())
expect(matcher.matches(0, 1, 2, 3, 3)).to(beFalse())
}
}
context("an array of matchers") {
let matcher: Dobby.Matcher<[Int]> = matches([equals(0), equals(1), equals(2)])
it("succeeds if all actual values equal the expected values") {
expect(matcher.matches([0, 1, 2])).to(beTrue())
}
it("fails if the amount of actual values differs from the amount of expected values") {
expect(matcher.matches([0, 1])).to(beFalse())
expect(matcher.matches([0, 1, 2, 3])).to(beFalse())
}
it("fails if any actual value does not equal the expected value") {
expect(matcher.matches([1, 1, 2])).to(beFalse())
expect(matcher.matches([0, 0, 2])).to(beFalse())
expect(matcher.matches([0, 1, 1])).to(beFalse())
}
}
context("a dictionary of matchers") {
let matcher: Dobby.Matcher<[Int: Int]> = matches([0: equals(0), 1: equals(1), 2: equals(2)])
it("succeeds if all actual pairs equal the expected pairs") {
expect(matcher.matches([0: 0, 1: 1, 2: 2])).to(beTrue())
}
it("fails if the amount of actual pairs differs from the amount of expected pairs") {
expect(matcher.matches([0: 0, 1: 1])).to(beFalse())
expect(matcher.matches([0: 0, 1: 1, 2: 2, 3: 3])).to(beFalse())
}
it("fails if any actual pair does not equal the expected pair") {
expect(matcher.matches([0: 1, 1: 1, 2: 2])).to(beFalse())
expect(matcher.matches([0: 0, 1: 0, 2: 2])).to(beFalse())
expect(matcher.matches([0: 0, 1: 1, 2: 1])).to(beFalse())
expect(matcher.matches([3: 0, 4: 1, 5: 2])).to(beFalse())
}
}
}
}
}
| 064f4558623c7e13eb6e067ae72104f3 | 41.564103 | 136 | 0.47315 | false | false | false | false |
jekahy/Adoreavatars | refs/heads/master | Adoravatars/DownloadTask.swift | mit | 1 | //
// DownloadTask.swift
// Adoravatars
//
// Created by Eugene on 12.07.17.
// Copyright © 2017 Eugene. All rights reserved.
//
import RxSwift
protocol DownloadTaskType {
var fileName:String{get}
var progress:Observable<Double>{get}
var status:Observable<DownloadTask.Status>{get}
var updatedAt:Observable<Date>{get}
var data:Observable<Data?>{get}
}
class DownloadTask:DownloadTaskType {
enum Status:String {
case queued = "queued"
case inProgress = "in progress"
case done = "done"
case failed = "failed"
}
let fileName:String
private let progressSubj = BehaviorSubject<Double>(value: 0)
private (set) lazy var progress:Observable<Double> = self.progressSubj.asObservable().distinctUntilChanged()
private let statusSubj = BehaviorSubject<Status>(value: .queued)
private (set) lazy var status:Observable<Status> = self.statusSubj.asObservable()
private let updatedAtSubj = BehaviorSubject<Date>(value: Date())
private (set) lazy var updatedAt:Observable<Date> = self.updatedAtSubj.asObservable()
private let dataSubj = BehaviorSubject<Data?>(value:nil)
private (set) lazy var data:Observable<Data?> = self.dataSubj.asObservable().shareReplay(1)
private let disposeBag = DisposeBag()
init(_ fileName:String, eventsObservable:Observable<DownloadTaskEvent>) {
self.fileName = fileName
eventsObservable.subscribe(onNext: { [weak self] downoadEvent in
self?.updatedAtSubj.onNext(Date())
switch downoadEvent{
case .progress(let progress):
self?.statusSubj.onNext(.inProgress)
self?.progressSubj.onNext(progress)
case .done(let data):
self?.dataSubj.onNext(data)
self?.statusSubj.onNext(.done)
self?.progressSubj.onNext(1)
default: break
}
}, onError: {[weak self] error in
self?.updatedAtSubj.onNext(Date())
self?.statusSubj.onNext(.failed)
}, onCompleted: { [weak self] in
self?.statusSubj.onNext(.done)
}).disposed(by: disposeBag)
}
}
| dc79eba256d24e0665c38f267c6ce126 | 30.133333 | 112 | 0.608137 | false | false | false | false |
volodg/iAsync.social | refs/heads/master | Pods/iAsync.network/Lib/NSError/NSNetworkErrors/JNSNetworkError.swift | mit | 1 | //
// JNSNetworkError.swift
// Wishdates
//
// Created by Vladimir Gorbenko on 18.08.14.
// Copyright (c) 2014 EmbeddedSources. All rights reserved.
//
import Foundation
import iAsync_utils
public class JNSNetworkError : JNetworkError {
let context: JURLConnectionParams
let nativeError: NSError
public required init(context: JURLConnectionParams, nativeError: NSError) {
self.context = context
self.nativeError = nativeError
super.init(description:"")
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override var localizedDescription: String {
return NSLocalizedString(
"J_NETWORK_GENERIC_ERROR",
bundle: NSBundle(forClass: self.dynamicType),
comment:"")
}
public class func createJNSNetworkErrorWithContext(
context: JURLConnectionParams, nativeError: NSError) -> JNSNetworkError {
var selfType: JNSNetworkError.Type!
//select class for error
let errorClasses: [JNSNetworkError.Type] =
[
JNSNoInternetNetworkError.self
]
selfType = firstMatch(errorClasses) { (object: JNSNetworkError.Type) -> Bool in
return object.isMineNSNetworkError(nativeError)
}
if selfType == nil {
selfType = JNSNetworkError.self
}
return selfType(context: context, nativeError: nativeError)
}
class func isMineNSNetworkError(error: NSError) -> Bool {
return false
}
public override func copyWithZone(zone: NSZone) -> AnyObject {
return self.dynamicType(context: context, nativeError: nativeError)
}
public override var errorLogDescription: String {
return "\(self.dynamicType) : \(localizedDescription) nativeError:\(nativeError) context:\(context)"
}
}
| 3ad278946667da727e4f974e9331ca1b | 26.266667 | 108 | 0.616137 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/Lumia/Lumia/Frame/CatalogByConvention/CBCNodeListViewController.swift | mit | 1 | //
// CBCNodeListViewController.swift
// Lumia
//
// Created by xiAo_Ju on 2020/1/20.
// Copyright © 2020 黄伯驹. All rights reserved.
//
import UIKit
// https://github.com/material-foundation/cocoapods-catalog-by-convention
/**
A node describes a single navigable page in the Catalog by Convention.
A node either has children or it is an example.
- If a node has children, then the node should be represented by a list of some sort.
- If a node is an example, then the example controller can be instantiated with
createExampleViewController.
*/
class CBCNode {
/** The title for this node. */
private(set) var title: String
/** The children of this node. */
var children: [CBCNode] = []
/**
The example you wish to debug as the initial view controller.
If there are multiple examples with catalogIsDebug returning YES
the debugLeaf will hold the example that has been iterated on last
in the hierarchy tree.
*/
var debugLeaf: CBCNode?
/**
This NSDictionary holds all the metadata related to this CBCNode.
If it is an example noe, a primary demo, related info,
if presentable in Catalog, etc.
*/
var metadata: [String: Any]?
/** Returns true if this is an example node. */
var isExample: Bool {
return exampleClass != nil
}
/**
Returns YES if this the primary demo for this component.
Can only return true if isExample also returns YES.
*/
var isPrimaryDemo: Bool {
guard let v = metadata?[CBCIsPrimaryDemo] as? Bool else {
return false
}
return v
}
/** Returns YES if this is a presentable example. */
var isPresentable: Bool {
guard let v = metadata?[CBCIsPresentable] as? Bool else {
return false
}
return v
}
/** Returns String representation of exampleViewController class name if it exists */
var exampleViewControllerName: String? {
assert(exampleClass != nil, "This node has no associated example.")
return exampleClass?.description()
}
/**
Returns an instance of a UIViewController for presentation purposes.
Check that isExample returns YES before invoking.
*/
var createExampleViewController: UIViewController {
assert(exampleClass != nil, "This node has no associated example.")
return CBCViewControllerFromClass(exampleClass!, metadata!)
}
/**
Returns a description of the example.
Check that isExample returns YES before invoking.
*/
var exampleDescription: String? {
guard let description = metadata?[CBCDescription] as? String else {
return nil
}
return description
}
/** Returns a link to related information for the example. */
var exampleRelatedInfo: URL? {
guard let relatedInfo = metadata?[CBCRelatedInfo] as? URL else {
return nil
}
return relatedInfo
}
fileprivate var map: [String: Any] = [:]
fileprivate var exampleClass: UIViewController.Type?
init(title: String) {
self.title = title
CBCFixViewDebuggingIfNeeded()
}
fileprivate func add(_ child: CBCNode) {
map[child.title] = child
children.append(child)
}
fileprivate func finalizeNode() {
children = children.sorted(by: { $0.title == $1.title })
}
}
public class CBCNodeListViewController: UIViewController {
/** Initializes a CBCNodeViewController instance with a non-example node. */
init(node: CBCNode) {
super.init(nibName: nil, bundle: nil)
self.node = node
title = node.title
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: self.view.bounds, style: .grouped)
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return tableView
}()
/** The node that this view controller must represent. */
private(set) var node: CBCNode!
public override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let selectedRow = tableView.indexPathForSelectedRow else { return }
transitionCoordinator?.animate(alongsideTransition: { context in
self.tableView.deselectRow(at: selectedRow, animated: true)
}, completion: { context in
if context.isCancelled {
self.tableView.selectRow(at: selectedRow, animated: false, scrollPosition: .none)
}
})
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.flashScrollIndicators()
}
}
extension CBCNodeListViewController: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return node.children.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = node.children[indexPath.row].title
cell.accessoryType = .disclosureIndicator
return cell;
}
}
extension CBCNodeListViewController: UITableViewDelegate {
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let node = self.node.children[indexPath.row]
var viewController: UIViewController? = CBCNodeListViewController(node: node)
if node.isExample {
viewController = node.createExampleViewController
}
show(viewController!, sender: nil)
}
}
func CBCAddNodeFromBreadCrumbs(_ tree: CBCNode, _ breadCrumbs: [String], _ aClass: UIViewController.Type, _ metadata: [String: Any]) {
// Walk down the navigation tree one breadcrumb at a time, creating nodes along the way.
var node = tree
for (ix, title) in breadCrumbs.enumerated() {
let isLastCrumb = ix == breadCrumbs.count - 1
// Don't walk the last crumb
if let n = node.map[title] as? CBCNode, !isLastCrumb {
node = n
continue
}
let child = CBCNode(title: title)
node.add(child)
child.metadata = metadata
if child.metadata?[CBCIsPrimaryDemo] as? Bool ?? false {
node.metadata = child.metadata
}
if child.metadata?[CBCIsDebug] as? Bool ?? false {
tree.debugLeaf = child
}
node = child
}
node.exampleClass = aClass
}
func CBCCreateTreeWithOnlyPresentable(_ onlyPresentable: Bool) -> CBCNode {
let allClasses = CBCGetAllCompatibleClasses()
let filteredClasses = allClasses.filter { objc in
let metadata = CBCCatalogMetadataFromClass(objc)
let breadcrumbs = metadata[CBCBreadcrumbs]
var validObject = breadcrumbs != nil && (breadcrumbs as? [Any] != nil)
if onlyPresentable {
validObject = validObject && (metadata[CBCIsPresentable] as? Bool ?? false)
}
return validObject
}
let tree = CBCNode(title: "Root")
for aClass in filteredClasses {
// Each example view controller defines its own breadcrumbs (metadata[CBCBreadcrumbs]).
let metadata = CBCCatalogMetadataFromClass(aClass)
let breadCrumbs = metadata[CBCBreadcrumbs] as? [Any]
if (breadCrumbs?.first as? String) != nil {
CBCAddNodeFromBreadCrumbs(tree, breadCrumbs as! [String], aClass, metadata);
} else if (breadCrumbs?.first as? [String]) != nil {
for parallelBreadCrumb in breadCrumbs! {
CBCAddNodeFromBreadCrumbs(tree, parallelBreadCrumb as! [String], aClass, metadata)
}
}
}
// Perform final post-processing on the nodes.
var queue = [tree]
while queue.count > 0 {
let node = queue.first
queue.remove(at: 0)
queue.append(contentsOf: node!.children)
node?.finalizeNode()
}
return tree
}
func CBCCreateNavigationTree() -> CBCNode {
return CBCCreateTreeWithOnlyPresentable(false)
}
func CBCCreatePresentableNavigationTree() -> CBCNode {
return CBCCreateTreeWithOnlyPresentable(true)
}
| 4ede31fe6a1a9a23056f23a816e90fe7 | 30.74359 | 134 | 0.650358 | false | false | false | false |
mperovic/ISO8601Formatter | refs/heads/master | ISO8601/ISO8601.swift | mit | 1 | //
// main.swift
// ISO8601
//
// Created by Miroslav Perovic on 6/23/15.
// Copyright © 2015 Miroslav Perovic. All rights reserved.
//
import Foundation
final class ISO8601Formatter: NSFormatter {
enum ISO8601DateStyle: Int {
case CalendarLongStyle // Default (YYYY-MM-DD)
case CalendarShortStyle // (YYYYMMDD)
case OrdinalLongStyle // (YYYY-DDD)
case OrdinalShortStyle // (YYYYDDD)
case WeekLongStyle // (YYYY-Www-D)
case WeekShortStyle // (YYYYWwwD)
}
enum ISO8601TimeStyle: Int {
case None
case LongStyle // Default (hh:mm:ss)
case ShortStyle // (hhmmss)
}
enum ISO8601TimeZoneStyle: Int {
case None
case UTC // Default (Z)
case LongStyle // (±hh:mm)
case ShortStyle // (±hhmm)
}
enum ISO8601FractionSeparator: Int {
case Comma // Default (,)
case Dot // (.)
}
var dateStyle: ISO8601DateStyle
var timeStyle: ISO8601TimeStyle
var fractionSeparator: ISO8601FractionSeparator
var timeZoneStyle: ISO8601TimeZoneStyle
var fractionDigits: Int
let days365 = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
let days366 = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]
convenience override init() {
self.init(
dateStyle: .CalendarLongStyle,
timeStyle: .LongStyle,
fractionSeparator: .Comma,
fractionDigits: 6,
timeZoneStyle: .UTC
)
}
init(dateStyle: ISO8601DateStyle, timeStyle: ISO8601TimeStyle, fractionSeparator: ISO8601FractionSeparator, fractionDigits: Int, timeZoneStyle: ISO8601TimeZoneStyle) {
self.dateStyle = dateStyle
self.timeStyle = timeStyle
self.fractionSeparator = fractionSeparator
self.fractionDigits = fractionDigits
self.timeZoneStyle = timeZoneStyle
super.init()
}
required convenience init?(coder aDecoder: NSCoder) {
self.init(
dateStyle: .CalendarLongStyle,
timeStyle: .LongStyle,
fractionSeparator: .Comma,
fractionDigits: 6,
timeZoneStyle: .UTC
)
}
func stringFromDate(date: NSDate) -> String? {
let calendar = NSCalendar.currentCalendar()
if timeZoneStyle == .UTC {
calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
}
let dateComponents = calendar.components(
[.Year, .Month, .Day, .WeekOfYear, .Hour, .Minute, .Second, .Weekday, .WeekdayOrdinal, .WeekOfYear, .YearForWeekOfYear, .TimeZone],
fromDate: date
)
var string: String
if dateComponents.year < 0 || dateComponents.year > 9999 {
return nil
}
string = String(format: "%04li", dateComponents.year)
if dateStyle == .WeekLongStyle || dateStyle == .WeekShortStyle {
// For weekOfYear calculation see more at: https://en.wikipedia.org/wiki/ISO_8601#Week_dates
if date.weekOfYear() == 53 {
string = String(format: "%04li", dateComponents.year - 1)
}
}
switch dateStyle {
case .CalendarLongStyle:
string = string + String(format: "-%02i-%02i", dateComponents.month, dateComponents.day)
case .CalendarShortStyle:
string = string + String(format: "%02i%02i", dateComponents.month, dateComponents.day)
case .OrdinalLongStyle:
string = string + String(format: "-%03i", date.dayOfYear())
case .OrdinalShortStyle:
string = string + String(format: "%03i", date.dayOfYear())
case .WeekLongStyle:
if dateComponents.weekday > 1 {
string = string + String(format: "-W%02i-%01i", date.weekOfYear(), dateComponents.weekday - 1)
} else {
string = string + String(format: "-W%02i-%01i", date.weekOfYear(), 7)
}
case .WeekShortStyle:
if dateComponents.weekday > 1 {
string = string + String(format: "W%02i%01i", dateComponents.weekOfYear, dateComponents.weekday - 1)
} else {
string = string + String(format: "W%02i%01i", dateComponents.weekOfYear, 7)
}
}
let timeString: String
switch timeStyle {
case .LongStyle:
timeString = String(format: "T%02i:%02i:%02i", dateComponents.hour, dateComponents.minute, dateComponents.second)
case .ShortStyle:
timeString = String(format: "T%02i:%02i:%02i", dateComponents.hour, dateComponents.minute, dateComponents.second)
case .None:
return string
}
string = string + timeString
if let timeZone = dateComponents.timeZone {
let timeZoneString: String
switch timeZoneStyle {
case .UTC:
timeZoneString = "Z"
case .LongStyle, .ShortStyle:
let hoursOffset = timeZone.secondsFromGMT / 3600
let secondsOffset = 0
let sign = hoursOffset >= 0 ? "+" : "-"
if timeZoneStyle == .LongStyle {
timeZoneString = String(format: "%@%02i:%02i", sign, hoursOffset, secondsOffset)
} else {
timeZoneString = String(format: "%@%02i%02i", sign, hoursOffset, secondsOffset)
}
case .None:
return string
}
string = string + timeZoneString
}
return string
}
func dateFromString(string: String) -> NSDate? {
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
gregorian.firstWeekday = 2 // Monday
let str = self.convertBasicToExtended(string)
let scanner = NSScanner(string: str)
scanner.charactersToBeSkipped = nil
let dateComponents = NSDateComponents()
// Year
var year = 0
guard scanner.scanInteger(&year) else {
return nil
}
guard year >= 0 && year <= 9999 else {
return nil
}
dateComponents.year = year
// Month or Week
guard scanner.scanString("-", intoString: nil) else {
return gregorian.dateFromComponents(dateComponents)
}
var month = 0
var ordinalDay = 0
switch dateStyle {
case .CalendarLongStyle, .CalendarShortStyle:
guard scanner.scanInteger(&month) else {
return gregorian.dateFromComponents(dateComponents)
}
dateComponents.month = month
case .OrdinalLongStyle, .OrdinalShortStyle:
guard scanner.scanInteger(&ordinalDay) else {
return gregorian.dateFromComponents(dateComponents)
}
let daysArray: [Int]
if ((year % 4) == 0 && (year % 100) != 0) || (year % 400) == 0 {
daysArray = days366
} else {
daysArray = days365
}
var theMonth = 0
for startDay in daysArray {
theMonth++
if startDay > ordinalDay {
month = theMonth - 1
break
}
}
dateComponents.month = month
case .WeekLongStyle, .WeekShortStyle:
guard scanner.scanString("W", intoString: nil) else {
return gregorian.dateFromComponents(dateComponents)
}
var week = 0
guard scanner.scanInteger(&week) else {
return gregorian.dateFromComponents(dateComponents)
}
if week < 0 || week > 53 {
return gregorian.dateFromComponents(dateComponents)
}
dateComponents.weekOfYear = week
}
// Day or DayOfWeek
var day = 0
switch dateStyle {
case .CalendarLongStyle, .CalendarShortStyle:
guard scanner.scanString("-", intoString: nil) else {
return gregorian.dateFromComponents(dateComponents)
}
guard scanner.scanInteger(&day) else {
return gregorian.dateFromComponents(dateComponents)
}
dateComponents.day = day
case .OrdinalLongStyle, .OrdinalShortStyle:
let daysArray: [Int]
if ((year % 4) == 0 && (year % 100) != 0) || (year % 400) == 0 {
daysArray = days366
} else {
daysArray = days365
}
var theDay = 0
var previousStartDay = 0
for startDay in daysArray {
if startDay > ordinalDay {
theDay = ordinalDay - previousStartDay
break
}
previousStartDay = startDay
}
dateComponents.day = theDay
case .WeekLongStyle, .WeekShortStyle:
guard scanner.scanString("-", intoString: nil) else {
return gregorian.dateFromComponents(dateComponents)
}
guard scanner.scanInteger(&day) else {
return gregorian.dateFromComponents(dateComponents)
}
if day < 0 || day > 7 {
return gregorian.dateFromComponents(dateComponents)
} else {
dateComponents.weekday = day
}
}
// Time
guard scanner.scanCharactersFromSet(NSCharacterSet(charactersInString: "T"), intoString: nil) else {
return gregorian.dateFromComponents(dateComponents)
}
// Hour
var hour = 0
guard scanner.scanInteger(&hour) else {
return gregorian.dateFromComponents(dateComponents)
}
if timeStyle != .None {
if hour < 0 || hour > 23 {
return gregorian.dateFromComponents(dateComponents)
} else {
dateComponents.hour = hour
}
}
// Minute
guard scanner.scanString(":", intoString: nil) else {
return gregorian.dateFromComponents(dateComponents)
}
var minute = 0
guard scanner.scanInteger(&minute) else {
return gregorian.dateFromComponents(dateComponents)
}
if timeStyle != .None {
if minute < 0 || minute > 59 {
return gregorian.dateFromComponents(dateComponents)
} else {
dateComponents.minute = minute
}
}
// Second
var scannerLocation = scanner.scanLocation
if scanner.scanString(":", intoString: nil) {
var second = 0
guard scanner.scanInteger(&second) else {
return gregorian.dateFromComponents(dateComponents)
}
if timeStyle != .None {
if second < 0 || second > 59 {
return gregorian.dateFromComponents(dateComponents)
} else {
dateComponents.second = second
}
}
} else {
scanner.scanLocation = scannerLocation
}
// Zulu
scannerLocation = scanner.scanLocation
scanner.scanUpToString("Z", intoString: nil)
if scanner.scanString("Z", intoString: nil) {
dateComponents.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return gregorian.dateFromComponents(dateComponents)
}
// Move back to the end of time
scanner.scanLocation = scannerLocation
// Look for offset
let signs = NSCharacterSet(charactersInString: "+-")
scanner.scanUpToCharactersFromSet(signs, intoString: nil)
var sign: NSString?
guard scanner.scanCharactersFromSet(signs, intoString: &sign) else {
return gregorian.dateFromComponents(dateComponents)
}
// Offset hour
var timeZoneOffset = 0
var timeZoneOffsetHour = 0
var timeZoneOffsetMinute = 0
guard scanner.scanInteger(&timeZoneOffsetHour) else {
return gregorian.dateFromComponents(dateComponents)
}
// Check for colon
let colonExists = scanner.scanString(":", intoString: nil)
if !colonExists && timeZoneOffsetHour > 14 {
timeZoneOffsetMinute = timeZoneOffsetHour % 100
timeZoneOffsetHour = Int(floor(Double(timeZoneOffsetHour) / 100.0))
} else {
scanner.scanInteger(&timeZoneOffsetMinute)
}
timeZoneOffset = (timeZoneOffsetHour * 60 * 60) + (timeZoneOffsetMinute * 60)
dateComponents.timeZone = NSTimeZone(forSecondsFromGMT: timeZoneOffset * (sign == "-" ? -1 : 1))
return gregorian.dateFromComponents(dateComponents)
}
// Private methods
private func checkAndUpdateTimeZone(string: NSMutableString, insertAtIndex index: Int) -> NSMutableString {
if self.timeZoneStyle == .ShortStyle {
string.insertString(":", atIndex: index)
}
return string
}
private func convertBasicToExtended(string: String) -> String {
func checkAndUpdateTimeStyle(var string: NSMutableString, insertAtIndex index: Int) -> NSMutableString {
if (self.timeStyle == .LongStyle) {
string = self.checkAndUpdateTimeZone(string, insertAtIndex: index + 9)
} else if (self.timeStyle == .ShortStyle) {
string = self.checkAndUpdateTimeZone(string, insertAtIndex: index + 7)
string.insertString(":", atIndex: index + 2)
string.insertString(":", atIndex: index)
}
return string
}
var str: NSMutableString = NSMutableString(string: string)
switch self.dateStyle {
case .CalendarLongStyle:
str = checkAndUpdateTimeStyle(str, insertAtIndex: 13)
case .CalendarShortStyle:
str = checkAndUpdateTimeStyle(str, insertAtIndex: 11)
str.insertString("-", atIndex: 6)
str.insertString("-", atIndex: 4)
case .OrdinalLongStyle:
str = checkAndUpdateTimeStyle(str, insertAtIndex: 11)
case .OrdinalShortStyle:
str = checkAndUpdateTimeStyle(str, insertAtIndex: 10)
str.insertString("-", atIndex: 4)
case .WeekLongStyle:
str = checkAndUpdateTimeStyle(str, insertAtIndex: 13)
case .WeekShortStyle:
str = checkAndUpdateTimeStyle(str, insertAtIndex: 11)
str.insertString("-", atIndex: 7)
str.insertString("-", atIndex: 4)
}
return String(str)
}
}
extension NSDate {
func isLeapYear() -> Bool {
let dateComponents = NSCalendar.currentCalendar().components(
[.Year, .Month, .Day, .WeekOfYear, .Hour, .Minute, .Second, .Weekday, .WeekdayOrdinal, .WeekOfYear, .TimeZone],
fromDate: self
)
return ((dateComponents.year % 4) == 0 && (dateComponents.year % 100) != 0) || (dateComponents.year % 400) == 0 ? true : false
}
func dayOfYear() -> Int {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "D"
return Int(dateFormatter.stringFromDate(self))!
}
func weekOfYear() -> Int {
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
gregorian.firstWeekday = 2 // Monday
gregorian.minimumDaysInFirstWeek = 4
let components = gregorian.components([.WeekOfYear, .YearForWeekOfYear], fromDate: self)
let week = components.weekOfYear
return week
}
} | 29426891c5a91e1c5ad7a15cb590b734 | 28.015487 | 168 | 0.688577 | false | false | false | false |
apple/swift-nio-extras | refs/heads/main | Sources/NIOHTTPCompression/HTTPRequestDecompressor.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import CNIOExtrasZlib
import NIOHTTP1
import NIOCore
/// Channel hander to decompress incoming HTTP data.
public final class NIOHTTPRequestDecompressor: ChannelDuplexHandler, RemovableChannelHandler {
/// Expect to receive `HTTPServerRequestPart` from the network
public typealias InboundIn = HTTPServerRequestPart
/// Pass `HTTPServerRequestPart` to the next pipeline state in an inbound direction.
public typealias InboundOut = HTTPServerRequestPart
/// Pass through `HTTPServerResponsePart` outbound.
public typealias OutboundIn = HTTPServerResponsePart
/// Pass through `HTTPServerResponsePart` outbound.
public typealias OutboundOut = HTTPServerResponsePart
private struct Compression {
let algorithm: NIOHTTPDecompression.CompressionAlgorithm
let contentLength: Int
}
private var decompressor: NIOHTTPDecompression.Decompressor
private var compression: Compression?
private var decompressionComplete: Bool
/// Initialise with limits.
/// - Parameter limit: Limit to how much inflation can occur to protect against bad cases.
public init(limit: NIOHTTPDecompression.DecompressionLimit) {
self.decompressor = NIOHTTPDecompression.Decompressor(limit: limit)
self.compression = nil
self.decompressionComplete = false
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let request = self.unwrapInboundIn(data)
switch request {
case .head(let head):
if
let encoding = head.headers[canonicalForm: "Content-Encoding"].first?.lowercased(),
let algorithm = NIOHTTPDecompression.CompressionAlgorithm(header: encoding),
let length = head.headers[canonicalForm: "Content-Length"].first.flatMap({ Int($0) })
{
do {
try self.decompressor.initializeDecoder(encoding: algorithm)
self.compression = Compression(algorithm: algorithm, contentLength: length)
} catch let error {
context.fireErrorCaught(error)
return
}
}
context.fireChannelRead(data)
case .body(var part):
guard let compression = self.compression else {
context.fireChannelRead(data)
return
}
while part.readableBytes > 0 && !self.decompressionComplete {
do {
var buffer = context.channel.allocator.buffer(capacity: 16384)
let result = try self.decompressor.decompress(part: &part, buffer: &buffer, compressedLength: compression.contentLength)
if result.complete {
self.decompressionComplete = true
}
context.fireChannelRead(self.wrapInboundOut(.body(buffer)))
} catch let error {
context.fireErrorCaught(error)
return
}
}
if part.readableBytes > 0 {
context.fireErrorCaught(NIOHTTPDecompression.ExtraDecompressionError.invalidTrailingData)
}
case .end:
if self.compression != nil {
let wasDecompressionComplete = self.decompressionComplete
self.decompressor.deinitializeDecoder()
self.compression = nil
self.decompressionComplete = false
if !wasDecompressionComplete {
context.fireErrorCaught(NIOHTTPDecompression.ExtraDecompressionError.truncatedData)
}
}
context.fireChannelRead(data)
}
}
}
#if swift(>=5.6)
@available(*, unavailable)
extension NIOHTTPRequestDecompressor: Sendable {}
#endif
| bce9871c2be3a240f67e7477ed515a1c | 37.875 | 140 | 0.613918 | false | false | false | false |
younata/RSSClient | refs/heads/master | TethysKitSpecs/Models/NetworkPagedCollectionSpec.swift | mit | 1 | import Quick
import Nimble
import Result
import CBGPromise
import FutureHTTP
@testable import TethysKit
private enum SomeError: Error {
case whatever
}
final class NetworkPagedCollectionSpec: QuickSpec {
override func spec() {
var subject: NetworkPagedCollection<String>!
var httpClient: FakeHTTPClient!
var pagesRequested: [String?] = []
var nextPageIndex: String? = nil
beforeEach {
pagesRequested = []
httpClient = FakeHTTPClient()
subject = NetworkPagedCollection<String>(
httpClient: httpClient,
requestFactory: { (pageNumber: String?) -> URLRequest in
pagesRequested.append(pageNumber)
let number = pageNumber ?? ""
return URLRequest(url: URL(string: "https://example.com/\(number)")!)
},
dataParser: { (data: Data) throws -> ([String], String?) in
guard let contents = String(data: data, encoding: .utf8) else {
throw SomeError.whatever
}
return (contents.components(separatedBy: ","), nextPageIndex)
}
)
}
it("immediately makes a request using the number given") {
expect(httpClient.requests).to(haveCount(1))
expect(httpClient.requests.last).to(equal(URLRequest(url: URL(string: "https://example.com/")!)))
expect(pagesRequested).to(equal([nil]))
}
func theCommonCollectionProperties(startIndex: NetworkPagedIndex, endIndex: NetworkPagedIndex, underestimatedCount: Int, line: UInt = #line) {
describe("asking for common collection properties at this point") {
it("startIndex") {
expect(subject.startIndex, line: line).to(equal(startIndex))
}
it("endIndex") {
expect(subject.endIndex, line: line).to(equal(endIndex))
}
it("underestimatedCount") {
expect(subject.underestimatedCount, line: line).to(equal(underestimatedCount))
}
}
}
theCommonCollectionProperties(startIndex: 0, endIndex: NetworkPagedIndex(actualIndex: 0, isIndefiniteEnd: true), underestimatedCount: 0)
it("converts to anycollection without hanging") {
expect(AnyCollection(subject)).toNot(beNil())
}
describe("when the request succeeds with valid data") {
beforeEach {
nextPageIndex = "2"
httpClient.requestPromises.last?.resolve(.success(HTTPResponse(
body: "foo,bar,baz,qux".data(using: .utf8)!,
status: .ok,
mimeType: "Text/Plain",
headers: [:]
)))
}
it("doesn't yet make another request") {
expect(httpClient.requests).to(haveCount(1))
expect(httpClient.requests.last).to(equal(URLRequest(url: URL(string: "https://example.com/")!)))
expect(pagesRequested).to(equal([nil]))
}
theCommonCollectionProperties(startIndex: 0, endIndex: NetworkPagedIndex(actualIndex: 4, isIndefiniteEnd: true), underestimatedCount: 4)
it("converts to anycollection without hanging") {
expect(AnyCollection(subject)).toNot(beNil())
}
it("makes another request when you reach the 75% point on the iteration/access") {
guard subject.underestimatedCount >= 3 else {
fail("not enough items loaded yet")
return
}
expect(subject[0]).to(equal("foo"))
expect(httpClient.requests).to(haveCount(1))
expect(subject[1]).to(equal("bar"))
expect(httpClient.requests).to(haveCount(1))
expect(subject[2]).to(equal("baz")) // the 75% point
expect(httpClient.requests).to(haveCount(2))
expect(httpClient.requests.last).to(equal(URLRequest(url: URL(string: "https://example.com/2")!)))
expect(pagesRequested).to(equal([nil, "2"]))
}
it("doesn't make multiple requests for the same data point") {
guard subject.underestimatedCount >= 4 else {
fail("not enough items loaded yet")
return
}
expect(subject[3]).to(equal("qux"))
expect(httpClient.requests).to(haveCount(2))
expect(subject[2]).to(equal("baz"))
expect(httpClient.requests).to(haveCount(2))
}
describe("if this next request succeeds with a next page") {
beforeEach {
nextPageIndex = "3"
guard httpClient.requestCallCount == 1 else { return }
_ = subject[3]
httpClient.requestPromises.last?.resolve(.success(HTTPResponse(
body: "a,b,c,d".data(using: .utf8)!,
status: .ok,
mimeType: "Text/Plain",
headers: [:]
)))
}
it("doesn't yet request the third page") {
expect(httpClient.requests).to(haveCount(2))
expect(pagesRequested).to(equal([nil, "2"]))
}
theCommonCollectionProperties(startIndex: 0, endIndex: NetworkPagedIndex(actualIndex: 8, isIndefiniteEnd: true), underestimatedCount: 8)
it("converts to anycollection without hanging") {
expect(AnyCollection(subject)).toNot(beNil())
}
it("doesn't re-request data it already has") {
_ = subject[2]
expect(httpClient.requests).to(haveCount(2))
}
it("makes another request when you reach the 75% point on the iteration/access for THIS requested data") {
guard subject.underestimatedCount >= 7 else {
fail("not enough items loaded yet")
return
}
expect(subject[4]).to(equal("a"))
expect(httpClient.requests).to(haveCount(2))
expect(subject[5]).to(equal("b"))
expect(httpClient.requests).to(haveCount(2))
expect(subject[6]).to(equal("c")) // the 75% point (index 6, as opposed to index 5 for 75% of entire data set).
expect(httpClient.requests).to(haveCount(3))
expect(httpClient.requests.last).to(equal(URLRequest(url: URL(string: "https://example.com/3")!)))
expect(pagesRequested).to(equal([nil, "2", "3"]))
}
it("doesn't make multiple requests for the same data point") {
guard subject.underestimatedCount >= 8 else {
fail("not enough items loaded yet")
return
}
expect(subject[7]).to(equal("d"))
expect(httpClient.requests).to(haveCount(3))
expect(subject[6]).to(equal("c"))
expect(httpClient.requests).to(haveCount(3))
}
}
describe("if this request succeeds with no next page") {
beforeEach {
nextPageIndex = nil
guard httpClient.requestCallCount == 1 else { return }
_ = subject[3]
httpClient.requestPromises.last?.resolve(.success(HTTPResponse(
body: "a,b,c,d".data(using: .utf8)!,
status: .ok,
mimeType: "Text/Plain",
headers: [:]
)))
}
it("doesn't request the third data, even when the entire collection is iterated through") {
expect(httpClient.requests).to(haveCount(2))
guard httpClient.requestCallCount == 2 else {
fail("Expected to have made 2 requests")
return
}
expect(pagesRequested).to(equal([nil, "2"]))
expect(Array(subject)).to(equal(["foo", "bar", "baz", "qux", "a", "b", "c", "d"]))
expect(httpClient.requests).to(haveCount(2))
expect(pagesRequested).to(equal([nil, "2"]))
}
theCommonCollectionProperties(startIndex: 0, endIndex: NetworkPagedIndex(actualIndex: 8, isIndefiniteEnd: false), underestimatedCount: 8)
it("converts to anycollection without hanging") {
expect(AnyCollection(subject)).to(haveCount(8))
expect(Array(AnyCollection(subject))).to(equal(["foo", "bar", "baz", "qux", "a", "b", "c", "d"]))
}
}
}
}
}
| 79b57b7db9090e1494df27d5383d1bec | 40.904545 | 153 | 0.515457 | false | false | false | false |
Chantalisima/Spirometry-app | refs/heads/master | EspiroGame/InstructionGameViewController.swift | apache-2.0 | 1 | //
// InstructionGameViewController.swift
// EspiroGame
//
// Created by Chantal de Leste on 28/4/17.
// Copyright © 2017 Universidad de Sevilla. All rights reserved.
//
import UIKit
import CoreBluetooth
class InstructionGameViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var mainPeripheral: CBPeripheral?
var mainView: MainViewController?
@IBOutlet weak var tableView: UITableView!
var number: [String] = ["1.","2.","3.","4.","5."]
var instruccions: [String] = [" Select the correct resistance in the pep device","Place mouthpiece into your mouth","Inhale a large breath","Hold the breath for 3 or 4 second","Exhale for 3 or 4 seconds, keeping the spacecraft floating and keep the spacecraft sailing without touching the spikes "]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("InstruccionTableViewCell", owner: self, options: nil)?.first as! InstruccionTableViewCell
cell.instruction.numberOfLines = 0
cell.number.text = number[indexPath.row]
cell.instruction.text = instruccions[indexPath.row]
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "game"{
let trainningController: TrainningViewController = segue.destination as! TrainningViewController
trainningController.mainPeripheral = self.mainPeripheral
print("segue to test")
if self.mainPeripheral != nil {
mainPeripheral?.delegate = trainningController
mainPeripheral?.discoverServices(nil)
print("peripheral equal to test peripheral")
}
}
}
}
| b7dcf850a551b4fbb359ec8ba6511301 | 32.319444 | 302 | 0.644018 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/TransitionsLibrary/TransitionsLibrary/Classes/PortalAnimationTransitioning.swift | mit | 1 | //
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
class PortalAnimationTransitioning: ReversibleAnimationTransitioning {
override func animateTransition(_ context: UIViewControllerContextTransitioning, fromVC: UIViewController, toVC: UIViewController, fromView: UIView, toView: UIView) {
if reverse {
executeReverseAnimation(context, fromVC: fromVC, toVC: toVC, fromView: fromView, toView: toView)
} else {
executeForwardsAnimation(context, fromVC: fromVC, toVC: toVC, fromView: fromView, toView: toView)
}
}
let ZOOM_SCALE: CGFloat = 0.8
func executeForwardsAnimation(_ context: UIViewControllerContextTransitioning, fromVC: UIViewController, toVC: UIViewController, fromView: UIView, toView: UIView) {
let containerView = context.containerView
let toViewSnapshot = toView.resizableSnapshotView(from: toView.frame, afterScreenUpdates: true, withCapInsets: UIEdgeInsets.zero)
let scale = CATransform3DIdentity
toViewSnapshot!.layer.transform = CATransform3DScale(scale, ZOOM_SCALE, ZOOM_SCALE, 1)
containerView.addSubview(toViewSnapshot!)
containerView.sendSubviewToBack(toViewSnapshot!)
let leftSnapshotRegion = CGRect(x: 0, y: 0, width: fromView.frame.width / 2, height: fromView.frame.height)
let leftHandView = fromView.resizableSnapshotView(from: leftSnapshotRegion, afterScreenUpdates: false, withCapInsets: UIEdgeInsets.zero)
leftHandView!.frame = leftSnapshotRegion
containerView.addSubview(leftHandView!)
let rightSnapshotRegion = CGRect(x: fromView.frame.width / 2, y: 0, width: fromView.frame.width / 2, height: fromView.frame.height)
let rightHandView = fromView.resizableSnapshotView(from: rightSnapshotRegion, afterScreenUpdates: false, withCapInsets: UIEdgeInsets.zero)
rightHandView!.frame = rightSnapshotRegion
containerView.addSubview(rightHandView!)
fromView.removeFromSuperview()
let duration = transitionDuration(using: context)
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
let leftOffset = CGRect.offsetBy(leftHandView!.frame)
leftHandView!.frame = leftOffset(-leftHandView!.frame.width, 0)
let rightOffset = CGRect.offsetBy(rightHandView!.frame)
rightHandView!.frame = rightOffset(rightHandView!.frame.width, 0)
toViewSnapshot!.center = toView.center
toViewSnapshot!.frame = toView.frame
}) { (flag) in
if context.transitionWasCancelled {
containerView.addSubview(fromView)
removeOtherViews(fromView)
} else {
containerView.addSubview(toView)
removeOtherViews(toView)
}
context.completeTransition(!context.transitionWasCancelled)
}
}
func executeReverseAnimation(_ context: UIViewControllerContextTransitioning, fromVC: UIViewController, toVC: UIViewController, fromView: UIView, toView: UIView) {
let containerView = context.containerView
containerView.addSubview(fromView)
toView.frame = context.finalFrame(for: toVC)
let offset = CGRect.offsetBy(toView.frame)
toView.frame = offset(toView.frame.width, 0)
containerView.addSubview(toView)
let leftSnapshotRegion = CGRect(x: 0, y: 0, width: toView.frame.width / 2, height: toView.frame.height)
let leftHandView = toView.resizableSnapshotView(from: leftSnapshotRegion, afterScreenUpdates: true, withCapInsets: UIEdgeInsets.zero)
leftHandView!.frame = leftSnapshotRegion
let leftOffset = CGRect.offsetBy(leftHandView!.frame)
leftHandView!.frame = leftOffset(-leftHandView!.frame.width, 0)
containerView.addSubview(leftHandView!)
let rightSnapshotRegion = CGRect(x: toView.frame.width / 2, y: 0, width: toView.frame.width / 2, height: toView.frame.height)
let rightHandView = toView.resizableSnapshotView(from: rightSnapshotRegion, afterScreenUpdates: true, withCapInsets: UIEdgeInsets.zero)
rightHandView!.frame = rightSnapshotRegion
let rightOffset = CGRect.offsetBy(rightHandView!.frame)
rightHandView!.frame = rightOffset(rightHandView!.frame.width, 0)
containerView.addSubview(rightHandView!)
let duration = transitionDuration(using: context)
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
leftHandView!.frame = leftOffset(leftHandView!.frame.width, 0)
rightHandView!.frame = rightOffset(-rightHandView!.frame.width, 0)
let scale = CATransform3DIdentity
fromView.layer.transform = CATransform3DScale(scale, self.ZOOM_SCALE, self.ZOOM_SCALE, 1)
}) { (flag) in
if context.transitionWasCancelled {
removeOtherViews(fromView)
} else {
removeOtherViews(toView)
toView.frame = (containerView.bounds)
}
context.completeTransition(!context.transitionWasCancelled)
}
}
}
func removeOtherViews(_ viewToKeep: UIView) {
if let containerView = viewToKeep.superview {
for view in containerView.subviews {
if view != viewToKeep {
view.removeFromSuperview()
}
}
}
}
| 1f93a47fcaedeba064ac17557db54ac2 | 51.754717 | 170 | 0.670601 | false | false | false | false |
cpmpercussion/microjam | refs/heads/develop | chirpey/ChirpRecorder.swift | mit | 1 | //
// Recorder.swift
// microjam
//
// Created by Henrik Brustad on 21/08/2017.
// Copyright © 2017 Charles Martin. All rights reserved.
//
import UIKit
/// A ChirpPlayerController with the ability to record a new ChirpPerformance
class ChirpRecorder: ChirpPlayer {
/// The ChirpRecorder's ChirpRecordingView
var recordingView: ChirpRecordingView
/// Storage for whether the recorder is enabled or not, controls whether touches are stored and playback starts on touch.
var recordingEnabled = false
/// Storage of the present playback/recording state: playing, recording or idle
var isRecording = false
/// Tells us whether the recording has been added to the stack in the performance handler
var recordingIsDone = false
/// Description of the ChirpPlayer with it's first ChirpPerformance.
override var description: String {
guard let perfString = chirpViews.first?.performance?.description else {
return "ChirpRecorder-NoPerformance"
}
return "ChirpRecorder-" + perfString
}
init(frame: CGRect) {
recordingView = ChirpRecordingView(frame: frame)
recordingView.clipsToBounds = true
recordingView.contentMode = .scaleAspectFill
super.init()
}
/// Convenience initialiser for creating a ChirpRecorder with the same performances as a given ChirpPlayer
convenience init(frame: CGRect, player: ChirpPlayer) {
self.init(frame: frame)
chirpViews = player.chirpViews
}
/// Convenience initialiser for creating a ChirpRecorder with an array of backing ChirpPerformances
convenience init(withArrayOfPerformances performanceArray: [ChirpPerformance]) {
let dummyFrame = CGRect.zero
self.init(frame: dummyFrame)
for perf in performanceArray {
let chirp = ChirpView(with: dummyFrame, andPerformance: perf)
chirpViews.append(chirp)
}
}
/// Starts a new recording if recordingEnabled, time is controlled by the superclass's progressTimer.
func record() -> Bool {
if recordingEnabled {
if !isRecording {
print("ChirpRecorder: Starting recording")
isRecording = true
recordingView.recording = true
// Starting progresstimer and playback of performances if any
play()
return true
}
}
return false
}
/// Override the superclass's play function to only playback once a recording is finished.
override func play() {
super.play()
if recordingIsDone {
play(chirp: recordingView)
}
}
/// Override superclass's stop function to control recording state.
override func stop() {
super.stop()
if isRecording {
isRecording = false
if self.recordingView.saveRecording() != nil {
self.recordingIsDone = true
self.recordingEnabled = false
}
}
if recordingIsDone, let performance = recordingView.performance {
// print("ChirpRecorder: Adding performance image as my display image: \(performance.title())")
self.recordingView.setImage() // clear the animation layer and reset the saved image
}
}
/// closeEachChirpView from the list.
func clearChirpViews() {
for chirp in chirpViews {
chirp.closeGracefully()
}
chirpViews = [ChirpView]() // set to nothing.
}
}
| b019563d32b70b95361842983ae6ee79 | 35.510204 | 125 | 0.64114 | false | false | false | false |
bixubot/AcquainTest | refs/heads/master | ChatRoom/ChatRoom/MessageController.swift | mit | 1 | //
// MessageController.swift
// ChatRoom
//
// Contains all the messages sent/received for current user from other users. Designated to be the root view when app is initiated.
//
// Created by Binwei Xu on 3/16/17.
// Copyright © 2017 Binwei Xu. All rights reserved.
//
import UIKit
import Firebase
class MessageController: UITableViewController {
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handleLogout))
let newmessageimage = UIImage(named: "new_message_icon")
navigationItem.rightBarButtonItem = UIBarButtonItem(image: newmessageimage, style: .plain, target: self, action: #selector(handleNewMessage))
// self.navigationController?.navigationBar.barTintColor = UIColor.black;
// if user is not logged in, show the login page
checkIfUserIsLoggedIn()
tableView.register(UserCell.self, forCellReuseIdentifier: cellId)
}
// to store all messages and group by users in a dictionary
var messages = [Message]()
var messagesDictionary = [String: Message]()
// acquire messages and present them
func observeUserMessages(){
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
return
}
//acquire the list of messages related to the current user
let ref = FIRDatabase.database().reference().child("user-messages").child(uid)
ref.observe(.childAdded, with: { (snapshot) in
let userId = snapshot.key
FIRDatabase.database().reference().child("user-messages").child(uid).child(userId).observe(.childAdded, with: { (snapshot) in
let messageId = snapshot.key
self.fetchMessageWithMessageId(messageId: messageId)
}, withCancel: nil)
}, withCancel: nil)
}
private func fetchMessageWithMessageId(messageId: String){
let messageReference = FIRDatabase.database().reference().child("messages").child(messageId)
// get the actual message from the list
messageReference.observeSingleEvent(of: .value, with: { (snapshot2) in
if let dictionary = snapshot2.value as? [String: AnyObject]{
let message = Message()
message.setValuesForKeys(dictionary)
if let chatPartnerId = message.chatPartnerId() {
self.messagesDictionary[chatPartnerId] = message
}
self.attemptReloadTable() //so we don't constantly reload data which causes gliches
}
}, withCancel: nil)
}
private func attemptReloadTable() {
self.timer?.invalidate()
self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.handleReloadTable), userInfo: nil, repeats: false)
}
var timer: Timer?
func handleReloadTable() {
self.messages = Array(self.messagesDictionary.values)
self.messages.sort(by: { (m1, m2) -> Bool in
return (m1.timestamp?.intValue)! > (m2.timestamp?.intValue)!
})
//this will crash because of background thread, so lets call this on dispatch_async main thread
//dispatch_async(dispatch_get_main_queue())
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messagesDictionary.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! UserCell
let message = messages[indexPath.row]
cell.message = message
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 66
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let message = messages[indexPath.row]
guard let chatPartnerId = message.chatPartnerId() else {
return // seek a better to catch error or missing data
}
let ref = FIRDatabase.database().reference().child("users").child(chatPartnerId)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: AnyObject] else {
return // seek a better to catch error or missing data
}
let user = User()
user.id = chatPartnerId
user.setValuesForKeys(dictionary)
self.showChatControllerForUser(user: user)
}, withCancel: nil)
}
override func viewWillAppear(_ animated: Bool) {
checkIfUserIsLoggedIn()
}
// allow user to send a new message to another user
func handleNewMessage() {
let newMessageController = NewMessageController()
//this allow user to click another user in the NewMessageController by creating a reference with var messagesController so that it will come back to current MessageController.
newMessageController.messagesController = self
// allows newMessageController to have a navigation bar at the top
let navController = UINavigationController(rootViewController: newMessageController)
present(navController, animated: true, completion: nil)
}
// helper method to check if a user is logged in
func checkIfUserIsLoggedIn(){
if FIRAuth.auth()?.currentUser?.uid == nil{
perform(#selector(handleLogout), with: nil, afterDelay: 0)
} else {
fetchUserAndSetupNavBarTitle()
}
}
// fetch info of current user to setup the nav bar
func fetchUserAndSetupNavBarTitle() {
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
// for some reason uid = nil
return
}
FIRDatabase.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: Any] {
let user = User()
user.setValuesForKeys(dictionary)
self.setupNavBarWithUser(user: user)
}
}, withCancel: nil)
}
// setup the layout of components in tab bar and present the view
func setupNavBarWithUser(user: User) {
messages.removeAll()
messagesDictionary.removeAll()
tableView.reloadData()
observeUserMessages()
let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
titleView.backgroundColor = UIColor.clear
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
titleView.addSubview(containerView)
containerView.centerXAnchor.constraint(equalTo: titleView.centerXAnchor).isActive = true
containerView.centerYAnchor.constraint(equalTo: titleView.centerYAnchor).isActive = true
let profileImageView = UIImageView()
profileImageView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.contentMode = .scaleAspectFill
profileImageView.layer.cornerRadius = 20
profileImageView.clipsToBounds = true
if let profileImageUrl = user.profileImageUrl {
profileImageView.loadImageUsingCacheWithUrlString(urlString: profileImageUrl)
}
containerView.addSubview(profileImageView)
//ios 9 constrant anchors: need x,y,width,height anchors
profileImageView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
profileImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
let nameLabel = UILabel()
titleView.addSubview(nameLabel)
containerView.addSubview(nameLabel)
nameLabel.text = user.name
nameLabel.translatesAutoresizingMaskIntoConstraints = false
nameLabel.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 8).isActive = true
nameLabel.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor).isActive = true
nameLabel.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
nameLabel.heightAnchor.constraint(equalTo: profileImageView.heightAnchor).isActive = true
self.navigationItem.titleView = titleView
}
// present the chat log view
func showChatControllerForUser(user: User){
let chatLogController = ChatLogController(collectionViewLayout: UICollectionViewFlowLayout())
chatLogController.user = user
navigationController?.pushViewController(chatLogController, animated: true)
}
// helper that handle the logout
func handleLogout() {
// when logout bottom is clicked, sign out the current account
do {
try FIRAuth.auth()?.signOut()
} catch let logoutError{
print(logoutError)
}
let loginController = LoginController()
loginController.messagesController = self //allow nav bar title update
present(loginController, animated:true, completion: nil)
}
}
| 208f380c6868e7ae21a5d629379bf46f | 39.532787 | 183 | 0.649949 | false | false | false | false |
shial4/VaporGCM | refs/heads/master | Sources/VaporGCM/DeviceGroup.swift | mit | 1 | //
// DeviceGroup.swift
// VaporGCM
//
// Created by Shial on 12/04/2017.
//
//
import JSON
///Request operation type
public enum DeviceGroupOperation: String {
///Create a device group
case create = "create"
///Add devices from an existing group
case add = "add"
///Remove devices from an existing group.
///If you remove all existing registration tokens from a device group, FCM deletes the device group.
case remove = "remove"
}
///With device group messaging, you can send a single message to multiple instances of an app running on devices belonging to a group. Typically, "group" refers a set of different devices that belong to a single user. All devices in a group share a common notification key, which is the token that FCM uses to fan out messages to all devices in the group.
public struct DeviceGroup {
///Operation parameter for the request
public let operation: DeviceGroupOperation
///name or identifier
public let notificationKeyName: String
///deviceToken Device token or topic to which message will be send
public let registrationIds: [String]
/**
Create DeviceGroup instance
- parameter operation: Operation parameter for the request
- parameter name: Name or identifier
- parameter registrationIds: Device token or topic to which message will be send
*/
public init(operation: DeviceGroupOperation, name: String, registrationIds: [String]) {
self.operation = operation
self.notificationKeyName = name
self.registrationIds = registrationIds
}
public func makeJSON() throws -> JSON {
let json = try JSON([
"operation": operation.rawValue.makeNode(in: nil),
"notification_key_name": notificationKeyName.makeNode(in: nil),
"registration_ids": try registrationIds.makeNode(in: nil)
].makeNode(in: nil))
return json
}
}
| c85986bcce5de8962db79d740b774654 | 36.346154 | 355 | 0.69207 | false | false | false | false |
justindarc/focus | refs/heads/master | XCUITest/SearchSuggestionsTest.swift | mpl-2.0 | 3 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import XCTest
class SearchSuggestionsPromptTest: BaseTestCase {
override func setUp() {
super.setUp()
dismissFirstRunUI()
}
override func tearDown() {
app.terminate()
super.tearDown()
}
func checkToggle(isOn: Bool) {
let targetValue = isOn ? "1" : "0"
XCTAssertEqual(app.tables.switches["BlockerToggle.enableSearchSuggestions"].value as! String, targetValue)
}
func checkSuggestions() {
// Check search cells are displayed correctly
let firstSuggestion = app.buttons.matching(identifier: "OverlayView.searchButton").element(boundBy: 0)
waitforExistence(element: firstSuggestion)
waitforExistence(element: app.buttons.matching(identifier: "OverlayView.searchButton").element(boundBy: 1))
waitforExistence(element: app.buttons.matching(identifier: "OverlayView.searchButton").element(boundBy: 2))
waitforExistence(element: app.buttons.matching(identifier: "OverlayView.searchButton").element(boundBy: 3))
let predicate = NSPredicate(format: "label BEGINSWITH 'g'")
let predicateQuery = app.buttons.matching(predicate)
// Confirm that we have at least four suggestions starting with "g"
XCTAssert(predicateQuery.count >= 4)
// Check tapping on first suggestion leads to correct page
firstSuggestion.tap()
waitForValueContains(element: app.textFields["URLBar.urlText"], value: "g")
}
func typeInURLBar(text: String) {
app.textFields["Search or enter address"].tap()
app.textFields["Search or enter address"].typeText(text)
}
func checkToggleStartsOff() {
waitforHittable(element: app.buttons["Settings"])
app.buttons["Settings"].tap()
checkToggle(isOn: false)
}
func testEnableThroughPrompt() {
// Check search suggestions toggle is initially OFF
checkToggleStartsOff()
// Activate prompt by typing in URL bar
app.buttons["SettingsViewController.doneButton"].tap()
typeInURLBar(text: "g")
// Prompt should display
waitforExistence(element: app.otherElements["SearchSuggestionsPromptView"])
// Press enable
app.buttons["SearchSuggestionsPromptView.enableButton"].tap()
// Ensure prompt disappears
waitforNoExistence(element: app.otherElements["SearchSuggestionsPromptView"])
// Ensure search suggestions are shown
checkSuggestions()
// Check search suggestions toggle is ON
waitforHittable(element: app.buttons["HomeView.settingsButton"])
app.buttons["HomeView.settingsButton"].tap()
checkToggle(isOn: true)
}
func testDisableThroughPrompt() {
// Check search suggestions toggle is initially OFF
checkToggleStartsOff()
// Activate prompt by typing in URL bar
app.buttons["SettingsViewController.doneButton"].tap()
typeInURLBar(text: "g")
// Prompt should display
waitforExistence(element: app.otherElements["SearchSuggestionsPromptView"])
// Press disable
app.buttons["SearchSuggestionsPromptView.disableButton"].tap()
// Ensure prompt disappears
waitforNoExistence(element: app.otherElements["SearchSuggestionsPromptView"])
// Ensure only one search cell is shown
let suggestion = app.buttons.matching(identifier: "OverlayView.searchButton").element(boundBy: 0)
waitforExistence(element: suggestion)
XCTAssertEqual("Search for g", suggestion.label)
// Check tapping on suggestion leads to correct page
suggestion.tap()
waitForValueContains(element: app.textFields["URLBar.urlText"], value: "g")
// Check search suggestions toggle is OFF
waitforHittable(element: app.buttons["HomeView.settingsButton"])
app.buttons["HomeView.settingsButton"].tap()
checkToggle(isOn: false)
}
func testEnableThroughToggle() {
// Check search suggestions toggle is initially OFF
checkToggleStartsOff()
// Turn toggle ON
app.tables.switches["BlockerToggle.enableSearchSuggestions"].tap()
// Prompt should not display
app.buttons["SettingsViewController.doneButton"].tap()
typeInURLBar(text: "g")
waitforNoExistence(element: app.otherElements["SearchSuggestionsPromptView"])
// Ensure search suggestions are shown
checkSuggestions()
}
func testEnableThenDisable() {
// Check search suggestions toggle is initially OFF
checkToggleStartsOff()
// Activate prompt by typing in URL bar
app.buttons["SettingsViewController.doneButton"].tap()
typeInURLBar(text: "g")
// Prompt should display
waitforExistence(element: app.otherElements["SearchSuggestionsPromptView"])
// Press enable
app.buttons["SearchSuggestionsPromptView.enableButton"].tap()
// Ensure prompt disappears
waitforNoExistence(element: app.otherElements["SearchSuggestionsPromptView"])
// Ensure search suggestions are shown
checkSuggestions()
// Disable through settings
waitforHittable(element: app.buttons["HomeView.settingsButton"])
app.buttons["HomeView.settingsButton"].tap()
app.tables.switches["BlockerToggle.enableSearchSuggestions"].tap()
checkToggle(isOn: false)
// Ensure only one search cell is shown
app.buttons["SettingsViewController.doneButton"].tap()
typeInURLBar(text: "g")
let suggestion = app.buttons.matching(identifier: "OverlayView.searchButton").element(boundBy: 0)
waitforExistence(element: suggestion)
XCTAssertEqual("Search for g", suggestion.label)
}
}
| fb546a51ec0d00834e19fec719a983bd | 36.354037 | 115 | 0.680246 | false | false | false | false |
legendecas/Rocket.Chat.iOS | refs/heads/sdk | Test.Shared/WebSocketMock+CommonResponse.swift | mit | 1 | //
// WebSocketMock+CommonResponse.swift
// Rocket.Chat
//
// Created by Lucas Woo on 8/13/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
enum WebSocketMockCommonResponse {
case connect
case login
case livechatInitiate
case livechatRegisterGuest
case livechatSendMessage
case livechatSendOfflineMessage
}
extension WebSocketMock {
// swiftlint:disable function_body_length
// swiftlint:disable cyclomatic_complexity
func use(_ commonResponse: WebSocketMockCommonResponse) {
switch commonResponse {
case .connect:
use { json, send in
guard json["msg"].stringValue == "connect" else { return }
send(JSON(object: ["msg": "connected"]))
}
case .login:
use { json, send in
guard json["msg"].stringValue == "method" else { return }
guard json["method"] == "login" else { return }
// LiveChat Login
if json["params"][0]["resume"].stringValue == "YadDPc_6IfL7YJuySZ3DkOx-LSdbCtUcsypMdHVgQhx" {
send(JSON(object: [
"fields": [
"profile": [
"guest": true,
"token": "6GQSl9lVbgaZjTVyJRbN"
],
"username": "guest-1984"
],
"collection": "users",
"id": "QtiyRkneTHcWYZefn",
"msg": "added"
]))
send(JSON(object: [
"id": json["id"].stringValue,
"result": [
"id": "QtiyRkneTHcWYZefn",
"token": "YadDPc_6IfL7YJuySZ3DkOx-LSdbCtUcsypMdHVgQhx",
"tokenExpires": [
"$date": 2510411097067
]
],
"msg": "result"
]))
}
}
case .livechatInitiate:
use { json, send in
guard json["msg"].stringValue == "method" else { return }
guard json["method"] == "livechat:getInitialData" else { return }
let data: [String: Any] = [
"id": json["id"].stringValue,
"result": [
"transcript": false,
"registrationForm": true,
"offlineTitle": "Leave a message (Changed)",
"triggers": [],
"displayOfflineForm": true,
"offlineSuccessMessage": "",
"departments": [
[
"_id": "sGDPYaB9i47CNRLNu",
"numAgents": 1,
"enabled": true,
"showOnRegistration": true,
"_updatedAt": [
"$date": 1500709708181
],
"description": "department description",
"name": "1depart"
],
[
"_id": "qPYPJuL6ZPTrRrzTN",
"numAgents": 1,
"enabled": true,
"showOnRegistration": true,
"_updatedAt": [
"$date": 1501163003597
],
"description": "tech support",
"name": "2depart"
]
],
"offlineMessage": "localhost: We are not online right now. Please leave us a message:",
"title": "Rocket.Local",
"color": "#C1272D",
"room": nil,
"offlineUnavailableMessage": "Not available offline form",
"enabled": true,
"offlineColor": "#666666",
"videoCall": false,
"language": "",
"transcriptMessage": "Would you like a copy of this chat emailed?",
"online": true,
"allowSwitchingDepartments": true
] as [String: Any?],
"msg": "result"
]
send(JSON(object: data))
}
case .livechatRegisterGuest:
use { json, send in
guard json["msg"].stringValue == "method" else { return }
guard json["method"] == "livechat:registerGuest" else { return }
let data: [String: Any] = [
"id": json["id"].stringValue,
"result": [
"token": "YadDPc_6IfL7YJuySZ3DkOx-LSdbCtUcsypMdHVgQhx",
"userId": "QtiyRkneTHcWYZefn"
],
"msg": "result"
]
send(JSON(object: data))
}
case .livechatSendMessage:
use { json, send in
guard json["msg"].stringValue == "method" else { return }
guard json["method"] == "livechat:sendMessageLivechat" else { return }
send(JSON(object: [
"id": json["id"].stringValue,
"result": [
"showConnecting": false,
"rid": "9dNp4a1a8IpqpNqedTI5",
"_id": "FF99C7A4-BBF9-4798-A03B-802FB31955B2",
"channels": [],
"token": "6GQSl9lVbgaZjTVyJRbN",
"alias": "Test",
"mentions": [],
"u": [
"_id": "QtiyRkneTHcWYZefn",
"username": "guest-1984",
"name": "Test"
],
"ts": [
"$date": 1502635097560
],
"msg": "test",
"_updatedAt": [
"$date": 1502635097567
],
"newRoom": true
],
"msg": "result"
]))
}
case .livechatSendOfflineMessage:
use { json, send in
guard json["msg"].stringValue == "method" else { return }
guard json["method"] == "livechat:sendOfflineMessage" else { return }
send(JSON(object: [
"id": json["id"].stringValue,
"msg": "result"
]))
}
}
}
// swiftlint:enable cyclomatic_complexity
// swiftlint:enable function_body_length
}
| b2180764a7993d5af6fec7cbf74bc0e1 | 40.297143 | 111 | 0.381071 | false | false | false | false |
deyton/swift | refs/heads/master | test/Constraints/closures.swift | apache-2.0 | 4 | // RUN: %target-typecheck-verify-swift
func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {}
var intArray : [Int]
_ = myMap(intArray, { String($0) })
_ = myMap(intArray, { x -> String in String(x) } )
// Closures with too few parameters.
func foo(_ x: (Int, Int) -> Int) {}
foo({$0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
struct X {}
func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {}
func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {}
var strings : [String]
_ = mySort(strings, { x, y in x < y })
// Closures with inout arguments.
func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U {
var t2 = t
return f(&t2)
}
struct X2 {
func g() -> Float { return 0 }
}
_ = f0(X2(), {$0.g()})
// Closures with inout arguments and '__shared' conversions.
func inoutToSharedConversions() {
func fooOW<T, U>(_ f : (__owned T) -> U) {}
fooOW({ (x : Int) in return Int(5) }) // '__owned'-to-'__owned' allowed
fooOW({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__owned' allowed
fooOW({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(_) -> _'}}
func fooIO<T, U>(_ f : (inout T) -> U) {}
fooIO({ (x : inout Int) in return Int(5) }) // 'inout'-to-'inout' allowed
fooIO({ (x : __shared Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__shared Int) -> Int' to expected argument type '(inout _) -> _'}}
fooIO({ (x : Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(inout _) -> _'}}
func fooSH<T, U>(_ f : (__shared T) -> U) {}
fooSH({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__shared' allowed
fooSH({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__shared _) -> _'}}
fooSH({ (x : Int) in return Int(5) }) // '__owned'-to-'__shared' allowed
}
// Autoclosure
func f1(f: @autoclosure () -> Int) { }
func f2() -> Int { }
f1(f: f2) // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}}{{9-9=()}}
f1(f: 5)
// Ternary in closure
var evenOrOdd : (Int) -> String = {$0 % 2 == 0 ? "even" : "odd"}
// <rdar://problem/15367882>
func foo() {
not_declared({ $0 + 1 }) // expected-error{{use of unresolved identifier 'not_declared'}}
}
// <rdar://problem/15536725>
struct X3<T> {
init(_: (T) -> ()) {}
}
func testX3(_ x: Int) {
var x = x
_ = X3({ x = $0 })
_ = x
}
// <rdar://problem/13811882>
func test13811882() {
var _ : (Int) -> (Int, Int) = {($0, $0)}
var x = 1
var _ : (Int) -> (Int, Int) = {($0, x)}
x = 2
}
// <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement
// <https://bugs.swift.org/browse/SR-3671>
func r21544303() {
var inSubcall = true
{
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
// This is a problem, but isn't clear what was intended.
var somethingElse = true {
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
var v2 : Bool = false
v2 = inSubcall
{ // expected-error {{cannot call value of non-function type 'Bool'}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }}
}
}
// <https://bugs.swift.org/browse/SR-3671>
func SR3671() {
let n = 42
func consume(_ x: Int) {}
{ consume($0) }(42)
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ print($0) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ [n] in print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ consume($0) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ (x: Int) in consume(x) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
// This is technically a valid call, so nothing goes wrong until (42)
{ $0(3) }
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) })
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
{ $0(3) }
{ [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) })
{ [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
// Equivalent but more obviously unintended.
{ $0(3) } // expected-note {{callee is here}}
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
({ $0(3) }) // expected-note {{callee is here}}
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
// Also a valid call (!!)
{ $0 { $0 } } { $0 { 1 } } // expected-error {{expression resolves to an unused function}}
consume(111)
}
// <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure
func r22162441(_ lines: [String]) {
_ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
_ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
}
func testMap() {
let a = 42
[1,a].map { $0 + 1.0 } // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }}
}
// <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier
[].reduce { $0 + $1 } // expected-error {{cannot invoke 'reduce' with an argument list of type '((_, _) -> _)'}}
// <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments
var _: () -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }}
var _: (Int) -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}}
var _: (Int) -> Int = { 0 }
// expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }}
var _: (Int, Int) -> Int = {0}
// expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
var _: (Int,Int) -> Int = {$0+$1+$2}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {$0+$1}
var _: () -> Int = {a in 0}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}}
var _: (Int) -> Int = {a,b in 0}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}}
var _: (Int) -> Int = {a,b,c in 0}
var _: (Int, Int) -> Int = {a in 0}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {a, b in a+b}
// <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument
func r15998821() {
func take_closure(_ x : (inout Int) -> ()) { }
func test1() {
take_closure { (a : inout Int) in
a = 42
}
}
func test2() {
take_closure { a in
a = 42
}
}
func withPtr(_ body: (inout Int) -> Int) {}
func f() { withPtr { p in return p } }
let g = { x in x = 3 }
take_closure(g)
}
// <rdar://problem/22602657> better diagnostics for closures w/o "in" clause
var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
// Crash when re-typechecking bodies of non-single expression closures
struct CC {}
func callCC<U>(_ f: (CC) -> U) -> () {}
func typeCheckMultiStmtClosureCrash() {
callCC { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{11-11= () -> Int in }}
_ = $0
return 1
}
}
// SR-832 - both these should be ok
func someFunc(_ foo: ((String) -> String)?,
bar: @escaping (String) -> String) {
let _: (String) -> String = foo != nil ? foo! : bar
let _: (String) -> String = foo ?? bar
}
// SR-1069 - Error diagnostic refers to wrong argument
class SR1069_W<T> {
func append<Key: AnyObject>(value: T, forKey key: Key) where Key: Hashable {}
}
class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() }
struct S<T> {
let cs: [SR1069_C<T>] = []
func subscribe<Object: AnyObject>(object: Object?, method: (Object, T) -> ()) where Object: Hashable {
let wrappedMethod = { (object: AnyObject, value: T) in }
// expected-error @+1 {{value of optional type 'Object?' not unwrapped; did you mean to use '!' or '?'?}}
cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) }
}
}
// Make sure we cannot infer an () argument from an empty parameter list.
func acceptNothingToInt (_: () -> Int) {}
func testAcceptNothingToInt(ac1: @autoclosure () -> Int) {
acceptNothingToInt({ac1($0)})
// expected-error@-1{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}}
}
// <rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference)
struct Thing {
init?() {}
}
// This throws a compiler error
let things = Thing().map { thing in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{34-34=-> (Thing) }}
// Commenting out this makes it compile
_ = thing
return thing
}
// <rdar://problem/21675896> QoI: [Closure return type inference] Swift cannot find members for the result of inlined lambdas with branches
func r21675896(file : String) {
let x: String = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{20-20= () -> String in }}
if true {
return "foo"
}
else {
return file
}
}().pathExtension
}
// <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _")
func ident<T>(_ t: T) -> T {}
var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}}
// <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block
var afterMessageCount : Int?
func uintFunc() -> UInt {}
func takeVoidVoidFn(_ a : () -> ()) {}
takeVoidVoidFn { () -> Void in
afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int?'}}
}
// <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure
func f19997471(_ x: String) {}
func f19997471(_ x: Int) {}
func someGeneric19997471<T>(_ x: T) {
takeVoidVoidFn {
f19997471(x) // expected-error {{cannot invoke 'f19997471' with an argument list of type '(T)'}}
// expected-note @-1 {{overloads for 'f19997471' exist with these partially matching parameter lists: (String), (Int)}}
}
}
// <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information
func f20371273() {
let x: [Int] = [1, 2, 3, 4]
let y: UInt = 4
_ = x.filter { ($0 + y) > 42 } // expected-warning {{deprecated}}
}
// <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r }
[0].map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{5-5=-> Int }}
_ in
let r = (1,2).0
return r
}
// <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type
func rdar21078316() {
var foo : [String : String]?
var bar : [(String, String)]?
bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) -> [(String, String)]' expects 1 argument, but 2 were used in closure body}}
}
// <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure
var numbers = [1, 2, 3]
zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}}
// <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type'
func foo20868864(_ callback: ([String]) -> ()) { }
func rdar20868864(_ s: String) {
var s = s
foo20868864 { (strings: [String]) in
s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}}
}
}
// <rdar://problem/22058555> crash in cs diags in withCString
func r22058555() {
var firstChar: UInt8 = 0
"abc".withCString { chars in
firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}}
}
}
// <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type
func r20789423() {
class C {
func f(_ value: Int) { }
}
let p: C
print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}}
let _f = { (v: Int) in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{23-23=-> String }}
print("a")
return "hi"
}
}
// Make sure that behavior related to allowing trailing closures to match functions
// with Any as a final parameter is the same after the changes made by SR-2505, namely:
// that we continue to select function that does _not_ have Any as a final parameter in
// presence of other possibilities.
protocol SR_2505_Initable { init() }
struct SR_2505_II : SR_2505_Initable {}
protocol P_SR_2505 {
associatedtype T: SR_2505_Initable
}
extension P_SR_2505 {
func test(it o: (T) -> Bool) -> Bool {
return o(T.self())
}
}
class C_SR_2505 : P_SR_2505 {
typealias T = SR_2505_II
func test(_ o: Any) -> Bool {
return false
}
func call(_ c: C_SR_2505) -> Bool {
// Note: no diagnostic about capturing 'self', because this is a
// non-escaping closure -- that's how we know we have selected
// test(it:) and not test(_)
return c.test { o in test(o) }
}
}
let _ = C_SR_2505().call(C_SR_2505())
// <rdar://problem/28909024> Returning incorrect result type from method invocation can result in nonsense diagnostic
extension Collection {
func r28909024(_ predicate: (Iterator.Element)->Bool) -> Index {
return startIndex
}
}
func fn_r28909024(n: Int) {
return (0..<10).r28909024 { // expected-error {{unexpected non-void return value in void function}}
_ in true
}
}
// SR-2994: Unexpected ambiguous expression in closure with generics
struct S_2994 {
var dataOffset: Int
}
class C_2994<R> {
init(arg: (R) -> Void) {}
}
func f_2994(arg: String) {}
func g_2994(arg: Int) -> Double {
return 2
}
C_2994<S_2994>(arg: { (r: S_2994) in f_2994(arg: g_2994(arg: r.dataOffset)) }) // expected-error {{cannot convert value of type 'Double' to expected argument type 'String'}}
let _ = { $0[$1] }(1, 1) // expected-error {{cannot subscript a value of incorrect or ambiguous type}}
let _ = { $0 = ($0 = {}) } // expected-error {{assigning a variable to itself}}
let _ = { $0 = $0 = 42 } // expected-error {{assigning a variable to itself}}
// https://bugs.swift.org/browse/SR-403
// The () -> T => () -> () implicit conversion was kicking in anywhere
// inside a closure result, not just at the top-level.
let mismatchInClosureResultType : (String) -> ((Int) -> Void) = {
(String) -> ((Int) -> Void) in
return { }
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}}
}
// SR-3520: Generic function taking closure with inout parameter can result in a variety of compiler errors or EXC_BAD_ACCESS
func sr3520_1<T>(_ g: (inout T) -> Int) {}
sr3520_1 { $0 = 1 } // expected-error {{cannot convert value of type '()' to closure result type 'Int'}}
func sr3520_2<T>(_ item: T, _ update: (inout T) -> Void) {
var x = item
update(&x)
}
var sr3250_arg = 42
sr3520_2(sr3250_arg) { $0 += 3 } // ok
// This test makes sure that having closure with inout argument doesn't crash with member lookup
struct S_3520 {
var number1: Int
}
func sr3520_set_via_closure<S, T>(_ closure: (inout S, T) -> ()) {}
sr3520_set_via_closure({ $0.number1 = $1 }) // expected-error {{type of expression is ambiguous without more context}}
// SR-1976/SR-3073: Inference of inout
func sr1976<T>(_ closure: (inout T) -> Void) {}
sr1976({ $0 += 2 }) // ok
// SR-3073: UnresolvedDotExpr in single expression closure
struct SR3073Lense<Whole, Part> {
let set: (inout Whole, Part) -> ()
}
struct SR3073 {
var number1: Int
func lenses() {
let _: SR3073Lense<SR3073, Int> = SR3073Lense(
set: { $0.number1 = $1 } // ok
)
}
}
// SR-3479: Segmentation fault and other error for closure with inout parameter
func sr3497_unfold<A, B>(_ a0: A, next: (inout A) -> B) {}
func sr3497() {
let _ = sr3497_unfold((0, 0)) { s in 0 } // ok
}
// SR-3758: Swift 3.1 fails to compile 3.0 code involving closures and IUOs
let _: ((Any?) -> Void) = { (arg: Any!) in }
// This example was rejected in 3.0 as well, but accepting it is correct.
let _: ((Int?) -> Void) = { (arg: Int!) in }
// rdar://30429709 - We should not attempt an implicit conversion from
// () -> T to () -> Optional<()>.
func returnsArray() -> [Int] { return [] }
returnsArray().flatMap { $0 }.flatMap { }
// expected-warning@-1 {{expression of type 'Int' is unused}}
// expected-warning@-2 {{result of call to 'flatMap' is unused}}
// rdar://problem/30271695
_ = ["hi"].flatMap { $0.isEmpty ? nil : $0 }
// rdar://problem/32432145 - compiler should emit fixit to remove "_ in" in closures if 0 parameters is expected
func r32432145(_ a: () -> ()) {}
r32432145 { _ in let _ = 42 } // Ok in Swift 3
r32432145 { _ in // Ok in Swift 3
print("answer is 42")
}
r32432145 { _,_ in
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 2 were used in closure body}} {{13-19=}}
print("answer is 42")
}
// rdar://problem/30106822 - Swift ignores type error in closure and presents a bogus error about the caller
[1, 2].first { $0.foo = 3 }
// expected-error@-1 {{value of type 'Int' has no member 'foo'}}
// rdar://problem/32433193, SR-5030 - Higher-order function diagnostic mentions the wrong contextual type conversion problem
protocol A_SR_5030 {
associatedtype Value
func map<U>(_ t : @escaping (Self.Value) -> U) -> B_SR_5030<U>
}
struct B_SR_5030<T> : A_SR_5030 {
typealias Value = T
func map<U>(_ t : @escaping (T) -> U) -> B_SR_5030<U> { fatalError() }
}
func sr5030_exFalso<T>() -> T {
fatalError()
}
extension A_SR_5030 {
func foo() -> B_SR_5030<Int> {
let tt : B_SR_5030<Int> = sr5030_exFalso()
return tt.map { x in (idx: x) }
// expected-error@-1 {{cannot convert value of type '(idx: (Int))' to closure result type 'Int'}}
}
}
| 1ba7ba759f66ba40d1be80ea366f11c1 | 34.553819 | 254 | 0.633625 | false | false | false | false |
yangchenghu/actor-platform | refs/heads/master | actor-apps/app-ios/ActorApp/Controllers/Settings/SettingsViewController.swift | mit | 1 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
import MobileCoreServices
class SettingsViewController: AATableViewController {
// MARK: -
// MARK: Private vars
private let UserInfoCellIdentifier = "UserInfoCellIdentifier"
private let TitledCellIdentifier = "TitledCellIdentifier"
private let TextCellIdentifier = "TextCellIdentifier"
private var tableData: UABaseTableData!
private let uid: Int
private var user: ACUserVM?
private var binder = Binder()
private var phones: JavaUtilArrayList?
// MARK: -
// MARK: Constructors
init() {
uid = Int(Actor.myUid())
super.init(style: UITableViewStyle.Plain)
var title = "";
if (MainAppTheme.tab.showText) {
title = NSLocalizedString("TabSettings", comment: "Settings Title")
}
tabBarItem = UITabBarItem(title: title,
image: MainAppTheme.tab.createUnselectedIcon("TabIconSettings"),
selectedImage: MainAppTheme.tab.createSelectedIcon("TabIconSettingsHighlighted"))
if (!MainAppTheme.tab.showText) {
tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = MainAppTheme.list.bgColor
title = localized("TabSettings")
user = Actor.getUserWithUid(jint(uid))
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.backgroundColor = MainAppTheme.list.backyardColor
tableData = UATableData(tableView: tableView)
tableData.registerClass(AvatarCell.self, forCellReuseIdentifier: UserInfoCellIdentifier)
tableData.registerClass(TitledCell.self, forCellReuseIdentifier: TitledCellIdentifier)
tableData.registerClass(TextCell.self, forCellReuseIdentifier: TextCellIdentifier)
var section = tableData.addSection(true)
.setFooterHeight(15)
// Avatar
section.addCustomCell { (tableView, indexPath) -> UITableViewCell in
let cell: AvatarCell = tableView.dequeueReusableCellWithIdentifier(self.UserInfoCellIdentifier, forIndexPath: indexPath) as! AvatarCell
cell.selectionStyle = .None
if self.user != nil {
cell.titleLabel.text = self.user!.getNameModel().get()
}
cell.didTap = { () -> () in
let avatar = self.user!.getAvatarModel().get()
if avatar != nil && avatar.getFullImage() != nil {
let full = avatar.getFullImage().getFileReference()
let small = avatar.getSmallImage().getFileReference()
let size = CGSize(width: Int(avatar.getFullImage().getWidth()), height: Int(avatar.getFullImage().getHeight()))
self.presentViewController(PhotoPreviewController(file: full, previewFile: small, size: size, fromView: cell.avatarView), animated: true, completion: nil)
}
}
return cell
}.setHeight(92)
// Profile: Set Photo
section.addActionCell("SettingsSetPhoto", actionClosure: { () -> Bool in
let hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
self.showActionSheet(hasCamera ? ["PhotoCamera", "PhotoLibrary"] : ["PhotoLibrary"],
cancelButton: "AlertCancel",
destructButton: self.user!.getAvatarModel().get() != nil ? "PhotoRemove" : nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if index == -2 {
self.confirmUser("PhotoRemoveGroupMessage",
action: "PhotoRemove",
cancel: "AlertCancel",
sourceView: self.view,
sourceRect: self.view.bounds,
tapYes: { () -> () in
Actor.removeMyAvatar()
})
} else if index >= 0 {
let takePhoto: Bool = (index == 0) && hasCamera
self.pickAvatar(takePhoto, closure: { (image) -> () in
Actor.changeOwnAvatar(image)
})
}
})
return true
})
// Profile: Set Name
section.addActionCell("SettingsChangeName", actionClosure: { () -> Bool in
let alertView = UIAlertView(title: nil,
message: NSLocalizedString("SettingsEditHeader", comment: "Title"),
delegate: nil,
cancelButtonTitle: NSLocalizedString("AlertCancel", comment: "Cancel Title"))
alertView.addButtonWithTitle(NSLocalizedString("AlertSave", comment: "Save Title"))
alertView.alertViewStyle = UIAlertViewStyle.PlainTextInput
alertView.textFieldAtIndex(0)!.autocapitalizationType = UITextAutocapitalizationType.Words
alertView.textFieldAtIndex(0)!.text = self.user!.getNameModel().get()
alertView.textFieldAtIndex(0)?.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
alertView.tapBlock = { (alertView, buttonIndex) -> () in
if (buttonIndex == 1) {
let textField = alertView.textFieldAtIndex(0)!
if textField.text!.length > 0 {
self.execute(Actor.editMyNameCommandWithName(textField.text))
}
}
}
alertView.show()
return true
})
// Settings
section = tableData.addSection(true)
.setHeaderHeight(15)
.setFooterHeight(15)
// Settings: Notifications
section.addNavigationCell("SettingsNotifications") { () -> Bool in
self.navigateNext(SettingsNotificationsViewController(), removeCurrent: false)
return false
}
// Settings: Privacy
section.addNavigationCell("SettingsSecurity") { () -> Bool in
self.navigateNext(SettingsPrivacyViewController(), removeCurrent: false)
return false
}
// Settings: Wallpapper
section.addNavigationCell("SettingsSecurity") { () -> Bool in
self.navigateNext(SettingsWallpapper(), removeCurrent: false)
return false
}
// Profile
section = tableData.addSection(true)
.setHeaderHeight(15)
.setFooterHeight(15)
// Profile: Nick
section
.addCustomCell { (tableView, indexPath) -> UITableViewCell in
let cell: TitledCell = tableView.dequeueReusableCellWithIdentifier(self.TitledCellIdentifier, forIndexPath: indexPath) as! TitledCell
cell.enableNavigationIcon()
if let nick = self.user!.getNickModel().get() {
cell.setTitle(localized("ProfileUsername"), content: "@\(nick)")
cell.setAction(false)
} else {
cell.setTitle(localized("ProfileUsername"), content: localized("SettingsUsernameNotSet"))
cell.setAction(true)
}
return cell
}
.setHeight(55)
.setCopy(self.user!.getNickModel().get())
.setAction { () -> Bool in
self.textInputAlert("SettingsUsernameTitle", content: self.user!.getNickModel().get(), action: "AlertSave") { (nval) -> () in
var nNick: String? = nval.trim()
if nNick?.length == 0 {
nNick = nil
}
self.executeSafe(Actor.editMyNickCommandWithNick(nNick))
}
return true
}
var about = self.user!.getAboutModel().get()
if about == nil {
about = localized("SettingsAboutNotSet")
}
let aboutCell = section
.addTextCell(localized("ProfileAbout"), text: about)
.setEnableNavigation(true)
if self.user!.getAboutModel().get() == nil {
aboutCell.setIsAction(true)
} else {
aboutCell.setCopy(self.user!.getAboutModel().get())
}
aboutCell.setAction { () -> Bool in
var text = self.user!.getAboutModel().get()
if text == nil {
text = ""
}
let controller = EditTextController(title: localized("SettingsChangeAboutTitle"), actionTitle: localized("NavigationSave"), content: text, completition: { (newText) -> () in
var updatedText: String? = newText.trim()
if updatedText?.length == 0 {
updatedText = nil
}
self.execute(Actor.editMyAboutCommandWithNick(updatedText))
})
let navigation = AANavigationController(rootViewController: controller)
self.presentViewController(navigation, animated: true, completion: nil)
return false
}
// Profile: Phones
section
.addCustomCells(55, countClosure: { () -> Int in
if (self.phones != nil) {
return Int(self.phones!.size())
}
return 0
}) { (tableView, index, indexPath) -> UITableViewCell in
let cell: TitledCell = tableView.dequeueReusableCellWithIdentifier(self.TitledCellIdentifier, forIndexPath: indexPath) as! TitledCell
if let phone = self.phones!.getWithInt(jint(index)) as? ACUserPhone {
cell.setTitle(phone.getTitle(), content: "+\(phone.getPhone())")
}
return cell
}.setAction { (index) -> Bool in
let phoneNumber = (self.phones?.getWithInt(jint(index)).getPhone())!
let hasPhone = UIApplication.sharedApplication().canOpenURL(NSURL(string: "telprompt://")!)
if (!hasPhone) {
UIPasteboard.generalPasteboard().string = "+\(phoneNumber)"
self.alertUser("NumberCopied")
} else {
UIApplication.sharedApplication().openURL(NSURL(string: "telprompt://+\(phoneNumber)")!)
}
return true
}.setCanCopy(true)
// Support
section = tableData.addSection(true)
.setHeaderHeight(15)
.setFooterHeight(15)
// Support: Ask Question
if let account = AppConfig.supportAccount {
section.addNavigationCell("SettingsAskQuestion") { () -> Bool in
self.executeSafe(Actor.findUsersCommandWithQuery(account)) { (val) -> Void in
var user:ACUserVM!
if let users = val as? IOSObjectArray {
if Int(users.length()) > 0 {
if let tempUser = users.objectAtIndex(0) as? ACUserVM {
user = tempUser
}
}
}
self.navigateDetail(ConversationViewController(peer: ACPeer.userWithInt(user.getId())))
}
return true
}
}
// Support: Twitter
if let twitter = AppConfig.appTwitter {
section.addNavigationCell("SettingsTwitter") { () -> Bool in
UIApplication.sharedApplication().openURL(NSURL(string: "https://twitter.com/\(twitter)")!)
return false
}
}
// Support: Home page
if let homePage = AppConfig.appHomePage {
section.addNavigationCell("SettingsAbout") { () -> Bool in
UIApplication.sharedApplication().openURL(NSURL(string: homePage)!)
return false
}
}
// Support: App version
let version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
section.addCommonCell()
.setContent(NSLocalizedString("SettingsVersion", comment: "Version").stringByReplacingOccurrencesOfString("{version}", withString: version, options: NSStringCompareOptions(), range: nil))
.setStyle(.Hint)
// Bind
tableView.reloadData()
binder.bind(user!.getNameModel()!) { (value: String?) -> () in
if value == nil {
return
}
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? AvatarCell {
cell.titleLabel.text = value!
}
}
binder.bind(user!.getAboutModel()) { (value: String?) -> () in
var about = self.user!.getAboutModel().get()
if about == nil {
about = localized("SettingsAboutNotSet")
aboutCell.setIsAction(true)
} else {
aboutCell.setIsAction(false)
}
aboutCell.setContent(localized("ProfileAbout"), text: about)
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 1)], withRowAnimation: UITableViewRowAnimation.Automatic)
}
binder.bind(user!.getNickModel()) { (value: String?) -> () in
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 1)], withRowAnimation: UITableViewRowAnimation.Automatic)
}
binder.bind(Actor.getOwnAvatarVM().getUploadState(), valueModel2: user!.getAvatarModel()) { (upload: ACAvatarUploadState?, avatar: ACAvatar?) -> () in
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? AvatarCell {
if (upload != nil && upload!.isUploading().boolValue) {
cell.avatarView.bind(self.user!.getNameModel().get(), id: jint(self.uid), fileName: upload?.getDescriptor())
cell.progress.hidden = false
cell.progress.startAnimating()
} else {
cell.avatarView.bind(self.user!.getNameModel().get(), id: jint(self.uid), avatar: avatar, clearPrev: false)
cell.progress.hidden = true
cell.progress.stopAnimating()
}
}
}
binder.bind(user!.getPresenceModel()) { (presence: ACUserPresence?) -> () in
let presenceText = Actor.getFormatter().formatPresence(presence, withSex: self.user!.getSex())
if presenceText != nil {
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? AvatarCell {
cell.subtitleLabel.text = presenceText
if presence!.getState().ordinal() == jint(ACUserPresence_State.ONLINE.rawValue) {
cell.subtitleLabel.applyStyle("user.online")
} else {
cell.subtitleLabel.applyStyle("user.offline")
}
}
}
}
binder.bind(user!.getPhonesModel(), closure: { (phones: JavaUtilArrayList?) -> () in
if phones != nil {
self.phones = phones
self.tableView.reloadData()
}
})
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
Actor.onProfileOpenWithUid(jint(uid))
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
Actor.onProfileClosedWithUid(jint(uid))
}
}
| ebff3b6211dd80dfff99c2d0a17417ea | 41.114504 | 199 | 0.546251 | false | false | false | false |
alisidd/iOS-WeJ | refs/heads/master | WeJ/Play Tracks/BackgroundTask.swift | gpl-3.0 | 1 | //
// BackgroundTask.swift
//
// Created by Yaro on 8/27/16.
// Copyright © 2016 Yaro. All rights reserved.
//
import AVFoundation
class BackgroundTask {
static var player = AVAudioPlayer()
static var isPlaying = false
static func startBackgroundTask() {
DispatchQueue.global(qos: .userInitiated).async {
if !isPlaying {
NotificationCenter.default.addObserver(self, selector: #selector(interuptedAudio), name: NSNotification.Name.AVAudioSessionInterruption, object: AVAudioSession.sharedInstance())
playAudio()
isPlaying = true
}
}
}
static func stopBackgroundTask() {
DispatchQueue.global(qos: .userInitiated).async {
if isPlaying {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVAudioSessionInterruption, object: nil)
player.stop()
isPlaying = false
}
}
}
@objc static func interuptedAudio(_ notification: Notification) {
if notification.name == NSNotification.Name.AVAudioSessionInterruption && notification.userInfo != nil {
var info = notification.userInfo!
var intValue = 0
(info[AVAudioSessionInterruptionTypeKey]! as AnyObject).getValue(&intValue)
if intValue == 1 { playAudio() }
}
}
private static func playAudio() {
do {
let bundle = Bundle.main.path(forResource: "BlankAudio", ofType: "wav")
let alertSound = URL(fileURLWithPath: bundle!)
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)
try player = AVAudioPlayer(contentsOf: alertSound)
player.numberOfLoops = -1
player.volume = 0.01
player.prepareToPlay()
player.play()
} catch { print(error) }
}
}
| bf00965efaadf8803e4c3cb9369e4147 | 34.12069 | 193 | 0.614629 | false | false | false | false |
proxyco/RxBluetoothKit | refs/heads/master | Source/BluetoothManager.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2016 Polidea
//
// 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 RxSwift
import CoreBluetooth
// swiftlint:disable line_length
/**
BluetoothManager is a class implementing ReactiveX API which wraps all Core Bluetooth Manager's functions allowing to
discover, connect to remote peripheral devices and more. It's using thin layer behind `RxCentralManagerType` protocol which is
implemented by `RxCBCentralManager` and should not be used directly by the user of a RxBluetoothKit library.
You can start using this class by discovering available services of nearby peripherals. Before calling any
public `BluetoothManager`'s functions you should make sure that Bluetooth is turned on and powered on. It can be done
by calling and observing returned value of `monitorState()` and then chaining it with `scanForPeripherals(_:options:)`:
bluetoothManager.rx_state
.filter { $0 == .PoweredOn }
.take(1)
.flatMap { manager.scanForPeripherals(nil) }
As a result you will receive `ScannedPeripheral` which contains `Peripheral` object, `AdvertisementData` and
peripheral's RSSI registered during discovery. You can then `connectToPeripheral(_:options:)` and do other operations.
- seealso: `Peripheral`
*/
public class BluetoothManager {
/// Implementation of Central Manager
private let centralManager: RxCentralManagerType
/// Queue on which all observables are serialised if needed
private let subscriptionQueue: SerializedSubscriptionQueue
/// Lock which should be used before accessing any internal structures
private let lock = NSLock()
/// Queue of scan operations which are waiting for an execution
private var scanQueue: [ScanOperation] = []
// MARK: Initialization
/**
Creates new `BluetoothManager` instance with specified implementation of `RxCentralManagerType` protocol which will be
used by this class. Most of a time `RxCBCentralManager` should be chosen by the user.
- parameter centralManager: Implementation of `RxCentralManagerType` protocol used by this class.
- parameter queueScheduler: Scheduler on which all serialised operations are executed (such as scans). By default
main thread is used.
*/
init(centralManager: RxCentralManagerType,
queueScheduler: SchedulerType = ConcurrentMainScheduler.instance) {
self.centralManager = centralManager
self.subscriptionQueue = SerializedSubscriptionQueue(scheduler: queueScheduler)
}
/**
Creates new `BluetoothManager` instance. By default all operations and events are executed and received on
main thread.
- warning: If you pass background queue to the method make sure to observe results on main thread for UI related
code.
- parameter queue: Queue on which bluetooth callbacks are received. By default main thread is used.
- parameter options: An optional dictionary containing initialization options for a central manager.
For more info about it please refer to [`Central Manager initialization options`](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManager_Class/index.html)
*/
convenience public init(queue: dispatch_queue_t = dispatch_get_main_queue(),
options: [String : AnyObject]? = nil) {
self.init(centralManager: RxCBCentralManager(queue: queue),
queueScheduler: ConcurrentDispatchQueueScheduler(queue: queue))
}
// MARK: Scanning
/**
Scans for `Peripheral`s after subscription to returned observable. First parameter `serviceUUIDs` is
an array of `Service` UUIDs which needs to be implemented by a peripheral to be discovered. If user don't want to
filter any peripherals, `nil` can be used instead. Additionally dictionary of
[`CBCentralManager` specific options](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManager_Class/#//apple_ref/doc/constant_group/Peripheral_Scanning_Options)
can be passed to allow further customisation.
Scans by default are infinite streams of `ScannedPeripheral` structures which need to be stopped by the user. For
example this can be done by limiting scanning to certain number of peripherals or time:
bluetoothManager.scanForPeripherals(nil)
.timeout(3.0, timeoutScheduler)
.take(2)
If different scan is currently in progress and peripherals needed by a user can be discovered by it, new scan is
shared. Otherwise scan is queued on thread specified in `init(centralManager:queueScheduler:)` and will be executed
when other scans finished with complete/error event or were unsubscribed.
As a result you will receive `ScannedPeripheral` which contains `Peripheral` object, `AdvertisementData` and
peripheral's RSSI registered during discovery. You can then `connectToPeripheral(_:options:)` and do other
operations.
- seealso: `Peripheral`
- parameter serviceUUIDs: Services of peripherals to search for. Nil value will accept all peripherals.
- parameter options: Optional scanning options.
- returns: Infinite stream of scanned peripherals.
*/
public func scanForPeripherals(serviceUUIDs: [CBUUID]?, options: [String: AnyObject]? = nil)
-> Observable<ScannedPeripheral> {
return Observable.deferred {
let observable: Observable<ScannedPeripheral> = { Void -> Observable<ScannedPeripheral> in
// If it's possible use existing scan - take if from the queue
self.lock.lock(); defer { self.lock.unlock() }
if let elem = self.scanQueue.findElement({ $0.acceptUUIDs(serviceUUIDs) }) {
guard serviceUUIDs != nil else {
return elem.observable
}
// When binding to existing scan we need to make sure that services are
// filtered properly
return elem.observable.filter { scannedPeripheral in
if let services = scannedPeripheral.advertisementData.serviceUUIDs {
return Set(services).isSupersetOf(serviceUUIDs!)
}
return false
}
}
let scanOperationBox = WeakBox<ScanOperation>()
// Create new scan which will be processed in a queue
let operation = Observable.create { (element: AnyObserver<ScannedPeripheral>) -> Disposable in
// Observable which will emit next element, when peripheral is discovered.
let disposable = self.centralManager.rx_didDiscoverPeripheral
.map { (peripheral, advertisment, rssi) -> ScannedPeripheral in
let peripheral = Peripheral(manager: self, peripheral: peripheral)
let advertismentData = AdvertisementData(advertisementData: advertisment)
return ScannedPeripheral(peripheral: peripheral,
advertisementData: advertismentData, RSSI: rssi)
}
.subscribe(element)
// Start scanning for devices
self.centralManager.scanForPeripheralsWithServices(serviceUUIDs, options: options)
return AnonymousDisposable {
// When disposed, stop all scans, and remove scanning operation from queue
self.centralManager.stopScan()
disposable.dispose()
do { self.lock.lock(); defer { self.lock.unlock() }
if let index = self.scanQueue.indexOf({ $0 == scanOperationBox.value! }) {
self.scanQueue.removeAtIndex(index)
}
}
}
}
.queueSubscribeOn(self.subscriptionQueue)
.publish()
.refCount()
let scanOperation = ScanOperation(UUIDs: serviceUUIDs, observable: operation)
self.scanQueue.append(scanOperation)
scanOperationBox.value = scanOperation
return operation
}()
// Allow scanning as long as bluetooth is powered on
return self.ensureState(.PoweredOn, observable: observable)
}
}
// MARK: State
/**
Continuous state of `BluetoothManager` instance described by `BluetoothState` which is equivalent to [`CBManagerState`](https://developer.apple.com/reference/corebluetooth/cbmanager/1648600-state).
- returns: Observable that emits `Next` immediately after subscribtion with current state of Bluetooth. Later,
whenever state changes events are emitted. Observable is infinite : doesn't generate `Complete`.
*/
public var rx_state: Observable<BluetoothState> {
return Observable.deferred {
return self.centralManager.rx_didUpdateState.startWith(self.centralManager.state)
}
}
/**
Current state of `BluetoothManager` instance described by `BluetoothState` which is equivalent to [`CBManagerState`](https://developer.apple.com/reference/corebluetooth/cbmanager/1648600-state).
- returns: Current state of `BluetoothManager` as `BluetoothState`.
*/
public var state: BluetoothState {
return centralManager.state
}
// MARK: Peripheral's Connection Management
/**
Establishes connection with `Peripheral` after subscription to returned observable. It's user responsibility
to close connection with `cancelConnectionToPeripheral(_:)` after subscription was completed. Unsubscribing from
returned observable cancels connection attempt. By default observable is waiting infinitely for successful
connection.
Additionally you can pass optional [dictionary](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManager_Class/#//apple_ref/doc/constant_group/Peripheral_Connection_Options)
to customise the behaviour of connection.
- parameter peripheral: The `Peripheral` to which `BluetoothManager` is attempting to connect.
- parameter options: Dictionary to customise the behaviour of connection.
- returns: Observable which emits next and complete events after connection is established.
*/
public func connectToPeripheral(peripheral: Peripheral, options: [String: AnyObject]? = nil)
-> Observable<Peripheral> {
let success = centralManager.rx_didConnectPeripheral
.filter { $0 == peripheral.peripheral }
.take(1)
.map { _ in return peripheral }
let error = centralManager.rx_didFailToConnectPeripheral
.filter { $0.0 == peripheral.peripheral }
.take(1)
.flatMap { (peripheral, error) -> Observable<Peripheral> in
Observable.error(BluetoothError.PeripheralConnectionFailed(
Peripheral(manager: self, peripheral: peripheral), error))
}
let observable = Observable<Peripheral>.create { observer in
if let error = BluetoothError.errorFromState(self.centralManager.state) {
observer.onError(error)
return NopDisposable.instance
}
guard !peripheral.isConnected else {
observer.onNext(peripheral)
observer.onCompleted()
return NopDisposable.instance
}
let disposable = success.amb(error).subscribe(observer)
self.centralManager.connectPeripheral(peripheral.peripheral, options: options)
return AnonymousDisposable {
if !peripheral.isConnected {
self.centralManager.cancelPeripheralConnection(peripheral.peripheral)
disposable.dispose()
}
}
}
return ensureState(.PoweredOn, observable: observable)
}
/**
Cancels an active or pending local connection to a `Peripheral` after observable subscription. It is not guaranteed
that physical connection will be closed immediately as well and all pending commands will not be executed.
- parameter peripheral: The `Peripheral` to which the `BluetoothManager` is either trying to
connect or has already connected.
- returns: Observable which emits next and complete events when peripheral successfully cancelled connection.
*/
public func cancelConnectionToPeripheral(peripheral: Peripheral) -> Observable<Peripheral> {
let observable = Observable<Peripheral>.create { observer in
let disposable = self.monitorPeripheralDisconnection(peripheral).take(1).subscribe(observer)
self.centralManager.cancelPeripheralConnection(peripheral.peripheral)
return AnonymousDisposable {
disposable.dispose()
}
}
return ensureState(.PoweredOn, observable: observable)
}
// MARK: Retrieving Lists of Peripherals
/**
Returns observable list of the `Peripheral`s which are currently connected to the `BluetoothManager` and contain
all of the specified `Service`'s UUIDs.
- parameter serviceUUIDs: A list of `Service` UUIDs
- returns: Observable which emits retrieved `Peripheral`s. They are in connected state and contain all of the
`Service`s with UUIDs specified in the `serviceUUIDs` parameter. Just after that complete event is emitted
*/
public func retrieveConnectedPeripheralsWithServices(serviceUUIDs: [CBUUID]) -> Observable<[Peripheral]> {
let observable = Observable<[Peripheral]>.deferred {
return self.centralManager.retrieveConnectedPeripheralsWithServices(serviceUUIDs).map {
(peripheralTable: [RxPeripheralType]) ->
[Peripheral] in peripheralTable.map {
Peripheral(manager: self, peripheral: $0)
}
}
}
return ensureState(.PoweredOn, observable: observable)
}
/**
Returns observable list of `Peripheral`s by their identifiers which are known to `BluetoothManager`.
- parameter identifiers: List of `Peripheral`'s identifiers which should be retrieved.
- returns: Observable which emits next and complete events when list of `Peripheral`s are retrieved.
*/
public func retrievePeripheralsWithIdentifiers(identifiers: [NSUUID]) -> Observable<[Peripheral]> {
let observable = Observable<[Peripheral]>.deferred {
return self.centralManager.retrievePeripheralsWithIdentifiers(identifiers).map {
(peripheralTable: [RxPeripheralType]) ->
[Peripheral] in peripheralTable.map {
Peripheral(manager: self, peripheral: $0)
}
}
}
return ensureState(.PoweredOn, observable: observable)
}
// MARK: Internal functions
/**
Ensure that `state` is and will be the only state of `BluetoothManager` during subscription.
Otherwise error is emitted.
- parameter state: `BluetoothState` which should be present during subscription.
- parameter observable: Observable into which potential errors should be merged.
- returns: New observable which merges errors with source observable.
*/
func ensureState<T>(state: BluetoothState, observable: Observable<T>) -> Observable<T> {
let statesObservable = rx_state
.filter { $0 != state && BluetoothError.errorFromState($0) != nil }
.map { state -> T in throw BluetoothError.errorFromState(state)! }
return Observable.absorb(statesObservable, observable)
}
/**
Ensure that specified `peripheral` is connected during subscription.
- parameter peripheral: `Peripheral` which should be connected during subscription.
- returns: Observable which emits error when `peripheral` is disconnected during subscription.
*/
func ensurePeripheralIsConnected<T>(peripheral: Peripheral) -> Observable<T> {
return Observable.deferred {
if !peripheral.isConnected {
return Observable.error(BluetoothError.PeripheralDisconnected(peripheral, nil))
}
return self.centralManager.rx_didDisconnectPeripheral
.filter { $0.0 == peripheral.peripheral }
.flatMap { (_, error) -> Observable<T> in
return Observable.error(BluetoothError.PeripheralDisconnected(peripheral, error))
}
}
}
/**
Emits `Peripheral` instance when it's connected.
- Parameter peripheral: `Peripheral` which is monitored for connection.
- Returns: Observable which emits next events when `peripheral` was connected.
*/
public func monitorPeripheralConnection(peripheral: Peripheral) -> Observable<Peripheral> {
return monitorPeripheralAction(centralManager.rx_didConnectPeripheral, peripheral: peripheral)
}
/**
Emits `Peripheral` instance when it's disconnected.
- Parameter peripheral: `Peripheral` which is monitored for disconnection.
- Returns: Observable which emits next events when `peripheral` was disconnected.
*/
public func monitorPeripheralDisconnection(peripheral: Peripheral) -> Observable<Peripheral> {
return monitorPeripheralAction(centralManager.rx_didDisconnectPeripheral.map { $0.0 }, peripheral: peripheral)
}
func monitorPeripheralAction(peripheralAction: Observable<RxPeripheralType>, peripheral: Peripheral)
-> Observable<Peripheral> {
let observable =
peripheralAction
.filter { $0 == peripheral.peripheral }
.map { _ in peripheral }
return ensureState(.PoweredOn, observable: observable)
}
#if os(iOS)
/**
Emits `RestoredState` instance, when state of `BluetoothManager` has been restored
- Returns: Observable which emits next events state has been restored
*/
public func listenOnRestoredState() -> Observable<RestoredState> {
return centralManager
.rx_willRestoreState
.take(1)
.map { RestoredState(restoredStateDictionary: $0, bluetoothManager: self) }
}
#endif
}
| 027e363b62ef5e6548554cb7bb9102a1 | 47.838235 | 216 | 0.666566 | false | false | false | false |
KeepGoing2016/Swift- | refs/heads/master | DUZB_XMJ/DUZB_XMJ/Classes/Home/Model/NormalCellModel.swift | apache-2.0 | 1 | //
// NormalCellModel.swift
// DUZB_XMJ
//
// Created by user on 16/12/27.
// Copyright © 2016年 XMJ. All rights reserved.
//
import UIKit
class NormalCellModel: NSObject {
/// 房间ID
var room_id : Int = 0
/// 房间图片对应的URLString
var vertical_src : String = ""
/// 判断是手机直播还是电脑直播
// 0 : 电脑直播(普通房间) 1 : 手机直播(秀场房间)
var isVertical : Int = 0
/// 房间名称
var room_name : String = ""
/// 主播昵称
var nickname : String = ""
/// 观看人数
var online : Int = 0
/// 所在城市
var anchor_city : String = ""
init(dict : [String:Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| 5f925336dc7bed939a50a311a8618121 | 19.361111 | 72 | 0.548431 | false | false | false | false |
DianQK/rx-sample-code | refs/heads/master | RxDataSourcesExample/CellButtonClickTableViewController.swift | mit | 1 | //
// CellButtonClickTableViewController.swift
// RxDataSourcesExample
//
// Created by DianQK on 04/10/2016.
// Copyright © 2016 T. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import SafariServices
class InfoTableViewCell: UITableViewCell {
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet fileprivate weak var detailButton: UIButton! {
didSet {
detailButton.layer.borderColor = UIColor.black.cgColor
detailButton.layer.borderWidth = 1
detailButton.layer.cornerRadius = 5
detailButton.addTarget(self, action: #selector(_detailButtonTap), for: .touchUpInside)
}
}
var detailButtonTap: (() -> ())?
var title: String? {
get {
return titleLabel.text
}
set(title) {
titleLabel.text = title
}
}
var disposeBag = DisposeBag()
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
private dynamic func _detailButtonTap() {
detailButtonTap?()
}
}
class CellButtonClickTableViewController: UITableViewController {
struct Info {
let name: String
let url: URL
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = nil
tableView.delegate = nil
let infoItems = [
Info(name: "Apple Developer", url: URL(string: "https://developer.apple.com/")!),
Info(name: "GitHub", url: URL(string: "https://github.com")!),
Info(name: "Dribbble", url: URL(string: "https://dribbble.com")!)
]
Observable.just(infoItems)
.bindTo(tableView.rx.items(cellIdentifier: "InfoTableViewCell", cellType: InfoTableViewCell.self)) { [unowned self] (row, element, cell) in
cell.title = element.name
// cell.detailButtonTap = {
// let safari = SFSafariViewController(url: element.url)
// safari.preferredControlTintColor = UIColor.black
// self.showDetailViewController(safari, sender: nil)
// }
cell.detailButton.rx.tap
.map { element.url }
.subscribe(onNext: { url in
print("Open :\(url)")
let safari = SFSafariViewController(url: element.url)
safari.preferredControlTintColor = UIColor.black
self.showDetailViewController(safari, sender: nil)
})
.disposed(by: cell.disposeBag)
}
.disposed(by: rx.disposeBag)
}
}
| 638c06e521248421ee4f15a36378648c | 28.846154 | 151 | 0.575847 | false | false | false | false |
Minecodecraft/EstateBand | refs/heads/master | EstateBand/HealthyViewController.swift | mit | 1 | //
// HealthyViewController.swift
// EstateBand
//
// Created by Minecode on 2017/6/27.
// Copyright © 2017年 org.minecode. All rights reserved.
//
import UIKit
class HealthyViewController: UIViewController {
// 控件
@IBOutlet weak var sosButton: UIButton!
@IBOutlet weak var restButton: UIButton!
@IBOutlet weak var refreshButton: UIButton!
@IBOutlet weak var healthyLabel: UILabel!
@IBOutlet weak var notiLabel: UILabel!
// 数据
var rate: Int = 85
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() {
sosButton.layer.cornerRadius = 50
restButton.layer.cornerRadius = 50
refreshButton.layer.cornerRadius = 50
self.notiLabel.textColor = UIColor.green
self.notiLabel.text = "Healthy"
self.healthyLabel.textColor = UIColor.green
self.healthyLabel.text = String(rate)
}
@IBAction func sosAction(_ sender: UIButton) {
}
@IBAction func restAction(_ sender: UIButton) {
}
@IBAction func refreshAction(_ sender: UIButton) {
let arc = arc4random_uniform(10)
rate += Int(arc)
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1.0)
healthyLabel.text = String(rate)
if rate >= 100 {
healthyLabel.textColor = UIColor.red
notiLabel.textColor = UIColor.red
notiLabel.text = String("You need rest now!")
}
UIView.commitAnimations()
}
}
| 16b76e3cf080951d0f92edad18be13fc | 22.811594 | 57 | 0.587949 | false | false | false | false |
MisterZhouZhou/Objective-C-Swift-StudyDemo | refs/heads/master | SwiftDemo/SwiftDemo/classes/modules/Main/ZWRootViewController.swift | apache-2.0 | 1 | //
// ZWRootViewController.swift
// Swift-Demo
//
// Created by rayootech on 16/6/2.
// Copyright © 2016年 rayootech. All rights reserved.
//
import UIKit
class ZWRootViewController: ZWBaseViewController ,UITableViewDataSource,UITableViewDelegate {
var dataArray:Dictionary<String,String> = Dictionary<String,String>()
//UITableView
lazy var mainTableView: UITableView = {
let tempTableView = UITableView (frame: CGRectZero, style: UITableViewStyle.Plain)
tempTableView.delegate = self
tempTableView.dataSource = self
return tempTableView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.whiteColor()
//添加视图
self .addSubVies()
//设置布局
self .layout()
}
//添加视图
func addSubVies ()
{
//添加UITableView
self.view.addSubview(self.mainTableView)
//去除底部多余线
self.mainTableView.tableFooterView = UIView()
}
//设置布局
func layout()
{
self.mainTableView.snp_makeConstraints { (make) in
make.left.top.equalTo(self.view)
make.width.equalTo(self.view)
make.height.equalTo(self.view)
}
}
//UITableView DataSource ,Delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArray.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
let dict:Dictionary<String,String> = self.dataArray
for (index,value) in dict.keys.enumerate(){
if index == indexPath.row {
cell.textLabel?.text = value
}
}
cell.selectionStyle = .None
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var vcStr :String = String()
let dict:Dictionary<String,String> = self.dataArray
for (index,value) in dict.values.enumerate(){
if index == indexPath.row {
vcStr = value
}
}
//进行跳转
self.navigationController!.pushViewControllerWithName(vcStr)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 5a823c9acd1986994a94aac5e040feb4 | 26.918919 | 109 | 0.618264 | false | false | false | false |
Shivam0911/IOS-Training-Projects | refs/heads/master | ListViewToGridViewConverter ONLINE/ListViewToGridViewConverter/listViewCell.swift | mit | 2 | //
// listViewCell.swift
// ListViewToGridViewConverter
//
// Created by MAC on 13/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import UIKit
class listViewCell: UICollectionViewCell {
@IBOutlet weak var carImage: UIImageView!
@IBOutlet weak var carName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// carImage.layer.cornerRadius = carImage.layer.bounds.height/2
// Initialization code
}
func populateTheData(_ data : [String:String]){
print(#function)
let imageUrl = data["CarImage"]!
self.carImage.backgroundColor = UIColor(patternImage: UIImage(named: imageUrl)!)
// carImage.backgroundColor = UIColor.cyan
carName.text = data["CarName"]!
}
override func prepareForReuse() {
}
}
| dc56d060130081702e88cdb436bd9b78 | 24.666667 | 88 | 0.644628 | false | false | false | false |
amraboelela/swift | refs/heads/master | stdlib/public/core/Hashing.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements helpers for hashing collections.
//
import SwiftShims
/// The inverse of the default hash table load factor. Factored out so that it
/// can be used in multiple places in the implementation and stay consistent.
/// Should not be used outside `Dictionary` implementation.
@usableFromInline @_transparent
internal var _hashContainerDefaultMaxLoadFactorInverse: Double {
return 1.0 / 0.75
}
#if _runtime(_ObjC)
/// Call `[lhs isEqual: rhs]`.
///
/// This function is part of the runtime because `Bool` type is bridged to
/// `ObjCBool`, which is in Foundation overlay.
@_silgen_name("swift_stdlib_NSObject_isEqual")
internal func _stdlib_NSObject_isEqual(_ lhs: AnyObject, _ rhs: AnyObject) -> Bool
#endif
/// A temporary view of an array of AnyObject as an array of Unmanaged<AnyObject>
/// for fast iteration and transformation of the elements.
///
/// Accesses the underlying raw memory as Unmanaged<AnyObject> using untyped
/// memory accesses. The memory remains bound to managed AnyObjects.
internal struct _UnmanagedAnyObjectArray {
/// Underlying pointer.
internal var value: UnsafeMutableRawPointer
internal init(_ up: UnsafeMutablePointer<AnyObject>) {
self.value = UnsafeMutableRawPointer(up)
}
internal init?(_ up: UnsafeMutablePointer<AnyObject>?) {
guard let unwrapped = up else { return nil }
self.init(unwrapped)
}
internal subscript(i: Int) -> AnyObject {
get {
let unmanaged = value.load(
fromByteOffset: i * MemoryLayout<AnyObject>.stride,
as: Unmanaged<AnyObject>.self)
return unmanaged.takeUnretainedValue()
}
nonmutating set(newValue) {
let unmanaged = Unmanaged.passUnretained(newValue)
value.storeBytes(of: unmanaged,
toByteOffset: i * MemoryLayout<AnyObject>.stride,
as: Unmanaged<AnyObject>.self)
}
}
}
#if _runtime(_ObjC)
/// An NSEnumerator implementation returning zero elements. This is useful when
/// a concrete element type is not recoverable from the empty singleton.
// NOTE: older runtimes called this class _SwiftEmptyNSEnumerator. The two
// must coexist without conflicting ObjC class names, so it was
// renamed. The old name must not be used in the new runtime.
final internal class __SwiftEmptyNSEnumerator
: __SwiftNativeNSEnumerator, _NSEnumerator {
internal override required init() {}
@objc
internal func nextObject() -> AnyObject? {
return nil
}
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>,
count: Int
) -> Int {
// Even though we never do anything in here, we need to update the
// state so that callers know we actually ran.
var theState = state.pointee
if theState.state == 0 {
theState.state = 1 // Arbitrary non-zero value.
theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)
theState.mutationsPtr = _fastEnumerationStorageMutationsPtr
}
state.pointee = theState
return 0
}
}
#endif
#if _runtime(_ObjC)
/// This is a minimal class holding a single tail-allocated flat buffer,
/// representing hash table storage for AnyObject elements. This is used to
/// store bridged elements in deferred bridging scenarios.
///
/// Using a dedicated class for this rather than a _BridgingBuffer makes it easy
/// to recognize these in heap dumps etc.
// NOTE: older runtimes called this class _BridgingHashBuffer.
// The two must coexist without a conflicting ObjC class name, so it
// was renamed. The old name must not be used in the new runtime.
internal final class __BridgingHashBuffer
: ManagedBuffer<__BridgingHashBuffer.Header, AnyObject> {
struct Header {
internal var owner: AnyObject
internal var hashTable: _HashTable
init(owner: AnyObject, hashTable: _HashTable) {
self.owner = owner
self.hashTable = hashTable
}
}
internal static func allocate(
owner: AnyObject,
hashTable: _HashTable
) -> __BridgingHashBuffer {
let buffer = self.create(minimumCapacity: hashTable.bucketCount) { _ in
Header(owner: owner, hashTable: hashTable)
}
return unsafeDowncast(buffer, to: __BridgingHashBuffer.self)
}
deinit {
for bucket in header.hashTable {
(firstElementAddress + bucket.offset).deinitialize(count: 1)
}
_fixLifetime(self)
}
internal subscript(bucket: _HashTable.Bucket) -> AnyObject {
@inline(__always) get {
_internalInvariant(header.hashTable.isOccupied(bucket))
defer { _fixLifetime(self) }
return firstElementAddress[bucket.offset]
}
}
@inline(__always)
internal func initialize(at bucket: _HashTable.Bucket, to object: AnyObject) {
_internalInvariant(header.hashTable.isOccupied(bucket))
(firstElementAddress + bucket.offset).initialize(to: object)
_fixLifetime(self)
}
}
#endif
| e89a27a18fedc08c068681baa7377733 | 33.175 | 82 | 0.700805 | false | false | false | false |
wangyun-hero/sinaweibo-with-swift | refs/heads/master | sinaweibo/Classes/View/Compose/View/WYComposeButton.swift | mit | 1 | //
// WYComposeButton.swift
// sinaweibo
//
// Created by 王云 on 16/9/7.
// Copyright © 2016年 王云. All rights reserved.
//
import UIKit
class WYComposeButton: UIButton {
//取消button点击之后的高亮效果
override var isHighlighted: Bool{
set{
}
get{
return false
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
imageView?.contentMode = .center
//文字居中
titleLabel?.textAlignment = .center
}
func test() {
print("ssss")
}
override func layoutSubviews() {
super.layoutSubviews()
let width = self.frame.width
let height = self.frame.height
imageView?.frame = CGRect(x: 0, y: 0, width: width, height: width)
titleLabel?.frame = CGRect(x: 0, y: width, width: width, height: height - width)
}
}
| 032657e18b96686441ecd74547955178 | 18.472727 | 88 | 0.54155 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/Extensions/UIViewController/UIViewControllerDimming.swift | mit | 1 | //
// UIViewControllerDimming.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 11/23/18.
//
import UIKit
let kDimViewAlpha: CGFloat = 0.6
let kDimViewAnimationDuration = 0.25
class DimView: UIView { }
extension UIViewController {
var dimViewTag: Int {
return "Dim_View".hashValue
}
var dimView: DimView {
if let res = view.viewWithTag(dimViewTag) as? DimView {
res.frame = view.bounds
return res
} else {
let dimView = DimView(frame: view.bounds)
dimView.tag = dimViewTag
dimView.backgroundColor = .black
dimView.alpha = kDimViewAlpha
view.addSubview(dimView)
return dimView
}
}
func startDimming() {
view.bringSubviewToFront(dimView)
dimView.isHidden = false
UIView.animate(withDuration: kDimViewAnimationDuration) { [dimView] in
dimView.alpha = kDimViewAlpha
}
}
func stopDimming() {
UIView.animate(withDuration: kDimViewAnimationDuration, animations: { [dimView] in
dimView.alpha = 0
}, completion: { [dimView] _ in
dimView.isHidden = true
})
}
}
| 0bdbbce1a469e1b5ade6151f8333bc25 | 22.519231 | 90 | 0.596893 | false | false | false | false |
siberianisaev/NeutronBarrel | refs/heads/master | NeutronBarrel/DataProtocol.swift | mit | 1 | //
// DataProtocol.swift
// NeutronBarrel
//
// Created by Andrey Isaev on 24/04/2017.
// Copyright © 2018 Flerov Laboratory. All rights reserved.
//
import Foundation
import AppKit
enum TOFKind: String {
case TOF = "TOF"
case TOF2 = "TOF2"
}
class DataProtocol {
fileprivate var dict = [String: Int]() {
didSet {
AVeto = dict["AVeto"]
TOF = dict[TOFKind.TOF.rawValue]
TOF2 = dict[TOFKind.TOF2.rawValue]
NeutronsOld = dict["Neutrons"]
Neutrons_N = getValues(ofTypes: ["N1", "N2", "N3", "N4"], prefix: false)
NeutronsNew = getValues(ofTypes: ["NNeut"])
CycleTime = dict["THi"]
BeamEnergy = dict["EnergyHi"]
BeamCurrent = dict["BeamTokHi"]
BeamBackground = dict["BeamFonHi"]
BeamIntegral = dict["IntegralHi"]
AlphaWell = getValues(ofTypes: ["AWel"])
AlphaWellFront = getValues(ofTypes: ["AWFr"])
AlphaWellBack = getValues(ofTypes: ["AWBk"])
AlphaMotherFront = getValues(ofTypes: ["AFr"])
AlphaDaughterFront = getValues(ofTypes: ["AdFr"])
AlphaFront = AlphaMotherFront.union(AlphaDaughterFront)
AlphaMotherBack = getValues(ofTypes: ["ABack", "ABk"])
AlphaDaughterBack = getValues(ofTypes: ["AdBk"])
AlphaBack = AlphaMotherBack.union(AlphaDaughterBack)
Gamma = getValues(ofTypes: ["Gam"])
}
}
fileprivate func getValues(ofTypes types: [String], prefix: Bool = true) -> Set<Int> {
var result = [Int]()
for type in types {
let values = dict.filter({ (key: String, value: Int) -> Bool in
if prefix {
return self.keyFor(value: value)?.hasPrefix(type) == true
} else {
return self.keyFor(value: value) == type
}
}).values
result.append(contentsOf: values)
}
return Set(result)
}
fileprivate var BeamEnergy: Int?
fileprivate var BeamCurrent: Int?
fileprivate var BeamBackground: Int?
fileprivate var BeamIntegral: Int?
fileprivate var AVeto: Int?
fileprivate var TOF: Int?
fileprivate var TOF2: Int?
fileprivate var NeutronsOld: Int?
fileprivate var Neutrons_N = Set<Int>()
fileprivate var NeutronsNew = Set<Int>()
fileprivate var CycleTime: Int?
fileprivate var AlphaWell = Set<Int>()
fileprivate var AlphaWellFront = Set<Int>()
fileprivate var AlphaWellBack = Set<Int>()
fileprivate var AlphaMotherFront = Set<Int>()
fileprivate var AlphaDaughterFront = Set<Int>()
fileprivate var AlphaFront = Set<Int>()
fileprivate var AlphaMotherBack = Set<Int>()
fileprivate var AlphaDaughterBack = Set<Int>()
fileprivate var AlphaBack = Set<Int>()
fileprivate var Gamma = Set<Int>()
fileprivate var isAlphaCache = [Int: Bool]()
func isAlpha(eventId: Int) -> Bool {
if let b = isAlphaCache[eventId] {
return b
} else {
var b = false
for s in [AlphaFront, AlphaBack, AlphaWell, AlphaWellFront, AlphaWellBack, AlphaMotherFront, AlphaMotherBack, AlphaDaughterFront, AlphaDaughterBack] {
if s.contains(eventId) {
b = true
break
}
}
isAlphaCache[eventId] = b
return b
}
}
class func load(_ path: String?) -> DataProtocol {
var result = [String: Int]()
if let path = path {
do {
var content = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
content = content.replacingOccurrences(of: " ", with: "")
let words = Event.words
for line in content.components(separatedBy: CharacterSet.newlines) {
if false == line.contains(":") || line.starts(with: "#") {
continue
}
let set = CharacterSet(charactersIn: ":,")
let components = line.components(separatedBy: set).filter() { $0 != "" }
let count = components.count
if words == count {
let key = components[count-1]
let value = Int(components[0])
result[key] = value
}
}
} catch {
print("Error load protocol from file at path \(path): \(error)")
}
}
let p = DataProtocol()
p.dict = result
if p.dict.count == 0 {
let alert = NSAlert()
alert.messageText = "Error"
alert.informativeText = "Please select protocol!"
alert.addButton(withTitle: "OK")
alert.alertStyle = .warning
alert.runModal()
}
p.encoderForEventIdCache.removeAll()
p.isValidEventIdForTimeCheckCache.removeAll()
return p
}
fileprivate var isValidEventIdForTimeCheckCache = [Int: Bool]()
/**
Not all events have time data.
*/
func isValidEventIdForTimeCheck(_ eventId: Int) -> Bool {
if let cached = isValidEventIdForTimeCheckCache[eventId] {
return cached
}
let value = isAlpha(eventId: eventId) || isTOFEvent(eventId) != nil || isGammaEvent(eventId) || isNeutronsOldEvent(eventId) || isNeutronsNewEvent(eventId) || isNeutrons_N_Event(eventId) || isVETOEvent(eventId)
isValidEventIdForTimeCheckCache[eventId] = value
return value
}
func keyFor(value: Int) -> String? {
for (k, v) in dict {
if v == value {
return k
}
}
return nil
}
func position(_ eventId: Int) -> String {
if AlphaMotherFront.contains(eventId) {
return "Fron"
} else if AlphaMotherBack.contains(eventId) {
return "Back"
} else if AlphaDaughterFront.contains(eventId) {
return "dFron"
} else if AlphaDaughterBack.contains(eventId) {
return "dBack"
} else if isVETOEvent(eventId) {
return "Veto"
} else if isGammaEvent(eventId) {
return "Gam"
} else if isAlphaWellBackEvent(eventId) {
return "WBack"
} else if isAlphaWellFrontEvent(eventId) {
return "WFront"
} else {
return "Wel"
}
}
func isAlphaFronEvent(_ eventId: Int) -> Bool {
return AlphaFront.contains(eventId)
}
func isAlphaBackEvent(_ eventId: Int) -> Bool {
return AlphaBack.contains(eventId)
}
func isAlphaWellEvent(_ eventId: Int) -> Bool {
return AlphaWell.contains(eventId)
}
func isAlphaWellFrontEvent(_ eventId: Int) -> Bool {
return AlphaWellFront.contains(eventId)
}
func isAlphaWellBackEvent(_ eventId: Int) -> Bool {
return AlphaWellBack.contains(eventId)
}
func isGammaEvent(_ eventId: Int) -> Bool {
return Gamma.contains(eventId)
}
func isVETOEvent(_ eventId: Int) -> Bool {
return AVeto == eventId
}
func isTOFEvent(_ eventId: Int) -> TOFKind? {
if TOF == eventId {
return .TOF
} else if TOF2 == eventId {
return .TOF2
}
return nil
}
func isNeutronsNewEvent(_ eventId: Int) -> Bool {
return NeutronsNew.contains(eventId)
}
func isNeutronsOldEvent(_ eventId: Int) -> Bool {
return NeutronsOld == eventId
}
func isNeutrons_N_Event(_ eventId: Int) -> Bool {
return Neutrons_N.contains(eventId)
}
func hasNeutrons_N() -> Bool {
return Neutrons_N.count > 0
}
func isCycleTimeEvent(_ eventId: Int) -> Bool {
return CycleTime == eventId
}
func isBeamEnergy(_ eventId: Int) -> Bool {
return BeamEnergy == eventId
}
func isBeamCurrent(_ eventId: Int) -> Bool {
return BeamCurrent == eventId
}
func isBeamBackground(_ eventId: Int) -> Bool {
return BeamBackground == eventId
}
func isBeamIntegral(_ eventId: Int) -> Bool {
return BeamIntegral == eventId
}
fileprivate var encoderForEventIdCache = [Int: CUnsignedShort]()
func encoderForEventId(_ eventId: Int) -> CUnsignedShort {
if let cached = encoderForEventIdCache[eventId] {
return cached
}
var value: CUnsignedShort
if let key = keyFor(value: eventId), let rangeDigits = key.rangeOfCharacter(from: .decimalDigits), let substring = String(key[rangeDigits.lowerBound...]).components(separatedBy: CharacterSet.init(charactersIn: "., ")).first, let encoder = Int(substring) {
value = CUnsignedShort(encoder)
} else if (AlphaWell.contains(eventId) && AlphaWell.count == 1) || (Gamma.contains(eventId) && Gamma.count == 1) {
value = 1
} else {
value = 0
}
encoderForEventIdCache[eventId] = value
return value
}
}
| 56ba36432b7d8ad83e6374f4a85f0aa2 | 32.4 | 263 | 0.557314 | false | false | false | false |
brentsimmons/Frontier | refs/heads/master | BeforeTheRename/FrontierCore/FrontierCore/ThreadSupervisor.swift | gpl-2.0 | 1 | //
// ThreadSupervisor.swift
// FrontierCore
//
// Created by Brent Simmons on 4/23/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
// When Frontier creates a thread, it should use ThreadSupervisor, which counts and manages threads. The thread verbs need ThreadSupervisor.
public struct ThreadSupervisor {
public static let mainThreadID = 0
public static let unknownThreadID = -1
public static var numberOfThreads: Int {
get {
return threads.count + 1 // Add one for main thread
}
}
private static var threads = [Int: ManagedThread]()
private static let lock = NSLock()
private static var incrementingThreadID = 1
public static func createAndRunThread(block: @escaping VoidBlock) {
let thread = ManagedThread(block: block)
thread.name = "Frontier Thread"
lock.lock()
thread.identifier = incrementingThreadID
incrementingThreadID = incrementingThreadID + 1
threads[thread.identifier] = thread
lock.unlock()
thread.start()
}
public static func currentThreadID() -> Int {
if Thread.isMainThread {
return mainThreadID
}
if let thread = Thread.current as? ManagedThread {
return thread.identifier
}
return unknownThreadID
}
// MARK: Thread callback
static func threadDidComplete(identifier: Int) {
lock.lock()
threads[identifier] = nil
lock.unlock()
}
}
| 1835aff42b7da868f8c1a92a258b5eac | 20.968254 | 140 | 0.721098 | false | false | false | false |
appfoundry/DRYLogging | refs/heads/master | Example/Tests/DefaultLoggerInheritanceSpec.swift | mit | 1 | //
// DefaultLoggerInheritanceSpec.swift
// DRYLogging
//
// Created by Michael Seghers on 15/11/2016.
// Copyright © 2016 Michael Seghers. All rights reserved.
//
import Foundation
import Quick
import Nimble
import DRYLogging
class DefaultLoggerInheritanceSpec : QuickSpec {
override func spec() {
describe("DefaultLogger Inheritance") {
var child:DefaultLogger!
var parent:DefaultLogger!
var grandParent:DefaultLogger!
beforeEach {
grandParent = DefaultLogger(name: "grandparent")
parent = DefaultLogger(name: "parent", parent: grandParent)
child = DefaultLogger(name: "child", parent: parent)
}
context("logger hierarchy from grandParent to child") {
it("child should inherit logLevel from parent") {
parent.logLevel = .info
expect(child.isInfoEnabled) == true
}
it("child should override parent logging level when set") {
parent.logLevel = .info
child.logLevel = .error
expect(child.isInfoEnabled) == false
}
}
context("logger hierarchy with appenders") {
var childAppender:LoggingAppenderMock!
var parentAppender:LoggingAppenderMock!
var grandParentAppender:LoggingAppenderMock!
beforeEach {
child.logLevel = .info
grandParentAppender = LoggingAppenderMock()
grandParent.add(appender: grandParentAppender)
parentAppender = LoggingAppenderMock()
parent.add(appender: parentAppender)
childAppender = LoggingAppenderMock()
child.add(appender: childAppender)
}
it("should append the message to the parent appender") {
child.info("test")
expect(parentAppender.messages).to(haveCount(1))
}
it("should append the message to the parent appender") {
child.info("test")
expect(grandParentAppender.messages).to(haveCount(1))
}
}
}
}
}
| 9ad9bb9e3f2b2cf81c3bbcb8bdbf3781 | 34.614286 | 75 | 0.514641 | false | false | false | false |
tLewisII/TJLSet | refs/heads/master | TJLSet/Source/Set.swift | mit | 1 | //
// Set.swift
// TJLSet
//
// Created by Terry Lewis II on 6/5/14.
// Copyright (c) 2014 Blue Plover Productions LLC. All rights reserved.
//
import Foundation
operator infix ∩ {}
operator infix ∪ {}
struct Set<A: Hashable> : Sequence {
var bucket:Dictionary<A, Bool> = Dictionary()
var array:Array<A> {
var arr = Array<A>()
for (key, _) in bucket {
arr += key
}
return arr
}
var count:Int {
return bucket.count
}
init(items:A...) {
for obj in items {
bucket[obj] = true
}
}
init(array:Array<A>) {
for obj in array {
bucket[obj] = true
}
}
func any() -> A {
let ar = self.array
let index = Int(arc4random_uniform(UInt32(ar.count)))
return ar[index]
}
func contains(item:A) -> Bool {
if let c = bucket[item] {
return c
} else {
return false
}
}
func member(item:A) -> A? {
if self.contains(item) {
return .Some(item)
} else {
return nil
}
}
func interectsSet(set:Set<A>) -> Bool {
for x in set {
if self.contains(x) {
return true
}
}
return false
}
func intersect(set:Set<A>) -> Set<A> {
var array:[A] = Array()
for x in self {
if let memb = set.member(x) {
array += memb
}
}
return Set(array:array)
}
func minus(set:Set<A>) -> Set<A> {
var array:[A] = Array()
for x in self {
if !set.contains(x) {
array += x
}
}
return Set(array:array)
}
func union(set:Set<A>) -> Set<A> {
var current = self.array
current += set.array
return Set(array: current)
}
func add(item:A) -> Set<A> {
if contains(item) {
return self
} else {
var arr = array
arr += item
return Set(array:arr)
}
}
func filter(f:(A -> Bool)) -> Set<A> {
var array = Array<A>()
for x in self {
if f(x) {
array += x
}
}
return Set(array: array)
}
func map<B>(f:(A -> B)) -> Set<B> {
var array:Array<B> = Array()
for x in self {
array += f(x)
}
return Set<B>(array: array)
}
func generate() -> SetGenerator<A> {
let items = self.array
return SetGenerator(items: items[0..<items.count])
}
}
struct SetGenerator<A> : Generator {
mutating func next() -> A? {
if items.isEmpty { return nil }
let ret = items[0]
items = items[1..<items.count]
return ret
}
var items:Slice<A>
}
extension Set : Printable,DebugPrintable {
var description:String {
return "\(self.array)"
}
var debugDescription:String {
return "\(self.array)"
}
}
func ==<A: Equatable>(lhs:Set<A>, rhs:Set<A>) -> Bool {
return lhs.bucket == rhs.bucket
}
func !=<A: Equatable>(lhs:Set<A>, rhs:Set<A>) -> Bool {
return lhs.bucket != rhs.bucket
}
func +=<A>(set:Set<A>, item:A) -> Set<A> {
if set.contains(item) {
return set
} else {
var arr = set.array
arr += item
return Set(array:arr)
}
}
func -<A>(lhs:Set<A>, rhs:Set<A>) -> Set<A> {
return lhs.minus(rhs)
}
func ∩<A>(lhs:Set<A>, rhs:Set<A>) -> Set<A> {
return lhs.intersect(rhs)
}
func ∪<A>(lhs:Set<A>, rhs:Set<A>) -> Set<A> {
return lhs.union(rhs)
}
| cb7c56b4ef15fda5fad43fd962b4fc91 | 19.263441 | 72 | 0.462192 | false | false | false | false |
caopengxu/scw | refs/heads/master | scw/scw/Code/Sign/RegisterController.swift | mit | 1 | //
// RegisterController.swift
// scw
//
// Created by cpx on 2017/7/27.
// Copyright © 2017年 scw. All rights reserved.
//
import UIKit
class RegisterController: UIViewController {
var judgeAgreement = true
@IBOutlet weak var phoneNumberTextF: MyTextFieldFont!
@IBOutlet weak var verificationTextF: MyTextFieldFont!
@IBOutlet weak var passwordTextF: MyTextFieldFont!
// MARK:=== viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK:=== 倒计时
@IBAction func countDownBtnClick(_ sender: CountDownButton) {
sender.startCountDown()
}
// MARK:=== 点击注册按钮
@IBAction func registerBtnClick(_ sender: PXCustomButton) {
}
// MARK:=== 点击对勾按钮
@IBAction func judgeAgreementBtnClick(_ sender: UIButton) {
if sender.tag == 0
{
sender.tag = 1;
sender.setImage(#imageLiteral(resourceName: "对勾灰色"), for: .normal)
judgeAgreement = false
}
else
{
sender.tag = 0;
sender.setImage(#imageLiteral(resourceName: "对勾红色"), for: .normal)
judgeAgreement = true
}
}
// MARK:=== 点击用户协议按钮
@IBAction func agreementBtnClick(_ sender: UIButton) {
}
// MARK:=== 点击返回按钮
@IBAction func returnBtnClick(_ sender: PXCustomButton) {
view.endEditing(true)
navigationController?.popViewController(animated: true)
}
// 点击其他地方收起键盘
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
// MARK:=== 隐藏状态栏
override var prefersStatusBarHidden: Bool {
return true
}
}
// MARK:=== <UITextFieldDelegate>
extension RegisterController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
UIView.animate(withDuration: 0.5) {
self.view.frame = CGRect.init(x: 0, y: -100, width: __ScreenWidth, height: __ScreenHeight)
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
UIView.animate(withDuration: 0.3) {
self.view.frame = CGRect.init(x: 0, y: 0, width: __ScreenWidth, height: __ScreenHeight)
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if phoneNumberTextF == textField
{
if (phoneNumberTextF.text?.lengthOfBytes(using: String.Encoding.utf8))! >= __PhoneNumberLength
{
print("手机号格式不对")
return false
}
}
if passwordTextF == textField
{
if (passwordTextF.text?.lengthOfBytes(using: String.Encoding.utf8))! >= __PasswordLength
{
print("密码最多支持15位")
return false
}
}
return true
}
}
| 193e85609ee5449b09cd68b53310df16 | 24.404959 | 129 | 0.561158 | false | false | false | false |
nicolastinkl/CardDeepLink | refs/heads/master | CardDeepLinkKit/CardDeepLinkKit/UIGitKit/Alamofire/Validation.swift | bsd-2-clause | 1 | // Validation.swift
//
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension Request {
/**
Used to represent whether validation was successful or encountered an error resulting in a failure.
- Success: The validation was successful.
- Failure: The validation failed encountering the provided error.
*/
internal enum ValidationResult {
case Success
case Failure(NSError)
}
/**
A closure used to validate a request that takes a URL request and URL response, and returns whether the
request was valid.
*/
internal typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult
/**
Validates the request, using the specified closure.
If validation fails, subsequent calls to response handlers will have an associated error.
- parameter validation: A closure to validate the request.
- returns: The request.
*/
internal func validate(validation: Validation) -> Self {
delegate.queue.addOperationWithBlock {
if let
response = self.response where self.delegate.error == nil,
case let .Failure(error) = validation(self.request, response)
{
self.delegate.error = error
}
}
return self
}
// MARK: - Status Code
/**
Validates that the response has a status code in the specified range.
If validation fails, subsequent calls to response handlers will have an associated error.
- parameter range: The range of acceptable status codes.
- returns: The request.
*/
internal func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
return validate { _, response in
if acceptableStatusCode.contains(response.statusCode) {
return .Success
} else {
let failureReason = "Response status code was unacceptable: \(response.statusCode)"
return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason))
}
}
}
// MARK: - Content-Type
private struct MIMEType {
let type: String
let subtype: String
init?(_ string: String) {
let components: [String] = {
let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex)
return split.componentsSeparatedByString("/")
}()
if let
type = components.first,
subtype = components.last
{
self.type = type
self.subtype = subtype
} else {
return nil
}
}
func matches(MIME: MIMEType) -> Bool {
switch (type, subtype) {
case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
return true
default:
return false
}
}
}
/**
Validates that the response has a content type in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
- parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
- returns: The request.
*/
internal func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
return validate { _, response in
guard let validData = self.delegate.data where validData.length > 0 else { return .Success }
if let
responseContentType = response.MIMEType,
responseMIMEType = MIMEType(responseContentType)
{
for contentType in acceptableContentTypes {
if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) {
return .Success
}
}
} else {
for contentType in acceptableContentTypes {
if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" {
return .Success
}
}
}
let failureReason: String
if let responseContentType = response.MIMEType {
failureReason = (
"Response content type \"\(responseContentType)\" does not match any acceptable " +
"content types: \(acceptableContentTypes)"
)
} else {
failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
}
return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason))
}
}
// MARK: - Automatic
/**
Validates that the response has a status code in the default acceptable range of 200...299, and that the content
type matches any specified in the Accept HTTP header field.
If validation fails, subsequent calls to response handlers will have an associated error.
- returns: The request.
*/
internal func validate() -> Self {
let acceptableStatusCodes: Range<Int> = 200..<300
let acceptableContentTypes: [String] = {
if let accept = request?.valueForHTTPHeaderField("Accept") {
return accept.componentsSeparatedByString(",")
}
return ["*/*"]
}()
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
}
}
| d08224611eb068ce4581cf63dec1d26f | 36.645503 | 129 | 0.618412 | false | false | false | false |
git-hushuai/MOMO | refs/heads/master | MMHSMeterialProject/LibaryFile/SQLiteDB/String-Extras.swift | apache-2.0 | 2 | //
// String-Extras.swift
// Swift Tools
//
// Created by Fahim Farook on 23/7/14.
// Copyright (c) 2014 RookSoft Pte. Ltd. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import AppKit
#endif
extension String {
func positionOf(sub:String)->Int {
var pos = -1
if let range = self.rangeOfString(sub) {
if !range.isEmpty {
pos = self.startIndex.distanceTo(range.startIndex)
}
}
return pos
}
func subStringFrom(pos:Int)->String {
var substr = ""
let start = self.startIndex.advancedBy(pos)
let end = self.endIndex
// println("String: \(self), start:\(start), end: \(end)")
let range = start..<end
substr = self[range]
// println("Substring: \(substr)")
return substr
}
func subStringTo(pos:Int)->String {
var substr = ""
let end = self.startIndex.advancedBy(pos-1)
let range = self.startIndex...end
substr = self[range]
return substr
}
func urlEncoded()->String {
let res:NSString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, self as NSString, nil,
"!*'();:@&=+$,/?%#[]", CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
return res as String
}
func urlDecoded()->String {
let res:NSString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, self as NSString, "", CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
return res as String
}
func range()->Range<String.Index> {
return Range<String.Index>(start:startIndex, end:endIndex)
}
}
| 8a89f40e144a0e1c62668f8b5c9c2736 | 23.983333 | 184 | 0.701801 | false | false | false | false |
BalestraPatrick/Tweetometer | refs/heads/master | Tweetometer/UserTopBarViewController.swift | mit | 2 | //
// UserTopBarViewController.swift
// Tweetometer
//
// Created by Patrick Balestra on 8/15/18.
// Copyright © 2018 Patrick Balestra. All rights reserved.
//
import UIKit
import TweetometerKit
protocol UserTopBarDelegate {
func openSettings(sender: UIView)
}
class UserTopBarViewController: UIViewController {
struct Dependencies {
let twitterSession: TwitterSession
let delegate: UserTopBarDelegate
}
private var dependencies: Dependencies!
@IBOutlet private var profileImageView: UIImageView!
@IBOutlet private var yourTimelineLabel: UILabel!
@IBOutlet private var usernameLabel: UILabel!
@IBOutlet var settingsButton: UIButton!
static func instantiate(with dependencies: Dependencies) -> UserTopBarViewController {
let this = StoryboardScene.UserTopBar.initialScene.instantiate()
this.dependencies = dependencies
return this
}
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
private func loadData() {
dependencies.twitterSession.loadUserData { result in
switch result {
case .success(let user):
self.profileImageView?.kf.setImage(with: URL(string: user.profileImageURL)!)
case .error:
self.profileImageView?.image = Asset.placeholder.image
}
}
profileImageView?.kf.indicatorType = .activity
profileImageView.layer.cornerRadius = profileImageView.bounds.width / 2
profileImageView.layer.masksToBounds = true
}
@IBAction func openSettings(_ sender: UIView) {
dependencies.delegate.openSettings(sender: sender)
}
}
| 0fc751e241c671b92928507765126479 | 28.275862 | 92 | 0.682568 | false | false | false | false |
BrikerMan/BMPlayer | refs/heads/master | Carthage/Checkouts/NVActivityIndicatorView/Source/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallTrianglePath.swift | apache-2.0 | 3 | //
// NVActivityIndicatorAnimationBallTrianglePath.swift
// NVActivityIndicatorView
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// 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 NVActivityIndicatorAnimationBallTrianglePath: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSize = size.width / 5
let deltaX = size.width / 2 - circleSize / 2
let deltaY = size.height / 2 - circleSize / 2
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let duration: CFTimeInterval = 2
#if swift(>=4.2)
let timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
#else
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
#endif
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform")
animation.keyTimes = [0, 0.33, 0.66, 1]
animation.timingFunctions = [timingFunction, timingFunction, timingFunction]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Top-center circle
let topCenterCircle = NVActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
changeAnimation(animation, values: ["{0,0}", "{hx,fy}", "{-hx,fy}", "{0,0}"], deltaX: deltaX, deltaY: deltaY)
topCenterCircle.frame = CGRect(x: x + size.width / 2 - circleSize / 2, y: y, width: circleSize, height: circleSize)
topCenterCircle.add(animation, forKey: "animation")
layer.addSublayer(topCenterCircle)
// Bottom-left circle
let bottomLeftCircle = NVActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
changeAnimation(animation, values: ["{0,0}", "{hx,-fy}", "{fx,0}", "{0,0}"], deltaX: deltaX, deltaY: deltaY)
bottomLeftCircle.frame = CGRect(x: x, y: y + size.height - circleSize, width: circleSize, height: circleSize)
bottomLeftCircle.add(animation, forKey: "animation")
layer.addSublayer(bottomLeftCircle)
// Bottom-right circle
let bottomRightCircle = NVActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
changeAnimation(animation, values: ["{0,0}", "{-fx,0}", "{-hx,-fy}", "{0,0}"], deltaX: deltaX, deltaY: deltaY)
bottomRightCircle.frame = CGRect(x: x + size.width - circleSize, y: y + size.height - circleSize, width: circleSize, height: circleSize)
bottomRightCircle.add(animation, forKey: "animation")
layer.addSublayer(bottomRightCircle)
}
func changeAnimation(_ animation: CAKeyframeAnimation, values rawValues: [String], deltaX: CGFloat, deltaY: CGFloat) {
let values = NSMutableArray(capacity: 5)
for rawValue in rawValues {
#if swift(>=4.2)
let point = NSCoder.cgPoint(for: translateString(rawValue, deltaX: deltaX, deltaY: deltaY))
#else
let point = CGPointFromString(translateString(rawValue, deltaX: deltaX, deltaY: deltaY))
#endif
values.add(NSValue(caTransform3D: CATransform3DMakeTranslation(point.x, point.y, 0)))
}
animation.values = values as [AnyObject]
}
func translateString(_ valueString: String, deltaX: CGFloat, deltaY: CGFloat) -> String {
let valueMutableString = NSMutableString(string: valueString)
let fullDeltaX = 2 * deltaX
let fullDeltaY = 2 * deltaY
var range = NSRange(location: 0, length: valueMutableString.length)
valueMutableString.replaceOccurrences(of: "hx", with: "\(deltaX)", options: NSString.CompareOptions.caseInsensitive, range: range)
range.length = valueMutableString.length
valueMutableString.replaceOccurrences(of: "fx", with: "\(fullDeltaX)", options: NSString.CompareOptions.caseInsensitive, range: range)
range.length = valueMutableString.length
valueMutableString.replaceOccurrences(of: "hy", with: "\(deltaY)", options: NSString.CompareOptions.caseInsensitive, range: range)
range.length = valueMutableString.length
valueMutableString.replaceOccurrences(of: "fy", with: "\(fullDeltaY)", options: NSString.CompareOptions.caseInsensitive, range: range)
return valueMutableString as String
}
}
| 268d797c553a318487798f56726ccafe | 49.654545 | 144 | 0.698672 | false | false | false | false |
SomnusLee1988/Azure | refs/heads/master | Pods/SLAlertController/SLAlertController/Classes/Extensions/UIImageExtension.swift | mit | 2 | //
// UIImageExtension.swift
// Pods
//
// Created by Somnus on 16/6/24.
//
//
import Foundation
import UIKit
public extension UIImage {
convenience init(color: UIColor, size: CGSize = CGSizeMake(1, 1)) {
let rect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(CGImage: image.CGImage!)
}
func imageWithColor(color:UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
let context:CGContextRef = UIGraphicsGetCurrentContext()!;
CGContextTranslateCTM(context, 0, self.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, .Normal);
let rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextClipToMask(context, rect, self.CGImage);
color.setFill();
CGContextFillRect(context, rect);
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
func imageFitInSize(viewsize:CGSize) -> UIImage
{
// calculate the fitted size
let size:CGSize = self.fitSize(self.size, inSize: viewsize);
UIGraphicsBeginImageContext(viewsize);
let dwidth:CGFloat = (viewsize.width - size.width) / 2.0;
let dheight:CGFloat = (viewsize.height - size.height) / 2.0;
let rect:CGRect = CGRectMake(dwidth, dheight, size.width, size.height);
self.drawInRect(rect);
let newimg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newimg;
}
func fitSize(thisSize:CGSize, inSize aSize:CGSize) -> CGSize
{
var scale:CGFloat;
var newsize = thisSize;
if (newsize.height > 0) && (newsize.height > aSize.height) {
scale = aSize.height / newsize.height;
newsize.width *= scale;
newsize.height *= scale;
}
if (newsize.width > 0) && (newsize.width >= aSize.width) {
scale = aSize.width / newsize.width;
newsize.width *= scale;
newsize.height *= scale;
}
return newsize;
}
}
| 7372f6b049778e2ff7388a225f8e1566 | 30.974359 | 79 | 0.606656 | false | false | false | false |
accepton/accepton-apple | refs/heads/master | Pod/Classes/AcceptOnUIMachine/Drivers/AcceptOnUIMachinePaymentDriver.swift | mit | 1 | import UIKit
//A payment driver is a generic interface for one payment processor
public protocol AcceptOnUIMachinePaymentDriverDelegate: class {
func transactionDidFailForDriver(driver: AcceptOnUIMachinePaymentDriver, withMessage message: String)
//Transaction has completed
func transactionDidSucceedForDriver(driver: AcceptOnUIMachinePaymentDriver, withChargeRes chargeRes: [String:AnyObject])
func transactionDidCancelForDriver(driver: AcceptOnUIMachinePaymentDriver)
var api: AcceptOnAPI { get }
}
public class AcceptOnUIMachinePaymentDriver: NSObject {
//-----------------------------------------------------------------------------------------------------
//Properties
//-----------------------------------------------------------------------------------------------------
public weak var delegate: AcceptOnUIMachinePaymentDriverDelegate!
class var name: String {
return "<unnamed>"
}
//Tokens that were retrieved from the drivers
public var nonceTokens: [String:AnyObject] = [:]
//Email is only for credit-card forms
var email: String?
//Meta-data is passed through from formOptions
var metadata: [String:AnyObject] {
return self.formOptions.metadata
}
//-----------------------------------------------------------------------------------------------------
//Constructors
//-----------------------------------------------------------------------------------------------------
var formOptions: AcceptOnUIMachineFormOptions!
public required init(formOptions: AcceptOnUIMachineFormOptions) {
self.formOptions = formOptions
}
public func beginTransaction() {
}
//At this point, you should have filled out the nonceTokens, optionally the raw credit card information
//and optionally 'email' properties. The 'email' property is passed as part of the transaction and is
//used for credit-card transactions only. For drivers that have more complex semantics, e.g. ApplePay,
//where you need to interleave actions within the transaction handshake, override the
//readyToCompleteTransactionDidFail and readyToCompleteTransactionDidSucceed to modify that behaviour.
func readyToCompleteTransaction(userInfo: Any?=nil) {
if nonceTokens.count > 0 || self.formOptions.creditCardParams != nil {
let chargeInfo = AcceptOnAPIChargeInfo(rawCardInfo: self.formOptions.creditCardParams, cardTokens: self.nonceTokens, email: email, metadata: self.metadata)
self.delegate.api.chargeWithTransactionId(self.formOptions.token.id, andChargeinfo: chargeInfo) { chargeRes, err in
if let err = err {
self.readyToCompleteTransactionDidFail(userInfo, withMessage: err.localizedDescription)
return
}
self.readyToCompleteTransactionDidSucceed(userInfo, withChargeRes: chargeRes!)
}
} else {
self.readyToCompleteTransactionDidFail(userInfo, withMessage: "Could not connect to any payment processing services")
}
}
//Override these functions if you need to interleave actions in the transaction stage. E.g. Dismiss
//a 3rd party UI or a 3-way handshake
////////////////////////////////////////////////////////////////////////////////////
func readyToCompleteTransactionDidFail(userInfo: Any?, withMessage message: String) {
// dispatch_async(dispatch_get_main_queue()) {
self.delegate.transactionDidFailForDriver(self, withMessage: message)
// }
}
func readyToCompleteTransactionDidSucceed(userInfo: Any?, withChargeRes chargeRes: [String:AnyObject]) {
// dispatch_async(dispatch_get_main_queue()) {
self.delegate.transactionDidSucceedForDriver(self, withChargeRes: chargeRes)
// }
}
////////////////////////////////////////////////////////////////////////////////////
}
| ca59b77139894a7bd3adc1e43b3225bf | 47.095238 | 167 | 0.598762 | false | false | false | false |
Yalantis/ColorMatchTabs | refs/heads/master | ColorMatchTabs/Classes/ViewController/ColorMatchTabsViewController.swift | mit | 1 | //
// ColorMatchTabsViewController.swift
// ColorMatchTabs
//
// Created by Serhii Butenko on 24/6/16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import UIKit
public protocol ColorMatchTabsViewControllerDataSource: class {
func numberOfItems(inController controller: ColorMatchTabsViewController) -> Int
func tabsViewController(_ controller: ColorMatchTabsViewController, viewControllerAt index: Int) -> UIViewController
func tabsViewController(_ controller: ColorMatchTabsViewController, titleAt index: Int) -> String
func tabsViewController(_ controller: ColorMatchTabsViewController, iconAt index: Int) -> UIImage
func tabsViewController(_ controller: ColorMatchTabsViewController, hightlightedIconAt index: Int) -> UIImage
func tabsViewController(_ controller: ColorMatchTabsViewController, tintColorAt index: Int) -> UIColor
}
public protocol ColorMatchTabsViewControllerDelegate: class {
func didSelectItemAt(_ index: Int)
}
extension ColorMatchTabsViewControllerDelegate {
func didSelectItemAt(_ index: Int) {}
}
open class ColorMatchTabsViewController: UITabBarController {
open weak var colorMatchTabDataSource: ColorMatchTabsViewControllerDataSource? {
didSet {
_view.scrollMenu.dataSource = colorMatchTabDataSource == nil ? nil : self
_view.tabs.dataSource = colorMatchTabDataSource == nil ? nil : self
reloadData()
}
}
open weak var colorMatchTabDelegate: ColorMatchTabsViewControllerDelegate?
open var scrollEnabled = true {
didSet {
updateScrollEnabled()
}
}
public let titleLabel = UILabel()
open var popoverViewController: PopoverViewController? {
didSet {
popoverViewController?.menu.dataSource = self
popoverViewController?.dataSource = self
let hidePopoverButton = popoverViewController == nil
_view.setCircleMenuButtonHidden(hidePopoverButton)
}
}
override open var title: String? {
didSet {
titleLabel.text = title
}
}
open var selectedSegmentIndex: Int {
return _view.tabs.selectedSegmentIndex
}
private var icons: [UIImageView] = []
private let circleTransition = CircleTransition()
var _view: MenuView! {
return view as? MenuView
}
open override func loadView() {
super.loadView()
view = MenuView(frame: view.frame)
}
open override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
setupTabSwitcher()
setupIcons()
setupScrollMenu()
setupCircleMenu()
updateScrollEnabled()
}
open func selectItem(at index: Int) {
updateNavigationBar(forSelectedIndex: index)
_view.tabs.selectedSegmentIndex = index
_view.scrollMenu.selectItem(atIndex: index)
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
selectItem(at: _view.tabs.selectedSegmentIndex)
setDefaultPositions()
}
open func reloadData() {
_view.tabs.reloadData()
_view.scrollMenu.reloadData()
popoverViewController?.menu.reloadData()
updateNavigationBar(forSelectedIndex: 0)
setupIcons()
}
}
// setup
private extension ColorMatchTabsViewController {
func setupIcons() {
guard let dataSource = colorMatchTabDataSource else {
return
}
icons.forEach { $0.removeFromSuperview() }
icons = []
for index in 0..<dataSource.numberOfItems(inController: self) {
let size = _view.circleMenuButton.bounds.size
let frame = CGRect(origin: .zero, size: CGSize(width: size.width / 2, height: size.height / 2))
let iconImageView = UIImageView(frame: frame)
iconImageView.image = dataSource.tabsViewController(self, hightlightedIconAt: index)
iconImageView.contentMode = .center
iconImageView.isHidden = true
view.addSubview(iconImageView)
icons.append(iconImageView)
}
}
func setupNavigationBar() {
navigationController?.navigationBar.shadowImage = UIImage(namedInCurrentBundle: "transparent_pixel")
let pixelImage = UIImage(namedInCurrentBundle: "pixel")
navigationController?.navigationBar.setBackgroundImage(pixelImage, for: .default)
titleLabel.frame = CGRect(x: 0, y: 0, width: 120, height: 40)
titleLabel.text = title
titleLabel.textAlignment = .center
navigationItem.titleView = titleLabel
}
func setupTabSwitcher() {
_view.tabs.selectedSegmentIndex = 0
_view.tabs.addTarget(self, action: #selector(changeContent(_:)), for: .valueChanged)
_view.tabs.dataSource = self
}
func setupScrollMenu() {
_view.scrollMenu.menuDelegate = self
}
func setupCircleMenu() {
_view.circleMenuButton.addTarget(self, action: #selector(showPopover(_:)), for: .touchUpInside)
}
func updateNavigationBar(forSelectedIndex index: Int) {
let color = colorMatchTabDataSource?.tabsViewController(self, tintColorAt: index) ?? .white
titleLabel.textColor = color
_view.scrollMenu.backgroundColor = color.withAlphaComponent(0.2)
}
func updateScrollEnabled() {
_view.scrollMenu.isScrollEnabled = scrollEnabled
}
}
// animations
private extension ColorMatchTabsViewController {
func setDefaultPositions() {
_view.tabs.setHighlighterHidden(false)
for (index, iconImageView) in icons.enumerated() {
UIView.animate(
withDuration: AnimationDuration,
delay: 0,
usingSpringWithDamping: 0.8,
initialSpringVelocity: 3,
options: [],
animations: {
let point = self._view.tabs.centerOfItem(atIndex: index)
iconImageView.center = self._view.tabs.convert(point, to: self.view)
let image: UIImage?
if index == self._view.tabs.selectedSegmentIndex {
image = self.colorMatchTabDataSource?.tabsViewController(self, hightlightedIconAt: index)
} else {
image = self.colorMatchTabDataSource?.tabsViewController(self, iconAt: index)
}
iconImageView.image = image
},
completion: { _ in
self._view.tabs.setIconsHidden(false)
iconImageView.isHidden = true
}
)
}
}
@objc
func showPopover(_ sender: AnyObject?) {
showDroppingItems()
showPopover()
}
func showDroppingItems() {
UIView.animate(withDuration: AnimationDuration) {
self._view.tabs.setHighlighterHidden(true)
}
for (index, iconImageView) in icons.enumerated() {
iconImageView.center = _view.tabs.centerOfItem(atIndex: index)
iconImageView.isHidden = false
UIView.animate(
withDuration: AnimationDuration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 3,
options: [],
animations: {
iconImageView.image = self.colorMatchTabDataSource?.tabsViewController(self, hightlightedIconAt: index)
iconImageView.center = CGPoint(
x: iconImageView.center.x,
y: iconImageView.center.y + self.view.frame.height / 2
)
},
completion: nil
)
}
_view.tabs.setIconsHidden(true)
}
func showPopover() {
guard let popoverViewController = popoverViewController else {
return
}
popoverViewController.transitioningDelegate = self
popoverViewController.highlightedItemIndex = _view.tabs.selectedSegmentIndex
popoverViewController.view.backgroundColor = .white
popoverViewController.reloadData()
present(popoverViewController, animated: true, completion: nil)
}
@objc
func changeContent(_ sender: ColorTabs) {
updateNavigationBar(forSelectedIndex: sender.selectedSegmentIndex)
if _view.scrollMenu.destinationIndex != sender.selectedSegmentIndex {
_view.scrollMenu.selectItem(atIndex: sender.selectedSegmentIndex)
}
}
}
extension ColorMatchTabsViewController: ScrollMenuDelegate {
open func scrollMenu(_ scrollMenu: ScrollMenu, didSelectedItemAt index: Int) {
updateNavigationBar(forSelectedIndex: index)
if _view.tabs.selectedSegmentIndex != index {
_view.tabs.selectedSegmentIndex = index
}
colorMatchTabDelegate?.didSelectItemAt(index)
}
}
extension ColorMatchTabsViewController: UIViewControllerTransitioningDelegate {
open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
presented.view.frame = presenting.view.frame
circleTransition.mode = .show
circleTransition.startPoint = _view.circleMenuButton.center
return circleTransition
}
open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
guard let dismissedViewController = dismissed as? PopoverViewController else {
return nil
}
circleTransition.mode = .hide
circleTransition.startPoint = dismissedViewController.menu.center
return circleTransition
}
}
// MARK: - Data sources
extension ColorMatchTabsViewController: ColorTabsDataSource {
open func numberOfItems(inTabSwitcher tabSwitcher: ColorTabs) -> Int {
return colorMatchTabDataSource?.numberOfItems(inController: self) ?? 0
}
open func tabSwitcher(_ tabSwitcher: ColorTabs, titleAt index: Int) -> String {
return colorMatchTabDataSource!.tabsViewController(self, titleAt: index)
}
open func tabSwitcher(_ tabSwitcher: ColorTabs, iconAt index: Int) -> UIImage {
return colorMatchTabDataSource!.tabsViewController(self, iconAt: index)
}
open func tabSwitcher(_ tabSwitcher: ColorTabs, hightlightedIconAt index: Int) -> UIImage {
return colorMatchTabDataSource!.tabsViewController(self, hightlightedIconAt: index)
}
open func tabSwitcher(_ tabSwitcher: ColorTabs, tintColorAt index: Int) -> UIColor {
return colorMatchTabDataSource!.tabsViewController(self, tintColorAt: index)
}
}
extension ColorMatchTabsViewController: ScrollMenuDataSource {
open func numberOfItemsInScrollMenu(_ scrollMenu: ScrollMenu) -> Int {
return colorMatchTabDataSource?.numberOfItems(inController: self) ?? 0
}
open func scrollMenu(_ scrollMenu: ScrollMenu, viewControllerAtIndex index: Int) -> UIViewController {
return colorMatchTabDataSource!.tabsViewController(self, viewControllerAt: index)
}
}
extension ColorMatchTabsViewController: CircleMenuDataSource {
open func numberOfItems(inMenu circleMenu: CircleMenu) -> Int {
return colorMatchTabDataSource?.numberOfItems(inController: self) ?? 0
}
open func circleMenu(_ circleMenu: CircleMenu, tintColorAt index: Int) -> UIColor {
return colorMatchTabDataSource!.tabsViewController(self, tintColorAt: index)
}
}
extension ColorMatchTabsViewController: PopoverViewControllerDataSource {
open func numberOfItems(inPopoverViewController popoverViewController: PopoverViewController) -> Int {
return colorMatchTabDataSource?.numberOfItems(inController: self) ?? 0
}
open func popoverViewController(_ popoverViewController: PopoverViewController, iconAt index: Int) -> UIImage {
return colorMatchTabDataSource!.tabsViewController(self, iconAt: index)
}
open func popoverViewController(_ popoverViewController: PopoverViewController, hightlightedIconAt index: Int) -> UIImage {
return colorMatchTabDataSource!.tabsViewController(self, hightlightedIconAt: index)
}
}
| 513476e19b41f96e28abd5fd4516f10c | 33.209115 | 175 | 0.647414 | false | false | false | false |
iAladdin/SwiftyFORM | refs/heads/master | Source/Cells/ViewControllerCell.swift | mit | 1 | //
// ViewControllerCell.swift
// SwiftyFORM
//
// Created by Simon Strandgaard on 05/11/14.
// Copyright (c) 2014 Simon Strandgaard. All rights reserved.
//
import UIKit
public class ViewControllerFormItemCellModel {
public let title: String
public let placeholder: String
public init(title: String, placeholder: String) {
self.title = title
self.placeholder = placeholder
}
}
public class ViewControllerFormItemCell: UITableViewCell, SelectRowDelegate {
public let model: ViewControllerFormItemCellModel
let innerDidSelectRow: (ViewControllerFormItemCell, ViewControllerFormItemCellModel) -> Void
public init(model: ViewControllerFormItemCellModel, didSelectRow: (ViewControllerFormItemCell, ViewControllerFormItemCellModel) -> Void) {
self.model = model
self.innerDidSelectRow = didSelectRow
super.init(style: .Value1, reuseIdentifier: nil)
accessoryType = .DisclosureIndicator
textLabel?.text = model.title
detailTextLabel?.text = model.placeholder
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func form_didSelectRow(indexPath: NSIndexPath, tableView: UITableView) {
DLog("will invoke")
// hide keyboard when the user taps this kind of row
tableView.form_firstResponder()?.resignFirstResponder()
innerDidSelectRow(self, model)
DLog("did invoke")
}
}
| 490e04bf7c740db6781b1b5505003129 | 28.869565 | 139 | 0.773654 | false | false | false | false |
justin999/gitap | refs/heads/master | gitap/PhotosCollectionViewDataSource.swift | mit | 1 | //
// PhotosCollectionViewDataSource.swift
// gitap
//
// Created by Koichi Sato on 2017/02/05.
// Copyright © 2017 Koichi Sato. All rights reserved.
//
import UIKit
import Photos
let photoThumbnailCountInRow:CGFloat = 3
let minimumSpacingBetweenCells: CGFloat = 1
let photoThumbnailLength = UIScreen.main.bounds.width / photoThumbnailCountInRow - (photoThumbnailCountInRow - minimumSpacingBetweenCells)
let photoThumbnailSize = CGSize(width: photoThumbnailLength, height: photoThumbnailLength)
class PhotosCollectionViewDataSource: NSObject {
var stateController: StateController
var fetchResult: PHFetchResult<PHAsset>!
fileprivate let imageManager = PHCachingImageManager()
init(collectionView: UICollectionView, stateController: StateController) {
self.stateController = stateController
super.init()
collectionView.dataSource = self
}
}
extension PhotosCollectionViewDataSource: UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return fetchResult.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let asset = fetchResult.object(at: indexPath.item)
// Dequeue a GridViewCell.
let cellId = String(describing: PhotoGridViewCell.self)
Utils.registerCCell(collectionView, nibName: cellId, cellId: cellId)
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as? PhotoGridViewCell
else { fatalError("unexpected cell in collection view") }
// Request an image for the asset from the PHCachingImageManager.
cell.representedAssetIdentifier = asset.localIdentifier
imageManager.requestImage(for: asset, targetSize: photoThumbnailSize, contentMode: .aspectFill, options: nil, resultHandler: { image, _ in
// The cell may have been recycled by the time this handler gets called;
// set the cell's thumbnail image only if it's still showing the same asset.
if cell.representedAssetIdentifier == asset.localIdentifier {
cell.thumbnailImage = image
}
})
return cell
}
}
| 0d006c97b913f41e3a4de41c53ddb83c | 37.387097 | 146 | 0.712605 | false | false | false | false |
material-motion/material-motion-swift | refs/heads/develop | examples/HowToUseReactiveConstraintsExample.swift | apache-2.0 | 1 | /*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MaterialMotion
class HowToUseReactiveConstraintsExampleViewController: ExampleViewController {
var runtime: MotionRuntime!
override func viewDidLoad() {
super.viewDidLoad()
let exampleView = center(createExampleView(), within: view)
view.addSubview(exampleView)
let axisLine = UIView(frame: .init(x: view.bounds.midX - 8, y: 0, width: 16, height: view.bounds.height))
axisLine.backgroundColor = .secondaryColor
view.insertSubview(axisLine, belowSubview: exampleView)
runtime = MotionRuntime(containerView: view)
let axisCenterX = runtime.get(axisLine.layer).position.x()
runtime.add(Draggable(), to: exampleView) { $0
.startWith(exampleView.layer.position)
.xLocked(to: axisCenterX)
}
runtime.add(Draggable(), to: axisLine) { $0.yLocked(to: axisLine.layer.position.y) }
}
override func exampleInformation() -> ExampleInfo {
return .init(title: type(of: self).catalogBreadcrumbs().last!,
instructions: "Drag the view to move it on the y axis.")
}
}
| 2a6561f8f4e1789953ed70d8cc29cc39 | 33.204082 | 109 | 0.73568 | false | false | false | false |
tdquang/CarlWrite | refs/heads/master | CVCalendar/CVCalendarWeekContentViewController.swift | mit | 1 | //
// CVCalendarWeekContentViewController.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 12/04/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
class CVCalendarWeekContentViewController: CVCalendarContentViewController {
private var weekViews: [Identifier : WeekView]
private var monthViews: [Identifier : MonthView]
override init(calendarView: CalendarView, frame: CGRect) {
weekViews = [Identifier : WeekView]()
monthViews = [Identifier : MonthView]()
super.init(calendarView: calendarView, frame: frame)
initialLoad(NSDate())
}
init(calendarView: CalendarView, frame: CGRect, presentedDate: NSDate) {
weekViews = [Identifier : WeekView]()
monthViews = [Identifier : MonthView]()
super.init(calendarView: calendarView, frame: frame)
presentedMonthView = MonthView(calendarView: calendarView, date: presentedDate)
presentedMonthView.updateAppearance(bounds)
initialLoad(presentedDate)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Load & Reload
func initialLoad(date: NSDate) {
monthViews[Previous] = getPreviousMonth(presentedMonthView.date)
monthViews[Presented] = presentedMonthView
monthViews[Following] = getFollowingMonth(presentedMonthView.date)
presentedMonthView.mapDayViews { dayView in
if self.matchedDays(dayView.date, Date(date: date)) {
self.insertWeekView(dayView.weekView, withIdentifier: self.Presented)
self.calendarView.coordinator.flush()
self.calendarView.touchController.receiveTouchOnDayView(dayView)
dayView.circleView?.removeFromSuperview()
}
}
if let presented = weekViews[Presented] {
insertWeekView(getPreviousWeek(presented), withIdentifier: Previous)
insertWeekView(getFollowingWeek(presented), withIdentifier: Following)
}
}
func reloadWeekViews() {
for (identifier, weekView) in weekViews {
weekView.frame.origin = CGPointMake(CGFloat(indexOfIdentifier(identifier)) * scrollView.frame.width, 0)
weekView.removeFromSuperview()
scrollView.addSubview(weekView)
}
}
// MARK: - Insertion
func insertWeekView(weekView: WeekView, withIdentifier identifier: Identifier) {
let index = CGFloat(indexOfIdentifier(identifier))
weekView.frame.origin = CGPointMake(scrollView.bounds.width * index, 0)
weekViews[identifier] = weekView
scrollView.addSubview(weekView)
}
func replaceWeekView(weekView: WeekView, withIdentifier identifier: Identifier, animatable: Bool) {
var weekViewFrame = weekView.frame
weekViewFrame.origin.x = weekViewFrame.width * CGFloat(indexOfIdentifier(identifier))
weekView.frame = weekViewFrame
weekViews[identifier] = weekView
if animatable {
scrollView.scrollRectToVisible(weekViewFrame, animated: false)
}
}
// MARK: - Load management
func scrolledLeft() {
if let presented = weekViews[Presented], let following = weekViews[Following] {
if pageLoadingEnabled {
pageLoadingEnabled = false
weekViews[Previous]?.removeFromSuperview()
replaceWeekView(presented, withIdentifier: Previous, animatable: false)
replaceWeekView(following, withIdentifier: Presented, animatable: true)
insertWeekView(getFollowingWeek(following), withIdentifier: Following)
}
}
}
func scrolledRight() {
if let presented = weekViews[Presented], let previous = weekViews[Previous] {
if pageLoadingEnabled {
pageLoadingEnabled = false
weekViews[Following]?.removeFromSuperview()
replaceWeekView(presented, withIdentifier: Following, animatable: false)
replaceWeekView(previous, withIdentifier: Presented, animatable: true)
insertWeekView(getPreviousWeek(previous), withIdentifier: Previous)
}
}
}
// MARK: - Override methods
override func updateFrames(rect: CGRect) {
super.updateFrames(rect)
for monthView in monthViews.values {
monthView.reloadViewsWithRect(rect != CGRectZero ? rect : scrollView.bounds)
}
reloadWeekViews()
if let presented = weekViews[Presented] {
scrollView.scrollRectToVisible(presented.frame, animated: false)
}
}
override func performedDayViewSelection(dayView: DayView) {
if dayView.isOut {
if dayView.date.day > 20 {
let presentedDate = dayView.monthView.date
calendarView.presentedDate = Date(date: self.dateBeforeDate(presentedDate))
presentPreviousView(dayView)
} else {
let presentedDate = dayView.monthView.date
calendarView.presentedDate = Date(date: self.dateAfterDate(presentedDate))
presentNextView(dayView)
}
}
}
override func presentPreviousView(view: UIView?) {
if presentationEnabled {
presentationEnabled = false
if let extra = weekViews[Following], let presented = weekViews[Presented], let previous = weekViews[Previous] {
UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.prepareTopMarkersOnWeekView(presented, hidden: false)
extra.frame.origin.x += self.scrollView.frame.width
presented.frame.origin.x += self.scrollView.frame.width
previous.frame.origin.x += self.scrollView.frame.width
self.replaceWeekView(presented, withIdentifier: self.Following, animatable: false)
self.replaceWeekView(previous, withIdentifier: self.Presented, animatable: false)
}) { _ in
extra.removeFromSuperview()
self.insertWeekView(self.getPreviousWeek(previous), withIdentifier: self.Previous)
self.updateSelection()
self.presentationEnabled = true
for weekView in self.weekViews.values {
self.prepareTopMarkersOnWeekView(weekView, hidden: false)
}
}
}
}
}
override func presentNextView(view: UIView?) {
if presentationEnabled {
presentationEnabled = false
if let extra = weekViews[Previous], let presented = weekViews[Presented], let following = weekViews[Following] {
UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.prepareTopMarkersOnWeekView(presented, hidden: false)
extra.frame.origin.x -= self.scrollView.frame.width
presented.frame.origin.x -= self.scrollView.frame.width
following.frame.origin.x -= self.scrollView.frame.width
self.replaceWeekView(presented, withIdentifier: self.Previous, animatable: false)
self.replaceWeekView(following, withIdentifier: self.Presented, animatable: false)
}) { _ in
extra.removeFromSuperview()
self.insertWeekView(self.getFollowingWeek(following), withIdentifier: self.Following)
self.updateSelection()
self.presentationEnabled = true
for weekView in self.weekViews.values {
self.prepareTopMarkersOnWeekView(weekView, hidden: false)
}
}
}
}
}
override func updateDayViews(hidden: Bool) {
setDayOutViewsVisible(hidden)
}
private var togglingBlocked = false
override func togglePresentedDate(date: NSDate) {
let presentedDate = Date(date: date)
if let presentedMonthView = monthViews[Presented], let presentedWeekView = weekViews[Presented], let selectedDate = calendarView.coordinator.selectedDayView?.date {
if !matchedDays(selectedDate, Date(date: date)) && !togglingBlocked {
if !matchedWeeks(presentedDate, selectedDate) {
togglingBlocked = true
weekViews[Previous]?.removeFromSuperview()
weekViews[Following]?.removeFromSuperview()
let currentMonthView = MonthView(calendarView: calendarView, date: date)
currentMonthView.updateAppearance(scrollView.bounds)
monthViews[Presented] = currentMonthView
monthViews[Previous] = getPreviousMonth(date)
monthViews[Following] = getFollowingMonth(date)
let currentDate = CVDate(date: date)
calendarView.presentedDate = currentDate
var currentWeekView: WeekView!
currentMonthView.mapDayViews { dayView in
if self.matchedDays(currentDate, dayView.date) {
if let weekView = dayView.weekView {
currentWeekView = weekView
currentWeekView.alpha = 0
}
}
}
insertWeekView(getPreviousWeek(currentWeekView), withIdentifier: Previous)
insertWeekView(currentWeekView, withIdentifier: Presented)
insertWeekView(getFollowingWeek(currentWeekView), withIdentifier: Following)
UIView.animateWithDuration(0.8, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
presentedWeekView.alpha = 0
currentWeekView.alpha = 1
}) { _ in
presentedWeekView.removeFromSuperview()
self.selectDayViewWithDay(currentDate.day, inWeekView: currentWeekView)
self.togglingBlocked = false
}
} else {
if let currentWeekView = weekViews[Presented] {
selectDayViewWithDay(presentedDate.day, inWeekView: currentWeekView)
}
}
}
}
}
}
// MARK: - WeekView management
extension CVCalendarWeekContentViewController {
func getPreviousWeek(presentedWeekView: WeekView) -> WeekView {
if let presentedMonthView = monthViews[Presented], let previousMonthView = monthViews[Previous] where presentedWeekView.monthView == presentedMonthView {
for weekView in presentedMonthView.weekViews {
if weekView.index == presentedWeekView.index - 1 {
return weekView
}
}
for weekView in previousMonthView.weekViews {
if weekView.index == previousMonthView.weekViews.count - 1 {
return weekView
}
}
} else if let previousMonthView = monthViews[Previous] {
monthViews[Following] = monthViews[Presented]
monthViews[Presented] = monthViews[Previous]
monthViews[Previous] = getPreviousMonth(previousMonthView.date)
presentedMonthView = monthViews[Previous]!
}
return getPreviousWeek(presentedWeekView)
}
func getFollowingWeek(presentedWeekView: WeekView) -> WeekView {
if let presentedMonthView = monthViews[Presented], let followingMonthView = monthViews[Following] where presentedWeekView.monthView == presentedMonthView {
for weekView in presentedMonthView.weekViews {
for weekView in presentedMonthView.weekViews {
if weekView.index == presentedWeekView.index + 1 {
return weekView
}
}
for weekView in followingMonthView.weekViews {
if weekView.index == 0 {
return weekView
}
}
}
} else if let followingMonthView = monthViews[Following] {
monthViews[Previous] = monthViews[Presented]
monthViews[Presented] = monthViews[Following]
monthViews[Following] = getFollowingMonth(followingMonthView.date)
presentedMonthView = monthViews[Following]!
}
return getFollowingWeek(presentedWeekView)
}
}
// MARK: - MonthView management
extension CVCalendarWeekContentViewController {
func getFollowingMonth(date: NSDate) -> MonthView {
let calendarManager = calendarView.manager
let firstDate = calendarManager.monthDateRange(date).monthStartDate
let components = Manager.componentsForDate(firstDate)
components.month += 1
let newDate = NSCalendar.currentCalendar().dateFromComponents(components)!
let monthView = MonthView(calendarView: calendarView, date: newDate)
let frame = CGRectMake(0, 0, scrollView.bounds.width, scrollView.bounds.height)
monthView.updateAppearance(frame)
return monthView
}
func getPreviousMonth(date: NSDate) -> MonthView {
let firstDate = calendarView.manager.monthDateRange(date).monthStartDate
let components = Manager.componentsForDate(firstDate)
components.month -= 1
let newDate = NSCalendar.currentCalendar().dateFromComponents(components)!
let monthView = MonthView(calendarView: calendarView, date: newDate)
let frame = CGRectMake(0, 0, scrollView.bounds.width, scrollView.bounds.height)
monthView.updateAppearance(frame)
return monthView
}
}
// MARK: - Visual preparation
extension CVCalendarWeekContentViewController {
func prepareTopMarkersOnWeekView(weekView: WeekView, hidden: Bool) {
weekView.mapDayViews { dayView in
dayView.topMarker?.hidden = hidden
}
}
func setDayOutViewsVisible(visible: Bool) {
for monthView in monthViews.values {
monthView.mapDayViews { dayView in
if dayView.isOut {
if !visible {
dayView.alpha = 0
dayView.hidden = false
}
UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
dayView.alpha = visible ? 0 : 1
}) { _ in
if visible {
dayView.alpha = 1
dayView.hidden = true
dayView.userInteractionEnabled = false
} else {
dayView.userInteractionEnabled = true
}
}
}
}
}
}
func updateSelection() {
let coordinator = calendarView.coordinator
if let selected = coordinator.selectedDayView {
for (index, monthView) in monthViews {
if indexOfIdentifier(index) != 1 {
monthView.mapDayViews { dayView in
if dayView == selected {
dayView.setDeselectedWithClearing(true)
coordinator.dequeueDayView(dayView)
}
}
}
}
}
if let presentedWeekView = weekViews[Presented], let presentedMonthView = monthViews[Presented] {
self.presentedMonthView = presentedMonthView
calendarView.presentedDate = Date(date: presentedMonthView.date)
var presentedDate: Date!
for dayView in presentedWeekView.dayViews {
if !dayView.isOut {
presentedDate = dayView.date
break
}
}
if let selected = coordinator.selectedDayView where !matchedWeeks(selected.date, presentedDate) {
let current = Date(date: NSDate())
if matchedWeeks(current, presentedDate) {
selectDayViewWithDay(current.day, inWeekView: presentedWeekView)
} else {
selectDayViewWithDay(presentedDate.day, inWeekView: presentedWeekView)
}
}
}
}
func selectDayViewWithDay(day: Int, inWeekView weekView: WeekView) {
let coordinator = calendarView.coordinator
weekView.mapDayViews { dayView in
if dayView.date.day == day && !dayView.isOut {
if let selected = coordinator.selectedDayView where selected != dayView {
self.calendarView.didSelectDayView(dayView)
}
coordinator.performDayViewSingleSelection(dayView)
}
}
}
}
// MARK: - UIScrollViewDelegate
extension CVCalendarWeekContentViewController {
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.contentOffset.y != 0 {
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, 0)
}
let page = Int(floor((scrollView.contentOffset.x - scrollView.frame.width / 2) / scrollView.frame.width) + 1)
if currentPage != page {
currentPage = page
}
lastContentOffset = scrollView.contentOffset.x
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
if let presented = weekViews[Presented] {
prepareTopMarkersOnWeekView(presented, hidden: true)
}
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if pageChanged {
switch direction {
case .Left: scrolledLeft()
case .Right: scrolledRight()
default: break
}
}
updateSelection()
pageLoadingEnabled = true
direction = .None
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate {
let rightBorder = scrollView.frame.width
if scrollView.contentOffset.x <= rightBorder {
direction = .Right
} else {
direction = .Left
}
}
for weekView in self.weekViews.values {
self.prepareTopMarkersOnWeekView(weekView, hidden: false)
}
}
} | f84a97ef26dbef952af0fa6471f41e84 | 39.38193 | 172 | 0.576506 | false | false | false | false |
dhardiman/MVVMTools | refs/heads/master | Sources/MVVM/TableViewCellSource.swift | mit | 1 | //
// TableViewCellSource.swift
// MVVM
//
// Created by Dave Hardiman on 22/03/2016.
// Copyright © 2016 David Hardiman. All rights reserved.
//
import UIKit
/**
* A `View` that can be reused
*/
public protocol ViewCell: View {
static var defaultReuseIdentifier: String { get }
}
// MARK: - Default implementation of reuse identifier for table view cells
public extension ViewCell where Self: UITableViewCell {
static var defaultReuseIdentifier: String {
return String(describing: self)
}
}
/**
* A protocol that describes a source for MVVM compatible table view cells
*/
public protocol TableViewCellSource: UITableViewDataSource {
/// The type of the view model being used by the cells. Used as a type
/// constraint in the extension below
associatedtype CellViewModelType: ViewModel
/// The table view being supplied
var tableView: UITableView! { get set }
}
public extension TableViewCellSource {
/**
Registers a table cell by nib name with the current table view
- parameter _: The type of the cell being registered
*/
func registerNib<T: UITableViewCell>(_: T.Type, bundle: Bundle? = nil) where T: ViewCell {
let nib = UINib(nibName: (String(describing: T.self)), bundle: bundle)
tableView?.register(nib, forCellReuseIdentifier: T.defaultReuseIdentifier)
}
/**
Retgisters a table cell by its class
- parameter _: The type of the cell being registered
*/
func registerClass<T: UITableViewCell>(_: T.Type) where T: ViewCell {
tableView?.register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier)
}
/**
Dequeues a cell from the current table view and configures the cell's view
model with the specified item
- parameter item: The item for the cell to display
- parameter atIndexPath: The indexPath to dequeue the cell for
- returns: A configured cell
*/
func cell<VC: ViewCell>(forItem item: CellViewModelType.ModelType, at indexPath: IndexPath) -> VC
where VC.ViewModelType == Self.CellViewModelType, VC: UITableViewCell {
guard let cell = tableView?.dequeueReusableCell(withIdentifier: VC.defaultReuseIdentifier, for: indexPath) as? VC else {
fatalError("No cell registered for \(VC.defaultReuseIdentifier)")
}
cell.viewModel.model = item
return cell
}
}
| 7c1340b63af40b15df9ee87e419d4c0b | 31.621622 | 128 | 0.690555 | false | false | false | false |
OneBusAway/onebusaway-iphone | refs/heads/develop | Carthage/Checkouts/swift-protobuf/Tests/SwiftProtobufPluginLibraryTests/Descriptor+TestHelpers.swift | apache-2.0 | 3 | // Sources/protoc-gen-swift/Descriptor+TestHelpers.swift - Additions to Descriptors
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
import SwiftProtobuf
import SwiftProtobufPluginLibrary
extension Google_Protobuf_FileDescriptorProto {
init(name: String, dependencies: [String] = [], publicDependencies: [Int32] = []) {
for idx in publicDependencies { precondition(Int(idx) <= dependencies.count) }
self.init()
self.name = name
dependency = dependencies
publicDependency = publicDependencies
}
init(textFormatStrings: [String]) throws {
let s = textFormatStrings.joined(separator: "\n") + "\n"
try self.init(textFormatString: s)
}
}
extension Google_Protobuf_FileDescriptorSet {
init(files: [Google_Protobuf_FileDescriptorProto]) {
self.init()
file = files
}
init(file: Google_Protobuf_FileDescriptorProto) {
self.init()
self.file = [file]
}
}
extension Google_Protobuf_EnumValueDescriptorProto {
init(name: String, number: Int32) {
self.init()
self.name = name
self.number = number
}
}
| 1b44955c0a7e89657dee7de5aa40fe0e | 29.044444 | 85 | 0.672337 | false | false | false | false |
Thomvis/BrightFutures | refs/heads/master | Tests/BrightFuturesTests/ExecutionContextTests.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2014 Thomas Visser
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import XCTest
import BrightFutures
class Counter {
var i: Int = 0
}
class ExecutionContextTests: XCTestCase {
func testImmediateOnMainThreadContextOnMainThread() {
let counter = Counter()
counter.i = 1
immediateOnMainExecutionContext {
XCTAssert(Thread.isMainThread)
counter.i = 2
}
XCTAssertEqual(counter.i, 2)
}
func testImmediateOnMainThreadContextOnBackgroundThread() {
let e = self.expectation()
DispatchQueue.global().async {
immediateOnMainExecutionContext {
XCTAssert(Thread.isMainThread)
e.fulfill()
}
}
self.waitForExpectations(timeout: 2, handler: nil)
}
func testDispatchQueueToContext() {
let key = DispatchSpecificKey<String>()
let value1 = "abc"
let queue1 = DispatchQueue(label: "test1", qos: DispatchQoS.default, attributes: [], autoreleaseFrequency: .inherit, target: nil)
queue1.setSpecific(key: key, value: value1)
let e1 = self.expectation()
queue1.context {
XCTAssertEqual(DispatchQueue.getSpecific(key: key), value1)
e1.fulfill()
}
let value2 = "def"
let queue2 = DispatchQueue(label: "test2", qos: DispatchQoS.default, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil)
queue2.setSpecific(key: key, value: value2)
let e2 = self.expectation()
queue2.context {
XCTAssertEqual(DispatchQueue.getSpecific(key: key), value2)
e2.fulfill()
}
self.waitForExpectations(timeout: 2, handler: nil)
}
}
| b0b569ca52ca666cb88cdb18629966c6 | 33.809524 | 146 | 0.652873 | false | true | false | false |
sunweifeng/SWFKit | refs/heads/master | SWFKit/Classes/Extend/URL+Helper.swift | mit | 1 | //
// URL+Helper.swift
// SWFKit
//
// Created by 孙伟峰 on 2016/12/12.
// Copyright © 2017年 Sun Weifeng. All rights reserved.
//
import UIKit
public extension URL {
public func getQuery() -> Dictionary<String, String>? {
var dict = Dictionary<String, String>()
guard let queryStr = self.query else {
return nil
}
let queryArr = queryStr.components(separatedBy: "&")
for queryItemStr in queryArr {
let queryItemArr = queryItemStr.components(separatedBy: "=")
if queryItemArr.count == 2 {
let name = queryItemArr[0]
let value = queryItemArr[1]
dict[name] = value
}
}
return dict
}
}
| eff82de97b5fba12e1a9eaa782c1d039 | 25.607143 | 72 | 0.558389 | false | false | false | false |
iAmrSalman/Dots | refs/heads/master | Sources/Reachability.swift | mit | 1 | //
// Reachability.swift
// Dots
//
// Created by Amr Salman on 4/4/17.
//
//
#if !os(watchOS)
import Foundation
import SystemConfiguration
import SystemConfiguration.CaptiveNetwork
public let ReachabilityStatusChangedNotification = "ReachabilityStatusChangedNotification"
public enum ReachabilityType: CustomStringConvertible {
case WWAN
case WiFi
public var description: String {
switch self {
case .WWAN: return "WWAN"
case .WiFi: return "WiFi"
}
}
}
public enum ReachabilityStatus: CustomStringConvertible {
case Offline
case Online(ReachabilityType)
case Unknown
public var description: String {
switch self {
case .Offline: return "Offline"
case .Online(let type): return "Online (\(type))"
case .Unknown: return "Unknown"
}
}
}
public class Reachability {
public init() { }
public func connectionStatus() -> ReachabilityStatus {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = (withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}) else {
return .Unknown
}
var flags : SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return .Unknown
}
return ReachabilityStatus(reachabilityFlags: flags)
}
public func monitorReachabilityChanges() {
let host = "google.com"
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
let reachability = SCNetworkReachabilityCreateWithName(nil, host)!
SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in
let status = ReachabilityStatus(reachabilityFlags: flags)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: ReachabilityStatusChangedNotification), object: nil, userInfo: ["Status": status.description])}, &context)
SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue)
}
}
extension ReachabilityStatus {
public init(reachabilityFlags flags: SCNetworkReachabilityFlags) {
let connectionRequired = flags.contains(.connectionRequired)
let isReachable = flags.contains(.reachable)
#if os(iOS)
let isWWAN = flags.contains(.isWWAN)
#endif
if !connectionRequired && isReachable {
#if os(iOS)
if isWWAN {
self = .Online(.WWAN)
} else {
self = .Online(.WiFi)
}
#else
self = .Online(.WiFi)
#endif
} else {
self = .Offline
}
}
}
#endif
| 32c84fc2a58f3cce4c7af001f29f15db | 25.740741 | 180 | 0.687673 | false | false | false | false |
carabina/AlecrimAsyncKit | refs/heads/master | Source/AlecrimAsyncKit/Core/AsyncAwait.swift | mit | 1 | //
// AsyncAwait.swift
// AlecrimAsyncKit
//
// Created by Vanderlei Martinelli on 2015-05-10.
// Copyright (c) 2015 Alecrim. All rights reserved.
//
import Foundation
private let _defaultTaskQueue: NSOperationQueue = {
let queue = NSOperationQueue()
queue.name = "com.alecrim.AlecrimAsyncKit.Task"
queue.qualityOfService = .Background
queue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount
return queue
}()
private let _defaultRunTaskQueue: NSOperationQueue = {
let queue = NSOperationQueue()
queue.name = "com.alecrim.AlecrimAsyncKit.RunTask"
queue.qualityOfService = .Background
queue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount
return queue
}()
private let _defaultRunTaskCompletionQueue: NSOperationQueue = NSOperationQueue.mainQueue()
// MARK: - async
@warn_unused_result
public func async<V>(queue: NSOperationQueue = _defaultTaskQueue, closure: () throws -> V) -> Task<V> {
return Task<V>(queue: queue, observers: nil, conditions: nil) { (task: Task<V>) -> Void in
do {
let value = try closure()
task.finishWithValue(value)
}
catch let error {
task.finishWithError(error)
}
}
}
@warn_unused_result
public func asyncEx<V>(queue: NSOperationQueue = _defaultTaskQueue, closure: (Task<V>) -> Void) -> Task<V> {
return Task<V>(queue: queue, observers: nil, conditions: nil, closure: closure)
}
//
@warn_unused_result
public func async<V>(queue: NSOperationQueue = _defaultTaskQueue, condition: TaskCondition, closure: () throws -> V) -> Task<V> {
return Task<V>(queue: queue, observers: nil, conditions: [condition]) { (task: Task<V>) -> Void in
do {
let value = try closure()
task.finishWithValue(value)
}
catch let error {
task.finishWithError(error)
}
}
}
@warn_unused_result
public func asyncEx<V>(queue: NSOperationQueue = _defaultTaskQueue, condition: TaskCondition, closure: (Task<V>) -> Void) -> Task<V> {
return Task<V>(queue: queue, observers: nil, conditions: [condition], closure: closure)
}
//
@warn_unused_result
public func async<V>(queue: NSOperationQueue = _defaultTaskQueue, conditions: [TaskCondition], closure: () throws -> V) -> Task<V> {
return Task<V>(queue: queue, observers: nil, conditions: conditions) { (task: Task<V>) -> Void in
do {
let value = try closure()
task.finishWithValue(value)
}
catch let error {
task.finishWithError(error)
}
}
}
@warn_unused_result
public func asyncEx<V>(queue: NSOperationQueue = _defaultTaskQueue, conditions: [TaskCondition], closure: (Task<V>) -> Void) -> Task<V> {
return Task<V>(queue: queue, observers: nil, conditions: conditions, closure: closure)
}
//
@warn_unused_result
public func async<V>(queue: NSOperationQueue = _defaultTaskQueue, observers: [TaskObserver], closure: () throws -> V) -> Task<V> {
return Task<V>(queue: queue, observers: observers, conditions: nil) { (task: Task<V>) -> Void in
do {
let value = try closure()
task.finishWithValue(value)
}
catch let error {
task.finishWithError(error)
}
}
}
@warn_unused_result
public func asyncEx<V>(queue: NSOperationQueue = _defaultTaskQueue, observers: [TaskObserver], closure: (Task<V>) -> Void) -> Task<V> {
return Task<V>(queue: queue, observers: observers, conditions: nil, closure: closure)
}
//
@warn_unused_result
public func async<V>(queue: NSOperationQueue = _defaultTaskQueue, conditions: [TaskCondition], observers: [TaskObserver], closure: () throws -> V) -> Task<V> {
return Task<V>(queue: queue, observers: observers, conditions: conditions) { (task: Task<V>) -> Void in
do {
let value = try closure()
task.finishWithValue(value)
}
catch let error {
task.finishWithError(error)
}
}
}
@warn_unused_result
public func asyncEx<V>(queue: NSOperationQueue = _defaultTaskQueue, conditions: [TaskCondition], observers: [TaskObserver], closure: (Task<V>) -> Void) -> Task<V> {
return Task<V>(queue: queue, observers: observers, conditions: conditions, closure: closure)
}
// MARK: - async - non failable task
@warn_unused_result
public func async<V>(queue: NSOperationQueue = _defaultTaskQueue, closure: () -> V) -> NonFailableTask<V> {
return NonFailableTask<V>(queue: queue, observers: nil) { (task: NonFailableTask<V>) -> Void in
let value = closure()
task.finishWithValue(value)
}
}
@warn_unused_result
public func asyncEx<V>(queue: NSOperationQueue = _defaultTaskQueue, closure: (NonFailableTask<V>) -> Void) -> NonFailableTask<V> {
return NonFailableTask<V>(queue: queue, observers: nil, closure: closure)
}
//
@warn_unused_result
public func async<V>(queue: NSOperationQueue = _defaultTaskQueue, observers: [TaskObserver], closure: () -> V) -> NonFailableTask<V> {
return NonFailableTask<V>(queue: queue, observers: observers) { (task: NonFailableTask<V>) -> Void in
let value = closure()
task.finishWithValue(value)
}
}
@warn_unused_result
public func asyncEx<V>(queue: NSOperationQueue = _defaultTaskQueue, observers: [TaskObserver], closure: (NonFailableTask<V>) -> Void) -> NonFailableTask<V> {
return NonFailableTask<V>(queue: queue, observers: observers, closure: closure)
}
// MARK: - await
public func await<V>(@noescape closure: () -> Task<V>) throws -> V {
return try closure().waitForCompletionAndReturnValue()
}
public func await<V>(task: Task<V>) throws -> V {
return try task.waitForCompletionAndReturnValue()
}
public func runTask<V>(task: Task<V>, queue: NSOperationQueue = _defaultRunTaskQueue, completionQueue: NSOperationQueue = _defaultRunTaskCompletionQueue, completion completionHandler: ((V!, ErrorType?) -> Void)? = nil) {
queue.addOperationWithBlock {
do {
let value = try task.waitForCompletionAndReturnValue()
if let completionHandler = completionHandler {
completionQueue.addOperationWithBlock {
completionHandler(value, nil)
}
}
}
catch let error {
if let completionHandler = completionHandler {
completionQueue.addOperationWithBlock {
completionHandler(nil, error)
}
}
}
}
}
// MARK: - await - non failable task
public func await<V>(@noescape closure: () -> NonFailableTask<V>) -> V {
return closure().waitForCompletionAndReturnValue()
}
public func await<V>(task: NonFailableTask<V>) -> V {
return task.waitForCompletionAndReturnValue()
}
public func runTask<V>(task: NonFailableTask<V>, queue: NSOperationQueue = _defaultRunTaskQueue, completionQueue: NSOperationQueue = _defaultRunTaskCompletionQueue, completion completionHandler: ((V) -> Void)? = nil) {
queue.addOperationWithBlock {
let value = task.waitForCompletionAndReturnValue()
if let completionHandler = completionHandler {
completionQueue.addOperationWithBlock {
completionHandler(value)
}
}
}
}
| eaa94b223cda1866a712a9fdc5f13657 | 33.558685 | 220 | 0.660101 | false | false | false | false |
1457792186/JWSwift | refs/heads/4.x | ARHome/Pods/Alamofire/Source/TaskDelegate.swift | apache-2.0 | 111 | //
// TaskDelegate.swift
//
// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
/// executing all operations attached to the serial operation queue upon task completion.
open class TaskDelegate: NSObject {
// MARK: Properties
/// The serial operation queue used to execute all operations after the task completes.
open let queue: OperationQueue
/// The data returned by the server.
public var data: Data? { return nil }
/// The error generated throughout the lifecyle of the task.
public var error: Error?
var task: URLSessionTask? {
set {
taskLock.lock(); defer { taskLock.unlock() }
_task = newValue
}
get {
taskLock.lock(); defer { taskLock.unlock() }
return _task
}
}
var initialResponseTime: CFAbsoluteTime?
var credential: URLCredential?
var metrics: AnyObject? // URLSessionTaskMetrics
private var _task: URLSessionTask? {
didSet { reset() }
}
private let taskLock = NSLock()
// MARK: Lifecycle
init(task: URLSessionTask?) {
_task = task
self.queue = {
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.isSuspended = true
operationQueue.qualityOfService = .utility
return operationQueue
}()
}
func reset() {
error = nil
initialResponseTime = nil
}
// MARK: URLSessionTaskDelegate
var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)?
@objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
var redirectRequest: URLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
@objc(URLSession:task:didReceiveChallenge:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if
let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
let serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
disposition = .useCredential
credential = URLCredential(trust: serverTrust)
} else {
disposition = .cancelAuthenticationChallenge
}
}
} else {
if challenge.previousFailureCount > 0 {
disposition = .rejectProtectionSpace
} else {
credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
completionHandler(disposition, credential)
}
@objc(URLSession:task:needNewBodyStream:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
{
var bodyStream: InputStream?
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
bodyStream = taskNeedNewBodyStream(session, task)
}
completionHandler(bodyStream)
}
@objc(URLSession:task:didCompleteWithError:)
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let taskDidCompleteWithError = taskDidCompleteWithError {
taskDidCompleteWithError(session, task, error)
} else {
if let error = error {
if self.error == nil { self.error = error }
if
let downloadDelegate = self as? DownloadTaskDelegate,
let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data
{
downloadDelegate.resumeData = resumeData
}
}
queue.isSuspended = false
}
}
}
// MARK: -
class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate {
// MARK: Properties
var dataTask: URLSessionDataTask { return task as! URLSessionDataTask }
override var data: Data? {
if dataStream != nil {
return nil
} else {
return mutableData
}
}
var progress: Progress
var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
var dataStream: ((_ data: Data) -> Void)?
private var totalBytesReceived: Int64 = 0
private var mutableData: Data
private var expectedContentLength: Int64?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
mutableData = Data()
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
progress = Progress(totalUnitCount: 0)
totalBytesReceived = 0
mutableData = Data()
expectedContentLength = nil
}
// MARK: URLSessionDataDelegate
var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
{
var disposition: URLSession.ResponseDisposition = .allow
expectedContentLength = response.expectedContentLength
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome downloadTask: URLSessionDownloadTask)
{
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
if let dataStream = dataStream {
dataStream(data)
} else {
mutableData.append(data)
}
let bytesReceived = Int64(data.count)
totalBytesReceived += bytesReceived
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
progress.totalUnitCount = totalBytesExpected
progress.completedUnitCount = totalBytesReceived
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: @escaping (CachedURLResponse?) -> Void)
{
var cachedResponse: CachedURLResponse? = proposedResponse
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
// MARK: -
class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate {
// MARK: Properties
var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask }
var progress: Progress
var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
var resumeData: Data?
override var data: Data? { return resumeData }
var destination: DownloadRequest.DownloadFileDestination?
var temporaryURL: URL?
var destinationURL: URL?
var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL }
// MARK: Lifecycle
override init(task: URLSessionTask?) {
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
progress = Progress(totalUnitCount: 0)
resumeData = nil
}
// MARK: URLSessionDownloadDelegate
var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)?
var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL)
{
temporaryURL = location
guard
let destination = destination,
let response = downloadTask.response as? HTTPURLResponse
else { return }
let result = destination(location, response)
let destinationURL = result.destinationURL
let options = result.options
self.destinationURL = destinationURL
do {
if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) {
try FileManager.default.removeItem(at: destinationURL)
}
if options.contains(.createIntermediateDirectories) {
let directory = destinationURL.deletingLastPathComponent()
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
try FileManager.default.moveItem(at: location, to: destinationURL)
} catch {
self.error = error
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(
session,
downloadTask,
bytesWritten,
totalBytesWritten,
totalBytesExpectedToWrite
)
} else {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
// MARK: -
class UploadTaskDelegate: DataTaskDelegate {
// MARK: Properties
var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask }
var uploadProgress: Progress
var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
uploadProgress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
uploadProgress = Progress(totalUnitCount: 0)
}
// MARK: URLSessionTaskDelegate
var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
func URLSession(
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else {
uploadProgress.totalUnitCount = totalBytesExpectedToSend
uploadProgress.completedUnitCount = totalBytesSent
if let uploadProgressHandler = uploadProgressHandler {
uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) }
}
}
}
}
| 20c8e651c2ef1d01ae7376eeaa51bd3a | 32.922747 | 149 | 0.662323 | false | false | false | false |
tangbing/swift_budejie | refs/heads/master | swift_budejie/classes/Other/Tool/NetworkTools.swift | mit | 1 |
//
// NetworkTools.swift
// swift_budejie
//
// Created by mac on 2017/7/20.
// Copyright © 2017年 macTb. All rights reserved.
//
import UIKit
//import Alamofire
//import SwiftyJSON
enum MethodType{
case get
case post
}
class NetworkTools {
// class func requestData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping (_ result : Any) -> ()) {
//
// // 1.获取类型
// let method = type == .get ? HTTPMethod.get : HTTPMethod.post
//
// // 2.发送网络请求
// Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
//
// // 3.获取结果
// // guard 如果条件不符合,执行else后的语句块
// guard let result = response.result.value else {
// print(response.result.error!)
// return
// }
// let swiftJson = JSON(result)
// // 4.将结果回调出去
// finishedCallback(swiftJson)
// }
// }
}
| 9b02bdd7f915d91a449ad6fc0c3144ba | 25.358974 | 161 | 0.546693 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.