repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
iOS-mamu/SS | P/Pods/ICSPullToRefresh/ICSPullToRefresh/ICSPullToRefresh.swift | 3 | 9156 | //
// ICSPullToRefresh.swift
// ICSPullToRefresh
//
// Created by LEI on 3/15/15.
// Copyright (c) 2015 TouchingAPP. All rights reserved.
//
import UIKit
private var pullToRefreshViewKey: Void?
public typealias ActionHandler = () -> ()
fileprivate struct Constants {
static let observeKeyContentOffset = "contentOffset"
static let observeKeyFrame = "frame"
static let pullToRefreshViewValueKey = "ICSPullToRefreshView"
static let pullToRefreshViewHeight: CGFloat = 60
}
public extension UIScrollView{
public var pullToRefreshView: PullToRefreshView? {
get {
return objc_getAssociatedObject(self, &pullToRefreshViewKey) as? PullToRefreshView
}
set(newValue) {
willChangeValue(forKey: Constants.pullToRefreshViewValueKey)
objc_setAssociatedObject(self, &pullToRefreshViewKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
didChangeValue(forKey: Constants.pullToRefreshViewValueKey)
}
}
public var showsPullToRefresh: Bool {
guard let pullToRefreshView = pullToRefreshView else {
return false
}
return !pullToRefreshView.isHidden
}
public func addPullToRefreshHandler(_ actionHandler: @escaping ActionHandler){
if pullToRefreshView == nil {
pullToRefreshView = PullToRefreshView(frame: CGRect(x: CGFloat(0), y: -Constants.pullToRefreshViewHeight, width: self.bounds.width, height: Constants.pullToRefreshViewHeight))
addSubview(pullToRefreshView!)
pullToRefreshView?.autoresizingMask = .flexibleWidth
pullToRefreshView?.scrollViewOriginContentTopInset = contentInset.top
}
pullToRefreshView?.actionHandler = actionHandler
setShowsPullToRefresh(true)
}
public func triggerPullToRefresh() {
pullToRefreshView?.state = .triggered
pullToRefreshView?.startAnimating()
}
public func setShowsPullToRefresh(_ showsPullToRefresh: Bool) {
guard let pullToRefreshView = pullToRefreshView else {
return
}
pullToRefreshView.isHidden = !showsPullToRefresh
if showsPullToRefresh {
addPullToRefreshObservers()
}else{
removePullToRefreshObservers()
}
}
func addPullToRefreshObservers() {
guard let pullToRefreshView = pullToRefreshView, !pullToRefreshView.isObserving else {
return
}
addObserver(pullToRefreshView, forKeyPath: Constants.observeKeyContentOffset, options:.new, context: nil)
addObserver(pullToRefreshView, forKeyPath: Constants.observeKeyFrame, options:.new, context: nil)
pullToRefreshView.isObserving = true
}
func removePullToRefreshObservers() {
guard let pullToRefreshView = pullToRefreshView, pullToRefreshView.isObserving else {
return
}
removeObserver(pullToRefreshView, forKeyPath: Constants.observeKeyContentOffset)
removeObserver(pullToRefreshView, forKeyPath: Constants.observeKeyFrame)
pullToRefreshView.isObserving = false
}
}
open class PullToRefreshView: UIView {
open var actionHandler: ActionHandler?
open var isObserving: Bool = false
var triggeredByUser: Bool = false
open var scrollView: UIScrollView? {
return self.superview as? UIScrollView
}
open var scrollViewOriginContentTopInset: CGFloat = 0
public enum State {
case stopped
case triggered
case loading
case all
}
open var state: State = .stopped {
willSet {
if state != newValue {
self.setNeedsLayout()
switch newValue{
case .loading:
setScrollViewContentInsetForLoading()
if state == .triggered {
actionHandler?()
}
default:
break
}
}
}
didSet {
switch state {
case .stopped:
resetScrollViewContentInset()
default:
break
}
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
initViews()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initViews()
}
open func startAnimating() {
if scrollView == nil {
return
}
animate {
guard let scrollView = self.scrollView else {
return
}
scrollView.setContentOffset(CGPoint(
x: scrollView.contentOffset.x,
y: -(scrollView.contentInset.top + self.bounds.height)
), animated: false)
}
triggeredByUser = true
state = .loading
}
open func stopAnimating() {
state = .stopped
if triggeredByUser {
animate {
guard let scrollView = self.scrollView else {
return
}
scrollView.setContentOffset(CGPoint(
x: scrollView.contentOffset.x,
y: -scrollView.contentInset.top
), animated: false)
}
}
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == Constants.observeKeyContentOffset {
srollViewDidScroll((change?[NSKeyValueChangeKey.newKey] as AnyObject).cgPointValue)
} else if keyPath == Constants.observeKeyFrame {
setNeedsLayout()
}
}
fileprivate func srollViewDidScroll(_ contentOffset: CGPoint?) {
guard let scrollView = scrollView, let contentOffset = contentOffset else {
return
}
guard state != .loading else {
return
}
let scrollOffsetThreshold = frame.origin.y - scrollViewOriginContentTopInset
if !scrollView.isDragging && state == .triggered {
state = .loading
} else if contentOffset.y < scrollOffsetThreshold && scrollView.isDragging && state == .stopped {
state = .triggered
} else if contentOffset.y >= scrollOffsetThreshold && state != .stopped {
state = .stopped
}
}
fileprivate func setScrollViewContentInset(_ contentInset: UIEdgeInsets) {
animate {
self.scrollView?.contentInset = contentInset
}
}
fileprivate func resetScrollViewContentInset() {
guard let scrollView = scrollView else {
return
}
var currentInset = scrollView.contentInset
currentInset.top = scrollViewOriginContentTopInset
setScrollViewContentInset(currentInset)
}
fileprivate func setScrollViewContentInsetForLoading() {
guard let scrollView = scrollView else {
return
}
let offset = max(scrollView.contentOffset.y * -1, 0)
var currentInset = scrollView.contentInset
currentInset.top = min(offset, scrollViewOriginContentTopInset + bounds.height)
setScrollViewContentInset(currentInset)
}
fileprivate func animate(_ animations: @escaping () -> ()) {
UIView.animate(withDuration: 0.3,
delay: 0,
options: [.allowUserInteraction, .beginFromCurrentState],
animations: animations
) { _ in
self.setNeedsLayout()
}
}
open override func layoutSubviews() {
super.layoutSubviews()
defaultView.frame = bounds
activityIndicator.center = defaultView.center
switch state {
case .stopped:
activityIndicator.stopAnimating()
case .loading:
activityIndicator.startAnimating()
default:
break
}
}
open override func willMove(toSuperview newSuperview: UIView?) {
guard newSuperview == nil, let _ = superview, let showsPullToRefresh = scrollView?.showsPullToRefresh, showsPullToRefresh else {
return
}
scrollView?.removePullToRefreshObservers()
}
// MARK: Basic Views
func initViews() {
addSubview(defaultView)
defaultView.addSubview(activityIndicator)
}
lazy var defaultView: UIView = {
let view = UIView()
return view
}()
lazy var activityIndicator: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
activityIndicator.hidesWhenStopped = false
return activityIndicator
}()
open func setActivityIndicatorColor(_ color: UIColor) {
activityIndicator.color = color
}
open func setActivityIndicatorStyle(_ style: UIActivityIndicatorViewStyle) {
activityIndicator.activityIndicatorViewStyle = style
}
}
| mit | f917e90a3a4e92105ac5ee3ecd52f549 | 30.902439 | 187 | 0.616863 | 6.047556 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/EditLinkViewController.swift | 2 | 10242 | import UIKit
protocol EditLinkViewControllerDelegate: AnyObject {
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didTapCloseButton button: UIBarButtonItem)
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didFinishEditingLink displayText: String?, linkTarget: String)
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didFailToExtractArticleTitleFromArticleURL articleURL: URL)
func editLinkViewControllerDidRemoveLink(_ editLinkViewController: EditLinkViewController)
}
class EditLinkViewController: ViewController {
weak var delegate: EditLinkViewControllerDelegate?
typealias Link = SectionEditorWebViewMessagingController.Link
private let link: Link
private let siteURL: URL
private var articleURL: URL
private let articleCell = ArticleRightAlignedImageCollectionViewCell()
private let dataStore: MWKDataStore
private var navigationBarVisibleHeightObservation: NSKeyValueObservation?
@IBOutlet private weak var contentView: UIView!
@IBOutlet private weak var scrollViewTopConstraint: NSLayoutConstraint!
@IBOutlet private weak var displayTextLabel: UILabel!
@IBOutlet private weak var displayTextView: UITextView!
@IBOutlet private weak var displayTextViewHeightConstraint: NSLayoutConstraint!
@IBOutlet private weak var linkTargetLabel: UILabel!
@IBOutlet private weak var linkTargetContainerView: UIView!
@IBOutlet private weak var linkTargetContainerViewHeightConstraint: NSLayoutConstraint!
@IBOutlet private weak var activityIndicatorView: UIActivityIndicatorView!
@IBOutlet private weak var removeLinkButton: AutoLayoutSafeMultiLineButton!
@IBOutlet private var separatorViews: [UIView] = []
private lazy var closeButton: UIBarButtonItem = {
let closeButton = UIBarButtonItem.wmf_buttonType(.X, target: self, action: #selector(close(_:)))
closeButton.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
return closeButton
}()
private lazy var doneButton = UIBarButtonItem(title: CommonStrings.doneTitle, style: .done, target: self, action: #selector(finishEditing(_:)))
init?(link: Link, siteURL: URL?, dataStore: MWKDataStore) {
guard
let siteURL = siteURL ?? MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL() ?? NSURL.wmf_URLWithDefaultSiteAndCurrentLocale(),
let articleURL = link.articleURL(for: siteURL)
else {
return nil
}
self.link = link
self.siteURL = siteURL
self.articleURL = articleURL
self.dataStore = dataStore
super.init(nibName: "EditLinkViewController", bundle: nil)
}
deinit {
navigationBarVisibleHeightObservation?.invalidate()
navigationBarVisibleHeightObservation = nil
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.displayType = .modal
title = CommonStrings.editLinkTitle
navigationItem.leftBarButtonItem = closeButton
navigationItem.rightBarButtonItem = doneButton
navigationItem.backBarButtonItem = UIBarButtonItem(title: CommonStrings.accessibilityBackTitle, style: .plain, target: nil, action: nil)
var textContainerInset = displayTextView.textContainerInset
textContainerInset.top = 15
displayTextLabel.text = WMFLocalizedString("edit-link-display-text-title", value: "Display text", comment: "Title for the display text label")
displayTextView.textContainerInset = textContainerInset
displayTextView.textContainer.lineFragmentPadding = 0
displayTextView.text = link.label ?? link.page
linkTargetLabel.text = WMFLocalizedString("edit-link-link-target-title", value: "Link target", comment: "Title for the link target label")
removeLinkButton.setTitle(WMFLocalizedString("edit-link-remove-link-title", value: "Remove link", comment: "Title for the remove link button"), for: .normal)
articleCell.isHidden = true
linkTargetContainerView.addSubview(articleCell)
navigationBarVisibleHeightObservation = navigationBar.observe(\.visibleHeight, options: [.new, .initial], changeHandler: { [weak self] (observation, change) in
guard let self = self else {
return
}
self.scrollViewTopConstraint.constant = self.navigationBar.visibleHeight
})
updateFonts()
apply(theme: theme)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchArticle()
}
private func fetchArticle() {
guard let article = dataStore.fetchArticle(with: articleURL) else {
guard let key = articleURL.wmf_databaseKey else {
return
}
dataStore.articleSummaryController.updateOrCreateArticleSummaryForArticle(withKey: key) { (article, _) in
guard let article = article else {
return
}
self.updateView(with: article)
}
return
}
updateView(with: article)
}
private func updateView(with article: WMFArticle) {
articleCell.configure(article: article, displayType: .compactList, index: 0, theme: theme, layoutOnly: false)
articleCell.topSeparator.isHidden = true
articleCell.bottomSeparator.isHidden = true
articleCell.extractLabel?.numberOfLines = 5
updateLinkTargetContainer()
articleCell.isHidden = false
activityIndicatorView.stopAnimating()
view.setNeedsLayout()
}
private func updateLinkTargetContainer() {
articleCell.frame = CGRect(origin: linkTargetContainerView.bounds.origin, size: articleCell.sizeThatFits(CGSize(width: linkTargetContainerView.bounds.width, height: UIView.noIntrinsicMetric), apply: true))
linkTargetContainerViewHeightConstraint.constant = articleCell.frame.height
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateFonts()
}
private func updateFonts() {
displayTextLabel.font = UIFont.wmf_font(.footnote, compatibleWithTraitCollection: traitCollection)
linkTargetLabel.font = UIFont.wmf_font(.footnote, compatibleWithTraitCollection: traitCollection)
displayTextView.font = UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection)
removeLinkButton.titleLabel?.font = UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection)
}
@objc private func close(_ sender: UIBarButtonItem) {
delegate?.editLinkViewController(self, didTapCloseButton: sender)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
displayTextViewHeightConstraint.constant = displayTextView.sizeThatFits(CGSize(width: displayTextView.bounds.width, height: UIView.noIntrinsicMetric)).height
updateLinkTargetContainer()
}
@objc private func finishEditing(_ sender: UIBarButtonItem) {
let displayText = displayTextView.text
guard let linkTarget = articleURL.wmf_title else {
assertionFailure("Failed to extract article title from url: \(articleURL)")
delegate?.editLinkViewController(self, didFailToExtractArticleTitleFromArticleURL: articleURL)
return
}
delegate?.editLinkViewController(self, didFinishEditingLink: displayText, linkTarget: linkTarget)
}
@IBAction private func removeLink(_ sender: UIButton) {
delegate?.editLinkViewControllerDidRemoveLink(self)
}
@IBAction private func searchArticles(_ sender: UITapGestureRecognizer) {
let searchViewController = SearchViewController()
searchViewController.shouldSetTitleViewWhenRecentSearchesAreDisabled = false
searchViewController.siteURL = siteURL
searchViewController.shouldSetSearchVisible = false
searchViewController.shouldBecomeFirstResponder = true
searchViewController.displayType = .backVisible
searchViewController.areRecentSearchesEnabled = false
searchViewController.dataStore = SessionSingleton.sharedInstance()?.dataStore
searchViewController.shouldShowCancelButton = false
searchViewController.delegate = self
searchViewController.delegatesSelection = true
searchViewController.showLanguageBar = false
searchViewController.navigationItem.title = title
searchViewController.searchTerm = articleURL.wmf_title
searchViewController.search()
searchViewController.apply(theme: theme)
navigationController?.pushViewController(searchViewController, animated: true)
}
override func apply(theme: Theme) {
super.apply(theme: theme)
self.theme = theme
guard viewIfLoaded != nil else {
return
}
contentView.backgroundColor = theme.colors.paperBackground
view.backgroundColor = theme.colors.baseBackground
separatorViews.forEach { $0.backgroundColor = theme.colors.border }
displayTextLabel.textColor = theme.colors.secondaryText
linkTargetLabel.textColor = theme.colors.secondaryText
removeLinkButton.tintColor = theme.colors.destructive
removeLinkButton.backgroundColor = theme.colors.paperBackground
closeButton.tintColor = theme.colors.primaryText
doneButton.tintColor = theme.colors.link
displayTextView.textColor = theme.colors.primaryText
activityIndicatorView.style = theme.isDark ? .white : .gray
}
}
extension EditLinkViewController: ArticleCollectionViewControllerDelegate {
func articleCollectionViewController(_ articleCollectionViewController: ArticleCollectionViewController, didSelectArticleWith articleURL: URL, at indexPath: IndexPath) {
self.articleURL = articleURL
navigationController?.popViewController(animated: true)
}
}
| mit | b7f3b83d6dea19aae56edccec8350ce2 | 47.311321 | 213 | 0.730033 | 5.849229 | false | false | false | false |
NewBeeInc/Tictoc | Tests/Tictoc/TictocTests.swift | 1 | 1316 | import XCTest
@testable import Tictoc
class TictocTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
XCTAssertTrue(tNow >= tToday.lowerBound)
XCTAssertTrue(tNow < tToday.upperBound)
XCTAssertTrue(Double(tNow) <= tMoment)
XCTAssertTrue(tNow >= tYesterday.upperBound)
XCTAssertTrue(tNow < tTomorrow.lowerBound)
XCTAssertTrue(tYesterday.upperBound < tTomorrow.lowerBound)
XCTAssertTrue(Tictoc.dayFromShortDate("2016-06-22")?.upperBound <= tToday.upperBound)
XCTAssertTrue(Tictoc.dayFromShortDate("2016-06-22")?.lowerBound <= tToday.lowerBound)
XCTAssertTrue(Tictoc.isTheDayToday(tToday))
XCTAssertFalse(Tictoc.isTheDayToday(tTomorrow))
XCTAssertFalse(Tictoc.isTheDayToday(tYesterday))
XCTAssertTrue(Tictoc.isToday(tNow))
XCTAssertFalse(Tictoc.isTomorrow(tNow))
XCTAssertTrue(Tictoc.dayFromShortDate(tNow.toDateShort()) == tToday)
print(tNow.toDateShort())
print(tNow.toTimeShort())
print(tNow.toDateFull())
print(tMoment.toMomentShort())
print(tMoment.toMomentFull())
}
static var allTests : [(String, (TictocTests) -> () throws -> Void)] {
return [
("testExample", testExample),
]
}
}
| apache-2.0 | 9eff0cde1fcd417483548aa13ab09c9d | 32.74359 | 96 | 0.731763 | 3.585831 | false | true | false | false |
Aazure/Mr-Ride-iOS | Mr-Ride-iOS/Mr-Ride-iOS/Model/Core Data/Route.swift | 1 | 1019 | //
// Route.swift
// Mr-Ride-iOS
//
// Created by Allegretto on 2016/6/3.
// Copyright © 2016年 AppWorks School Jocy Hsiao. All rights reserved.
//
import Foundation
import CoreData
class Route: NSManagedObject {
class func add(moc: NSManagedObjectContext, created: NSDate, latitude: Double, longitude: Double){
let route = NSEntityDescription.insertNewObjectForEntityForName("Route", inManagedObjectContext: moc) as! Route
route.created = created
route.latitude = latitude
route.longitude = longitude
do{
try moc.save()
}catch{
fatalError("Failure to save context \(error)")
}
}
class func getAllLocation(moc: NSManagedObjectContext) -> [Route]{
let request = NSFetchRequest(entityName: "Route")
do{
return try moc.executeFetchRequest(request) as! [Route]
}catch{
fatalError("Failed to fetch data: \(error)")
}
}
}
| mit | a241b83775ffafe3303eee13c06ea18b | 25.051282 | 119 | 0.610236 | 4.703704 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Swift/Classes/Extension/UIDevice+Extension.swift | 1 | 3837 | //
// UIDevice+Extension.swift
// Example
//
// Created by Slience on 2021/1/13.
//
import UIKit
extension UIDevice {
class var isPortrait: Bool {
let orientation = UIApplication.shared.statusBarOrientation
if orientation == .landscapeLeft ||
orientation == .landscapeRight {
return false
}
return true
}
class var navigationBarHeight: CGFloat {
statusBarHeight + 44
}
class var statusBarHeight: CGFloat {
let statusBarHeight: CGFloat
let window = UIApplication.shared.windows.first
if #available(iOS 13.0, *) {
statusBarHeight = (window?.windowScene?.statusBarManager?.statusBarFrame.size.height)!
} else {
statusBarHeight = UIApplication.shared.statusBarFrame.size.height
}
return statusBarHeight
}
class var topMargin: CGFloat {
if isAllIPhoneX {
return statusBarHeight
}
return 0
}
class var leftMargin: CGFloat {
if isAllIPhoneX {
if !isPortrait {
return 44
}
}
return 0
}
class var rightMargin: CGFloat {
if isAllIPhoneX {
if !isPortrait {
return 44
}
}
return 0
}
class var bottomMargin: CGFloat {
if isAllIPhoneX {
if isPortrait {
return 34
}else {
return 21
}
}
return 0
}
class var isPad: Bool {
current.userInterfaceIdiom == .pad
}
class var isAllIPhoneX: Bool {
isIPhoneX ||
isIPhoneXR ||
isIPhoneXsMax ||
isIPhoneXsMax ||
isIPhoneTwelveMini ||
isIPhoneTwelve ||
isIPhoneTwelveProMax
}
class var isIPhoneX: Bool {
if UIScreen.instancesRespond(to: Selector(("currentMode"))) == true &&
isPad == false {
if __CGSizeEqualToSize(CGSize(width: 1125, height: 2436), UIScreen.main.currentMode!.size) {
return true
}
}
return false
}
class var isIPhoneXR: Bool {
if UIScreen.instancesRespond(to: Selector(("currentMode"))) == true &&
isPad == false {
if __CGSizeEqualToSize(CGSize(width: 828, height: 1792), UIScreen.main.currentMode!.size) {
return true
}
}
return false
}
class var isIPhoneXsMax: Bool {
if UIScreen.instancesRespond(to: Selector(("currentMode"))) == true &&
isPad == false {
if __CGSizeEqualToSize(CGSize(width: 1242, height: 2688), UIScreen.main.currentMode!.size) {
return true
}
}
return false
}
class var isIPhoneTwelveMini: Bool {
if UIScreen.instancesRespond(to: Selector(("currentMode"))) == true &&
isPad == false {
if __CGSizeEqualToSize(CGSize(width: 1080, height: 2340), UIScreen.main.currentMode!.size) {
return true
}
}
return false
}
class var isIPhoneTwelve: Bool {
if UIScreen.instancesRespond(to: Selector(("currentMode"))) == true &&
isPad == false {
if __CGSizeEqualToSize(CGSize(width: 1170, height: 2532), UIScreen.main.currentMode!.size) {
return true
}
}
return false
}
class var isIPhoneTwelveProMax: Bool {
if UIScreen.instancesRespond(to: Selector(("currentMode"))) == true &&
isPad == false {
if __CGSizeEqualToSize(CGSize(width: 1284, height: 2778), UIScreen.main.currentMode!.size) {
return true
}
}
return false
}
}
| mit | 8ccb484589c6dedc18e8907d8d493487 | 28.515385 | 104 | 0.538181 | 5.04205 | false | false | false | false |
omniprog/SwiftZSTD | Sources/ZSTDProcessor.swift | 1 | 3200 | //
// ZSTDProcessor.swift
//
// Created by Anatoli on 12/06/16.
// Copyright © 2016 Anatoli Peredera. All rights reserved.
//
import Foundation
/**
* Class that supports compression/decompression of an in-memory buffer without using
* a dictionary. A compression/decompression context can be used optionally to speed
* up processing of multiple buffers.
*/
public class ZSTDProcessor
{
let commonProcessor : ZSTDProcessorCommon
var currentCL : Int32 = 0
/**
* Initializer.
*
* - paremeter useContext : true if use of context is desired
*/
public init(useContext : Bool = false)
{
commonProcessor = ZSTDProcessorCommon(useContext: useContext)
}
/**
* Compress a buffer. Input is sent to the C API without copying by using the
* Data.withUnsafeBytes() method. The C API places the output straight into the newly-
* created Data instance, which is possible because there are no other references
* to the instance at this point, so calling withUnsafeMutableBytes() does not trigger
* a copy-on-write.
*
* - parameter dataIn : input Data
* - parameter compressionLevel : must be 1-22, levels >= 20 to be used with caution
* - returns: compressed frame
*/
public func compressBuffer(_ dataIn : Data, compressionLevel : Int32) throws -> Data
{
guard isValidCompressionLevel(compressionLevel) else {
throw ZSTDError.invalidCompressionLevel(cl: compressionLevel)
}
currentCL = compressionLevel
return try commonProcessor.compressBufferCommon(dataIn, compressFrameHelper)
}
/**
* A private helper passed to commonProcessor.compressBufferCommon().
*/
private func compressFrameHelper(dst : UnsafeMutableRawPointer,
dstCapacity : Int,
src : UnsafeRawPointer,
srcSize : Int) -> Int {
if commonProcessor.compCtx != nil {
return ZSTD_compressCCtx(commonProcessor.compCtx, dst, dstCapacity, src, srcSize, currentCL);
} else {
return ZSTD_compress(dst, dstCapacity, src, srcSize, currentCL)
}
}
/**
* Decompress a frame that resulted from a previous compression of a buffer by a call
* to compressBuffer().
*
* - parameter dataIn: frame to be decompressed
* - returns: a Data instance wrapping the decompressed buffer
*/
public func decompressFrame(_ dataIn : Data) throws -> Data
{
return try commonProcessor.decompressFrameCommon(dataIn, decompressFrameHelper)
}
/**
* A private helper passed to commonProcessor.decompressFrameCommon().
*/
private func decompressFrameHelper(dst : UnsafeMutableRawPointer,
dstCapacity : Int,
src : UnsafeRawPointer, srcSize : Int) -> Int {
if commonProcessor.decompCtx != nil {
return ZSTD_decompressDCtx(commonProcessor.decompCtx, dst, dstCapacity, src, srcSize);
} else {
return ZSTD_decompress(dst, dstCapacity, src, srcSize)
}
}
}
| bsd-3-clause | 1895766c54e55623aa4e5b29b8d567bf | 34.94382 | 105 | 0.6402 | 4.676901 | false | false | false | false |
JGiola/swift-corelibs-foundation | Foundation/NSURL.swift | 1 | 60245 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
#if os(macOS) || os(iOS)
internal let kCFURLPOSIXPathStyle = CFURLPathStyle.cfurlposixPathStyle
internal let kCFURLWindowsPathStyle = CFURLPathStyle.cfurlWindowsPathStyle
#endif
private func _standardizedPath(_ path: String) -> String {
if !path.absolutePath {
return path._nsObject.standardizingPath
}
return path
}
internal func _pathComponents(_ path: String?) -> [String]? {
guard let p = path else {
return nil
}
var result = [String]()
if p.length == 0 {
return result
} else {
let characterView = p
var curPos = characterView.startIndex
let endPos = characterView.endIndex
if characterView[curPos] == "/" {
result.append("/")
}
while curPos < endPos {
while curPos < endPos && characterView[curPos] == "/" {
curPos = characterView.index(after: curPos)
}
if curPos == endPos {
break
}
var curEnd = curPos
while curEnd < endPos && characterView[curEnd] != "/" {
curEnd = characterView.index(after: curEnd)
}
result.append(String(characterView[curPos ..< curEnd]))
curPos = curEnd
}
}
if p.length > 1 && p.hasSuffix("/") {
result.append("/")
}
return result
}
public struct URLResourceKey : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(lhs: URLResourceKey, rhs: URLResourceKey) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension URLResourceKey {
public static let keysOfUnsetValuesKey = URLResourceKey(rawValue: "NSURLKeysOfUnsetValuesKey")
public static let nameKey = URLResourceKey(rawValue: "NSURLNameKey")
public static let localizedNameKey = URLResourceKey(rawValue: "NSURLLocalizedNameKey")
public static let isRegularFileKey = URLResourceKey(rawValue: "NSURLIsRegularFileKey")
public static let isDirectoryKey = URLResourceKey(rawValue: "NSURLIsDirectoryKey")
public static let isSymbolicLinkKey = URLResourceKey(rawValue: "NSURLIsSymbolicLinkKey")
public static let isVolumeKey = URLResourceKey(rawValue: "NSURLIsVolumeKey")
public static let isPackageKey = URLResourceKey(rawValue: "NSURLIsPackageKey")
public static let isApplicationKey = URLResourceKey(rawValue: "NSURLIsApplicationKey")
public static let applicationIsScriptableKey = URLResourceKey(rawValue: "NSURLApplicationIsScriptableKey")
public static let isSystemImmutableKey = URLResourceKey(rawValue: "NSURLIsSystemImmutableKey")
public static let isUserImmutableKey = URLResourceKey(rawValue: "NSURLIsUserImmutableKey")
public static let isHiddenKey = URLResourceKey(rawValue: "NSURLIsHiddenKey")
public static let hasHiddenExtensionKey = URLResourceKey(rawValue: "NSURLHasHiddenExtensionKey")
public static let creationDateKey = URLResourceKey(rawValue: "NSURLCreationDateKey")
public static let contentAccessDateKey = URLResourceKey(rawValue: "NSURLContentAccessDateKey")
public static let contentModificationDateKey = URLResourceKey(rawValue: "NSURLContentModificationDateKey")
public static let attributeModificationDateKey = URLResourceKey(rawValue: "NSURLAttributeModificationDateKey")
public static let linkCountKey = URLResourceKey(rawValue: "NSURLLinkCountKey")
public static let parentDirectoryURLKey = URLResourceKey(rawValue: "NSURLParentDirectoryURLKey")
public static let volumeURLKey = URLResourceKey(rawValue: "NSURLVolumeURLKey")
public static let typeIdentifierKey = URLResourceKey(rawValue: "NSURLTypeIdentifierKey")
public static let localizedTypeDescriptionKey = URLResourceKey(rawValue: "NSURLLocalizedTypeDescriptionKey")
public static let labelNumberKey = URLResourceKey(rawValue: "NSURLLabelNumberKey")
public static let labelColorKey = URLResourceKey(rawValue: "NSURLLabelColorKey")
public static let localizedLabelKey = URLResourceKey(rawValue: "NSURLLocalizedLabelKey")
public static let effectiveIconKey = URLResourceKey(rawValue: "NSURLEffectiveIconKey")
public static let customIconKey = URLResourceKey(rawValue: "NSURLCustomIconKey")
public static let fileResourceIdentifierKey = URLResourceKey(rawValue: "NSURLFileResourceIdentifierKey")
public static let volumeIdentifierKey = URLResourceKey(rawValue: "NSURLVolumeIdentifierKey")
public static let preferredIOBlockSizeKey = URLResourceKey(rawValue: "NSURLPreferredIOBlockSizeKey")
public static let isReadableKey = URLResourceKey(rawValue: "NSURLIsReadableKey")
public static let isWritableKey = URLResourceKey(rawValue: "NSURLIsWritableKey")
public static let isExecutableKey = URLResourceKey(rawValue: "NSURLIsExecutableKey")
public static let fileSecurityKey = URLResourceKey(rawValue: "NSURLFileSecurityKey")
public static let isExcludedFromBackupKey = URLResourceKey(rawValue: "NSURLIsExcludedFromBackupKey")
public static let tagNamesKey = URLResourceKey(rawValue: "NSURLTagNamesKey")
public static let pathKey = URLResourceKey(rawValue: "NSURLPathKey")
public static let canonicalPathKey = URLResourceKey(rawValue: "NSURLCanonicalPathKey")
public static let isMountTriggerKey = URLResourceKey(rawValue: "NSURLIsMountTriggerKey")
public static let generationIdentifierKey = URLResourceKey(rawValue: "NSURLGenerationIdentifierKey")
public static let documentIdentifierKey = URLResourceKey(rawValue: "NSURLDocumentIdentifierKey")
public static let addedToDirectoryDateKey = URLResourceKey(rawValue: "NSURLAddedToDirectoryDateKey")
public static let quarantinePropertiesKey = URLResourceKey(rawValue: "NSURLQuarantinePropertiesKey")
public static let fileResourceTypeKey = URLResourceKey(rawValue: "NSURLFileResourceTypeKey")
public static let thumbnailDictionaryKey = URLResourceKey(rawValue: "NSURLThumbnailDictionaryKey")
public static let thumbnailKey = URLResourceKey(rawValue: "NSURLThumbnailKey")
public static let fileSizeKey = URLResourceKey(rawValue: "NSURLFileSizeKey")
public static let fileAllocatedSizeKey = URLResourceKey(rawValue: "NSURLFileAllocatedSizeKey")
public static let totalFileSizeKey = URLResourceKey(rawValue: "NSURLTotalFileSizeKey")
public static let totalFileAllocatedSizeKey = URLResourceKey(rawValue: "NSURLTotalFileAllocatedSizeKey")
public static let isAliasFileKey = URLResourceKey(rawValue: "NSURLIsAliasFileKey")
public static let volumeLocalizedFormatDescriptionKey = URLResourceKey(rawValue: "NSURLVolumeLocalizedFormatDescriptionKey")
public static let volumeTotalCapacityKey = URLResourceKey(rawValue: "NSURLVolumeTotalCapacityKey")
public static let volumeAvailableCapacityKey = URLResourceKey(rawValue: "NSURLVolumeAvailableCapacityKey")
public static let volumeResourceCountKey = URLResourceKey(rawValue: "NSURLVolumeResourceCountKey")
public static let volumeSupportsPersistentIDsKey = URLResourceKey(rawValue: "NSURLVolumeSupportsPersistentIDsKey")
public static let volumeSupportsSymbolicLinksKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSymbolicLinksKey")
public static let volumeSupportsHardLinksKey = URLResourceKey(rawValue: "NSURLVolumeSupportsHardLinksKey")
public static let volumeSupportsJournalingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsJournalingKey")
public static let volumeIsJournalingKey = URLResourceKey(rawValue: "NSURLVolumeIsJournalingKey")
public static let volumeSupportsSparseFilesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSparseFilesKey")
public static let volumeSupportsZeroRunsKey = URLResourceKey(rawValue: "NSURLVolumeSupportsZeroRunsKey")
public static let volumeSupportsCaseSensitiveNamesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCaseSensitiveNamesKey")
public static let volumeSupportsCasePreservedNamesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCasePreservedNamesKey")
public static let volumeSupportsRootDirectoryDatesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsRootDirectoryDatesKey")
public static let volumeSupportsVolumeSizesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsVolumeSizesKey")
public static let volumeSupportsRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsRenamingKey")
public static let volumeSupportsAdvisoryFileLockingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsAdvisoryFileLockingKey")
public static let volumeSupportsExtendedSecurityKey = URLResourceKey(rawValue: "NSURLVolumeSupportsExtendedSecurityKey")
public static let volumeIsBrowsableKey = URLResourceKey(rawValue: "NSURLVolumeIsBrowsableKey")
public static let volumeMaximumFileSizeKey = URLResourceKey(rawValue: "NSURLVolumeMaximumFileSizeKey")
public static let volumeIsEjectableKey = URLResourceKey(rawValue: "NSURLVolumeIsEjectableKey")
public static let volumeIsRemovableKey = URLResourceKey(rawValue: "NSURLVolumeIsRemovableKey")
public static let volumeIsInternalKey = URLResourceKey(rawValue: "NSURLVolumeIsInternalKey")
public static let volumeIsAutomountedKey = URLResourceKey(rawValue: "NSURLVolumeIsAutomountedKey")
public static let volumeIsLocalKey = URLResourceKey(rawValue: "NSURLVolumeIsLocalKey")
public static let volumeIsReadOnlyKey = URLResourceKey(rawValue: "NSURLVolumeIsReadOnlyKey")
public static let volumeCreationDateKey = URLResourceKey(rawValue: "NSURLVolumeCreationDateKey")
public static let volumeURLForRemountingKey = URLResourceKey(rawValue: "NSURLVolumeURLForRemountingKey")
public static let volumeUUIDStringKey = URLResourceKey(rawValue: "NSURLVolumeUUIDStringKey")
public static let volumeNameKey = URLResourceKey(rawValue: "NSURLVolumeNameKey")
public static let volumeLocalizedNameKey = URLResourceKey(rawValue: "NSURLVolumeLocalizedNameKey")
public static let volumeIsEncryptedKey = URLResourceKey(rawValue: "NSURLVolumeIsEncryptedKey")
public static let volumeIsRootFileSystemKey = URLResourceKey(rawValue: "NSURLVolumeIsRootFileSystemKey")
public static let volumeSupportsCompressionKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCompressionKey")
public static let volumeSupportsFileCloningKey = URLResourceKey(rawValue: "NSURLVolumeSupportsFileCloningKey")
public static let volumeSupportsSwapRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSwapRenamingKey")
public static let volumeSupportsExclusiveRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsExclusiveRenamingKey")
public static let isUbiquitousItemKey = URLResourceKey(rawValue: "NSURLIsUbiquitousItemKey")
public static let ubiquitousItemHasUnresolvedConflictsKey = URLResourceKey(rawValue: "NSURLUbiquitousItemHasUnresolvedConflictsKey")
public static let ubiquitousItemIsDownloadingKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsDownloadingKey")
public static let ubiquitousItemIsUploadedKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsUploadedKey")
public static let ubiquitousItemIsUploadingKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsUploadingKey")
public static let ubiquitousItemDownloadingStatusKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadingStatusKey")
public static let ubiquitousItemDownloadingErrorKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadingErrorKey")
public static let ubiquitousItemUploadingErrorKey = URLResourceKey(rawValue: "NSURLUbiquitousItemUploadingErrorKey")
public static let ubiquitousItemDownloadRequestedKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadRequestedKey")
public static let ubiquitousItemContainerDisplayNameKey = URLResourceKey(rawValue: "NSURLUbiquitousItemContainerDisplayNameKey")
}
public struct URLFileResourceType : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(lhs: URLFileResourceType, rhs: URLFileResourceType) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension URLFileResourceType {
public static let namedPipe = URLFileResourceType(rawValue: "NSURLFileResourceTypeNamedPipe")
public static let characterSpecial = URLFileResourceType(rawValue: "NSURLFileResourceTypeCharacterSpecial")
public static let directory = URLFileResourceType(rawValue: "NSURLFileResourceTypeDirectory")
public static let blockSpecial = URLFileResourceType(rawValue: "NSURLFileResourceTypeBlockSpecial")
public static let regular = URLFileResourceType(rawValue: "NSURLFileResourceTypeRegular")
public static let symbolicLink = URLFileResourceType(rawValue: "NSURLFileResourceTypeSymbolicLink")
public static let socket = URLFileResourceType(rawValue: "NSURLFileResourceTypeSocket")
public static let unknown = URLFileResourceType(rawValue: "NSURLFileResourceTypeUnknown")
}
open class NSURL : NSObject, NSSecureCoding, NSCopying {
typealias CFType = CFURL
internal var _base = _CFInfo(typeID: CFURLGetTypeID())
internal var _flags : UInt32 = 0
internal var _encoding : CFStringEncoding = 0
internal var _string : UnsafeMutablePointer<CFString>? = nil
internal var _baseURL : UnsafeMutablePointer<CFURL>? = nil
internal var _extra : OpaquePointer? = nil
internal var _resourceInfo : OpaquePointer? = nil
internal var _range1 = NSRange(location: 0, length: 0)
internal var _range2 = NSRange(location: 0, length: 0)
internal var _range3 = NSRange(location: 0, length: 0)
internal var _range4 = NSRange(location: 0, length: 0)
internal var _range5 = NSRange(location: 0, length: 0)
internal var _range6 = NSRange(location: 0, length: 0)
internal var _range7 = NSRange(location: 0, length: 0)
internal var _range8 = NSRange(location: 0, length: 0)
internal var _range9 = NSRange(location: 0, length: 0)
internal var _cfObject : CFType {
if type(of: self) === NSURL.self {
return unsafeBitCast(self, to: CFType.self)
} else {
return CFURLCreateWithString(kCFAllocatorSystemDefault, relativeString._cfObject, self.baseURL?._cfObject)
}
}
open override var hash: Int {
return Int(bitPattern: CFHash(_cfObject))
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURL else { return false }
return CFEqual(_cfObject, other._cfObject)
}
open override var description: String {
if self.relativeString != self.absoluteString {
return "\(self.relativeString) -- \(self.baseURL!)"
} else {
return self.absoluteString
}
}
deinit {
_CFDeinit(self)
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
public static var supportsSecureCoding: Bool { return true }
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let base = aDecoder.decodeObject(of: NSURL.self, forKey:"NS.base")?._swiftObject
let relative = aDecoder.decodeObject(of: NSString.self, forKey:"NS.relative")
if relative == nil {
return nil
}
self.init(string: String._unconditionallyBridgeFromObjectiveC(relative!), relativeTo: base)
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.baseURL?._nsObject, forKey:"NS.base")
aCoder.encode(self.relativeString._bridgeToObjectiveC(), forKey:"NS.relative")
}
public init(fileURLWithPath path: String, isDirectory isDir: Bool, relativeTo baseURL: URL?) {
super.init()
let thePath = _standardizedPath(path)
if thePath.length > 0 {
_CFURLInitWithFileSystemPathRelativeToBase(_cfObject, thePath._cfObject, kCFURLPOSIXPathStyle, isDir, baseURL?._cfObject)
} else if let baseURL = baseURL {
_CFURLInitWithFileSystemPathRelativeToBase(_cfObject, baseURL.path._cfObject, kCFURLPOSIXPathStyle, baseURL.hasDirectoryPath, nil)
}
}
public convenience init(fileURLWithPath path: String, relativeTo baseURL: URL?) {
let thePath = _standardizedPath(path)
var isDir: ObjCBool = false
if thePath.hasSuffix("/") {
isDir = true
} else {
let absolutePath: String
if let absPath = baseURL?.appendingPathComponent(path).path {
absolutePath = absPath
} else {
absolutePath = path
}
let _ = FileManager.default.fileExists(atPath: absolutePath, isDirectory: &isDir)
}
self.init(fileURLWithPath: thePath, isDirectory: isDir.boolValue, relativeTo: baseURL)
}
public convenience init(fileURLWithPath path: String, isDirectory isDir: Bool) {
self.init(fileURLWithPath: path, isDirectory: isDir, relativeTo: nil)
}
public init(fileURLWithPath path: String) {
let thePath: String
let pathString = NSString(string: path)
if !pathString.isAbsolutePath {
thePath = pathString.standardizingPath
} else {
thePath = path
}
var isDir: ObjCBool = false
if thePath.hasSuffix("/") {
isDir = true
} else {
if !FileManager.default.fileExists(atPath: path, isDirectory: &isDir) {
isDir = false
}
}
super.init()
_CFURLInitWithFileSystemPathRelativeToBase(_cfObject, thePath._cfObject, kCFURLPOSIXPathStyle, isDir.boolValue, nil)
}
public convenience init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory isDir: Bool, relativeTo baseURL: URL?) {
let pathString = String(cString: path)
self.init(fileURLWithPath: pathString, isDirectory: isDir, relativeTo: baseURL)
}
public convenience init?(string URLString: String) {
self.init(string: URLString, relativeTo:nil)
}
public init?(string URLString: String, relativeTo baseURL: URL?) {
super.init()
if !_CFURLInitWithURLString(_cfObject, URLString._cfObject, true, baseURL?._cfObject) {
return nil
}
}
public init(dataRepresentation data: Data, relativeTo baseURL: URL?) {
super.init()
// _CFURLInitWithURLString does not fail if checkForLegalCharacters == false
data.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Void in
if let str = CFStringCreateWithBytes(kCFAllocatorSystemDefault, ptr, data.count, CFStringEncoding(kCFStringEncodingUTF8), false) {
_CFURLInitWithURLString(_cfObject, str, false, baseURL?._cfObject)
} else if let str = CFStringCreateWithBytes(kCFAllocatorSystemDefault, ptr, data.count, CFStringEncoding(kCFStringEncodingISOLatin1), false) {
_CFURLInitWithURLString(_cfObject, str, false, baseURL?._cfObject)
} else {
fatalError()
}
}
}
public init(absoluteURLWithDataRepresentation data: Data, relativeTo baseURL: URL?) {
super.init()
data.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Void in
if _CFURLInitAbsoluteURLWithBytes(_cfObject, ptr, data.count, CFStringEncoding(kCFStringEncodingUTF8), baseURL?._cfObject) {
return
}
if _CFURLInitAbsoluteURLWithBytes(_cfObject, ptr, data.count, CFStringEncoding(kCFStringEncodingISOLatin1), baseURL?._cfObject) {
return
}
fatalError()
}
}
/* Returns the data representation of the URL's relativeString. If the URL was initialized with -initWithData:relativeTo:, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the relativeString encoded with NSUTF8StringEncoding.
*/
open var dataRepresentation: Data {
let bytesNeeded = CFURLGetBytes(_cfObject, nil, 0)
assert(bytesNeeded > 0)
let buffer = malloc(bytesNeeded)!.bindMemory(to: UInt8.self, capacity: bytesNeeded)
let bytesFilled = CFURLGetBytes(_cfObject, buffer, bytesNeeded)
if bytesFilled == bytesNeeded {
return Data(bytesNoCopy: buffer, count: bytesNeeded, deallocator: .free)
} else {
fatalError()
}
}
open var absoluteString: String {
if let absURL = CFURLCopyAbsoluteURL(_cfObject) {
return CFURLGetString(absURL)._swiftObject
}
return CFURLGetString(_cfObject)._swiftObject
}
// The relative portion of a URL. If baseURL is nil, or if the receiver is itself absolute, this is the same as absoluteString
open var relativeString: String {
return CFURLGetString(_cfObject)._swiftObject
}
open var baseURL: URL? {
return CFURLGetBaseURL(_cfObject)?._swiftObject
}
// if the receiver is itself absolute, this will return self.
open var absoluteURL: URL? {
return CFURLCopyAbsoluteURL(_cfObject)?._swiftObject
}
/* Any URL is composed of these two basic pieces. The full URL would be the concatenation of [myURL scheme], ':', [myURL resourceSpecifier]
*/
open var scheme: String? {
return CFURLCopyScheme(_cfObject)?._swiftObject
}
internal var _isAbsolute : Bool {
return self.baseURL == nil && self.scheme != nil
}
open var resourceSpecifier: String? {
// Note that this does NOT have the same meaning as CFURL's resource specifier, which, for decomposeable URLs is merely that portion of the URL which comes after the path. NSURL means everything after the scheme.
if !_isAbsolute {
return self.relativeString
} else {
let cf = _cfObject
guard CFURLCanBeDecomposed(cf) else {
return CFURLCopyResourceSpecifier(cf)?._swiftObject
}
guard baseURL == nil else {
return CFURLGetString(cf)?._swiftObject
}
let netLoc = CFURLCopyNetLocation(cf)?._swiftObject
let path = CFURLCopyPath(cf)?._swiftObject
let theRest = CFURLCopyResourceSpecifier(cf)?._swiftObject
if let netLoc = netLoc {
let p = path ?? ""
let rest = theRest ?? ""
return "//\(netLoc)\(p)\(rest)"
} else if let path = path {
let rest = theRest ?? ""
return "\(path)\(rest)"
} else {
return theRest
}
}
}
/* If the URL conforms to rfc 1808 (the most common form of URL), the following accessors will return the various components; otherwise they return nil. The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is @"//". In all cases, they return the component's value after resolving the receiver against its base URL.
*/
open var host: String? {
return CFURLCopyHostName(_cfObject)?._swiftObject
}
open var port: NSNumber? {
let port = CFURLGetPortNumber(_cfObject)
if port == -1 {
return nil
} else {
return NSNumber(value: port)
}
}
open var user: String? {
return CFURLCopyUserName(_cfObject)?._swiftObject
}
open var password: String? {
let absoluteURL = CFURLCopyAbsoluteURL(_cfObject)
#if os(Linux) || os(Android) || CYGWIN
let passwordRange = CFURLGetByteRangeForComponent(absoluteURL, kCFURLComponentPassword, nil)
#else
let passwordRange = CFURLGetByteRangeForComponent(absoluteURL, .password, nil)
#endif
guard passwordRange.location != kCFNotFound else {
return nil
}
// For historical reasons, the password string should _not_ have its percent escapes removed.
let bufSize = CFURLGetBytes(absoluteURL, nil, 0)
var buf = [UInt8](repeating: 0, count: bufSize)
guard CFURLGetBytes(absoluteURL, &buf, bufSize) >= 0 else {
return nil
}
let passwordBuf = buf[passwordRange.location ..< passwordRange.location+passwordRange.length]
return passwordBuf.withUnsafeBufferPointer { ptr in
NSString(bytes: ptr.baseAddress!, length: passwordBuf.count, encoding: String.Encoding.utf8.rawValue)?._swiftObject
}
}
open var path: String? {
let absURL = CFURLCopyAbsoluteURL(_cfObject)
return CFURLCopyFileSystemPath(absURL, kCFURLPOSIXPathStyle)?._swiftObject
}
open var fragment: String? {
return CFURLCopyFragment(_cfObject, nil)?._swiftObject
}
open var parameterString: String? {
return CFURLCopyParameterString(_cfObject, nil)?._swiftObject
}
open var query: String? {
return CFURLCopyQueryString(_cfObject, nil)?._swiftObject
}
// The same as path if baseURL is nil
open var relativePath: String? {
return CFURLCopyFileSystemPath(_cfObject, kCFURLPOSIXPathStyle)?._swiftObject
}
/* Determines if a given URL string's path represents a directory (i.e. the path component in the URL string ends with a '/' character). This does not check the resource the URL refers to.
*/
open var hasDirectoryPath: Bool {
return CFURLHasDirectoryPath(_cfObject)
}
/* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding.
*/
open func getFileSystemRepresentation(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferLength: Int) -> Bool {
return buffer.withMemoryRebound(to: UInt8.self, capacity: maxBufferLength) {
CFURLGetFileSystemRepresentation(_cfObject, true, $0, maxBufferLength)
}
}
/* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding. The returned C string will be automatically freed just as a returned object would be released; your code should copy the representation or use getFileSystemRepresentation:maxLength: if it needs to store the representation outside of the autorelease context in which the representation is created.
*/
// Memory leak. See https://github.com/apple/swift-corelibs-foundation/blob/master/Docs/Issues.md
open var fileSystemRepresentation: UnsafePointer<Int8> {
let bufSize = Int(PATH_MAX + 1)
let _fsrBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: bufSize)
_fsrBuffer.initialize(repeating: 0, count: bufSize)
if getFileSystemRepresentation(_fsrBuffer, maxLength: bufSize) {
return UnsafePointer(_fsrBuffer)
}
// FIXME: This used to return nil, but the corresponding Darwin
// implementation is marked as non-nullable.
fatalError("URL cannot be expressed in the filesystem representation;" +
"use getFileSystemRepresentation to handle this case")
}
// Whether the scheme is file:; if myURL.isFileURL is true, then myURL.path is suitable for input into FileManager or NSPathUtilities.
open var isFileURL: Bool {
return _CFURLIsFileURL(_cfObject)
}
/* A string constant for the "file" URL scheme. If you are using this to compare to a URL's scheme to see if it is a file URL, you should instead use the NSURL fileURL property -- the fileURL property is much faster. */
open var standardized: URL? {
guard (path != nil) else {
return nil
}
let URLComponents = NSURLComponents(string: relativeString)
guard ((URLComponents != nil) && (URLComponents!.path != nil)) else {
return nil
}
guard (URLComponents!.path!.contains("..") || URLComponents!.path!.contains(".")) else{
return URLComponents!.url(relativeTo: baseURL)
}
URLComponents!.path! = _pathByRemovingDots(pathComponents!)
return URLComponents!.url(relativeTo: baseURL)
}
/* Returns whether the URL's resource exists and is reachable. This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. If this method returns NO, the optional error is populated. This method is currently applicable only to URLs for file system resources. For other URL types, NO is returned. Symbol is present in iOS 4, but performs no operation.
*/
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
// TODO: should be `checkResourceIsReachableAndReturnError` with autoreleased error parameter.
// Currently Autoreleased pointers is not supported on Linux.
open func checkResourceIsReachable() throws -> Bool {
guard isFileURL,
let path = path else {
throw NSError(domain: NSCocoaErrorDomain,
code: CocoaError.Code.fileReadUnsupportedScheme.rawValue)
}
guard FileManager.default.fileExists(atPath: path) else {
throw NSError(domain: NSCocoaErrorDomain,
code: CocoaError.Code.fileReadNoSuchFile.rawValue,
userInfo: [
"NSURL" : self,
"NSFilePath" : path])
}
return true
}
/* Returns a file path URL that refers to the same resource as a specified URL. File path URLs use a file system style path. An error will occur if the url parameter is not a file URL. A file reference URL's resource must exist and be reachable to be converted to a file path URL. Symbol is present in iOS 4, but performs no operation.
*/
open var filePathURL: URL? {
guard isFileURL else {
return nil
}
return URL(string: absoluteString)
}
override open var _cfTypeID: CFTypeID {
return CFURLGetTypeID()
}
open func removeAllCachedResourceValues() { NSUnimplemented() }
open func removeCachedResourceValue(forKey key: URLResourceKey) { NSUnimplemented() }
open func resourceValues(forKeys keys: [URLResourceKey]) throws -> [URLResourceKey : Any] { NSUnimplemented() }
open func setResourceValue(_ value: Any?, forKey key: URLResourceKey) throws { NSUnimplemented() }
open func setResourceValues(_ keyedValues: [URLResourceKey : Any]) throws { NSUnimplemented() }
open func setTemporaryResourceValue(_ value: Any?, forKey key: URLResourceKey) { NSUnimplemented() }
}
extension NSCharacterSet {
// Predefined character sets for the six URL components and subcomponents which allow percent encoding. These character sets are passed to -stringByAddingPercentEncodingWithAllowedCharacters:.
// Returns a character set containing the characters allowed in an URL's user subcomponent.
open class var urlUserAllowed: CharacterSet {
return _CFURLComponentsGetURLUserAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's password subcomponent.
open class var urlPasswordAllowed: CharacterSet {
return _CFURLComponentsGetURLPasswordAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's host subcomponent.
open class var urlHostAllowed: CharacterSet {
return _CFURLComponentsGetURLHostAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's path component. ';' is a legal path character, but it is recommended that it be percent-encoded for best compatibility with NSURL (-stringByAddingPercentEncodingWithAllowedCharacters: will percent-encode any ';' characters if you pass the URLPathAllowedCharacterSet).
open class var urlPathAllowed: CharacterSet {
return _CFURLComponentsGetURLPathAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's query component.
open class var urlQueryAllowed: CharacterSet {
return _CFURLComponentsGetURLQueryAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's fragment component.
open class var urlFragmentAllowed: CharacterSet {
return _CFURLComponentsGetURLFragmentAllowedCharacterSet()._swiftObject
}
}
extension NSString {
// Returns a new string made from the receiver by replacing all characters not in the allowedCharacters set with percent encoded characters. UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded. This method is intended to percent-encode an URL component or subcomponent string, NOT the entire URL string. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.
open func addingPercentEncoding(withAllowedCharacters allowedCharacters: CharacterSet) -> String? {
return _CFStringCreateByAddingPercentEncodingWithAllowedCharacters(kCFAllocatorSystemDefault, self._cfObject, allowedCharacters._cfObject)._swiftObject
}
// Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters.
open var removingPercentEncoding: String? {
return _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, self._cfObject)?._swiftObject
}
}
extension NSURL {
/* The following methods work on the path portion of a URL in the same manner that the NSPathUtilities methods on NSString do.
*/
open class func fileURL(withPathComponents components: [String]) -> URL? {
let path = NSString.pathWithComponents(components)
if components.last == "/" {
return URL(fileURLWithPath: path, isDirectory: true)
} else {
return URL(fileURLWithPath: path)
}
}
internal func _pathByFixingSlashes(compress : Bool = true, stripTrailing: Bool = true) -> String? {
guard let p = path else {
return nil
}
if p == "/" {
return p
}
var result = p
if compress {
let startPos = result.startIndex
var endPos = result.endIndex
var curPos = startPos
while curPos < endPos {
if result[curPos] == "/" {
var afterLastSlashPos = curPos
while afterLastSlashPos < endPos && result[afterLastSlashPos] == "/" {
afterLastSlashPos = result.index(after: afterLastSlashPos)
}
if afterLastSlashPos != result.index(after: curPos) {
result.replaceSubrange(curPos ..< afterLastSlashPos, with: ["/"])
endPos = result.endIndex
}
curPos = afterLastSlashPos
} else {
curPos = result.index(after: curPos)
}
}
}
if stripTrailing && result.hasSuffix("/") {
result.remove(at: result.index(before: result.endIndex))
}
return result
}
open var pathComponents: [String]? {
return _pathComponents(path)
}
open var lastPathComponent: String? {
guard let fixedSelf = _pathByFixingSlashes() else {
return nil
}
if fixedSelf.length <= 1 {
return fixedSelf
}
return String(fixedSelf.suffix(from: fixedSelf._startOfLastPathComponent))
}
open var pathExtension: String? {
guard let fixedSelf = _pathByFixingSlashes() else {
return nil
}
if fixedSelf.length <= 1 {
return ""
}
if let extensionPos = fixedSelf._startOfPathExtension {
return String(fixedSelf.suffix(from: extensionPos))
} else {
return ""
}
}
open func appendingPathComponent(_ pathComponent: String) -> URL? {
var result : URL? = appendingPathComponent(pathComponent, isDirectory: false)
if !pathComponent.hasSuffix("/") && isFileURL {
if let urlWithoutDirectory = result {
var isDir: ObjCBool = false
if FileManager.default.fileExists(atPath: urlWithoutDirectory.path, isDirectory: &isDir) && isDir.boolValue {
result = self.appendingPathComponent(pathComponent, isDirectory: true)
}
}
}
return result
}
open func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL? {
return CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, _cfObject, pathComponent._cfObject, isDirectory)?._swiftObject
}
open var deletingLastPathComponent: URL? {
return CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorSystemDefault, _cfObject)?._swiftObject
}
open func appendingPathExtension(_ pathExtension: String) -> URL? {
return CFURLCreateCopyAppendingPathExtension(kCFAllocatorSystemDefault, _cfObject, pathExtension._cfObject)?._swiftObject
}
open var deletingPathExtension: URL? {
return CFURLCreateCopyDeletingPathExtension(kCFAllocatorSystemDefault, _cfObject)?._swiftObject
}
/* The following methods work only on `file:` scheme URLs; for non-`file:` scheme URLs, these methods return the URL unchanged.
*/
open var standardizingPath: URL? {
// Documentation says it should expand initial tilde, but it does't do this on OS X.
// In remaining cases it works just like URLByResolvingSymlinksInPath.
return resolvingSymlinksInPath
}
open var resolvingSymlinksInPath: URL? {
return _resolveSymlinksInPath(excludeSystemDirs: true)
}
internal func _resolveSymlinksInPath(excludeSystemDirs: Bool) -> URL? {
guard isFileURL else {
return URL(string: absoluteString)
}
guard let selfPath = path else {
return URL(string: absoluteString)
}
let absolutePath: String
if selfPath.hasPrefix("/") {
absolutePath = selfPath
} else {
let workingDir = FileManager.default.currentDirectoryPath
absolutePath = workingDir._bridgeToObjectiveC().appendingPathComponent(selfPath)
}
var components = URL(fileURLWithPath: absolutePath).pathComponents
guard !components.isEmpty else {
return URL(string: absoluteString)
}
var resolvedPath = components.removeFirst()
for component in components {
switch component {
case "", ".":
break
case "..":
resolvedPath = resolvedPath._bridgeToObjectiveC().deletingLastPathComponent
default:
resolvedPath = resolvedPath._bridgeToObjectiveC().appendingPathComponent(component)
if let destination = FileManager.default._tryToResolveTrailingSymlinkInPath(resolvedPath) {
resolvedPath = destination
}
}
}
// It might be a responsibility of NSURL(fileURLWithPath:). Check it.
var isExistingDirectory: ObjCBool = false
let _ = FileManager.default.fileExists(atPath: resolvedPath, isDirectory: &isExistingDirectory)
if excludeSystemDirs {
resolvedPath = resolvedPath._tryToRemovePathPrefix("/private") ?? resolvedPath
}
if isExistingDirectory.boolValue && !resolvedPath.hasSuffix("/") {
resolvedPath += "/"
}
return URL(fileURLWithPath: resolvedPath)
}
fileprivate func _pathByRemovingDots(_ comps: [String]) -> String {
var components = comps
if(components.last == "/") {
components.removeLast()
}
guard !components.isEmpty else {
return self.path!
}
let isAbsolutePath = components.first == "/"
var result : String = components.removeFirst()
for component in components {
switch component {
case ".":
break
case ".." where isAbsolutePath:
result = result._bridgeToObjectiveC().deletingLastPathComponent
default:
result = result._bridgeToObjectiveC().appendingPathComponent(component)
}
}
if(self.path!.hasSuffix("/")) {
result += "/"
}
return result
}
}
// NSURLQueryItem encapsulates a single query name-value pair. The name and value strings of a query name-value pair are not percent encoded. For use with the NSURLComponents queryItems property.
open class NSURLQueryItem : NSObject, NSSecureCoding, NSCopying {
public init(name: String, value: String?) {
self.name = name
self.value = value
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
public static var supportsSecureCoding: Bool {
return true
}
required public init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let encodedName = aDecoder.decodeObject(forKey: "NS.name") as! NSString
self.name = encodedName._swiftObject
let encodedValue = aDecoder.decodeObject(forKey: "NS.value") as? NSString
self.value = encodedValue?._swiftObject
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.name._bridgeToObjectiveC(), forKey: "NS.name")
aCoder.encode(self.value?._bridgeToObjectiveC(), forKey: "NS.value")
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURLQueryItem else { return false }
return other === self
|| (other.name == self.name
&& other.value == self.value)
}
open private(set) var name: String
open private(set) var value: String?
}
open class NSURLComponents: NSObject, NSCopying {
private let _components : CFURLComponents!
open override func copy() -> Any {
return copy(with: nil)
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURLComponents else { return false }
return self === other
|| (scheme == other.scheme
&& user == other.user
&& password == other.password
&& host == other.host
&& port == other.port
&& path == other.path
&& query == other.query
&& fragment == other.fragment)
}
open override var hash: Int {
var hasher = Hasher()
hasher.combine(scheme)
hasher.combine(user)
hasher.combine(password)
hasher.combine(host)
hasher.combine(port)
hasher.combine(path)
hasher.combine(query)
hasher.combine(fragment)
return hasher.finalize()
}
open func copy(with zone: NSZone? = nil) -> Any {
let copy = NSURLComponents()
copy.scheme = self.scheme
copy.user = self.user
copy.password = self.password
copy.host = self.host
copy.port = self.port
copy.path = self.path
copy.query = self.query
copy.fragment = self.fragment
return copy
}
// Initialize a NSURLComponents with the components of a URL. If resolvingAgainstBaseURL is YES and url is a relative URL, the components of [url absoluteURL] are used. If the url string from the NSURL is malformed, nil is returned.
public init?(url: URL, resolvingAgainstBaseURL resolve: Bool) {
_components = _CFURLComponentsCreateWithURL(kCFAllocatorSystemDefault, url._cfObject, resolve)
super.init()
if _components == nil {
return nil
}
}
// Initialize a NSURLComponents with a URL string. If the URLString is malformed, nil is returned.
public init?(string URLString: String) {
_components = _CFURLComponentsCreateWithString(kCFAllocatorSystemDefault, URLString._cfObject)
super.init()
if _components == nil {
return nil
}
}
public override init() {
_components = _CFURLComponentsCreate(kCFAllocatorSystemDefault)
}
// Returns a URL created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
open var url: URL? {
guard let result = _CFURLComponentsCopyURL(_components) else { return nil }
return unsafeBitCast(result, to: URL.self)
}
// Returns a URL created from the NSURLComponents relative to a base URL. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
open func url(relativeTo baseURL: URL?) -> URL? {
if let componentString = string {
return URL(string: componentString, relativeTo: baseURL)
}
return nil
}
// Returns a URL string created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
open var string: String? {
return _CFURLComponentsCopyString(_components)?._swiftObject
}
// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided.
// Getting these properties removes any percent encoding these components may have (if the component allows percent encoding). Setting these properties assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
// Attempting to set the scheme with an invalid scheme string will cause an exception.
open var scheme: String? {
get {
return _CFURLComponentsCopyScheme(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetScheme(_components, new?._cfObject) {
fatalError()
}
}
}
open var user: String? {
get {
return _CFURLComponentsCopyUser(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetUser(_components, new?._cfObject) {
fatalError()
}
}
}
open var password: String? {
get {
return _CFURLComponentsCopyPassword(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPassword(_components, new?._cfObject) {
fatalError()
}
}
}
open var host: String? {
get {
return _CFURLComponentsCopyHost(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetHost(_components, new?._cfObject) {
fatalError()
}
}
}
// Attempting to set a negative port number will cause an exception.
open var port: NSNumber? {
get {
if let result = _CFURLComponentsCopyPort(_components) {
return unsafeBitCast(result, to: NSNumber.self)
} else {
return nil
}
}
set(new) {
if !_CFURLComponentsSetPort(_components, new?._cfObject) {
fatalError()
}
}
}
open var path: String? {
get {
return _CFURLComponentsCopyPath(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPath(_components, new?._cfObject) {
fatalError()
}
}
}
open var query: String? {
get {
return _CFURLComponentsCopyQuery(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetQuery(_components, new?._cfObject) {
fatalError()
}
}
}
open var fragment: String? {
get {
return _CFURLComponentsCopyFragment(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetFragment(_components, new?._cfObject) {
fatalError()
}
}
}
// Getting these properties retains any percent encoding these components may have. Setting these properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause an exception. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with NSURL (-stringByAddingPercentEncodingWithAllowedCharacters: will percent-encode any ';' characters if you pass the urlPathAllowed).
open var percentEncodedUser: String? {
get {
return _CFURLComponentsCopyPercentEncodedUser(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedUser(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedPassword: String? {
get {
return _CFURLComponentsCopyPercentEncodedPassword(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedPassword(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedHost: String? {
get {
return _CFURLComponentsCopyPercentEncodedHost(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedHost(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedPath: String? {
get {
return _CFURLComponentsCopyPercentEncodedPath(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedPath(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedQuery: String? {
get {
return _CFURLComponentsCopyPercentEncodedQuery(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedQuery(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedFragment: String? {
get {
return _CFURLComponentsCopyPercentEncodedFragment(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedFragment(_components, new?._cfObject) {
fatalError()
}
}
}
/* These properties return the character range of a component in the URL string returned by -[NSURLComponents string]. If the component does not exist in the NSURLComponents object, {NSNotFound, 0} is returned. Note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
*/
open var rangeOfScheme: NSRange {
return NSRange(_CFURLComponentsGetRangeOfScheme(_components))
}
open var rangeOfUser: NSRange {
return NSRange(_CFURLComponentsGetRangeOfUser(_components))
}
open var rangeOfPassword: NSRange {
return NSRange(_CFURLComponentsGetRangeOfPassword(_components))
}
open var rangeOfHost: NSRange {
return NSRange(_CFURLComponentsGetRangeOfHost(_components))
}
open var rangeOfPort: NSRange {
return NSRange(_CFURLComponentsGetRangeOfPort(_components))
}
open var rangeOfPath: NSRange {
return NSRange(_CFURLComponentsGetRangeOfPath(_components))
}
open var rangeOfQuery: NSRange {
return NSRange(_CFURLComponentsGetRangeOfQuery(_components))
}
open var rangeOfFragment: NSRange {
return NSRange(_CFURLComponentsGetRangeOfFragment(_components))
}
// The getter method that underlies the queryItems property parses the query string based on these delimiters and returns an NSArray containing any number of NSURLQueryItem objects, each of which represents a single key-value pair, in the order in which they appear in the original query string. Note that a name may appear more than once in a single query string, so the name values are not guaranteed to be unique. If the NSURLComponents object has an empty query component, queryItems returns an empty NSArray. If the NSURLComponents object has no query component, queryItems returns nil.
// The setter method that underlies the queryItems property combines an NSArray containing any number of NSURLQueryItem objects, each of which represents a single key-value pair, into a query string and sets the NSURLComponents' query property. Passing an empty NSArray to setQueryItems sets the query component of the NSURLComponents object to an empty string. Passing nil to setQueryItems removes the query component of the NSURLComponents object.
// Note: If a name-value pair in a query is empty (i.e. the query string starts with '&', ends with '&', or has "&&" within it), you get a NSURLQueryItem with a zero-length name and and a nil value. If a query's name-value pair has nothing before the equals sign, you get a zero-length name. If a query's name-value pair has nothing after the equals sign, you get a zero-length value. If a query's name-value pair has no equals sign, the query name-value pair string is the name and you get a nil value.
open var queryItems: [URLQueryItem]? {
get {
// This CFURL implementation returns a CFArray of CFDictionary; each CFDictionary has an entry for name and optionally an entry for value
guard let queryArray = _CFURLComponentsCopyQueryItems(_components) else {
return nil
}
let count = CFArrayGetCount(queryArray)
return (0..<count).map { idx in
let oneEntry = unsafeBitCast(CFArrayGetValueAtIndex(queryArray, idx), to: NSDictionary.self)
let swiftEntry = oneEntry._swiftObject
let entryName = swiftEntry["name"] as! String
let entryValue = swiftEntry["value"] as? String
return URLQueryItem(name: entryName, value: entryValue)
}
}
set(new) {
guard let new = new else {
self.percentEncodedQuery = nil
return
}
// The CFURL implementation requires two CFArrays, one for names and one for values
var names = [CFTypeRef]()
var values = [CFTypeRef]()
for entry in new {
names.append(entry.name._cfObject)
if let v = entry.value {
values.append(v._cfObject)
} else {
values.append(kCFNull)
}
}
_CFURLComponentsSetQueryItems(_components, names._cfObject, values._cfObject)
}
}
}
extension NSURL: _CFBridgeable, _SwiftBridgeable {
typealias SwiftType = URL
internal var _swiftObject: SwiftType { return URL(reference: self) }
}
extension CFURL : _NSBridgeable, _SwiftBridgeable {
typealias NSType = NSURL
typealias SwiftType = URL
internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) }
internal var _swiftObject: SwiftType { return _nsObject._swiftObject }
}
extension URL : _NSBridgeable, _CFBridgeable {
typealias NSType = NSURL
typealias CFType = CFURL
internal var _nsObject: NSType { return self.reference }
internal var _cfObject: CFType { return _nsObject._cfObject }
}
extension NSURL : _StructTypeBridgeable {
public typealias _StructType = URL
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
extension NSURLComponents : _StructTypeBridgeable {
public typealias _StructType = URLComponents
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
extension NSURLQueryItem : _StructTypeBridgeable {
public typealias _StructType = URLQueryItem
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 | 1d672ddbd877a0a8ac4cf5467aa1ffae | 44.296992 | 740 | 0.675293 | 5.541808 | false | false | false | false |
tkremenek/swift | test/expr/unary/keypath/keypath-mutation.swift | 38 | 1043 | // RUN: %target-typecheck-verify-swift
struct User {
var id: Int
var name: String
}
func setting<Root, Value>(_ kp: WritableKeyPath<Root, Value>, _ root: Root, _ value: Value) -> Root {
var copy = root
// Should not warn about lack of mutation
copy[keyPath: kp] = value
return copy
}
func referenceSetting<Root, Value>(_ kp: ReferenceWritableKeyPath<Root, Value>, _ root: Root, _ value: Value) -> Root {
// Should warn about lack of mutation, since a RefKeyPath doesn't modify its
// base.
// expected-warning@+1 {{was never mutated}}
var copy = root
copy[keyPath: kp] = value
// Should not warn about lack of use of `immCopy`
let immCopy = root
immCopy[keyPath: kp] = value
return copy
}
func referenceUsage<Root, Value>(_ kp: ReferenceWritableKeyPath<Root, Value>, _ root: Root, _ value: Value) -> Root {
// Should warn about lack of mutation, since a RefKeyPath doesn't modify its
// base.
// expected-warning@+1 {{was never mutated}}
var copy = root
copy[keyPath: kp] = value
return copy
}
| apache-2.0 | e18aa69858b19a6d1ff8c409d4f62f8d | 28.8 | 119 | 0.678811 | 3.685512 | false | false | false | false |
ParsifalC/CPCollectionViewKit | Demos/CPCollectionViewWheelLayoutSwiftDemo/CPCollectionViewWheelLayoutSwift/CPTableViewController.swift | 1 | 1351 | //
// CPTableViewController.swift
// CollectionViewWheelLayout-Swift
//
// Created by Parsifal on 2017/1/7.
// Copyright © 2017年 Parsifal. All rights reserved.
//
import UIKit
import CPCollectionViewKit
class CPTableViewController:UITableViewController {
let wheelTypes = ["leftBottom", "rightBottom",
"leftTop", "rightTop",
"leftCenter", "rightCenter",
"topCenter", "bottomCenter"]
var selectType = WheelLayoutType.leftBottom
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell",
for: indexPath)
cell.textLabel?.text = wheelTypes[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return wheelTypes.count
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let indexPath = tableView.indexPath(for: sender as! UITableViewCell)
let vc = segue.destination as! CPViewController
vc.wheelType = WheelLayoutType(rawValue: (indexPath?.row)!)!
}
}
| mit | 8792f056c102626124c910d21691cc42 | 33.564103 | 109 | 0.646884 | 5.204633 | false | false | false | false |
jarrodparkes/DominoKit | Sources/Collection+Shuffle.swift | 1 | 1190 | /*
This source file is part of the Swift.org open source project
Copyright 2015 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
#if swift(>=2.2) && !swift(>=3.0)
public typealias Collection = CollectionType
public protocol MutableCollection: MutableCollectionType {
associatedtype IndexDistance
}
extension Array: MutableCollection {
public typealias IndexDistance = Int
}
#endif
public extension Collection {
func shuffled() -> [Iterator.Element] {
var array = Array(self)
array.shuffle()
return array
}
}
public extension MutableCollection where Index == Int, IndexDistance == Int {
mutating func shuffle() {
guard count > 1 else { return }
for i in 0..<count - 1 {
let j = random(count - i) + i
guard i != j else { continue }
#if swift(>=4.0)
swapAt(i, j)
#else
swap(&self[i], &self[j])
#endif
}
}
}
| mit | d309337734570470da1ffc1ffcdfb8b5 | 26.045455 | 77 | 0.615966 | 4.559387 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/ProjectActivities/Datasource/ProjectActivitiesDataSourceTests.swift | 1 | 4499 | @testable import Kickstarter_Framework
@testable import KsApi
@testable import Library
import Prelude
import XCTest
internal final class ProjectActivitiesDataSourceTests: XCTestCase {
let dataSource = ProjectActivitiesDataSource()
let tableView = UITableView()
func testDataSource() {
let timeZone = TimeZone(abbreviation: "UTC")!
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone
withEnvironment(calendar: calendar) {
let section = ProjectActivitiesDataSource.Section.activities.rawValue
let project = Project.template
let activities = [
Activity.template
|> Activity.lens.category .~ Activity.Category.backing
|> Activity.lens.createdAt .~ 1_474_606_800 // 2016-09-23T05:00:00Z
|> Activity.lens.project .~ project,
Activity.template
|> Activity.lens.category .~ Activity.Category.commentPost
|> Activity.lens.createdAt .~ 1_474_605_000 // 2016-09-23T04:30:00Z
|> Activity.lens.project .~ project,
Activity.template
|> Activity.lens.category .~ Activity.Category.success
|> Activity.lens.createdAt .~ 1_474_700_400 // 2016-09-24T07:00:00Z
|> Activity.lens.project .~ project,
Activity.template
|> Activity.lens.category .~ Activity.Category.launch
|> Activity.lens.createdAt .~ 1_474_538_400 // 2016-09-22T10:00:00Z
|> Activity.lens.project .~ project
]
self.dataSource.load(
projectActivityData:
ProjectActivityData(activities: activities, project: project, groupedDates: true)
)
XCTAssertEqual(section + 1, self.dataSource.numberOfSections(in: tableView))
XCTAssertEqual(7, self.dataSource.tableView(tableView, numberOfRowsInSection: section))
XCTAssertEqual("ProjectActivityDateCell", self.dataSource.reusableId(item: 0, section: section))
XCTAssertEqual("ProjectActivitySuccessCell", self.dataSource.reusableId(item: 1, section: section))
XCTAssertEqual("ProjectActivityDateCell", self.dataSource.reusableId(item: 2, section: section))
XCTAssertEqual("ProjectActivityBackingCell", self.dataSource.reusableId(item: 3, section: section))
XCTAssertEqual("ProjectActivityCommentCell", self.dataSource.reusableId(item: 4, section: section))
XCTAssertEqual("ProjectActivityDateCell", self.dataSource.reusableId(item: 5, section: section))
XCTAssertEqual("ProjectActivityLaunchCell", self.dataSource.reusableId(item: 6, section: section))
}
}
func testGroupedDatesIsFalse() {
let timeZone = TimeZone(abbreviation: "UTC")!
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone
withEnvironment(calendar: calendar) {
let section = ProjectActivitiesDataSource.Section.activities.rawValue
let project = Project.template
let activities = [
Activity.template
|> Activity.lens.category .~ Activity.Category.backing
|> Activity.lens.createdAt .~ 1_474_606_800 // 2016-09-23T05:00:00Z
|> Activity.lens.project .~ project,
Activity.template
|> Activity.lens.category .~ Activity.Category.success
|> Activity.lens.createdAt .~ 1_474_605_000 // 2016-09-23T04:30:00Z
|> Activity.lens.project .~ project
]
self.dataSource.load(
projectActivityData:
ProjectActivityData(activities: activities, project: project, groupedDates: false)
)
XCTAssertEqual(4, self.dataSource.tableView(tableView, numberOfRowsInSection: section))
XCTAssertEqual("ProjectActivityDateCell", self.dataSource.reusableId(item: 0, section: section))
XCTAssertEqual("ProjectActivityBackingCell", self.dataSource.reusableId(item: 1, section: section))
XCTAssertEqual(
"ProjectActivityDateCell", self.dataSource.reusableId(item: 2, section: section),
"Should append second date cell, even though date is the same as the first date cell"
)
XCTAssertEqual("ProjectActivitySuccessCell", self.dataSource.reusableId(item: 3, section: section))
}
}
func testEmptyState() {
let section = ProjectActivitiesDataSource.Section.emptyState.rawValue
self.dataSource.emptyState(visible: true)
XCTAssertEqual(1, self.dataSource.tableView(self.tableView, numberOfRowsInSection: section))
XCTAssertEqual("ProjectActivityEmptyStateCell", self.dataSource.reusableId(item: 0, section: section))
}
}
| apache-2.0 | 57d46ba88242408466be22084ae181c1 | 45.381443 | 106 | 0.708157 | 4.586137 | false | true | false | false |
JohnCoates/Aerial | Aerial/Source/Controllers/CustomVideoController.swift | 1 | 23105 | //
// CustomVideoController.swift
// Aerial
//
// Created by Guillaume Louel on 21/05/2019.
// Copyright © 2019 John Coates. All rights reserved.
//
import Foundation
import AppKit
import AVKit
class CustomVideoController: NSWindowController, NSWindowDelegate, NSDraggingDestination {
@IBOutlet var mainPanel: NSWindow!
// This is the panel workaround for Catalina
@IBOutlet var addFolderCatalinaPanel: NSPanel!
@IBOutlet var addFolderTextField: NSTextField!
@IBOutlet var folderOutlineView: NSOutlineView!
@IBOutlet var topPathControl: NSPathControl!
@IBOutlet var folderView: NSView!
@IBOutlet var fileView: NSView!
@IBOutlet var onboardingLabel: NSTextField!
@IBOutlet var folderShortNameTextField: NSTextField!
@IBOutlet var timePopUpButton: NSPopUpButton!
@IBOutlet var editPlayerView: AVPlayerView!
@IBOutlet var videoNameTextField: NSTextField!
@IBOutlet var poiTableView: NSTableView!
@IBOutlet var addPoi: NSButton!
@IBOutlet var removePoi: NSButton!
@IBOutlet var addPoiPopover: NSPopover!
@IBOutlet var timeTextField: NSTextField!
@IBOutlet var timeTextStepper: NSStepper!
@IBOutlet var timeTextFormatter: NumberFormatter!
@IBOutlet var descriptionTextField: NSTextField!
@IBOutlet var durationLabel: NSTextField!
@IBOutlet var resolutionLabel: NSTextField!
@IBOutlet var cvcMenu: NSMenu!
@IBOutlet var menuRemoveFolderAndVideos: NSMenuItem!
@IBOutlet var menuRemoveVideo: NSMenuItem!
var currentFolder: Folder?
var currentAsset: Asset?
var currentAssetDuration: Int?
var hasAwokenAlready = false
var sw: NSWindow?
var controller: SourcesViewController?
// MARK: - Lifecycle
required init?(coder: NSCoder) {
super.init(coder: coder)
debugLog("cvcinit")
}
override init(window: NSWindow?) {
super.init(window: window)
self.sw = window
debugLog("cvcinit2")
}
override func awakeFromNib() {
if !hasAwokenAlready {
debugLog("cvcawake")
// self.menu = cvcMenu
folderOutlineView.dataSource = self
folderOutlineView.delegate = self
folderOutlineView.menu = cvcMenu
cvcMenu.delegate = self
if #available(OSX 10.13, *) {
folderOutlineView.registerForDraggedTypes([.fileURL, .URL])
} else {
// Fallback on earlier versions
}
poiTableView.dataSource = self
poiTableView.delegate = self
hasAwokenAlready = true
editPlayerView.player = AVPlayer()
NotificationCenter.default.addObserver(
self,
selector: #selector(self.windowWillClose(_:)),
name: NSWindow.willCloseNotification,
object: nil)
}
}
// We will receive this notification for every panel/window so we need to ensure it's the correct one
func windowWillClose(_ notification: Notification) {
if let wobj = notification.object as? NSPanel {
if wobj.title == "Manage Custom Videos" {
debugLog("Closing cvc")
// TODO 2.0
/*
let manifestInstance = ManifestLoader.instance
manifestInstance.saveCustomVideos()
manifestInstance.addCallback { manifestVideos in
if let contr = self.controller {
contr.loaded(manifestVideos: [])
}
}
manifestInstance.loadManifestsFromLoadedFiles() */
}
}
}
// This is the public function to make this visible
func show(sender: NSButton, controller: SourcesViewController) {
self.controller = controller
if !mainPanel.isVisible {
mainPanel.makeKeyAndOrderFront(sender)
folderOutlineView.expandItem(nil, expandChildren: true)
folderOutlineView.deselectAll(self)
folderView.isHidden = true
fileView.isHidden = true
topPathControl.isHidden = true
}
}
// MARK: - Edit Folders
@IBAction func folderNameChange(_ sender: NSTextField) {
if let folder = currentFolder {
folder.label = sender.stringValue
folderOutlineView.reloadData()
}
}
// MARK: - Add a new folder of videos to parse
@IBAction func addFolderButton(_ sender: NSButton) {
debugLog("addFolder")
if #available(OSX 10.15, *) {
// On Catalina, we can't use NSOpenPanel right now
addFolderTextField.stringValue = ""
addFolderCatalinaPanel.makeKeyAndOrderFront(self)
} else {
let addFolderPanel = NSOpenPanel()
addFolderPanel.allowsMultipleSelection = false
addFolderPanel.canChooseDirectories = true
addFolderPanel.canCreateDirectories = false
addFolderPanel.canChooseFiles = false
addFolderPanel.title = "Select a folder containing videos"
addFolderPanel.begin { (response) in
if response.rawValue == NSFileHandlingPanelOKButton {
self.processPathForVideos(url: addFolderPanel.url!)
}
addFolderPanel.close()
}
}
}
@IBAction func addFolderCatalinaConfirm(_ sender: Any) {
let strFolder = addFolderTextField.stringValue
if FileManager.default.fileExists(atPath: strFolder as String) {
self.processPathForVideos(url: URL(fileURLWithPath: strFolder, isDirectory: true))
}
addFolderCatalinaPanel.close()
}
func processPathForVideos(url: URL) {
debugLog("processing url for videos : \(url) ")
let folderName = url.lastPathComponent
// let manifestInstance = ManifestLoader.instance
do {
let urls = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles])
var assets = [VideoAsset]()
for lurl in urls {
if lurl.path.lowercased().hasSuffix(".mp4") || lurl.path.lowercased().hasSuffix(".mov") {
assets.append(VideoAsset(accessibilityLabel: folderName,
id: NSUUID().uuidString,
title: lurl.lastPathComponent,
timeOfDay: "day",
scene: "",
pointsOfInterest: [:],
url4KHDR: "",
url4KSDR: lurl.path,
url1080H264: "",
url1080HDR: "",
url1080SDR: "",
url: "",
type: "nature"))
}
}
// ...
if SourceList.hasNamed(name: url.lastPathComponent) {
Aerial.helper.showInfoAlert(title: "Source name mismatch",
text: "A source with this name already exists. Try renaming your folder and try again.")
} else {
debugLog("Creating source \(url.lastPathComponent)")
// Generate and save the Source
let source = Source(name: url.lastPathComponent,
description: "Local files from \(url.path)",
manifestUrl: "manifest.json",
type: .local,
scenes: [.nature],
isCachable: false,
license: "",
more: "")
SourceList.saveSource(source)
// Then the entries
let videoManifest = VideoManifest(assets: assets, initialAssetCount: 1, version: 1)
SourceList.saveEntries(source: source, manifest: videoManifest)
}
/*
if let cvf = manifestInstance.customVideoFolders {
// check if we have this folder already ?
if !cvf.hasFolder(withUrl: url.path) && !assets.isEmpty {
cvf.folders.append(Folder(url: url.path, label: folderName, assets: assets))
} else if !assets.isEmpty {
// We need to append in place those that don't exist yet
let folderIndex = cvf.getFolderIndex(withUrl: url.path)
for asset in assets {
if !cvf.folders[folderIndex].hasAsset(withUrl: asset.url) {
cvf.folders[folderIndex].assets.append(asset)
}
}
}
} else {
// Create our initial CVF with the parsed folder
manifestInstance.customVideoFolders = CustomVideoFolders(folders: [Folder(url: url.path, label: folderName, assets: assets)])
}*/
folderOutlineView.reloadData()
folderOutlineView.expandItem(nil, expandChildren: true)
folderOutlineView.deselectAll(self)
} catch {
errorLog("Could not process directory")
}
}
// MARK: - Edit Files
@IBAction func videoNameChange(_ sender: NSTextField) {
if let asset = currentAsset {
asset.accessibilityLabel = sender.stringValue
folderOutlineView.reloadData()
}
}
@IBAction func timePopUpChange(_ sender: NSPopUpButton) {
if let asset = currentAsset {
if sender.indexOfSelectedItem == 0 {
asset.time = "day"
} else {
asset.time = "night"
}
}
}
// MARK: - Add/Remove POIs
@IBAction func addPoiClick(_ sender: NSButton) {
addPoiPopover.show(relativeTo: sender.preparedContentRect, of: sender, preferredEdge: .maxY)
}
@IBAction func removePoiClick(_ sender: NSButton) {
if let asset = currentAsset {
let keys = asset.pointsOfInterest.keys.map { Int($0)!}.sorted()
asset.pointsOfInterest.removeValue(forKey: String(keys[poiTableView.selectedRow]))
poiTableView.reloadData()
}
}
@IBAction func addPoiValidate(_ sender: NSButton) {
if let asset = currentAsset {
if timeTextField.stringValue != "" && descriptionTextField.stringValue != "" {
if asset.pointsOfInterest[timeTextField.stringValue] == nil {
asset.pointsOfInterest[timeTextField.stringValue] = descriptionTextField.stringValue
// We also reset the popup so it's clean for next poi
timeTextField.stringValue = ""
descriptionTextField.stringValue = ""
poiTableView.reloadData()
addPoiPopover.close()
}
}
}
}
@IBAction func timeStepperChange(_ sender: NSStepper) {
if let player = editPlayerView.player {
player.seek(to: CMTime(seconds: Double(sender.intValue), preferredTimescale: 1))
}
}
@IBAction func timeTextChange(_ sender: NSTextField) {
if let player = editPlayerView.player {
player.seek(to: CMTime(seconds: Double(sender.intValue), preferredTimescale: 1))
}
}
@IBAction func tableViewTimeField(_ sender: NSTextField) {
if let asset = currentAsset {
if poiTableView.selectedRow != -1 {
let keys = asset.pointsOfInterest.keys.map { Int($0)!}.sorted()
asset.pointsOfInterest.switchKey(fromKey: String(keys[poiTableView.selectedRow]), toKey: sender.stringValue)
}
}
}
@IBAction func tableViewDescField(_ sender: NSTextField) {
if let asset = currentAsset {
if poiTableView.selectedRow != -1 {
let keys = asset.pointsOfInterest.keys.map { Int($0)!}.sorted()
asset.pointsOfInterest[String(keys[poiTableView.selectedRow])] = sender.stringValue
}
}
}
// MARK: - Context menu
@IBAction func menuRemoveFolderAndVideoClick(_ sender: NSMenuItem) {
if let folder = sender.representedObject as? Folder {
let manifestInstance = ManifestLoader.instance
if let cvf = manifestInstance.customVideoFolders {
cvf.folders.remove(at: cvf.getFolderIndex(withUrl: folder.url))
}
}
folderOutlineView.reloadData()
}
@IBAction func menuRemoveVideoClick(_ sender: NSMenuItem) {
if let asset = sender.representedObject as? Asset {
let manifestInstance = ManifestLoader.instance
if let cvf = manifestInstance.customVideoFolders {
for fld in cvf.folders {
let index = fld.getAssetIndex(withUrl: asset.url)
if index > -1 {
fld.assets.remove(at: index)
}
}
}
}
folderOutlineView.reloadData()
}
}
// MARK: - Data source for side bar
extension CustomVideoController: NSOutlineViewDataSource {
// Find and return the child of an item. If item == nil, we need to return a child of the
// root node otherwise we find and return the child of the parent node indicated by 'item'
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
let manifestInstance = ManifestLoader.instance
if let source = item as? Source {
return VideoList.instance.videos.filter({ $0.source.name == source.name })[index]
}
// Return a source
return SourceList.foundSources.filter({ $0.type == .local })[index]
}
// Tell the view controller whether an item can be expanded (i.e. it has children) or not
// (i.e. it doesn't)
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
// A folder may have childs if it's not empty
if let folder = item as? Folder {
return !folder.assets.isEmpty
}
// But not assets
return false
}
// Tell the view how many children an item has
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
let manifestInstance = ManifestLoader.instance
// A folder may have childs
if let source = item as? Source {
return VideoList.instance.videos.filter({ $0.source.name == source.name }).count
}
return SourceList.foundSources.filter({ $0.type == .local }).count
}
}
// MARK: - Delegate for side bar
extension CustomVideoController: NSOutlineViewDelegate {
// Add text to the view. 'item' will either be a Creature object or a string. If it's the former we just
// use the 'type' attribute otherwise we downcast it to a string and use that instead.
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
var text = ""
if let source = item as? Source {
text = source.name
} else if let video = item as? AerialVideo {
text = video.name
}
// Create our table cell -- note the reference to 'creatureCell' that we set when configuring the table cell
let tableCell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "folderCell"), owner: nil) as! NSTableCellView
tableCell.textField!.stringValue = text
return tableCell
}
// We update our view here when an item is selected
func outlineView(_ outlineView: NSOutlineView, shouldSelectItem item: Any) -> Bool {
debugLog("selected \(item)")
if let source = item as? Source {
topPathControl.isHidden = false
folderView.isHidden = false
fileView.isHidden = true
onboardingLabel.isHidden = true
topPathControl.url = URL(fileURLWithPath: source.manifestUrl)
folderShortNameTextField.stringValue = source.description
currentAsset = nil
currentFolder = nil // folder
} else if let file = item as? Asset {
topPathControl.isHidden = false
folderView.isHidden = true
fileView.isHidden = false
onboardingLabel.isHidden = true
topPathControl.url = URL(fileURLWithPath: file.url)
videoNameTextField.stringValue = file.accessibilityLabel
if file.time == "day" {
timePopUpButton.selectItem(at: 0)
} else {
timePopUpButton.selectItem(at: 1)
}
currentFolder = nil
currentAsset = file // We use this later to populate the table view
removePoi.isEnabled = false
if let player = editPlayerView.player {
let localitem = AVPlayerItem(url: URL(fileURLWithPath: file.url))
currentAssetDuration = Int(localitem.asset.duration.convertScale(1, method: .default).value)
let currentResolution = getResolution(asset: localitem.asset)
let crString = String(Int(currentResolution.width)) + "x" + String(Int(currentResolution.height))
timeTextStepper.minValue = 0
timeTextStepper.maxValue = Double(currentAssetDuration!)
timeTextFormatter.minimum = 0
timeTextFormatter.maximum = NSNumber(value: currentAssetDuration!)
durationLabel.stringValue = String(currentAssetDuration!) + " seconds"
resolutionLabel.stringValue = crString
player.replaceCurrentItem(with: localitem)
}
poiTableView.reloadData()
} else {
topPathControl.isHidden = true
folderView.isHidden = true
fileView.isHidden = true
onboardingLabel.isHidden = false
}
return true
}
func getResolution(asset: AVAsset) -> CGSize {
guard let track = asset.tracks(withMediaType: AVMediaType.video).first else { return CGSize.zero }
let size = track.naturalSize.applying(track.preferredTransform)
return CGSize(width: abs(size.width), height: abs(size.height))
}
func outlineView(_ outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: Any?, proposedChildIndex index: Int) -> NSDragOperation {
return NSDragOperation.copy
}
func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool {
if let items = info.draggingPasteboard.pasteboardItems {
for item in items {
if #available(OSX 10.13, *) {
if let str = item.string(forType: .fileURL) {
let surl = URL(fileURLWithPath: str).standardized
debugLog("received drop \(surl)")
if surl.isDirectory {
debugLog("processing dir")
self.processPathForVideos(url: surl)
}
}
} else {
// Fallback on earlier versions
}
}
}
return true
}
}
// MARK: - Extension for poi table view
extension CustomVideoController: NSTableViewDataSource, NSTableViewDelegate {
// currentAsset contains the selected video asset
func numberOfRows(in tableView: NSTableView) -> Int {
if let asset = currentAsset {
return asset.pointsOfInterest.count
} else {
return 0
}
}
// This is where we populate the tableview
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if let asset = currentAsset {
var text: String
if tableColumn!.identifier.rawValue == "timeColumn" {
let keys = asset.pointsOfInterest.keys.map { Int($0)!}.sorted()
text = String(keys[row])
} else {
let keys = asset.pointsOfInterest.keys.map { Int($0)!}.sorted()
text = asset.pointsOfInterest[String(keys[row])]!
}
if let cell = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as? NSTableCellView {
cell.textField?.stringValue = text
cell.imageView?.image = nil
return cell
}
}
return nil
}
func tableViewSelectionDidChange(_ notification: Notification) {
if let asset = currentAsset {
if poiTableView.selectedRow >= 0 {
removePoi.isEnabled = true
let keys = asset.pointsOfInterest.keys.map { Int($0)!}.sorted()
if let player = editPlayerView.player {
player.seek(to: CMTime(seconds: Double(keys[poiTableView.selectedRow]), preferredTimescale: 1))
}
} else {
removePoi.isEnabled = false
}
}
}
}
extension Dictionary {
mutating func switchKey(fromKey: Key, toKey: Key) {
if let entry = removeValue(forKey: fromKey) {
self[toKey] = entry
}
}
}
extension URL {
/*var isDirectory: Bool? {
do {
let values = try self.resourceValues(
forKeys: Set([URLResourceKey.isDirectoryKey])
)
return values.isDirectory
} catch { return nil }
}*/
var isDirectory: Bool {
return (try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true
}
var subDirectories: [URL] {
guard isDirectory else { return [] }
return (try? FileManager.default.contentsOfDirectory(at: self,
includingPropertiesForKeys: nil,
options: [.skipsHiddenFiles]).filter(\.isDirectory)) ?? []
}
}
extension CustomVideoController: NSMenuDelegate {
func menuNeedsUpdate(_ menu: NSMenu) {
let row = folderOutlineView.clickedRow
guard row != -1 else { return }
let rowItem = folderOutlineView.item(atRow: row)
if (rowItem as? Folder) != nil {
menuRemoveVideo.isHidden = true
menuRemoveFolderAndVideos.isHidden = false
} else if (rowItem as? Asset) != nil {
menuRemoveVideo.isHidden = false
menuRemoveFolderAndVideos.isHidden = true
}
// Mark the clicked item here
for item in menu.items {
item.representedObject = rowItem
}
}
}
| mit | be4fd57a222faec1648ad61387a3e49b | 36.87541 | 162 | 0.580679 | 5.167524 | false | false | false | false |
EclipseSoundscapes/EclipseSoundscapes | EclipseSoundscapes/Features/About/Legal/PhotoCredits/Cells/PhotoCreditCell.swift | 1 | 4083 | //
// PhotoCreditCell.swift
// EclipseSoundscapes
//
// Created by Arlindo Goncalves on 8/1/17.
//
// Copyright © 2017 Arlindo Goncalves.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see [http://www.gnu.org/licenses/].
//
// For Contact email: [email protected]
import Eureka
struct PhotoCredit : Equatable {
var name: String
var website: String
var makers: String
var photo: UIImage?
init(name: String, website: String, makers: String, photo: UIImage?) {
self.name = name
self.website = website
self.makers = makers
self.photo = photo
}
static func == (lhs: PhotoCredit, rhs: PhotoCredit) -> Bool {
return lhs.name == rhs.name
}
}
final class PhotoCreditCell: Cell<PhotoCredit>, CellType {
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var websiteBtn: UIButton!
required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func setup() {
super.setup()
selectionStyle = .none
nameLabel.font = UIFont.getDefautlFont(.meduium, size: 15)
nameLabel.adjustsFontSizeToFitWidth = true
nameLabel.textAlignment = .center
nameLabel.numberOfLines = 0
websiteBtn.titleLabel?.font = UIFont.getDefautlFont(.condensedMedium, size: 14)
websiteBtn.titleLabel?.adjustsFontSizeToFitWidth = true
websiteBtn.contentHorizontalAlignment = .center
websiteBtn.addTarget(self, action: #selector(openWebsite), for: .touchUpInside)
websiteBtn.isAccessibilityElement = false
photoImageView.contentMode = .scaleAspectFit
photoImageView.clipsToBounds = true
height = { return 125 }
accessibilityTraits = [UIAccessibilityTraits.link, UIAccessibilityTraits.header]
}
override func update() {
super.update()
if let credit = row.value {
nameLabel.text = credit.name + "\n" + credit.makers
websiteBtn.setTitle(credit.website, for: .normal)
if let photo = credit.photo {
photoImageView.image = photo
}
self.accessibilityLabel = credit.name + " " + credit.makers
}
}
override func accessibilityActivate() -> Bool {
self.openWebsite()
return true
}
@objc func openWebsite() {
guard
let photo = row.value,
let url = URL.init(string: photo.website)
else { return }
let alert = UIAlertController(title: localizedString(key: "Open in Safari"), message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: localizedString(key: "Sure"), style: .default) { _ in
LinkManager.shared.openUrl(url)
})
alert.addAction(UIAlertAction(title: localizedString(key: "Cancel"), style: .default, handler: nil))
let top = UIApplication.shared.getTopViewController()
top.present(alert, animated: true, completion: nil)
}
}
final class PhotoCreditRow: Row<PhotoCreditCell>, RowType {
required init(tag: String?) {
super.init(tag: tag)
cellProvider = CellProvider<PhotoCreditCell>(nibName: "PhotoCreditCell")
}
}
| gpl-3.0 | 7897a02cc952d282f705ecea004d1af9 | 33.302521 | 122 | 0.650661 | 4.530522 | false | false | false | false |
arnaudbenard/npm-stats | Pods/Charts/Charts/Classes/Components/ChartYAxis.swift | 66 | 7530 | //
// ChartYAxis.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
/// Class representing the y-axis labels settings and its entries.
/// Be aware that not all features the YLabels class provides are suitable for the RadarChart.
/// Customizations that affect the value range of the axis need to be applied before setting data for the chart.
public class ChartYAxis: ChartAxisBase
{
@objc
public enum YAxisLabelPosition: Int
{
case OutsideChart
case InsideChart
}
/// Enum that specifies the axis a DataSet should be plotted against, either Left or Right.
@objc
public enum AxisDependency: Int
{
case Left
case Right
}
public var entries = [Double]()
public var entryCount: Int { return entries.count; }
/// the number of y-label entries the y-labels should have, default 6
private var _labelCount = Int(6)
/// indicates if the top y-label entry is drawn or not
public var drawTopYLabelEntryEnabled = true
/// if true, the y-labels show only the minimum and maximum value
public var showOnlyMinMaxEnabled = false
/// flag that indicates if the axis is inverted or not
public var inverted = false
/// if true, the y-label entries will always start at zero
public var startAtZeroEnabled = true
/// if true, the set number of y-labels will be forced
public var forceLabelsEnabled = true
/// the formatter used to customly format the y-labels
public var valueFormatter: NSNumberFormatter?
/// the formatter used to customly format the y-labels
internal var _defaultValueFormatter = NSNumberFormatter()
/// A custom minimum value for this axis.
/// If set, this value will not be calculated automatically depending on the provided data.
/// Use resetCustomAxisMin() to undo this.
/// Do not forget to set startAtZeroEnabled = false if you use this method.
/// Otherwise, the axis-minimum value will still be forced to 0.
public var customAxisMin = Double.NaN
/// Set a custom maximum value for this axis.
/// If set, this value will not be calculated automatically depending on the provided data.
/// Use resetCustomAxisMax() to undo this.
public var customAxisMax = Double.NaN
/// axis space from the largest value to the top in percent of the total axis range
public var spaceTop = CGFloat(0.1)
/// axis space from the smallest value to the bottom in percent of the total axis range
public var spaceBottom = CGFloat(0.1)
public var axisMaximum = Double(0)
public var axisMinimum = Double(0)
/// the total range of values this axis covers
public var axisRange = Double(0)
/// the position of the y-labels relative to the chart
public var labelPosition = YAxisLabelPosition.OutsideChart
/// the side this axis object represents
private var _axisDependency = AxisDependency.Left
/// the minimum width that the axis should take
/// :default 0.0
public var minWidth = CGFloat(0)
/// the maximum width that the axis can take.
/// use zero for disabling the maximum
/// :default 0.0 (no maximum specified)
public var maxWidth = CGFloat(0)
public override init()
{
super.init()
_defaultValueFormatter.minimumIntegerDigits = 1
_defaultValueFormatter.maximumFractionDigits = 1
_defaultValueFormatter.minimumFractionDigits = 1
_defaultValueFormatter.usesGroupingSeparator = true
self.yOffset = 0.0
}
public init(position: AxisDependency)
{
super.init()
_axisDependency = position
_defaultValueFormatter.minimumIntegerDigits = 1
_defaultValueFormatter.maximumFractionDigits = 1
_defaultValueFormatter.minimumFractionDigits = 1
_defaultValueFormatter.usesGroupingSeparator = true
self.yOffset = 0.0
}
public var axisDependency: AxisDependency
{
return _axisDependency
}
public func setLabelCount(count: Int, force: Bool)
{
_labelCount = count
if (_labelCount > 25)
{
_labelCount = 25
}
if (_labelCount < 2)
{
_labelCount = 2
}
forceLabelsEnabled = force
}
/// the number of label entries the y-axis should have
/// max = 25,
/// min = 2,
/// default = 6,
/// be aware that this number is not fixed and can only be approximated
public var labelCount: Int
{
get
{
return _labelCount
}
set
{
setLabelCount(newValue, force: false);
}
}
/// By calling this method, any custom minimum value that has been previously set is reseted, and the calculation is done automatically.
public func resetCustomAxisMin()
{
customAxisMin = Double.NaN
}
/// By calling this method, any custom maximum value that has been previously set is reseted, and the calculation is done automatically.
public func resetCustomAxisMax()
{
customAxisMax = Double.NaN
}
public func requiredSize() -> CGSize
{
var label = getLongestLabel() as NSString
var size = label.sizeWithAttributes([NSFontAttributeName: labelFont])
size.width += xOffset * 2.0
size.height += yOffset * 2.0
size.width = max(minWidth, min(size.width, maxWidth > 0.0 ? maxWidth : size.width))
return size
}
public func getRequiredHeightSpace() -> CGFloat
{
return requiredSize().height + 2.5 * 2.0 + yOffset
}
public override func getLongestLabel() -> String
{
var longest = ""
for (var i = 0; i < entries.count; i++)
{
var text = getFormattedLabel(i)
if (count(longest) < count(text))
{
longest = text
}
}
return longest
}
/// Returns the formatted y-label at the specified index. This will either use the auto-formatter or the custom formatter (if one is set).
public func getFormattedLabel(index: Int) -> String
{
if (index < 0 || index >= entries.count)
{
return ""
}
return (valueFormatter ?? _defaultValueFormatter).stringFromNumber(entries[index])!
}
/// Returns true if this axis needs horizontal offset, false if no offset is needed.
public var needsOffset: Bool
{
if (isEnabled && isDrawLabelsEnabled && labelPosition == .OutsideChart)
{
return true
}
else
{
return false
}
}
public var isInverted: Bool { return inverted; }
public var isStartAtZeroEnabled: Bool { return startAtZeroEnabled; }
/// :returns: true if focing the y-label count is enabled. Default: false
public var isForceLabelsEnabled: Bool { return forceLabelsEnabled }
public var isShowOnlyMinMaxEnabled: Bool { return showOnlyMinMaxEnabled; }
public var isDrawTopYLabelEntryEnabled: Bool { return drawTopYLabelEntryEnabled; }
} | mit | 3fc56da0d7f11bfe5a5c80dfb65cf8d7 | 29.864754 | 142 | 0.632935 | 5.013316 | false | false | false | false |
milseman/swift | stdlib/public/SDK/XCTest/XCTest.swift | 4 | 46791 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import XCTest // Clang module
import CoreGraphics
import _SwiftXCTestOverlayShims
// --- XCTest API Swiftification ---
public extension XCTContext {
/// Create and run a new activity with provided name and block.
public class func runActivity<Result>(named name: String, block: (XCTActivity) throws -> Result) rethrows -> Result {
let context = _XCTContextCurrent()
if _XCTContextShouldStartActivity(context, XCTActivityTypeUserCreated) {
return try autoreleasepool {
let activity = _XCTContextWillStartActivity(context, name, XCTActivityTypeUserCreated)
defer {
_XCTContextDidFinishActivity(context, activity)
}
return try block(activity)
}
} else {
fatalError("XCTContext.runActivity(named:block:) failed because activities are disallowed in the current configuration.")
}
}
}
#if os(macOS)
@available(swift 4.0)
@available(macOS 10.11, *)
public extension XCUIElement {
/// Types a single key from the XCUIKeyboardKey enumeration with the specified modifier flags.
@nonobjc public func typeKey(_ key: XCUIKeyboardKey, modifierFlags: XCUIKeyModifierFlags) {
// Call the version of the method defined in XCTest.framework.
typeKey(key.rawValue, modifierFlags: modifierFlags)
}
}
#endif
// --- Failure Formatting ---
/// Register the failure, expected or unexpected, of the current test case.
func _XCTRegisterFailure(_ expected: Bool, _ condition: String, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) {
// Call the real _XCTFailureHandler.
let test = _XCTCurrentTestCase()
_XCTPreformattedFailureHandler(test, expected, file.description, line, condition, message())
}
/// Produce a failure description for the given assertion type.
func _XCTFailureDescription(_ assertionType: _XCTAssertionType, _ formatIndex: UInt, _ expressionStrings: CVarArg...) -> String {
// In order to avoid revlock/submission issues between XCTest and the Swift XCTest overlay,
// we are using the convention with _XCTFailureFormat that (formatIndex >= 100) should be
// treated just like (formatIndex - 100), but WITHOUT the expression strings. (Swift can't
// stringify the expressions, only their values.) This way we don't have to introduce a new
// BOOL parameter to this semi-internal function and coordinate that across builds.
//
// Since there's a single bottleneck in the overlay where we invoke _XCTFailureFormat, just
// add the formatIndex adjustment there rather than in all of the individual calls to this
// function.
return String(format: _XCTFailureFormat(assertionType, formatIndex + 100), arguments: expressionStrings)
}
// --- Exception Support ---
/// The Swift-style result of evaluating a block which may throw an exception.
enum _XCTThrowableBlockResult {
case success
case failedWithError(error: Error)
case failedWithException(className: String, name: String, reason: String)
case failedWithUnknownException
}
/// Asks some Objective-C code to evaluate a block which may throw an exception or error,
/// and if it does consume the exception and return information about it.
func _XCTRunThrowableBlock(_ block: () throws -> Void) -> _XCTThrowableBlockResult {
var blockErrorOptional: Error?
let exceptionResult = _XCTRunThrowableBlockBridge({
do {
try block()
} catch {
blockErrorOptional = error
}
})
if let blockError = blockErrorOptional {
return .failedWithError(error: blockError)
} else if let exceptionResult = exceptionResult {
if exceptionResult["type"] == "objc" {
return .failedWithException(
className: exceptionResult["className"]!,
name: exceptionResult["name"]!,
reason: exceptionResult["reason"]!)
} else {
return .failedWithUnknownException
}
} else {
return .success
}
}
// --- Supported Assertions ---
public func XCTFail(_ message: String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.fail
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, "" as NSString), message, file, line)
}
public func XCTAssertNil(_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.`nil`
// evaluate the expression exactly once
var expressionValueOptional: Any?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
// test both Optional and value to treat .none and nil as synonymous
var passed: Bool
var expressionValueStr: String = "nil"
if let expressionValueUnwrapped = expressionValueOptional {
passed = false
expressionValueStr = "\(expressionValueUnwrapped)"
} else {
passed = true
}
if !passed {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNil failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotNil(_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notNil
// evaluate the expression exactly once
var expressionValueOptional: Any?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
// test both Optional and value to treat .none and nil as synonymous
var passed: Bool
var expressionValueStr: String = "nil"
if let expressionValueUnwrapped = expressionValueOptional {
passed = true
expressionValueStr = "\(expressionValueUnwrapped)"
} else {
passed = false
}
if !passed {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotNil failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssert(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
// XCTAssert is just a cover for XCTAssertTrue.
XCTAssertTrue(expression, message, file: file, line: line)
}
public func XCTAssertTrue(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.`true`
// evaluate the expression exactly once
var expressionValueOptional: Bool?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
let expressionValue = expressionValueOptional!
if !expressionValue {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertTrue failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertFalse(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.`false`
// evaluate the expression exactly once
var expressionValueOptional: Bool?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
let expressionValue = expressionValueOptional!
if expressionValue {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertFalse failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: T = expressionValue1Optional!
let expressionValue2: T = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
// FIXME(ABI): once <rdar://problem/17144340> is implemented, this could be
// changed to take two T rather than two T? since Optional<Equatable>: Equatable
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T?, _ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
// FIXME: remove optionality once this is generic over Equatable T
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
if expressionValue1Optional != expressionValue2Optional {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
// once this function is generic over T, it will only print these
// values as optional when they are...
let expressionValueStr1 = String(describing: expressionValue1Optional)
let expressionValueStr2 = String(describing: expressionValue2Optional)
// FIXME: this file seems to use `as NSString` unnecessarily a lot,
// unless I'm missing something.
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
// FIXME(ABI): Due to <rdar://problem/17144340> we need overrides of
// XCTAssertEqual for:
// ContiguousArray<T>
// ArraySlice<T>
// Array<T>
// Dictionary<T, U>
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ArraySlice<T>, _ expression2: @autoclosure () throws -> ArraySlice<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: ArraySlice<T>?
var expressionValue2Optional: ArraySlice<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ArraySlice<T> = expressionValue1Optional!
let expressionValue2: ArraySlice<T> = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ContiguousArray<T>, _ expression2: @autoclosure () throws -> ContiguousArray<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: ContiguousArray<T>?
var expressionValue2Optional: ContiguousArray<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ContiguousArray<T> = expressionValue1Optional!
let expressionValue2: ContiguousArray<T> = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> [T], _ expression2: @autoclosure () throws -> [T], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: [T]?
var expressionValue2Optional: [T]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T] = expressionValue1Optional!
let expressionValue2: [T] = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T, U : Equatable>(_ expression1: @autoclosure () throws -> [T: U], _ expression2: @autoclosure () throws -> [T: U], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: [T: U]?
var expressionValue2Optional: [T: U]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T: U] = expressionValue1Optional!
let expressionValue2: [T: U] = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: T = expressionValue1Optional!
let expressionValue2: T = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T?, _ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
if expressionValue1Optional == expressionValue2Optional {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = String(describing: expressionValue1Optional)
let expressionValueStr2 = String(describing: expressionValue2Optional)
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
// FIXME: Due to <rdar://problem/16768059> we need overrides of XCTAssertNotEqual for:
// ContiguousArray<T>
// ArraySlice<T>
// Array<T>
// Dictionary<T, U>
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ContiguousArray<T>, _ expression2: @autoclosure () throws -> ContiguousArray<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: ContiguousArray<T>?
var expressionValue2Optional: ContiguousArray<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ContiguousArray<T> = expressionValue1Optional!
let expressionValue2: ContiguousArray<T> = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ArraySlice<T>, _ expression2: @autoclosure () throws -> ArraySlice<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: ArraySlice<T>?
var expressionValue2Optional: ArraySlice<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ArraySlice<T> = expressionValue1Optional!
let expressionValue2: ArraySlice<T> = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> [T], _ expression2: @autoclosure () throws -> [T], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: [T]?
var expressionValue2Optional: [T]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T] = expressionValue1Optional!
let expressionValue2: [T] = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T, U : Equatable>(_ expression1: @autoclosure () throws -> [T: U], _ expression2: @autoclosure () throws -> [T: U], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: [T: U]?
var expressionValue2Optional: [T: U]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T: U] = expressionValue1Optional!
let expressionValue2: [T: U] = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
func _XCTCheckEqualWithAccuracy_Double(_ value1: Double, _ value2: Double, _ accuracy: Double) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
func _XCTCheckEqualWithAccuracy_Float(_ value1: Float, _ value2: Float, _ accuracy: Float) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
func _XCTCheckEqualWithAccuracy_CGFloat(_ value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
public func XCTAssertEqual<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equalWithAccuracy
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
var equalWithAccuracy: Bool = false
switch (expressionValue1, expressionValue2, accuracy) {
case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble)
case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat)
case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat)
default:
// unknown type, fail with prejudice
_preconditionFailure("unsupported floating-point type passed to XCTAssertEqual")
}
if !equalWithAccuracy {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
let accuracyStr = "\(accuracy)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
@available(*, deprecated, renamed: "XCTAssertEqual(_:_:accuracy:file:line:)")
public func XCTAssertEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(expression1, expression2, accuracy: accuracy, message, file: file, line: line)
}
func _XCTCheckNotEqualWithAccuracy_Double(_ value1: Double, _ value2: Double, _ accuracy: Double) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
func _XCTCheckNotEqualWithAccuracy_Float(_ value1: Float, _ value2: Float, _ accuracy: Float) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
func _XCTCheckNotEqualWithAccuracy_CGFloat(_ value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
public func XCTAssertNotEqual<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqualWithAccuracy
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
var notEqualWithAccuracy: Bool = false
switch (expressionValue1, expressionValue2, accuracy) {
case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble)
case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat)
case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat)
default:
// unknown type, fail with prejudice
_preconditionFailure("unsupported floating-point type passed to XCTAssertNotEqual")
}
if !notEqualWithAccuracy {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
let accuracyStr = "\(accuracy)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
@available(*, deprecated, renamed: "XCTAssertNotEqual(_:_:accuracy:file:line:)")
public func XCTAssertNotEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
XCTAssertNotEqual(expression1, expression2, accuracy: accuracy, message, file: file, line: line)
}
public func XCTAssertGreaterThan<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.greaterThan
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 > expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertGreaterThan failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertGreaterThanOrEqual<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line)
{
let assertionType = _XCTAssertionType.greaterThanOrEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 >= expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertGreaterThanOrEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertLessThan<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.lessThan
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 < expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertLessThan failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertLessThanOrEqual<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line)
{
let assertionType = _XCTAssertionType.lessThanOrEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 <= expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertLessThanOrEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertThrowsError<T>(_ expression: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, _ errorHandler: (_ error: Error) -> Void = { _ in }) {
// evaluate expression exactly once
var caughtErrorOptional: Error?
let result = _XCTRunThrowableBlock {
do {
_ = try expression()
} catch {
caughtErrorOptional = error
}
}
switch result {
case .success:
if let caughtError = caughtErrorOptional {
errorHandler(caughtError)
} else {
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: did not throw an error", message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertThrowsError failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: throwing \(reason)", message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: throwing an unknown exception", message, file, line)
}
}
public func XCTAssertNoThrow<T>(_ expression: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.noThrow
let result = _XCTRunThrowableBlock { _ = try expression() }
switch result {
case .success:
return
case .failedWithError(let error):
_XCTRegisterFailure(true, "XCTAssertNoThrow failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
#if XCTEST_ENABLE_EXCEPTION_ASSERTIONS
// --- Currently-Unsupported Assertions ---
public func XCTAssertThrows(_ expression: @autoclosure () -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_Throws
// FIXME: Unsupported
}
public func XCTAssertThrowsSpecific(_ expression: @autoclosure () -> Any?, _ exception: Any, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_ThrowsSpecific
// FIXME: Unsupported
}
public func XCTAssertThrowsSpecificNamed(_ expression: @autoclosure () -> Any?, _ exception: Any, _ name: String, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_ThrowsSpecificNamed
// FIXME: Unsupported
}
public func XCTAssertNoThrowSpecific(_ expression: @autoclosure () -> Any?, _ exception: Any, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_NoThrowSpecific
// FIXME: Unsupported
}
public func XCTAssertNoThrowSpecificNamed(_ expression: @autoclosure () -> Any?, _ exception: Any, _ name: String, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_NoThrowSpecificNamed
// FIXME: Unsupported
}
#endif
| apache-2.0 | 84061dcabe47d57f47986bb2df161243 | 40.481383 | 259 | 0.709324 | 4.351437 | false | false | false | false |
mcberros/onTheMap | onTheMap/ParseApiConvenience.swift | 1 | 2580 | //
// ParseApiConvenience.swift
// onTheMap
//
// Created by Carmen Berros on 07/03/16.
// Copyright © 2016 mcberros. All rights reserved.
//
import Foundation
extension ParseApiClient {
func getLocationsList(completionHandler: (success: Bool, errorString: String?) -> Void){
let parameters = [ ParseApiClient.ParameterKeys.Limit: 100,
ParseApiClient.ParameterKeys.Order: ParseApiClient.ParameterValues.AscendingUpdatedAt]
let urlString = ParseApiClient.Constants.BaseParseURL + ParseApiClient.Methods.GetStudentLocationsMethod + ParseApiClient.escapedParameters(parameters as! [String : AnyObject])
taskForGETMethod(urlString) { (success, result, errorString) -> Void in
if success {
guard let results = result["results"] as? [[String: AnyObject]] else {
completionHandler(success: false, errorString: "No results for Students list")
return
}
Students.sharedInstance().students = StudentInformation.studentsFromResults(results)
completionHandler(success: true, errorString: "")
} else {
completionHandler(success: false, errorString: errorString)
}
}
}
func postStudentInformation(mediaURL: String, latitude: Double, longitude: Double, mapString: String, completionHandler: (success: Bool, errorString: String?) -> Void) {
let urlString = ParseApiClient.Constants.BaseParseURL + ParseApiClient.Methods.GetStudentLocationsMethod
let uniqueKey = UdacityApiClient.sharedInstance().userID!
let firstName = UdacityApiClient.sharedInstance().firstName!
let lastName = UdacityApiClient.sharedInstance().lastName!
let jsonBody: [String: AnyObject] = ["uniqueKey": uniqueKey, "firstName": firstName,
"lastName": lastName,
"mapString": mapString,
"mediaURL": mediaURL,
"latitude": latitude,
"longitude": longitude]
taskForPOSTMethod(urlString, jsonBody: jsonBody) {
(success, result, errorString) in
if success {
if let _ = result["objectID"] as? String {
completionHandler(success: true, errorString: errorString)
} else {
completionHandler(success: true, errorString: "No valid response form post student")
}
} else {
completionHandler(success: false, errorString: errorString)
}
}
}
}
| mit | 379f62adfba9befab45588a5d693adb8 | 39.936508 | 184 | 0.63513 | 5.384134 | false | false | false | false |
Stitch7/Instapod | Instapod/CoreData/CoreDataStore.swift | 1 | 4807 | //
// CoreDataStore.swift
// Instapod
//
// Created by Christopher Reitz on 23.11.15.
// Copyright © 2016 Christopher Reitz. All rights reserved.
//
import UIKit
import CoreData
class CoreDataStore {
// MARK: - Properties
let storeName: String
// MARK: - Initializer
init(storeName: String) {
self.storeName = storeName
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// Save Core Data store file to the application's documents directory
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count - 1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = Bundle.main.url(forResource: self.storeName, withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let options = [
NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true
]
let url = self.applicationDocumentsDirectory.appendingPathComponent("\(self.storeName).sqlite")
print(url)
// if NSFileManager.defaultManager().fileExistsAtPath(url.path!) == false {
// self.preloadDatabase()
// }
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
} catch {
// Report any error we got
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data." as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let domain = Bundle.main.bundleIdentifier
let wrappedError = NSError(domain: domain!, code: 9999, userInfo: dict)
// TODO: Replace this with code to handle the error appropriately.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
func preloadDatabase() {
let mainBundle = Bundle.main
let sourceURLs = [
mainBundle.url(forResource: storeName, withExtension: "sqlite")!,
mainBundle.url(forResource: storeName, withExtension: "sqlite-wal")!,
mainBundle.url(forResource: storeName, withExtension: "sqlite-shm")!
]
let destinationURLs = [
applicationDocumentsDirectory.appendingPathComponent("\(storeName).sqlite"),
applicationDocumentsDirectory.appendingPathComponent("\(storeName).sqlite-wal"),
applicationDocumentsDirectory.appendingPathComponent("\(storeName).sqlite-shm")
]
for i in 0..<sourceURLs.count {
do {
try FileManager.default.copyItem(at: sourceURLs[i], to: destinationURLs[i])
} catch {
print("ERROR: copy failed")
}
}
}
func deleteAllData(_ entity: String) {
print("truncating table \(entity) ...")
let fetchRequest: NSFetchRequest<NSManagedObject> = NSFetchRequest(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do {
let results = try managedObjectContext.fetch(fetchRequest)
for managedObject in results {
managedObjectContext.delete(managedObject)
}
try managedObjectContext.save()
managedObjectContext.reset()
} catch let error as NSError {
print("Detele all data in \(entity) error : \(error) \(error.userInfo)")
}
}
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// TODO: Replace this implementation with code to handle the error appropriately.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | b4834e0d249a2811cc64684b023f0f9d | 34.865672 | 137 | 0.636704 | 5.76259 | false | false | false | false |
freak4pc/netfox | netfox/Core/NFXProtocol.swift | 1 | 5736 | //
// NFXProtocol.swift
// netfox
//
// Copyright © 2016 netfox. All rights reserved.
//
import Foundation
@objc
open class NFXProtocol: URLProtocol
{
var connection: NSURLConnection?
var model: NFXHTTPModel?
var session: URLSession?
override open class func canInit(with request: URLRequest) -> Bool
{
return canServeRequest(request)
}
override open class func canInit(with task: URLSessionTask) -> Bool
{
guard let request = task.currentRequest else { return false }
return canServeRequest(request)
}
fileprivate class func canServeRequest(_ request: URLRequest) -> Bool
{
if !NFX.sharedInstance().isEnabled() {
return false
}
if let url = request.url {
if !(url.absoluteString.hasPrefix("http")) && !(url.absoluteString.hasPrefix("https")) {
return false
}
for ignoredURL in NFX.sharedInstance().getIgnoredURLs() {
if url.absoluteString.hasPrefix(ignoredURL) {
return false
}
}
} else {
return false
}
if URLProtocol.property(forKey: "NFXInternal", in: request) != nil {
return false
}
return true
}
override open func startLoading()
{
self.model = NFXHTTPModel()
var req: NSMutableURLRequest
req = (NFXProtocol.canonicalRequest(for: request) as NSURLRequest).mutableCopy() as! NSMutableURLRequest
self.model?.saveRequest(req as URLRequest)
URLProtocol.setProperty("1", forKey: "NFXInternal", in: req)
if session == nil {
session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
}
session!.dataTask(with: req as URLRequest, completionHandler: {data, response, error in
self.model?.saveRequestBody(req as URLRequest)
self.model?.logRequest(req as URLRequest)
if let error = error {
self.model?.saveErrorResponse()
self.loaded()
self.client?.urlProtocol(self, didFailWithError: error)
} else {
if let data = data {
self.model?.saveResponse(response!, data: data)
}
self.loaded()
}
if let response = response, let client = self.client {
client.urlProtocol(self, didReceive: response, cacheStoragePolicy: NFX.swiftSharedInstance.cacheStoragePolicy)
}
if let data = data {
self.client!.urlProtocol(self, didLoad: data)
}
if let client = self.client {
client.urlProtocolDidFinishLoading(self)
}
}).resume()
}
override open func stopLoading()
{
}
override open class func canonicalRequest(for request: URLRequest) -> URLRequest
{
return request
}
func loaded()
{
if (self.model != nil) {
NFXHTTPModelManager.sharedInstance.add(self.model!)
}
NotificationCenter.default.post(name: Notification.Name.NFXReloadData, object: nil)
}
}
extension NFXProtocol : URLSessionDelegate {
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
client?.urlProtocol(self, didLoad: data)
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
let policy = URLCache.StoragePolicy(rawValue: request.cachePolicy.rawValue) ?? .notAllowed
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: policy)
completionHandler(.allow)
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error {
client?.urlProtocol(self, didFailWithError: error)
} else {
client?.urlProtocolDidFinishLoading(self)
}
}
public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
if let mutableRequest = (request as NSURLRequest).mutableCopy() as? NSMutableURLRequest {
URLProtocol.removeProperty(forKey: "NFXInternal", in: mutableRequest)
client?.urlProtocol(self, wasRedirectedTo: request, redirectResponse: response)
completionHandler(request)
}
}
public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
guard let error = error else { return }
client?.urlProtocol(self, didFailWithError: error)
}
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let wrappedChallenge = URLAuthenticationChallenge(authenticationChallenge: challenge, sender: NFXAuthenticationChallengeSender(handler: completionHandler))
client?.urlProtocol(self, didReceive: wrappedChallenge)
}
#if !os(OSX)
public func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
client?.urlProtocolDidFinishLoading(self)
}
#endif
}
| mit | 9bc6e004af7f4436b127d66d42ccc6d5 | 34.401235 | 211 | 0.617437 | 5.498562 | false | false | false | false |
CocoaHeadsConference/CHConferenceApp | NSBrazilConf/Extensions/String+CMTime.swift | 1 | 1539 | //
// String+CMTime.swift
// CocoaheadsConf
//
// Created by Guilherme Rambo on 24/11/16.
// Copyright © 2016 Cocoaheads. All rights reserved.
//
import Foundation
import CoreMedia
extension String {
init?(time: CMTime) {
guard time.isValid
&& !time.isIndefinite
&& !time.isNegativeInfinity
&& !time.isPositiveInfinity else { return nil }
self.init(Float(CMTimeGetSeconds(time)))
}
init?(time: Float) {
let date = Date(timeInterval: TimeInterval(time), since: Date())
let components = Calendar.current.dateComponents([.hour, .minute, .second], from: Date(), to: date)
var output = ""
if let hours = components.hour, hours > 0 {
output = output.appendingFormat("%02d:", abs(hours))
}
if let minutes = components.minute {
output = output.appendingFormat("%02d:", abs(minutes))
}
if let seconds = components.second {
output = output.appendingFormat("%02d", abs(seconds))
} else {
return nil
}
self.init(output)
}
}
extension DateFormatter {
static let yyyyMMdd: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.calendar = Calendar(identifier: .iso8601)
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
}
| mit | 60965fc48231ce9e6db1e31cdcca6fd8 | 25.517241 | 107 | 0.583875 | 4.47093 | false | false | false | false |
pinterest/plank | Examples/Cocoa/Tests/Objective_CTests/ObjcEqualityTests.swift | 1 | 15087 | //
// ObjcEqualityTests.swift
// CoreTests
//
// Created by Greg Bolsinga on 6/10/19.
//
import XCTest
@testable import Objective_C
class ObjcEqualityTests: XCTestCase {
func testEquality_arrayProp() {
let t: [String] = ["String"]
let builder = EverythingBuilder()
builder.arrayProp = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.arrayProp as? [String], t)
XCTAssertEqual(e2.arrayProp as? [String], t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_booleanProp() {
let t = true
let builder = EverythingBuilder()
builder.booleanProp = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.booleanProp, t)
XCTAssertEqual(e2.booleanProp, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_charEnum() {
let t = EverythingCharEnum.charCase1
let builder = EverythingBuilder()
builder.charEnum = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.charEnum, t)
XCTAssertEqual(e2.charEnum, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_dateProp() {
let t = NSDate.distantFuture
let builder = EverythingBuilder()
builder.dateProp = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.dateProp, t)
XCTAssertEqual(e2.dateProp, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_intEnum() {
let t = EverythingIntEnum.intCase1
let builder = EverythingBuilder()
builder.intEnum = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.intEnum, t)
XCTAssertEqual(e2.intEnum, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_intProp() {
let t = 23
let builder = EverythingBuilder()
builder.intProp = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.intProp, t)
XCTAssertEqual(e2.intProp, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_listPolymorphicValues() {
let t: [String] = ["String"]
let builder = EverythingBuilder()
builder.listPolymorphicValues = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.listPolymorphicValues as? [String], t)
XCTAssertEqual(e2.listPolymorphicValues as? [String], t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_listWithListAndOtherModelValues() {
let t: [[User]] = [[UserBuilder().build()]]
let builder = EverythingBuilder()
builder.listWithListAndOtherModelValues = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.listWithListAndOtherModelValues, t)
XCTAssertEqual(e2.listWithListAndOtherModelValues, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_listWithMapAndOtherModelValues() {
let t: [[String: User]] = [["k": UserBuilder().build()]]
let builder = EverythingBuilder()
builder.listWithMapAndOtherModelValues = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.listWithMapAndOtherModelValues, t)
XCTAssertEqual(e2.listWithMapAndOtherModelValues, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_listWithObjectValues() {
let t: [String] = ["String"]
let builder = EverythingBuilder()
builder.listWithObjectValues = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.listWithObjectValues, t)
XCTAssertEqual(e2.listWithObjectValues, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_listWithOtherModelValues() {
let t: [User] = [UserBuilder().build()]
let builder = EverythingBuilder()
builder.listWithOtherModelValues = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.listWithOtherModelValues, t)
XCTAssertEqual(e2.listWithOtherModelValues, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_listWithPrimitiveValues() {
let t: [Int] = [23]
let builder = EverythingBuilder()
builder.listWithPrimitiveValues = t as [NSNumber]
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.listWithPrimitiveValues as? [Int], t)
XCTAssertEqual(e2.listWithPrimitiveValues as? [Int], t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_mapPolymorphicValues() {
let t: [String: EverythingMapPolymorphicValues] = ["k": EverythingMapPolymorphicValues.object(with: UserBuilder().build())]
let builder = EverythingBuilder()
builder.mapPolymorphicValues = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.mapPolymorphicValues, t)
XCTAssertEqual(e2.mapPolymorphicValues, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_mapProp() {
let t: [Int: Int] = [23: 45]
let builder = EverythingBuilder()
builder.mapProp = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.mapProp as? [Int: Int], t)
XCTAssertEqual(e2.mapProp as? [Int: Int], t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_mapWithListAndOtherModelValues() {
let t: [String: [User]] = ["k": [UserBuilder().build()]]
let builder = EverythingBuilder()
builder.mapWithListAndOtherModelValues = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.mapWithListAndOtherModelValues, t)
XCTAssertEqual(e2.mapWithListAndOtherModelValues, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_mapWithMapAndOtherModelValues() {
let t: [String: [Int: Int]] = ["k": [23: 45]]
let builder = EverythingBuilder()
builder.mapWithMapAndOtherModelValues = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.mapWithMapAndOtherModelValues as? [String: [Int: Int]], t)
XCTAssertEqual(e2.mapWithMapAndOtherModelValues as? [String: [Int: Int]], t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_mapWithObjectValues() {
let t: [String: String] = ["k": "v"]
let builder = EverythingBuilder()
builder.mapWithObjectValues = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.mapWithObjectValues, t)
XCTAssertEqual(e2.mapWithObjectValues, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_mapWithOtherModelValues() {
let t: [String: User] = ["k": UserBuilder().build()]
let builder = EverythingBuilder()
builder.mapWithOtherModelValues = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.mapWithOtherModelValues, t)
XCTAssertEqual(e2.mapWithOtherModelValues, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_mapWithPrimitiveValues() {
let t: [String: Int] = ["k": 23]
let builder = EverythingBuilder()
builder.mapWithPrimitiveValues = t as [String: NSNumber]
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.mapWithPrimitiveValues as? [String: Int], t)
XCTAssertEqual(e2.mapWithPrimitiveValues as? [String: Int], t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_nsintegerEnum() {
let t = EverythingNsintegerEnum.nsintegerCase1
let builder = EverythingBuilder()
builder.nsintegerEnum = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.nsintegerEnum, t)
XCTAssertEqual(e2.nsintegerEnum, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_nsuintegerEnum() {
let t = EverythingNsuintegerEnum.nsuintegerCase2
let builder = EverythingBuilder()
builder.nsuintegerEnum = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.nsuintegerEnum, t)
XCTAssertEqual(e2.nsuintegerEnum, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_numberProp() {
let t = 2.3
let builder = EverythingBuilder()
builder.numberProp = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.numberProp, t)
XCTAssertEqual(e2.numberProp, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_otherModelProp() {
let t = UserBuilder().build()
let builder = EverythingBuilder()
builder.otherModelProp = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.otherModelProp, t)
XCTAssertEqual(e2.otherModelProp, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_polymorphicProp() {
let t = EverythingPolymorphicProp.object(withBoolean: true)
let builder = EverythingBuilder()
builder.polymorphicProp = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.polymorphicProp, t)
XCTAssertEqual(e2.polymorphicProp, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_setProp() {
let t: Set = [23]
let builder = EverythingBuilder()
builder.setProp = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.setProp, t)
XCTAssertEqual(e2.setProp, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_setPropWithOtherModelValues() {
let t: Set = [UserBuilder().build()]
let builder = EverythingBuilder()
builder.setPropWithOtherModelValues = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.setPropWithOtherModelValues, t)
XCTAssertEqual(e2.setPropWithOtherModelValues, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_setPropWithPrimitiveValues() {
let t: Set = [23]
let builder = EverythingBuilder()
builder.setPropWithPrimitiveValues = t as Set<NSNumber>
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.setPropWithPrimitiveValues as? Set<Int>, t)
XCTAssertEqual(e2.setPropWithPrimitiveValues as? Set<Int>, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_setPropWithValues() {
let t: Set = ["string"]
let builder = EverythingBuilder()
builder.setPropWithValues = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.setPropWithValues, t)
XCTAssertEqual(e2.setPropWithValues, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_shortEnum() {
let t = EverythingShortEnum.shortCase1
let builder = EverythingBuilder()
builder.shortEnum = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.shortEnum, t)
XCTAssertEqual(e2.shortEnum, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_stringEnum() {
let t = EverythingStringEnum.case1
let builder = EverythingBuilder()
builder.stringEnum = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.stringEnum, t)
XCTAssertEqual(e2.stringEnum, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_stringProp() {
let t = "test"
let builder = EverythingBuilder()
builder.stringProp = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.stringProp, t)
XCTAssertEqual(e2.stringProp, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_type() {
let t = "type"
let builder = EverythingBuilder()
builder.type = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.type, t)
XCTAssertEqual(e2.type, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_unsignedCharEnum() {
let t = EverythingUnsignedCharEnum.unsignedCharCase2
let builder = EverythingBuilder()
builder.unsignedCharEnum = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.unsignedCharEnum, t)
XCTAssertEqual(e2.unsignedCharEnum, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_unsignedIntEnum() {
let t = EverythingUnsignedIntEnum.unsignedIntCase2
let builder = EverythingBuilder()
builder.unsignedIntEnum = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.unsignedIntEnum, t)
XCTAssertEqual(e2.unsignedIntEnum, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_unsignedShortEnum() {
let t = EverythingUnsignedShortEnum.charCase2
let builder = EverythingBuilder()
builder.unsignedShortEnum = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.unsignedShortEnum, t)
XCTAssertEqual(e2.unsignedShortEnum, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
func testEquality_uriProp() {
let t = URL(string: "http://example.com")
let builder = EverythingBuilder()
builder.uriProp = t
let e1 = builder.build()
let e2 = builder.build()
XCTAssertEqual(e1.uriProp, t)
XCTAssertEqual(e2.uriProp, t)
XCTAssertEqual(e1, e2)
XCTAssertEqual(e1.hash, e2.hash)
}
}
| apache-2.0 | b5815553e8092134a0f356bdb906100c | 32.97973 | 131 | 0.62239 | 3.923797 | false | true | false | false |
chronodm/apsu-core-swift | ApsuCore/Entity.swift | 1 | 1012 | //
// Entity.swift
// ApsuCore
//
// Created by David Moles on 7/4/14.
// Copyright (c) 2014 David Moles. All rights reserved.
//
public struct Entity: Hashable, CustomStringConvertible {
// ------------------------------------------------------------
// MARK: - Fields
public let id: CFUUID
public let hashValue: Int
public var description: String {
get {
let idString = CFUUIDCreateString(nil, id) as String
return "Entity(\(idString))"
}
}
// ------------------------------------------------------------
// MARK: - Initializers
public init(_ id: CFUUID) {
self.id = id
self.hashValue = Int(CFHash(id))
}
public init() {
let uuid = CFUUIDCreate(nil)
self.id = uuid
self.hashValue = Int(CFHash(uuid))
}
}
// ------------------------------------------------------------
// MARK: - Equatable
public func == (lhs: Entity, rhs: Entity) -> Bool {
return lhs.id == rhs.id
}
| mit | 4f47c27c55712752f182f0103407fe55 | 23.095238 | 67 | 0.462451 | 4.438596 | false | false | false | false |
montionugera/yellow | yellow-ios/SwiftyRecordButton.swift | 1 | 3454 | /*Copyright (c) 2016, Andrew Walz.
Redistribution and use in source and binary forms, with or without modification,are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import UIKit
import SwiftyCam
class SwiftyRecordButton: SwiftyCamButton {
private var circleBorder: CALayer!
private var innerCircle: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
drawButton()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
drawButton()
}
private func drawButton() {
self.backgroundColor = UIColor.clear
circleBorder = CALayer()
circleBorder.backgroundColor = UIColor.clear.cgColor
circleBorder.borderWidth = 6.0
circleBorder.borderColor = UIColor.white.cgColor
circleBorder.bounds = self.bounds
circleBorder.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
circleBorder.cornerRadius = self.frame.size.width / 2
layer.insertSublayer(circleBorder, at: 0)
}
public func growButton() {
innerCircle = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
innerCircle.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
innerCircle.backgroundColor = UIColor.red
innerCircle.layer.cornerRadius = innerCircle.frame.size.width / 2
innerCircle.clipsToBounds = true
self.addSubview(innerCircle)
UIView.animate(withDuration: 0.6, delay: 0.0, options: .curveEaseOut, animations: {
self.innerCircle.transform = CGAffineTransform(scaleX: 62.4, y: 62.4)
self.circleBorder.setAffineTransform(CGAffineTransform(scaleX: 1.352, y: 1.352))
self.circleBorder.borderWidth = (6 / 1.352)
}, completion: nil)
}
public func shrinkButton() {
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: {
self.innerCircle.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.circleBorder.setAffineTransform(CGAffineTransform(scaleX: 1.0, y: 1.0))
self.circleBorder.borderWidth = 6.0
}, completion: { (success) in
self.innerCircle.removeFromSuperview()
self.innerCircle = nil
})
}
}
| mit | fd0b7c87d207195a81301a35a7d7ceef | 45.675676 | 161 | 0.696873 | 4.764138 | false | false | false | false |
HabitRPG/habitrpg-ios | Habitica API Client/Habitica API Client/Base/HabiticaResponse.swift | 1 | 1209 | //
// HabiticaResponse.swift
// Habitica API Client
//
// Created by Phillip Thelen on 07.03.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
public class HabiticaResponse<T: Decodable>: Decodable {
public var success: Bool = false
public var data: T?
public var error: String?
public var message: String?
public var userV: Int?
public var notifications: [NotificationProtocol]?
enum CodingKeys: String, CodingKey {
case success
case data
case error
case message
case userV
case notifications
}
required public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
success = (try? values.decode(Bool.self, forKey: .success)) ?? true
data = try? values.decode(T.self, forKey: .data)
error = try? values.decode(String.self, forKey: .error)
message = try? values.decode(String.self, forKey: .message)
userV = (try? values.decode(Int.self, forKey: .userV)) ?? 0
notifications = try? values.decode([APINotification].self, forKey: .notifications)
}
}
| gpl-3.0 | f38757584ca248cdcff5da194574ff73 | 29.974359 | 90 | 0.652318 | 4.122867 | false | false | false | false |
tad-iizuka/swift-sdk | Source/ToneAnalyzerV3/ToneAnalyzer.swift | 1 | 5426 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/**
The IBM Watson Tone Analyzer service uses linguistic analysis to detect emotional tones,
social propensities, and writing styles in written communication. Then it offers suggestions
to help the writer improve their intended language tones.
**/
public class ToneAnalyzer {
/// The base URL to use when contacting the service.
public var serviceURL = "https://gateway.watsonplatform.net/tone-analyzer/api"
/// The default HTTP headers for all requests to the service.
public var defaultHeaders = [String: String]()
private let credentials: Credentials
private let version: String
private let domain = "com.ibm.watson.developer-cloud.ToneAnalyzerV3"
/**
Create a `ToneAnalyzer` object.
- parameter username: The username used to authenticate with the service.
- parameter password: The password used to authenticate with the service.
- parameter version: The release date of the version of the API to use. Specify the date
in "YYYY-MM-DD" format.
*/
public init(username: String, password: String, version: String) {
self.credentials = Credentials.basicAuthentication(username: username, password: password)
self.version = version
}
/**
If the given data represents an error returned by the Visual Recognition service, then return
an NSError with information about the error that occured. Otherwise, return nil.
- parameter data: Raw data returned from the service that may represent an error.
*/
private func dataToError(data: Data) -> NSError? {
do {
let json = try JSON(data: data)
let code = try json.getInt(at: "code")
let error = try json.getString(at: "error")
let help = try? json.getString(at: "help")
let description = try? json.getString(at: "description")
var userInfo = [
NSLocalizedFailureReasonErrorKey: error
]
if let recoverySuggestion = help ?? description {
userInfo[NSLocalizedRecoverySuggestionErrorKey] = recoverySuggestion
}
return NSError(domain: domain, code: code, userInfo: userInfo)
} catch {
return nil
}
}
/**
Analyze the tone of the given text.
The message is analyzed for several tones—social, emotional, and writing. For each tone,
various traits are derived (e.g. conscientiousness, agreeableness, and openness).
- parameter ofText: The text to analyze.
- parameter tones: Filter the results by a specific tone. Valid values for `tones` are
`emotion`, `writing`, or `social`.
- parameter sentences: Should sentence-level tone analysis by performed?
- parameter failure: A function invoked if an error occurs.
- parameter success: A function invoked with the tone analysis.
*/
public func getTone(
ofText text: String,
tones: [String]? = nil,
sentences: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (ToneAnalysis) -> Void)
{
// construct body
guard let body = try? JSON(dictionary: ["text": text]).serialize() else {
let failureReason = "Classification text could not be serialized to JSON."
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
let error = NSError(domain: domain, code: 0, userInfo: userInfo)
failure?(error)
return
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let tones = tones {
let tonesList = tones.joined(separator: ",")
queryParameters.append(URLQueryItem(name: "tones", value: tonesList))
}
if let sentences = sentences {
queryParameters.append(URLQueryItem(name: "sentences", value: "\(sentences)"))
}
// construct REST request
let request = RestRequest(
method: "POST",
url: serviceURL + "/v3/tone",
credentials: credentials,
headerParameters: defaultHeaders,
acceptType: "application/json",
contentType: "application/json",
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(dataToError: dataToError) {
(response: RestResponse<ToneAnalysis>) in
switch response.result {
case .success(let toneAnalysis): success(toneAnalysis)
case .failure(let error): failure?(error)
}
}
}
}
| apache-2.0 | 0f78decc94053f5d9f02d22501fbfdb4 | 38.882353 | 98 | 0.641593 | 4.926431 | false | false | false | false |
hipposan/Oslo | Oslo/ProfileViewController.swift | 1 | 8262 | //
// ProfileViewController.swift
// Oslo
//
// Created by hippo_san on 6/24/16.
// Copyright © 2016 Ziyideas. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController {
var photo: Photo!
var profileImage: UIImage!
fileprivate var personalPhotos = [Photo]()
fileprivate var totalPhotosCount: Int = 0
fileprivate var photoCache = NSCache<NSString, UIImage>()
fileprivate var downloadedPersonalPhotos = [UIImage?]()
fileprivate var currentPage = 1
private var loadingView: LoadingView! {
didSet {
loadingView.frame = collectionView.bounds
loadingView.frame.size.width = self.view.frame.size.width
}
}
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var userLabel: UILabel!
@IBOutlet weak var bioLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet var portfolioImage: UIImageView!
@IBOutlet var portfolioName: UIButton!
@IBOutlet var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
avatarImageView.image = profileImage
userLabel.text = photo.name
bioLabel.text = photo.bio
if photo.location != "" {
locationLabel.text = photo.location
} else {
locationLabel.text = localize(with: "No Location")
}
if photo.portfolioURL.contains("instagram.com") {
portfolioImage.image = #imageLiteral(resourceName: "instagram")
let instagramName = photo.portfolioURL.components(separatedBy: "/")
portfolioName.setTitle(instagramName[3], for: .normal)
} else {
portfolioImage.image = #imageLiteral(resourceName: "portfolio")
portfolioName.setTitle(localize(with: "Website"), for: .normal)
}
currentPage = 1
loadingView = LoadingView()
collectionView.addSubview(loadingView)
load()
}
func load(with page: Int = 1) {
let urlString = Constants.Base.UnsplashAPI + "/users/\(photo.userName)/photos"
let url = URL(string: urlString)!
if let token = Token.getToken() {
NetworkService.request(url: url,
method: NetworkService.HTTPMethod.GET,
parameters: [Constants.Parameters.ClientID as Dictionary<String, AnyObject>,
["page": page as AnyObject]],
headers: ["Authorization": "Bearer " + token]) { jsonData in
guard let data = (jsonData as? [Dictionary<String, AnyObject>]) else { return }
let firstData = data[0]
if let user = firstData["user"] as? [String: AnyObject],
let totalPhotos = user["total_photos"] as? Int {
self.totalPhotosCount = totalPhotos
}
OperationService.parseJsonWithPhotoData(jsonData as! [Dictionary<String, AnyObject>]) { photo in
self.personalPhotos.append(photo)
self.downloadedPersonalPhotos.append(nil)
}
OperationQueue.main.addOperation {
self.collectionView.reloadData()
self.loadingView.removeFromSuperview()
}
}
} else {
NetworkService.request(url: url,
method: NetworkService.HTTPMethod.GET,
parameters: [Constants.Parameters.ClientID as Dictionary<String, AnyObject>]) { jsonData in
guard let data = (jsonData as? [Dictionary<String, AnyObject>]) else { return }
let firstData = data[0]
if let user = firstData["user"] as? [String: AnyObject],
let totalPhotos = user["total_photos"] as? Int {
self.totalPhotosCount = totalPhotos
}
OperationService.parseJsonWithPhotoData(jsonData as! [Dictionary<String, AnyObject>]) { photo in
self.personalPhotos.append(photo)
self.downloadedPersonalPhotos.append(nil)
}
OperationQueue.main.addOperation {
self.collectionView.reloadData()
self.loadingView.removeFromSuperview()
}
}
}
}
}
extension ProfileViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return personalPhotos.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PersonalPhoto", for: indexPath) as! ProfileCollectionViewCell
cell.personalPhotoImageView.image = nil
let photoURLString = personalPhotos[indexPath.row].imageURL
if let photoURL = URL(string: photoURLString) {
if let cachedImage = self.photoCache.object(forKey: photoURLString as NSString) {
cell.personalPhotoImageView.image = cachedImage
self.downloadedPersonalPhotos[indexPath.row] = cachedImage
} else {
NetworkService.image(with: photoURL) { image in
self.photoCache.setObject(image, forKey: photoURLString as NSString)
self.downloadedPersonalPhotos[indexPath.row] = image
if let updateCell = collectionView.cellForItem(at: indexPath) as? ProfileCollectionViewCell {
updateCell.personalPhotoImageView.alpha = 0
UIView.animate(withDuration: 0.3) {
updateCell.personalPhotoImageView.alpha = 1
updateCell.personalPhotoImageView.image = image
}
}
}
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.row == personalPhotos.count - 1 && indexPath.row != totalPhotosCount - 1 {
currentPage += 1
load(with: currentPage)
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: "PhotoSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "PhotoSegue" {
if let selectedIndexPath = collectionView.indexPathsForSelectedItems?[0].row,
let destinationViewController = segue.destination as? PersonalPhotoViewController {
destinationViewController.photo = personalPhotos[selectedIndexPath]
destinationViewController.personalPhoto = downloadedPersonalPhotos[selectedIndexPath]
if let photosTableViewController = navigationController?.viewControllers[0] as? PhotosTableViewController {
destinationViewController.delegate = photosTableViewController
}
}
} else if segue.identifier == "PortfolioSegue" {
if let destinationViewController = segue.destination as? PortfolioWebViewController {
destinationViewController.navigationItem.title = localizedFormat(with: "%@'s website", and: photo.name)
destinationViewController.portfolioURL = photo.portfolioURL
}
}
}
}
extension ProfileViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.size.height, height: collectionView.frame.size.height)
}
}
| mit | 4563ffdcde01a8d366c24aa2c0102757 | 40.722222 | 158 | 0.605375 | 5.805341 | false | false | false | false |
cohena100/Shimi | Shimi/Services/EntriesService.swift | 1 | 4854 | //
// EntriesService.swift
// Shimi
//
// Created by Pango-mac on 31/05/2017.
// Copyright © 2017 TsiliGiliMiliTili. All rights reserved.
//
import Foundation
import RxSwift
import RealmSwift
import NSObject_Rx
import RxRealm
import SwiftyBeaver
import SwifterSwift
class EntriesService: NSObject {
enum EntryAction {
case enter(Date)
case exit(Date)
}
let db: Realm
let entryAction = Variable(EntriesService.EntryAction.enter(Date()))
let total = Variable<TimeInterval>(0)
init(db: Realm) {
self.db = db
super.init()
self.entryAction.asObservable().skip(1).subscribe(onNext: { (action) in
self.handleEntry(action)
}, onError: nil, onCompleted: nil, onDisposed: nil).addDisposableTo(self.rx_disposeBag)
let entries = self.db.objects(Entry.self)
Observable.array(from: entries)
.map { (entries) -> TimeInterval in
return self.partitionByDay(entries: entries).flatMap {
let sum = $0.reduce(0.0, { (soFar, nextEntry) -> TimeInterval in
if let exitDate = nextEntry.exit {
return soFar + exitDate.timeIntervalSince(nextEntry.enter)
} else {
return soFar
}
})
return sum - db.objects(Settings.self)[0].workHoursADay
}.reduce(0,+)
}.subscribe(onNext: { sum in
self.total.value = sum
print(self.total.value)
}).addDisposableTo(rx_disposeBag)
}
func isEnterState() -> Bool {
let entries = db.objects(Entry.self).sorted(byKeyPath: #keyPath(Entry.enter), ascending: false)
return (entries.count > 0 && entries[0].exit == nil) ? false : true
}
fileprivate func handleEntry(_ action: EntryAction) {
let entries = fetchEntries()
switch action {
case .enter(let enterDate):
if entries.count == 0 {
try! db.write {
let newEntry = Entry(enter: enterDate)
db.add(newEntry)
}
} else if let _ = entries[0].exit {
try! db.write {
let newEntry = Entry(enter: enterDate)
db.add(newEntry)
}
} else {
try! db.write {
let currentEntry = entries[0]
currentEntry.enter = enterDate
}
}
case .exit(let exitDate):
try! db.write {
let currentEntry = entries[0]
currentEntry.exit = exitDate
SwiftyBeaver.debug("enter: \(currentEntry.enter), exit: \(String(describing: currentEntry.exit))")
}
}
}
fileprivate func fetchEntries() -> Results<Entry> {
return db.objects(Entry.self).sorted(byKeyPath: #keyPath(Entry.enter), ascending: false)
}
fileprivate func partitionByDay(entries: [Entry]) -> [[Entry]] {
if entries.count == 0 {
return []
}
if entries.count == 1 {
return [[entries[0]]]
}
var result: [[Entry]] = []
var currentDayEntries: [Entry] = []
for entry in entries {
if currentDayEntries.count == 0 {
currentDayEntries.append(entry)
} else {
if Calendar.current.isDate(currentDayEntries[0].enter, inSameDayAs: entry.enter) {
if let exitDate = entry.exit {
if Calendar.current.isDate(currentDayEntries[0].enter, inSameDayAs: exitDate) {
currentDayEntries.append(entry)
} else {
let endOfDay = currentDayEntries[0].enter.end(of: .day)!.adding(.second, value: 1)
let currentDayEntry = Entry(enter: entry.enter)
currentDayEntry.exit = endOfDay
currentDayEntries.append(currentDayEntry)
result.append(currentDayEntries)
let nextDayEntry = Entry(enter: endOfDay)
nextDayEntry.exit = exitDate
currentDayEntries = [nextDayEntry]
}
} else {
currentDayEntries.append(entry)
}
} else {
result.append(currentDayEntries)
currentDayEntries = [entry]
}
}
}
if currentDayEntries.count > 0 {
result.append(currentDayEntries)
}
return result
}
}
| mit | e48845ec9d015669a22a41ba530ead61 | 35.488722 | 114 | 0.507521 | 4.926904 | false | false | false | false |
DanielAsher/SwiftReferenceApp | SwiftReferenceApp/SwiftReferenceAppTests/SwiftReferenceAppSpecs.swift | 1 | 2100 | //
// SwiftReferenceAppTests.swift
// SwiftReferenceAppTests
//
// Created by Daniel Asher on 21/08/2015.
// Copyright (c) 2015 StoryShare. All rights reserved.
//
import UIKit
import XCTest
import Nimble
import Quick
import SwiftTask
import SwiftyStateMachine
import RxSwift
import SwiftReferenceApp
class SwiftReferenceAppSpecs: QuickSpec {
override func spec()
{
describe("Framework dependencies")
{
it("loads SwiftTask")
{
var str = "Started..."
let task = Task<Void, String, Void> { p, fulfill, r, c in
fulfill("Finished!")
}.success { value -> String in
str = value
return value }
expect(str).toEventually(equal("Finished!"))
}
it("loads SwiftyStateMachine")
{
let schema = StateMachineSchema<AppState, AppEvent, String>(initialState: AppState.Initial)
{ state, event in
switch (state, event)
{
case (.Initial, .Start):
return (AppState.Idle, nil)
default:
return nil
}
}
let machine = StateMachine(schema: schema, subject: "")
machine.addDidTransitionCallback { oldState, event, newState, trace in print("\(oldState) <- \(event) |-> \(newState)")
}
machine.handleEventAsync(AppEvent.Start, delay: 0.5)
expect ( machine.state ).toEventually ( equal ( AppState.Idle ))
}
}
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit | 8b40a9fbb82c8c196987d85211f23e62 | 28.166667 | 136 | 0.472381 | 5.614973 | false | true | false | false |
wordpress-mobile/AztecEditor-iOS | WordPressEditor/WordPressEditor/Classes/Renderers/SpecialTagAttachmentRenderer.swift | 2 | 2991 | import Aztec
import Foundation
import UIKit
// MARK: - SpecialTagAttachmentRenderer. This render aims rendering WordPress specific tags.
//
final public class SpecialTagAttachmentRenderer {
/// Text Color
///
var textColor = UIColor.gray
public init() {}
}
// MARK: - TextViewCommentsDelegate Methods
//
extension SpecialTagAttachmentRenderer: TextViewAttachmentImageProvider {
public func textView(_ textView: TextView, shouldRender attachment: NSTextAttachment) -> Bool {
guard let commentAttachment = attachment as? CommentAttachment else {
return false
}
return Tags.supported.contains(commentAttachment.text)
}
public func textView(_ textView: TextView, imageFor attachment: NSTextAttachment, with size: CGSize) -> UIImage? {
guard let attachment = attachment as? CommentAttachment else {
return nil
}
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let label = attachment.text.uppercased()
let colorMessage = NSAttributedString(string: label, attributes: [.foregroundColor: textColor])
let textRect = colorMessage.boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
let textPosition = CGPoint(x: ((size.width - textRect.width) * 0.5), y: ((size.height - textRect.height) * 0.5))
colorMessage.draw(in: CGRect(origin: textPosition, size: CGSize(width: size.width, height: textRect.size.height)))
let path = UIBezierPath()
let dashes = [ Constants.defaultDashCount, Constants.defaultDashCount ]
path.setLineDash(dashes, count: dashes.count, phase: 0.0)
path.lineWidth = Constants.defaultDashWidth
let centerY = round(size.height * 0.5)
path.move(to: CGPoint(x: 0, y: centerY))
path.addLine(to: CGPoint(x: ((size.width - textRect.width) * 0.5) - Constants.defaultDashWidth, y: centerY))
path.move(to: CGPoint(x: ((size.width + textRect.width) * 0.5) + Constants.defaultDashWidth, y: centerY))
path.addLine(to: CGPoint(x: size.width, y: centerY))
textColor.setStroke()
path.stroke()
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
public func textView(_ textView: TextView, boundsFor attachment: NSTextAttachment, with lineFragment: CGRect) -> CGRect {
let padding = textView.textContainer.lineFragmentPadding
let width = lineFragment.width - padding * 2
return CGRect(origin: .zero, size: CGSize(width: width, height: Constants.defaultHeight))
}
}
// MARK: - Constants
//
extension SpecialTagAttachmentRenderer {
struct Constants {
static let defaultDashCount = CGFloat(8.0)
static let defaultDashWidth = CGFloat(2.0)
static let defaultHeight = CGFloat(44.0)
}
struct Tags {
static let supported = ["more", "nextpage"]
}
}
| mpl-2.0 | bbe720559ee464344ee2eacfda514e2f | 32.988636 | 128 | 0.681712 | 4.608629 | false | false | false | false |
SpriteKitAlliance/SKAButton | Example/SKAToolKit/Scenes/ButtonGameScene.swift | 1 | 6252 | //
// ButtonGameScene.swift
// SKAToolKit
//
// Copyright (c) 2015 Sprite Kit Alliance
//
// 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 SpriteKit
class ButtonGameScene: SKScene {
var button: SKAButtonSprite!
var disableButton: SKAButtonSprite!
var danceAction: SKAction!
let danceKey = "action-dance"
let shakeKey = "action-shake"
let shakeHarderKey = "action-shake-harder"
let atlas = SKTextureAtlas(named: "Textures")
override func didMove(to view: SKView) {
super.didMove(to: view)
//Setup The Disable Button
disableButton = SKAButtonSprite(color: UIColor.red, size: CGSize(width: 260, height: 44))
disableButton.setTexture(self.atlas.textureNamed("disable"), forState: .Normal)
disableButton.setTexture(self.atlas.textureNamed("enabled"), forState: .Selected)
disableButton.position = CGPoint(x: view.center.x, y: UIScreen.main.bounds.height - 100)
disableButton.addTarget(self, selector: #selector(ButtonGameScene.disableSKA(_:)), forControlEvents: .TouchUpInside)
disableButton.setButtonTargetSize(CGSize(width: 300, height: 60))
disableButton.setAdjustsSpriteOnHighlight()
addChild(disableButton)
//Dance Action
let textures = [self.atlas.textureNamed("ska-dance1"), self.atlas.textureNamed("ska-dance2"), self.atlas.textureNamed("ska-dance1"), self.atlas.textureNamed("ska-dance3")]
let dance = SKAction.animate(with: textures, timePerFrame: 0.12, resize: true, restore: true)
danceAction = SKAction.repeatForever(dance)
//SKA Button
//This also sets the .Normal texture as the stand and clear color
button = SKAButtonSprite(texture: self.atlas.textureNamed("ska-stand"), color: UIColor.clear, size: CGSize(width: 126, height: 112))
addChild(button)
button.addTarget(self, selector: #selector(ButtonGameScene.touchUpInside(_:)), forControlEvents: .TouchUpInside)
button.addTarget(self, selector: #selector(ButtonGameScene.touchUpOutside(_:)), forControlEvents: .TouchUpOutside)
button.addTarget(self, selector: #selector(ButtonGameScene.dragOutside(_:)), forControlEvents: .DragOutside)
button.addTarget(self, selector: #selector(ButtonGameScene.dragInside(_:)), forControlEvents: .DragInside)
button.addTarget(self, selector: #selector(ButtonGameScene.dragEnter(_:)), forControlEvents: .DragEnter)
button.addTarget(self, selector: #selector(ButtonGameScene.dragExit(_:)), forControlEvents: .DragExit)
button.addTarget(self, selector: #selector(ButtonGameScene.touchDown(_:)), forControlEvents: .TouchDown)
button.setTexture(self.atlas.textureNamed("ska-pressed"), forState: .Highlighted)
button.setTexture(self.atlas.textureNamed("ska-disabled"), forState: .Disabled)
button.position = CGPoint(x: view.center.x, y: 200)
button.setAdjustsSpriteOnDisable()
}
func touchUpInside(_ sender:Any) {
print("SKABUTTON: touchUpInside")
//Remove the shake action
button.removeAction(forKey: shakeKey)
if button.selected {
button.selected = false
button.removeAction(forKey: danceKey)
//Remove shake harder if not dancing
button.removeAction(forKey: shakeHarderKey)
} else {
button.selected = true
button.run(danceAction, withKey: danceKey)
}
}
func touchUpOutside(_ sender:Any) {
print("SKABUTTON: touchUpOutside")
button.removeAction(forKey: shakeKey)
button.removeAction(forKey: shakeHarderKey)
}
func dragOutside(_ sender:Any) {
print("SKABUTTON: dragOutside")
}
func dragInside(_ sender:Any) {
print("SKABUTTON: dragInside")
}
func dragEnter(_ sender:Any) {
print("SKABUTTON: dragEnter")
button.removeAction(forKey: danceKey)
//Shake a lot
button.run(makeNewShakeAction(4), withKey: shakeHarderKey)
}
func dragExit(_ sender:Any) {
print("SKABUTTON: dragExit")
button.removeAction(forKey: shakeKey)
button.removeAction(forKey: shakeHarderKey)
if button.selected {
button.selected = true
button.run(danceAction, withKey: danceKey)
}
}
func touchDown(_ sender:Any) {
print("SKABUTTON: touchDown")
button.removeAction(forKey: danceKey)
button.removeAction(forKey: shakeHarderKey)
//Shake a little
button.run(makeNewShakeAction(2), withKey: shakeKey)
}
func disableSKA(_ sender:Any?) {
button.enabled = !button.enabled
disableButton.selected = !button.enabled
}
//Set up a new shake action with random movements horizontally
func makeNewShakeAction(_ shakeAmount:Int) -> SKAction {
let shakeLeft = CGFloat(-(Int(arc4random()) % shakeAmount + 1))
let shakeRight = CGFloat(Int(arc4random()) % shakeAmount + 1)
let shake1 = SKAction.moveBy(x: shakeLeft, y: 0, duration: 0.02)
let shake2 = SKAction.moveBy(x: -shakeLeft, y: 0, duration: 0.01)
let shake3 = SKAction.moveBy(x: shakeRight, y: 0, duration: 0.02)
let shake4 = SKAction.moveBy(x: -shakeRight, y: 0, duration: 0.01)
let shakes = SKAction.sequence([shake1, shake2, shake3, shake4])
return SKAction.repeatForever(shakes)
}
}
| mit | 1353237f298859c82d03a52662afdbae | 37.592593 | 175 | 0.712892 | 4.007692 | false | false | false | false |
Acidburn0zzz/firefox-ios | XCUITests/ThirdPartySearchTest.swift | 1 | 6432 | /* 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
let mozDeveloperWebsite = "https://developer.mozilla.org/en-US"
let searchFieldPlaceholder = "Search MDN"
class ThirdPartySearchTest: BaseTestCase {
fileprivate func dismissKeyboardAssistant(forApp app: XCUIApplication) {
app.buttons["Done"].tap()
}
func testCustomSearchEngines() {
addCustomSearchEngine()
waitForExistence(app.navigationBars["Search"].buttons["Settings"], timeout: 3)
app.navigationBars["Search"].buttons["Settings"].tap()
app.navigationBars["Settings"].buttons["AppSettingsTableViewController.navigationItem.leftBarButtonItem"].tap()
// Perform a search using a custom search engine
app.textFields["url"].tap()
waitForExistence(app.buttons["urlBar-cancel"])
UIPasteboard.general.string = "window"
app.textFields.firstMatch.press(forDuration: 1)
app.staticTexts["Paste"].tap()
app.scrollViews.otherElements.buttons["Mozilla Engine search"].tap()
waitUntilPageLoad()
var url = app.textFields["url"].value as! String
if url.hasPrefix("https://") == false {
url = "https://\(url)"
}
XCTAssert(url.hasPrefix("https://developer.mozilla.org/en-US"), "The URL should indicate that the search was performed on MDN and not the default")
}
func testCustomSearchEngineAsDefault() {
addCustomSearchEngine()
// Go to settings and set MDN as the default
waitForExistence(app.tables.staticTexts["Google"])
app.tables.staticTexts["Google"].tap()
waitForExistence(app.tables.staticTexts["Mozilla Engine"])
app.tables.staticTexts["Mozilla Engine"].tap()
dismissSearchScreen()
// Perform a search to check
app.textFields["url"].tap()
UIPasteboard.general.string = "window"
app.textFields.firstMatch.press(forDuration: 1)
app.staticTexts["Paste & Go"].tap()
waitUntilPageLoad()
// Ensure that the default search is MDN
var url = app.textFields["url"].value as! String
if url.hasPrefix("https://") == false {
url = "https://\(url)"
}
XCTAssert(url.hasPrefix("https://developer.mozilla.org/en-US/search"), "The URL should indicate that the search was performed on MDN and not the default")
}
func testCustomSearchEngineDeletion() {
addCustomSearchEngine()
waitForExistence(app.navigationBars["Search"].buttons["Settings"], timeout: 3)
app.navigationBars["Search"].buttons["Settings"].tap()
app.navigationBars["Settings"].buttons["AppSettingsTableViewController.navigationItem.leftBarButtonItem"].tap()
app.textFields["url"].tap()
waitForExistence(app.buttons["urlBar-cancel"])
UIPasteboard.general.string = "window"
app.textFields.firstMatch.press(forDuration: 1)
app.staticTexts["Paste"].tap()
waitForExistence(app.scrollViews.otherElements.buttons["Mozilla Engine search"])
XCTAssertTrue(app.scrollViews.otherElements.buttons["Mozilla Engine search"].exists)
// Need to go step by step to Search Settings. The ScreenGraph will fail to go to the Search Settings Screen
waitForExistence(app.buttons["urlBar-cancel"], timeout: 3)
app.buttons["urlBar-cancel"].tap()
app.buttons["TabToolbar.menuButton"].tap()
app.tables["Context Menu"].staticTexts["Settings"].tap()
app.tables.staticTexts["Google"].tap()
navigator.performAction(Action.RemoveCustomSearchEngine)
dismissSearchScreen()
// Perform a search to check
waitForExistence(app.textFields["url"], timeout: 3)
app.textFields["url"].tap()
waitForExistence(app.buttons["urlBar-cancel"])
UIPasteboard.general.string = "window"
app.textFields.firstMatch.press(forDuration: 1)
app.staticTexts["Paste"].tap()
waitForNoExistence(app.scrollViews.otherElements.buttons["Mozilla Engine search"])
XCTAssertFalse(app.scrollViews.otherElements.buttons["Mozilla Engine search"].exists)
}
private func addCustomSearchEngine() {
navigator.performAction(Action.CloseURLBarOpen)
navigator.nowAt(NewTabScreen)
navigator.performAction(Action.AddCustomSearchEngine)
waitForExistence(app.buttons["customEngineSaveButton"], timeout: 3)
app.buttons["customEngineSaveButton"].tap()
// Workaround for iOS14 need to wait for those elements and tap again
if #available(iOS 14.0, *) {
waitForExistence(app.navigationBars["Add Search Engine"], timeout: 3)
app.navigationBars["Add Search Engine"].buttons["Save"].tap()
}
}
private func dismissSearchScreen() {
waitForExistence(app.navigationBars["Search"].buttons["Settings"])
app.navigationBars["Search"].buttons["Settings"].tap()
app.navigationBars["Settings"].buttons["AppSettingsTableViewController.navigationItem.leftBarButtonItem"].tap()
}
func testCustomEngineFromIncorrectTemplate() {
navigator.performAction(Action.CloseURLBarOpen)
navigator.nowAt(NewTabScreen)
navigator.goto(AddCustomSearchSettings)
app.textViews["customEngineTitle"].tap()
app.typeText("Feeling Lucky")
UIPasteboard.general.string = "http://www.google.com/search?q=&btnI"
let tablesQuery = app.tables
let customengineurlTextView = tablesQuery.textViews["customEngineUrl"].staticTexts["URL (Replace Query with %s)"]
XCTAssertTrue(customengineurlTextView.exists)
customengineurlTextView.tap()
customengineurlTextView.press(forDuration: 2.0)
app.staticTexts["Paste"].tap()
waitForExistence(app.buttons["customEngineSaveButton"], timeout: 3)
app.buttons["customEngineSaveButton"].tap()
waitForExistence(app.navigationBars["Add Search Engine"], timeout: 3)
app.navigationBars["Add Search Engine"].buttons["Save"].tap()
waitForExistence(app.alerts.element(boundBy: 0))
XCTAssert(app.alerts.element(boundBy: 0).label == "Failed")
}
}
| mpl-2.0 | 8e70c06967a63514804921d7531b4e52 | 43.979021 | 162 | 0.673507 | 4.947692 | false | false | false | false |
jPaolantonio/JPAttributedString | JPAttributedString/Classes/AttributedStringDSL.swift | 1 | 1544 | import UIKit
public struct AttributedStringDSL {
let attributable: Attributable
init(attributable: Attributable) {
self.attributable = attributable
}
public func set(_ string: String, attributes: StringAttributes) {
let attributedString = NSAttributedString(string: string, attributes: attributes.attributes())
attributable.setAttributedText(attributedString)
}
public func set(_ string: String, _ closure: (_ attributes: StringAttributes) -> Void) {
let stringAttributes = StringAttributes()
closure(stringAttributes)
set(string, attributes: stringAttributes)
}
public func append(_ string: String, attributes: StringAttributes) {
let mutableAttributableString: NSMutableAttributedString
if let currentText = attributable.getAttributedText() {
mutableAttributableString = NSMutableAttributedString(attributedString: currentText)
} else {
mutableAttributableString = NSMutableAttributedString()
}
let attributedString = NSAttributedString(string: string, attributes: attributes.attributes())
mutableAttributableString.append(attributedString)
attributable.setAttributedText(mutableAttributableString)
}
public func append(_ string: String, _ closure: (_ attributes: StringAttributes) -> Void) {
let stringAttributes = StringAttributes()
closure(stringAttributes)
append(string, attributes: stringAttributes)
}
}
| mit | 4299c875e321399ddf562109fe0b068a | 38.589744 | 102 | 0.698834 | 5.697417 | false | false | false | false |
nodes-ios/NStack | NStackSDK/NStackSDK/Classes/Translations/TranslationManager.swift | 1 | 23215 | //
// TranslationsManager.swift
// NStack
//
// Created by Chris Combs on 08/09/15.
// Copyright © 2015 Nodes. All rights reserved.
//
import Foundation
import Serpent
import Cashier
import Alamofire
/// The Translations Manager handles everything related to translations.
///
/// Usually, direct interaction with the `Translations Manager` shouldn't be neccessary, since
/// it is setup automatically by the NStack manager, and the translations are accessible by the
/// global 'tr' variable defined in the auto-generated translations Swift file.
public class TranslationManager {
/// Repository that provides translations.
let repository: TranslationsRepository
/// The translations object type.
let translationsType: Translatable.Type
/// Persistent store to use to store information.
let store: NOPersistentStore
/// File manager handling persisting new translation data.
let fileManager: FileManager
/// Logger used to log valuable information.
let logger: LoggerType
/// In memory cache of the translations object.
var translationsObject: Translatable?
/// In memory cache of the last language object.
public fileprivate(set) var currentLanguage: Language?
/// Internal handler closure for language change.
var languageChangedAction: (() -> Void)?
/// The previous accept header string that was used.
var lastAcceptHeader: String? {
get {
return store.object(forKey: Constants.CacheKeys.prevAcceptedLanguage) as? String
}
set {
guard let newValue = newValue else {
logger.logVerbose("Last accept header deleted.")
store.deleteObject(forKey: Constants.CacheKeys.prevAcceptedLanguage)
return
}
logger.logVerbose("Last accept header set to: \(newValue).")
store.setObject(newValue, forKey: Constants.CacheKeys.prevAcceptedLanguage)
}
}
/// This language will be used instead of the phones' language when it is not `nil`. Remember
/// to call `updateTranslations()` after changing the value.
/// Otherwise, the effect will not be seen.
public var languageOverride: Language? {
get {
return store.serializableForKey(Constants.CacheKeys.languageOverride)
}
set {
if let newValue = newValue {
logger.logVerbose("Override language set to: \(newValue.locale)")
store.setSerializable(newValue, forKey: Constants.CacheKeys.languageOverride)
} else {
logger.logVerbose("Override language deleted.")
store.deleteSerializableForKey(Constants.CacheKeys.languageOverride)
}
clearTranslations()
}
}
// MARK: - Lifecycle -
/// Instantiates and sets the type of the translations object and the repository from which
/// translations are fetched. Usually this is invoked by the NStack start method, so under normal
/// circumstances, it should not be neccessary to invoke it directly.
///
/// - Parameters:
/// - translationsType: The type of the translations object that should be used.
/// - repository: Repository that can provide translations.
internal init(translationsType: Translatable.Type,
repository: TranslationsRepository,
logger: LoggerType,
store: NOPersistentStore = Constants.persistentStore,
fileManager: FileManager = .default) {
self.translationsType = translationsType
self.repository = repository
self.store = store
self.fileManager = fileManager
self.logger = logger
self.logger.customName = "-Translations"
}
///Find a translation for a key.
///
/// - Parameters:
/// - keyPath: The key that string should be found on.
public func translationString(keyPath: String) -> String? {
guard !keyPath.isEmpty else {
return nil
}
// Try to load if we don't have any translations
if translationsObject == nil {
loadTranslations()
}
let dictionary = translationsObject?.encodableRepresentation() as? NSDictionary
return dictionary?.value(forKeyPath: keyPath) as? String
}
// MARK: - Update & Fetch -
/// Fetches the latest version of the translations. Normally, the translations are aquired
/// when performing the NStack public call, so in most scenarios, this method won't have to
/// be called directly. Use it if you need to force refresh the translations during
/// app use, for example if manually switching language.
///
/// - Parameter completion: Called when translation fetching has finished. Check if the error
/// object is nil to determine whether the operation was a succes.
public func updateTranslations(_ completion: ((_ error: NStackError.Translations?) -> Void)? = nil) {
logger.logVerbose("Starting translations update asynchronously.")
repository.fetchTranslations(acceptLanguage: acceptLanguage) { response in
switch response.result {
case .success(let translationsData):
self.logger.logVerbose("New translations downloaded.")
var languageChanged = false
if self.lastAcceptHeader != self.acceptLanguage {
self.logger.logVerbose("Language changed from last time, clearing first.")
self.clearTranslations(includingPersisted: true)
languageChanged = true
}
self.lastAcceptHeader = self.acceptLanguage
self.set(response: translationsData)
completion?(nil)
if languageChanged {
self.logger.logVerbose("Running language changed action.")
self.languageChangedAction?()
}
case .failure(let error):
self.logger.logError("Error downloading translations data.\n",
"Response: ", response.response ?? "No response", "\n",
"Data: ", response.data ?? "No data", "\n",
"Error: ", error.localizedDescription)
completion?(.updateFailed(reason: error.localizedDescription))
}
}
}
/// Gets the languages for which translations are available.
///
/// - Parameter completion: An Alamofire DataResponse object containing the array or languages on success.
public func fetchAvailableLanguages(_ completion: @escaping (Alamofire.DataResponse<[Language]>) -> Void) {
logger.logVerbose("Fetching available language asynchronously.")
repository.fetchAvailableLanguages(completion: completion)
}
/// Gets the language which is currently used for translations, based on the accept header.
///
/// - Parameter completion: An Alamofire DataResponse object containing the language on success.
public func fetchCurrentLanguage(_ completion: @escaping (Alamofire.DataResponse<Language>) -> Void) {
logger.logVerbose("Fetching current language asynchronously.")
repository.fetchCurrentLanguage(acceptLanguage: acceptLanguage, completion: completion)
}
// MARK: - Accept Language -
/// Returns a string containing the current locale's preferred languages in a prioritized
/// manner to be used in a accept-language header. If no preferred language available,
/// fallback language is returned (English). Format example:
///
/// "da;q=1.0,en-gb;q=0.8,en;q=0.7"
///
/// - Returns: An accept language header string.
public var acceptLanguage: String {
var components: [String] = []
// If we should have language override, then append custom language code
if let languageOverride = languageOverride {
components.append(languageOverride.locale + ";q=1.0")
}
// Get all languages and calculate lowest quality
var languages = repository.fetchPreferredLanguages()
// Append fallback language if we don't have any provided
if components.count == 0 && languages.count == 0 {
languages.append("en")
}
let startValue = 1.0 - (0.1 * Double(components.count))
let endValue = startValue - (0.1 * Double(languages.count))
// Goes through max quality to the lowest (or 0.5, whichever is higher) by 0.1 decrease
// and appends a component with the language code and quality, like this:
// en-gb;q=1.0
for quality in stride(from: startValue, to: max(endValue, 0.5), by: -0.1) {
components.append("\(languages.removeFirst());q=\(quality)")
}
// Joins all components together to get "da;q=1.0,en-gb;q=0.8" string
return components.joined(separator: ",")
}
// MARK: - Translations -
/// The parsed translations object is cached in memory, but persisted as a dictionary.
/// If a persisted version cannot be found, the fallback json file in the bundle will be used.
///
/// - Returns: A translations object.
public func translations<T: Translatable>() -> T {
// Clear translations if language changed
if lastAcceptHeader != acceptLanguage {
logger.logVerbose("Language changed from last time, clearing translations.")
lastAcceptHeader = acceptLanguage
clearTranslations()
}
// Check object in memory
if let cachedObject = translationsObject as? T {
return cachedObject
}
// Load persisted or fallback translations
loadTranslations()
// Now we must have correct translations, so return it
return translationsObject as! T
}
/// Clears both the memory and persistent cache. Used for debugging purposes.
///
/// - Parameter includingPersisted: If set to `true`, local persisted translation
/// file will be deleted.
public func clearTranslations(includingPersisted: Bool = false) {
logger.logVerbose("In memory translations cleared.")
translationsObject = nil
if includingPersisted {
persistedTranslations = nil
}
}
/// Loads and initializes the translations object from either persisted or fallback dictionary.
func loadTranslations() {
logger.logVerbose("Loading translations.")
let dictionary = translationsDictionary
// Set our language
currentLanguage = languageOverride ?? processLanguage(dictionary)
// Figure out and set translations
let parsed = processAllTranslations(dictionary)
let translations = translationsType.init(dictionary: parsed)
translationsObject = translations
}
// MARK: - Dictionaries -
/// Saves the translations set.
///
/// - Parameter translations: The new translations.
func set(response: TranslationsResponse?) {
guard let dictionary = response?.encodableRepresentation() as? NSDictionary else {
logger.logError("Failed to create dicitonary from translations API response.")
return
}
// Persist the object
persistedTranslations = dictionary
// Reload the translations
_ = loadTranslations()
}
/// Returns the saved dictionary representation of the translations.
var translationsDictionary: NSDictionary {
return persistedTranslations ?? fallbackTranslations
}
/// Translations that were downloaded and persisted on disk.
var persistedTranslations: NSDictionary? {
get {
logger.logVerbose("Getting persisted traslations.")
guard let url = translationsFileUrl else {
logger.logWarning("No persisted translations available, returing nil.")
return nil
}
return NSDictionary(contentsOf: url)
}
set {
guard let translationsFileUrl = translationsFileUrl else {
return
}
// Delete if new value is nil
guard let newValue = newValue else {
guard fileManager.fileExists(atPath: translationsFileUrl.path) else {
logger.logVerbose("No persisted translation file stored, aborting.")
return
}
do {
logger.logVerbose("Deleting persisted translations file.")
try fileManager.removeItem(at: translationsFileUrl)
} catch {
logger.logError("Failed to delete persisted translatons." +
error.localizedDescription)
}
return
}
// Save to disk
var url = translationsFileUrl
guard newValue.write(to: url, atomically: true) else {
logger.logError("Failed to persist translations to disk.")
return
}
logger.logVerbose("Translations persisted to disk.")
// Exclude from backup
do {
logger.logVerbose("Excluding persisted translations from backup.")
var resourceValues = URLResourceValues()
resourceValues.isExcludedFromBackup = true
try url.setResourceValues(resourceValues)
} catch {
logger.log("Failed to exclude translations from backup. \(error.localizedDescription)",
level: .warning)
}
}
}
/// Loads the local JSON copy, has a return value so that it can be synchronously
/// loaded the first time they're needed. The local JSON copy contains all available languages,
/// and the right one is chosen based on the current locale.
///
/// - Returns: A dictionary representation of the selected local translations set.
var fallbackTranslations: NSDictionary {
for bundle in repository.fetchBundles() {
guard let filePath = bundle.path(forResource: "Translations", ofType: "json") else {
logger.logWarning("Bundle did not contain Translations.json file: " +
"\(bundle.bundleIdentifier ?? "N/A").")
continue
}
let fileUrl = URL(fileURLWithPath: filePath)
let data: Data
do {
logger.logVerbose("Loading fallback translations file at: \(filePath)")
data = try Data(contentsOf: fileUrl)
} catch {
logger.logError("Failed to get data from fallback translations file: " +
error.localizedDescription)
continue
}
do {
logger.logVerbose("Converting loaded file to JSON object.")
let json = try JSONSerialization.jsonObject(with: data, options: [.allowFragments])
guard let dictionary = json as? NSDictionary else {
logger.logError("Failed to get NSDictionary from fallback JSON file.")
continue
}
return dictionary
} catch {
logger.logError("Error loading translations JSON file: " +
error.localizedDescription)
}
}
logger.logError("Failed to load fallback translations, file non-existent.")
return [:]
}
// MARK: - Parsing -
/// Unwraps and extracts proper language dictionary out of the dictionary containing
/// all translations.
///
/// - Parameter dictionary: Dictionary containing all translations under the `data` key.
/// - Returns: Returns extracted language dictioanry for current accept language.
func processAllTranslations(_ dictionary: NSDictionary) -> NSDictionary? {
logger.logVerbose("Processing translations dictionary.")
guard let translations = dictionary.value(forKey: "data") as? NSDictionary else {
logger.logError("Failed to get data from all translations NSDictionary. \(dictionary)")
return nil
}
return extractLanguageDictionary(fromDictionary: translations)
}
/// Unwraps and extracts last language dictionary out of the meta containing
/// all translations.
///
/// - Parameter dictionary: Dictionary containing all translations under the `meta` key.
/// - Returns: Returns extracted language for last language.
func processLanguage(_ dictionary: NSDictionary) -> Language? {
logger.logVerbose("Processing language dictionary.")
guard let meta = dictionary.value(forKey: "meta") as? NSDictionary else {
logger.logError("Failed to get meta from all translations NSDictionary. \(dictionary)")
return nil
}
guard let language = meta.value(forKey: "language") as? NSDictionary else {
logger.logError("Failed to get language from all meta NSDictionary. \(meta)")
return nil
}
return Language(dictionary: language)
}
/// Uses the device's current locale to select the appropriate translations set.
///
/// - Parameter json: A dictionary containing translation sets by language code key.
/// - Returns: A translations set as a dictionary.
func extractLanguageDictionary(fromDictionary dictionary: NSDictionary) -> NSDictionary {
logger.logVerbose("Extracting language dictionary.")
var languageDictionary: NSDictionary? = nil
// First try overriden language
if let languageOverride = languageOverride {
logger.logVerbose("Language override enabled, trying it first.")
languageDictionary = translationsMatching(language: languageOverride,
inDictionary: dictionary)
if let languageDictionary = languageDictionary {
return languageDictionary
}
}
// This is removed so that only the device's current language is used. This is a request
// from the consultant teams and matches what Android does. NStack will determine the best
// language for the user.
//let languages = repository.fetchPreferredLanguages()
guard let language = repository.fetchCurrentPhoneLanguage() else {
logger.logError("Error loading translations. No language available.")
return [:]
}
let languages = [language]
// This is removed as it causes bugs when you don't have an exact locale match to your
// phone's language, but do match a secondary language. For example, if your phone is
// set to en-US, and have da-DK as a backup language, and NStack offers en-GB or da-DK,
// this will match to Danish instead of English. Eventually this should be refactored to support
// region-specific translations, but that is very much an edge case.
logger.logVerbose("Finding language for matching preferred languages: \(languages).")
// Find matching language and region
// for lan in languages {
// // Try matching on both language and region
// if let dictionary = dictionary.value(forKey: lan) as? NSDictionary {
// logger.logVerbose("Found matching language for language with region: " + lan)
// return dictionary
// }
// }
let shortLanguages = languages.map({ $0.substring(to: 2) })
logger.logVerbose("Finding language for matching preferred short languages: \(languages).")
// Find matching language only
for lanShort in shortLanguages {
// Match just on language
if let dictionary = translationsMatching(locale: lanShort, inDictionary: dictionary) {
logger.logVerbose("Found matching language for short language code: " + lanShort)
return dictionary
}
}
// Take preferred language from backend
if let currentLanguage = currentLanguage,
let languageDictionary = translationsMatching(locale: currentLanguage.locale, inDictionary: dictionary) {
logger.logVerbose("Finding translations for language recommended by API: \(currentLanguage.locale).")
return languageDictionary
}
logger.logWarning("Falling back to first language in dictionary: \(dictionary.allKeys.first ?? "None")")
languageDictionary = dictionary.allValues.first as? NSDictionary
if let languageDictionary = languageDictionary {
return languageDictionary
}
logger.logError("Error loading translations. No translations available.")
return [:]
}
/// Searches the translation file for a key matching the provided language code.
///
/// - Parameters:
/// - language: The desired language. If `nil`, first language will be used.
/// - json: The dictionary containing translations for all languages.
/// - Returns: Translations dictionary for the given language.
func translationsMatching(language: Language, inDictionary dictionary: NSDictionary) -> NSDictionary? {
return translationsMatching(locale: language.locale, inDictionary: dictionary)
}
/// Searches the translation file for a key matching the provided language code.
///
/// - Parameters:
/// - locale: A language code of the desired language.
/// - json: The dictionary containing translations for all languages.
/// - Returns: Translations dictionary for the given language.
func translationsMatching(locale: String, inDictionary dictionary: NSDictionary) -> NSDictionary? {
// If we have perfect match on language and region
if let dictionary = dictionary.value(forKey: locale) as? NSDictionary {
return dictionary
}
// Try shortening keys in dictionary
for case let key as String in dictionary.allKeys {
if key.substring(to: 2) == locale {
return dictionary.value(forKey: key) as? NSDictionary
}
}
return nil
}
// MARK: - Helpers -
/// The URL used to persist downloaded translations.
var translationsFileUrl: URL? {
return fileManager.documentsDirectory?.appendingPathComponent("Translations.nstack")
}
}
| mit | fef0446120a98ea063c813f406885875 | 41.672794 | 117 | 0.618635 | 5.618103 | false | false | false | false |
teambition/SwipeableTableViewCell | SwipeableTableViewCell/SwipeableTableViewCell.swift | 1 | 20742 | //
// SwipeableTableViewCell.swift
// SwipeableTableViewCell
//
// Created by 洪鑫 on 15/12/15.
// Copyright © 2015年 Teambition. All rights reserved.
//
import UIKit
let kAccessoryTrailingSpace: CGFloat = 15
let kSectionIndexWidth: CGFloat = 15
let kTableViewPanState = "state"
public enum SwipeableCellState {
case closed
case swiped
}
public protocol SwipeableTableViewCellDelegate: class {
func swipeableCell(_ cell: SwipeableTableViewCell, isScrollingToState state: SwipeableCellState)
func swipeableCellSwipeEnabled(_ cell: SwipeableTableViewCell) -> Bool
func allowMultipleCellsSwipedSimultaneously() -> Bool
func swipeableCellDidEndScroll(_ cell: SwipeableTableViewCell)
}
public extension SwipeableTableViewCellDelegate {
func swipeableCell(_ cell: SwipeableTableViewCell, isScrollingToState state: SwipeableCellState) {
}
func swipeableCellSwipeEnabled(_ cell: SwipeableTableViewCell) -> Bool {
return true
}
func allowMultipleCellsSwipedSimultaneously() -> Bool {
return false
}
func swipeableCellDidEndScroll(_ cell: SwipeableTableViewCell) {
}
}
open class SwipeableTableViewCell: UITableViewCell, UIScrollViewDelegate {
open weak var delegate: SwipeableTableViewCellDelegate?
open fileprivate(set) var state: SwipeableCellState = .closed {
didSet {
if state != oldValue {
updateContainerViewBackgroundColor()
}
}
}
open var actions: [SwipeableCellAction]? {
didSet {
actionsView.setActions(actions)
actionsView.layoutIfNeeded()
layoutIfNeeded()
}
}
fileprivate weak var tableView: UITableView? {
didSet {
removeOldTableViewPanObserver()
tableViewPanGestureRecognizer = nil
if let tableView = tableView {
tableViewPanGestureRecognizer = tableView.panGestureRecognizer
if let dataSource = tableView.dataSource {
if dataSource.responds(to: #selector(UITableViewDataSource.sectionIndexTitles(for:))) {
if let _ = dataSource.sectionIndexTitles?(for: tableView) {
additionalPadding = kSectionIndexWidth
}
}
}
tableView.isDirectionalLockEnabled = true
tapGesture.require(toFail: tableView.panGestureRecognizer)
tableViewPanGestureRecognizer!.addObserver(self, forKeyPath: kTableViewPanState, options: [.new], context: nil)
}
}
}
fileprivate var tableViewPanGestureRecognizer: UIPanGestureRecognizer?
fileprivate var additionalPadding: CGFloat = 0 {
didSet {
trainingOffset.constant = -additionalPadding
layoutIfNeeded()
}
}
open fileprivate(set) var containerView: UIView!
open fileprivate(set) lazy var scrollView: SwipeableCellScrollView = {
let scrollView = SwipeableCellScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.isScrollEnabled = true
return scrollView
}()
lazy var tapGesture: UITapGestureRecognizer = { [unowned self] in
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SwipeableTableViewCell.scrollViewTapped(_:)))
tapGesture.cancelsTouchesInView = false
tapGesture.numberOfTapsRequired = 1
return tapGesture
}()
lazy var longPressGesture: UILongPressGestureRecognizer = {
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(SwipeableTableViewCell.scrollViewLongPressed(_:)))
longPressGesture.cancelsTouchesInView = false
longPressGesture.minimumPressDuration = 0.16
return longPressGesture
}()
lazy var actionsView: SwipeableCellActionsView = { [unowned self] in
let actions = self.actions ?? []
let actionsView = SwipeableCellActionsView(actions: actions, parentCell: self)
return actionsView
}()
lazy var clipView: UIView = { [unowned self] in
let view = UIView(frame: self.frame)
view.translatesAutoresizingMaskIntoConstraints = false
view.clipsToBounds = false
return view
}()
fileprivate var clipViewConstraint = NSLayoutConstraint()
fileprivate var trainingOffset = NSLayoutConstraint()
fileprivate var isLayoutUpdating = false
// MARK: - Life cycle
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configureSwipeableCell()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureSwipeableCell()
}
override open func layoutSubviews() {
super.layoutSubviews()
updateContainerViewBackgroundColor()
containerView.frame = contentView.frame
containerView.frame.size.width = frame.width - additionalPadding
containerView.frame.size.height = frame.height
scrollView.contentSize = CGSize(width: frame.width + actionsView.frame.width, height: frame.height)
if !scrollView.isTracking && !scrollView.isDecelerating {
scrollView.contentOffset = contentOffset(of: state)
}
updateCell()
}
override open func prepareForReuse() {
super.prepareForReuse()
if state != .closed {
hideActions(animated: false)
}
}
deinit {
scrollView.delegate = nil
removeOldTableViewPanObserver()
}
// MARK: - Overriding
override open func didMoveToSuperview() {
tableView = nil
if let tableView = superview as? UITableView {
self.tableView = tableView
} else if let tableView = superview?.superview as? UITableView {
self.tableView = tableView
}
}
override open var frame: CGRect {
willSet {
isLayoutUpdating = true
}
didSet {
isLayoutUpdating = false
let widthChanged = frame.width != oldValue.width
if widthChanged {
layoutIfNeeded()
}
}
}
override open func setSelected(_ selected: Bool, animated: Bool) {
actionsView.pushBackgroundColors()
super.setSelected(selected, animated: animated)
actionsView.popBackgroundColors()
}
// MARK: - TableView related
fileprivate func removeOldTableViewPanObserver() {
tableViewPanGestureRecognizer?.removeObserver(self, forKeyPath: kTableViewPanState)
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let keyPath = keyPath, let object = object as? UIPanGestureRecognizer, let tableViewPanGestureRecognizer = tableViewPanGestureRecognizer {
if keyPath == kTableViewPanState && object == tableViewPanGestureRecognizer {
if let change = change, let new = change[.newKey] as? Int, (new == 2 || new == 3) {
setHighlighted(false, animated: false)
}
}
}
}
fileprivate func shouldHighlight() -> Bool {
if let tableView = tableView, let delegate = tableView.delegate {
if delegate.responds(to: #selector(UITableViewDelegate.tableView(_:shouldHighlightRowAt:))) {
if let cellIndexPath = tableView.indexPathForRow(at: center) {
return delegate.tableView!(tableView, shouldHighlightRowAt: cellIndexPath)
}
}
}
return true
}
fileprivate func selectCell() {
if state == .swiped {
return
}
if let tableView = tableView, let delegate = tableView.delegate {
var cellIndexPath = tableView.indexPathForRow(at: center)
if delegate.responds(to: #selector(UITableViewDelegate.tableView(_:willSelectRowAt:))) {
if let indexPath = cellIndexPath {
cellIndexPath = delegate.tableView!(tableView, willSelectRowAt: indexPath)
}
}
if let indexPath = cellIndexPath {
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
if delegate.responds(to: #selector(UITableViewDelegate.tableView(_:didSelectRowAt:))) {
delegate.tableView!(tableView, didSelectRowAt: indexPath)
}
}
}
}
fileprivate func deselectCell() {
if state == .swiped {
return
}
if let tableView = tableView, let delegate = tableView.delegate {
var cellIndexPath = tableView.indexPathForRow(at: center)
if delegate.responds(to: #selector(UITableViewDelegate.tableView(_:willDeselectRowAt:))) {
if let indexPath = cellIndexPath {
cellIndexPath = delegate.tableView!(tableView, willDeselectRowAt: indexPath)
}
}
if let indexPath = cellIndexPath {
tableView.deselectRow(at: indexPath, animated: false)
if delegate.responds(to: #selector(UITableViewDelegate.tableView(_:didDeselectRowAt:))) {
delegate.tableView!(tableView, didDeselectRowAt: indexPath)
}
}
}
}
// MARK: - Helper
open func showActions(animated: Bool) {
DispatchQueue.main.async {
self.scrollView.setContentOffset(self.contentOffset(of: .swiped), animated: animated)
self.delegate?.swipeableCell(self, isScrollingToState: .swiped)
}
}
open func hideActions(animated: Bool) {
DispatchQueue.main.async {
self.scrollView.setContentOffset(self.contentOffset(of: .closed), animated: animated)
self.delegate?.swipeableCell(self, isScrollingToState: .closed)
}
}
open func hideAllOtherCellsActions(animated: Bool) {
if let tableView = tableView {
for cell in tableView.visibleCells {
if let cell = cell as? SwipeableTableViewCell {
if cell != self {
cell.hideActions(animated: animated)
}
}
}
}
}
fileprivate func contentOffset(of state: SwipeableCellState) -> CGPoint {
return state == .swiped ? CGPoint(x: actionsView.frame.width, y: 0) : .zero
}
fileprivate func updateCell() {
if isLayoutUpdating {
return
}
if scrollView.contentOffset.equalTo(contentOffset(of: .closed)) {
state = .closed
} else {
state = .swiped
}
if let frame = contentView.superview?.convert(contentView.frame, to: self) {
var frame = frame
frame.size.width = self.frame.width
clipViewConstraint.constant = min(0, frame.maxX - self.frame.maxX)
actionsView.isHidden = clipViewConstraint.constant == 0
if let accessoryView = accessoryView {
if !isEditing {
accessoryView.frame.origin.x = frame.width - accessoryView.frame.width - kAccessoryTrailingSpace + frame.minX - additionalPadding
}
} else if accessoryType != .none && !isEditing {
if let subviews = scrollView.superview?.subviews {
for subview in subviews {
if let accessory = subview as? UIButton {
accessory.frame.origin.x = frame.width - accessory.frame.width - kAccessoryTrailingSpace + frame.minX - additionalPadding
} else if String(describing: type(of: subview)) == "UITableViewCellDetailDisclosureView" {
subview.frame.origin.x = frame.width - subview.frame.width - kAccessoryTrailingSpace + frame.minX - additionalPadding
}
}
}
}
if !scrollView.isDragging && !scrollView.isDecelerating {
tapGesture.isEnabled = true
longPressGesture.isEnabled = state == .closed
} else {
tapGesture.isEnabled = false
longPressGesture.isEnabled = false
}
scrollView.isScrollEnabled = !isEditing
}
}
fileprivate func configureSwipeableCell() {
state = .closed
isLayoutUpdating = false
scrollView.delegate = self
containerView = UIView()
scrollView.addSubview(containerView)
insertSubview(scrollView, at: 0)
containerView.addSubview(contentView)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: ["scrollView": scrollView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|", options: [], metrics: nil, views: ["scrollView": scrollView]))
tapGesture.delegate = self
scrollView.addGestureRecognizer(tapGesture)
longPressGesture.delegate = self
scrollView.addGestureRecognizer(longPressGesture)
scrollView.insertSubview(clipView, at: 0)
clipViewConstraint = NSLayoutConstraint(item: clipView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)
clipViewConstraint.priority = .defaultHigh
trainingOffset = NSLayoutConstraint(item: clipView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)
addConstraint(NSLayoutConstraint(item: clipView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: clipView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0))
addConstraint(trainingOffset)
addConstraint(clipViewConstraint)
clipView.addSubview(actionsView)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[actionsView]|", options: [], metrics: nil, views: ["actionsView": actionsView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[actionsView]|", options: [], metrics: nil, views: ["actionsView": actionsView]))
}
fileprivate func updateContainerViewBackgroundColor() {
if isSelected || isHighlighted || state == .closed {
containerView.backgroundColor = .clear
} else {
if backgroundColor == .clear || backgroundColor == nil {
containerView.backgroundColor = .white
} else {
containerView.backgroundColor = backgroundColor
}
}
}
fileprivate func shouldAllowMultipleCellsSwipedSimultaneously() -> Bool {
return delegate?.allowMultipleCellsSwipedSimultaneously() ?? false
}
fileprivate func swipeEnabled() -> Bool {
return delegate?.swipeableCellSwipeEnabled(self) ?? true
}
// MARK: - Selector
@objc func scrollViewTapped(_ gestureRecognizer: UIGestureRecognizer) {
if state == .closed {
if let tableView = tableView {
if tableView.hasSwipedCells() {
hideAllOtherCellsActions(animated: true)
return
}
}
if isSelected {
deselectCell()
} else if shouldHighlight() {
selectCell()
}
} else {
hideActions(animated: true)
}
}
@objc func scrollViewLongPressed(_ gestureRecognizer: UIGestureRecognizer) {
switch gestureRecognizer.state {
case .began:
if shouldHighlight() && !isHighlighted {
setHighlighted(true, animated: false)
}
case .ended:
if isHighlighted {
setHighlighted(false, animated: false)
scrollViewTapped(gestureRecognizer)
}
case .cancelled, .failed:
setHighlighted(false, animated: false)
default:
break
}
}
// MARK: - UIScrollView delegate
open func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let currentLength = abs(clipViewConstraint.constant)
let totalLength = actionsView.frame.width
var targetState: SwipeableCellState = .closed
if velocity.x > 0.5 {
targetState = .swiped
} else if velocity.x < -0.5 {
targetState = .closed
} else {
if currentLength >= totalLength / 2 {
targetState = .swiped
} else {
targetState = .closed
}
}
let targetLocation = contentOffset(of: targetState)
targetContentOffset.pointee = targetLocation
delegate?.swipeableCell(self, isScrollingToState: targetState)
if state != .closed && !shouldAllowMultipleCellsSwipedSimultaneously() {
hideAllOtherCellsActions(animated: true)
}
}
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isSelected {
deselectCell()
}
if !swipeEnabled() {
scrollView.contentOffset = contentOffset(of: .closed)
}
updateCell()
}
open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
updateCell()
delegate?.swipeableCellDidEndScroll(self)
}
open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
updateCell()
delegate?.swipeableCellDidEndScroll(self)
}
open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
tapGesture.isEnabled = true
}
}
// MARK: - UIGestureRecognizer delegate
override open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if let panGesture = tableView?.panGestureRecognizer {
if (gestureRecognizer == panGesture && otherGestureRecognizer == longPressGesture) || (gestureRecognizer == longPressGesture && otherGestureRecognizer == panGesture) {
if let tableView = tableView {
if tableView.hasSwipedCells() {
hideAllOtherCellsActions(animated: true)
}
}
return true
}
}
return false
}
override open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if let view = touch.view {
return !(view is UIControl)
}
return true
}
}
public class SwipeableCellScrollView: UIScrollView {
override public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == panGestureRecognizer {
let gesture = gestureRecognizer as! UIPanGestureRecognizer
let translation = gesture.translation(in: gesture.view)
return abs(translation.y) <= abs(translation.x)
}
return true
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer is UIPanGestureRecognizer {
let gesture = gestureRecognizer as! UIPanGestureRecognizer
let yVelocity = gesture.velocity(in: gesture.view).y
return abs(yVelocity) <= 0.25
}
return true
}
}
public extension UITableView {
func hideAllSwipeableCellsActions(animated: Bool) {
for cell in visibleCells {
if let cell = cell as? SwipeableTableViewCell {
cell.hideActions(animated: animated)
}
}
}
func hasSwipedCells() -> Bool {
for cell in visibleCells {
if let cell = cell as? SwipeableTableViewCell {
if cell.state == .swiped {
return true
}
}
}
return false
}
}
| mit | a4bf9458fc2738267e16ae3facf5d688 | 37.115809 | 181 | 0.626525 | 5.743767 | false | false | false | false |
coach-plus/ios | CoachPlus/ui/teamselection/TeamSelectionView.swift | 1 | 2018 | //
// TeamSelectionView.swift
// CoachPlus
//
// Created by Maurice Breit on 13.04.17.
// Copyright © 2017 Mathandoro GbR. All rights reserved.
//
import UIKit
import NibDesignable
class TeamSelectionView: NibDesignable {
@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var imageV: UIImageView!
@IBInspectable var image: UIImage {
get {
return self.imageV.image!
}
set(image) {
self.imageV.image = image
}
}
@IBInspectable var name: String {
get {
return self.nameLbl.text!
}
set(text) {
self.nameLbl.text = text
}
}
override init (frame : CGRect) {
super.init(frame : frame)
self.initSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initSetup()
}
func initSetup() {
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(teamTapped(sender:)))
self.addGestureRecognizer(tapRecognizer)
}
@objc func teamTapped(sender:UIBarButtonItem) {
FlowManager.openDrawer()
/**
let controller = UIApplication.shared.keyWindow?.rootViewController//UIApplication.topViewController(base: nil)
if let navVc = controller as? CoachPlusNavigationViewController {
FlowManager.openDrawer()
} else if let navVc = controller as? CoachPlusViewController {
navVc.slideMenuController()?.openLeft()
} else if let navVc = controller as? HomeDrawerController {
navVc.slideMenuController()?.openLeft()
}**/
}
func setup(team:Team?) {
self.name = "?"
if (team != nil) {
self.nameLbl.text = team!.name
}
self.imageV.setTeamImage(team: team, placeholderColor: UIColor.white)
}
}
| mit | 0c9207d249226d18df286088344b1c77 | 22.729412 | 119 | 0.565692 | 4.883777 | false | false | false | false |
bardonadam/SlidingTabBar | Pod/Classes/SlidingTabAnimationController.swift | 1 | 4052 | //
// SlidingTabAnimationController.swift
//
//
// Created by Adam Bardon on 02/03/16.
// Copyright © 2016 Adam Bardon. All rights reserved.
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
import UIKit
public class SlidingTabAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
public enum TransitioningDirection {
case Left
case Right
case Both
case Reverse
}
private let transitionDuration: NSTimeInterval
private let shouldUseDirection: TransitioningDirection
private let fromIndex: Int
private let toIndex: Int
public init(transitionDuration: NSTimeInterval, direction: TransitioningDirection? = .Both, fromIndex: Int, toIndex: Int) {
self.transitionDuration = transitionDuration
self.shouldUseDirection = direction!
self.fromIndex = fromIndex
self.toIndex = toIndex
}
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return transitionDuration
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
if let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey),
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) {
let fromView = fromVC.view
let toView = toVC.view
let containerView = transitionContext.containerView()!
containerView.clipsToBounds = false
containerView.addSubview(toView)
let toViewEndFrame = transitionContext.finalFrameForViewController(toVC)
var toViewStartFrame = toViewEndFrame
var fromViewEndFrame = fromView.frame
switch shouldUseDirection {
case .Both:
let direction = self.toIndex - self.fromIndex
// .Right
if direction > 0 {
fromViewEndFrame.origin.x -= (containerView.frame.width)
toViewStartFrame.origin.x += (containerView.frame.width)
}
// .Left
else {
fromViewEndFrame.origin.x += (containerView.frame.width)
toViewStartFrame.origin.x -= (containerView.frame.width)
}
case .Reverse:
let direction = self.toIndex - self.fromIndex
// .Right
if direction > 0 {
fromViewEndFrame.origin.x += (containerView.frame.width)
toViewStartFrame.origin.x -= (containerView.frame.width)
}
// .Left
else {
fromViewEndFrame.origin.x -= (containerView.frame.width)
toViewStartFrame.origin.x += (containerView.frame.width)
}
case .Left:
fromViewEndFrame.origin.x += (containerView.frame.width)
toViewStartFrame.origin.x -= (containerView.frame.width)
// .Right
default:
fromViewEndFrame.origin.x -= (containerView.frame.width)
toViewStartFrame.origin.x += (containerView.frame.width)
}
toView.frame = toViewStartFrame
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
toView.frame = toViewEndFrame
fromView.frame = fromViewEndFrame
}, completion: { (completed) -> Void in
fromView.removeFromSuperview()
transitionContext.completeTransition(completed)
containerView.clipsToBounds = true
})
}
}
}
| mit | 98d5a3090ad0f5201de88e18130f5d84 | 37.951923 | 165 | 0.59294 | 6.001481 | false | false | false | false |
paulz/ImageCoordinateSpace | Unit Tests/CGAffineTransform+Scale_Spec.swift | 1 | 1054 | import Quick
import Nimble
@testable import ImageCoordinateSpace
class CGAffineTransform_Scale_Spec: QuickSpec {
override func spec() {
describe(CGAffineTransform.self) {
context(CGAffineTransform.scale) {
it("should pass X and Y to block and return block result") {
let transform = CGAffineTransform(scaleX: 2, y: 3)
expect(transform.scale(using: {
expect($0) == 2
expect($1) == 3
return 5
})) == 5
}
}
context(CGAffineTransform.init(scaleTo:from:)) {
it("should create tranform that will scale from one size to another") {
let from = CGSize.nextRandom()
let to = CGSize.nextRandom()
let transform = CGAffineTransform(scaleTo: to, from: from)
expect(from.applying(transform)) ≈ to ± 0.0001
}
}
}
}
}
| mit | 4cd9e2fd6fa7f51bf0197c9975e53f15 | 35.241379 | 87 | 0.494767 | 5.389744 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue | iOS/Venue/DataSources/ManagerHelper.swift | 1 | 2771 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
/**
* Protocol to provide success and failure messages
*/
@objc protocol HelperDelegate {
func resourceSuccess(response: WLResponse!)
func resourceFailure(response: String!)
}
/**
* Helper class to connect to MFP and initiate a resource request ]
*/
class ManagerHelper: NSObject {
/// HelperDelegate for the ManagerHelper
weak var delegate: HelperDelegate!
/// String containing the url to initiate the resource request
var URLString: String!
/// Optional params string to pass into Javascript adapters/procedures
var params: String?
init(URLString: String!, delegate: HelperDelegate!) {
self.URLString = URLString
self.delegate = delegate
super.init()
WLClient.sharedInstance().wlConnectWithDelegate(self)
}
/**
Method to initiate a connection to the WLClient.sharedInstance()
*/
func getResource() {
MQALogger.log("Getting resource at URL: \(URLString)", withLevel: MQALogLevelInfo)
print("Getting resource at URL: \(URLString)")
let request = WLResourceRequest(URL: NSURL(string: URLString), method: WLHttpMethodGet)
// Set parameters on data call if available
if let parameters = self.params {
request.setQueryParameterValue(parameters, forName: "params")
}
request.sendWithCompletionHandler { (response, error) -> Void in
if(error != nil) { // connection success with error
self.delegate.resourceFailure("ERROR: \(response.responseText)")
} else if(response != nil) { //connection success with correct data
self.delegate.resourceSuccess(response)
}
}
}
/**
Helper method to add params to an MFP request
- parameter params: params in a string array like so: `['233', 01]`
*/
func addProcedureParams(params: String) {
self.params = params
}
}
extension ManagerHelper: WLDelegate {
/**
Method called upon successful MFP connection to send data if resource request is successful, or resource failure error message if unsuccessful
:param: response WLResponse containing user data
*/
func onSuccess(response: WLResponse!) {
MQALogger.log("Connection SUCCESS!")
}
/**
Method called upon failure to connect to MFP, will send errorMsg
:param: response WLFailResponse containing failure response
*/
func onFailure(response: WLFailResponse!) {
MQALogger.log("Connection FAILURE!")
self.delegate.resourceFailure("no connection")
}
} | epl-1.0 | b2c4ceb0a57dd2340d35fff367cfa1c0 | 28.168421 | 146 | 0.653791 | 5.054745 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothGATT/ATTError.swift | 1 | 7657 | //
// ATTError.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 4/12/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
/**
The possible errors returned by a GATT server (a remote peripheral) during Bluetooth low energy ATT transactions.
These error constants are based on the Bluetooth ATT error codes, defined in the Bluetooth 4.0 specification.
For more information about these errors, see the Bluetooth 4.0 specification, Volume 3, Part F, Section 3.4.1.1.
*/
@frozen
public enum ATTError: UInt8, Error {
/// Invalid Handle
///
/// The attribute handle given was not valid on this server.
case invalidHandle = 0x01
/// Read Not Permitted
///
/// The attribute cannot be read.
case readNotPermitted = 0x02
/// Write Not Permitted
///
/// The attribute cannot be written.
case writeNotPermitted = 0x03
/// Invalid PDU
///
/// The attribute PDU was invalid.
case invalidPDU = 0x04
/// Insufficient Authentication
///
/// The attribute requires authentication before it can be read or written.
case insufficientAuthentication = 0x05
/// Request Not Supported
///
/// Attribute server does not support the request received from the client.
case requestNotSupported = 0x06
/// Invalid Offset
///
/// Offset specified was past the end of the attribute.
case invalidOffset = 0x07
/// Insufficient Authorization
///
/// The attribute requires authorization before it can be read or written.
case insufficientAuthorization = 0x08
/// Prepare Queue Full
///
/// Too many prepare writes have been queued.
case prepareQueueFull = 0x09
/// Attribute Not Found
///
/// No attribute found within the given attribute handle range.
case attributeNotFound = 0x0A
/// Attribute Not Long
///
/// The attribute cannot be read or written using the *Read Blob Request*.
case attributeNotLong = 0x0B
/// Insufficient Encryption Key Size
///
/// The *Encryption Key Size* used for encrypting this link is insufficient.
case insufficientEncryptionKeySize = 0x0C
/// Invalid Attribute Value Length
///
/// The attribute value length is invalid for the operation.
case invalidAttributeValueLength = 0x0D
/// Unlikely Error
///
/// The attribute request that was requested has encountered an error that was unlikely,
/// and therefore could not be completed as requested.
case unlikelyError = 0x0E
/// Insufficient Encryption
///
/// The attribute requires encryption before it can be read or written.
case insufficientEncryption = 0x0F
/// Unsupported Group Type
///
/// The attribute type is not a supported grouping attribute as defined by a higher layer specification.
case unsupportedGroupType = 0x10
/// Insufficient Resources
///
/// Insufficient Resources to complete the request.
case insufficientResources = 0x11
}
// MARK: - CustomStringConvertible
extension ATTError: CustomStringConvertible {
public var description: String {
return name
}
}
// MARK: - Description Values
public extension ATTError {
var name: String {
switch self {
case .invalidHandle:
return "Invalid Handle"
case .readNotPermitted:
return "Read Not Permitted"
case .writeNotPermitted:
return "Write Not Permitted"
case .invalidPDU:
return "Invalid PDU"
case .insufficientAuthentication:
return "Insufficient Authentication"
case .requestNotSupported:
return "Request Not Supported"
case .invalidOffset:
return "Invalid Offset"
case .insufficientAuthorization:
return "Insufficient Authorization"
case .prepareQueueFull:
return "Prepare Queue Full"
case .attributeNotFound:
return "Attribute Not Found"
case .attributeNotLong:
return "Attribute Not Long"
case .insufficientEncryptionKeySize:
return "Insufficient Encryption Key Size"
case .invalidAttributeValueLength:
return "Invalid Attribute Value Length"
case .unlikelyError:
return "Unlikely Error"
case .insufficientEncryption:
return "Insufficient Encryption"
case .unsupportedGroupType:
return "Unsupported Group Type"
case .insufficientResources:
return "Insufficient Resources"
}
}
var errorDescription: String {
switch self {
case .invalidHandle:
return "The attribute handle given was not valid on this server."
case .readNotPermitted:
return "The attribute cannot be read."
case .writeNotPermitted:
return "The attribute cannot be written."
case .invalidPDU:
return "The attribute PDU was invalid."
case .insufficientAuthentication:
return "The attribute requires authentication before it can be read or written."
case .requestNotSupported:
return "Attribute server does not support the request received from the client."
case .invalidOffset:
return "Offset specified was past the end of the attribute."
case .insufficientAuthorization:
return "The attribute requires authorization before it can be read or written."
case .prepareQueueFull:
return "Too many prepare writes have been queued."
case .attributeNotFound:
return "No attribute found within the given attri- bute handle range."
case .attributeNotLong:
return "The attribute cannot be read using the Read Blob Request."
case .insufficientEncryptionKeySize:
return "The Encryption Key Size used for encrypting this link is insufficient."
case .invalidAttributeValueLength:
return "The attribute value length is invalid for the operation."
case .unlikelyError:
return "The attribute request that was requested has encountered an error that was unlikely, and therefore could not be completed as requested."
case .insufficientEncryption:
return "The attribute requires encryption before it can be read or written."
case .unsupportedGroupType:
return "The attribute type is not a supported grouping attribute as defined by a higher layer specification."
case .insufficientResources:
return "Insufficient Resources to complete the request."
}
}
}
// MARK: - CustomNSError
import Foundation
extension ATTError: CustomNSError {
public static var errorDomain: String {
return "org.pureswift.Bluetooth.ATTError"
}
public var errorCode: Int {
return Int(rawValue)
}
public var errorUserInfo: [String: Any] {
return [
NSLocalizedDescriptionKey: name,
NSLocalizedFailureReasonErrorKey: errorDescription
]
}
}
| mit | b96f0c998c0fa8d215d3d5b7eb6c097d | 33.642534 | 156 | 0.61651 | 5.52381 | false | false | false | false |
MartinOSix/DemoKit | dSwift/SwiftDemoKit/SwiftDemoKit/TableHeadViewController.swift | 1 | 2080 | //
// TableHeadViewController.swift
// SwiftDemoKit
//
// Created by runo on 17/3/20.
// Copyright © 2017年 com.runo. All rights reserved.
//
import UIKit
class TableHeadViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let datas = ["下拉"]
let tableView = UITableView.init(frame: kScreenBounds, style: .plain)
let headView = UIImageView.init(frame: CGRect.init(x: 0.0, y: 0.0, width: kScreenWidth, height: kScreenHeight/3.0))
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
headView.backgroundColor = .white
headView.contentMode = .scaleAspectFill
headView.clipsToBounds = true
view.addSubview(headView)
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
tableView.contentInset.top = kScreenHeight/3.0
view.sendSubview(toBack: tableView)
//加载图片
let url = URL.init(string: "http://c.hiphotos.baidu.com/zhidao/pic/item/5ab5c9ea15ce36d3c704f35538f33a87e950b156.jpg")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let _ = data,error == nil else { return }
//回到主线程
DispatchQueue.main.sync {
self.headView.image = UIImage.init(data: data!)
}
}
task.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell.init(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = datas[indexPath.row]
return cell
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.headView.frame.size.height = scrollView.contentOffset.y * -1
}
}
| apache-2.0 | 2ff3c6373212a317efca5dc66ff7b910 | 32.145161 | 138 | 0.650122 | 4.409871 | false | false | false | false |
ming1016/smck | smck/Lib/RxSwift/Rx.swift | 15 | 1822 | //
// Rx.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if TRACE_RESOURCES
fileprivate var resourceCount: AtomicInt = 0
/// Resource utilization information
public struct Resources {
/// Counts internal Rx resource allocations (Observables, Observers, Disposables, etc.). This provides a simple way to detect leaks during development.
public static var total: Int32 {
return resourceCount.valueSnapshot()
}
/// Increments `Resources.total` resource count.
///
/// - returns: New resource count
public static func incrementTotal() -> Int32 {
return AtomicIncrement(&resourceCount)
}
/// Decrements `Resources.total` resource count
///
/// - returns: New resource count
public static func decrementTotal() -> Int32 {
return AtomicDecrement(&resourceCount)
}
}
#endif
/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass.
func abstractMethod() -> Swift.Never {
rxFatalError("Abstract method")
}
func rxFatalError(_ lastMessage: String) -> Swift.Never {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage)
}
func incrementChecked(_ i: inout Int) throws -> Int {
if i == Int.max {
throw RxError.overflow
}
defer { i += 1 }
return i
}
func decrementChecked(_ i: inout Int) throws -> Int {
if i == Int.min {
throw RxError.overflow
}
defer { i -= 1 }
return i
}
| apache-2.0 | 6277ff11645400efb0c53a0283107333 | 29.864407 | 230 | 0.647446 | 4.5525 | false | false | false | false |
stripe/stripe-ios | Example/UI Examples/CardFormViewController.swift | 1 | 1657 | //
// CardFormViewController.swift
// UI Examples
//
// Created by Cameron Sabol on 3/2/21.
// Copyright © 2021 Stripe. All rights reserved.
//
import Stripe
import UIKit
class CardFormViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Card Form"
if #available(iOS 13.0, *) {
view.backgroundColor = .systemBackground
} else {
// Fallback on earlier versions
view.backgroundColor = .white
}
let cardForm = STPCardFormView()
cardForm.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(cardForm)
NSLayoutConstraint.activate([
cardForm.leadingAnchor.constraint(equalToSystemSpacingAfter: view.safeAreaLayoutGuide.leadingAnchor, multiplier: 4),
view.safeAreaLayoutGuide.trailingAnchor.constraint(equalToSystemSpacingAfter: cardForm.trailingAnchor, multiplier: 4),
cardForm.centerXAnchor.constraint(equalTo: view.centerXAnchor),
cardForm.topAnchor.constraint(greaterThanOrEqualToSystemSpacingBelow: view.safeAreaLayoutGuide.topAnchor, multiplier: 1),
view.safeAreaLayoutGuide.bottomAnchor.constraint(greaterThanOrEqualToSystemSpacingBelow: cardForm.bottomAnchor, multiplier: 1),
cardForm.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .done, target: self, action: #selector(done))
}
@objc func done() {
dismiss(animated: true, completion: nil)
}
}
| mit | 6cf39f5ef5d8fae264d30424d06c4791 | 35.8 | 139 | 0.683575 | 5.429508 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/NewVersion/BookShelf/ZSShelfManager.swift | 1 | 15562 | //
// ZSShelfManager.swift
// zhuishushenqi
//
// Created by caony on 2020/1/8.
// Copyright © 2020 QS. All rights reserved.
//
import UIKit
import HandyJSON
import YungCache
class ZSShelfManager {
private let shelfBooksPath = "bookshelf"
private let shelfBooksPathKey = "shelfBooksPathKey"
private let shelfBooksHistoryPath = "bookshelf/history"
static let share = ZSShelfManager()
let booksCache:Cache<Data>
let shelfsCache:Cache<Data>
// 每个book的localPath
var books:[String] = [] {
didSet {
booksCache.setObjs(books, forKey: shelfBooksPath)
}
}
var aikanBooks:[String:ZSAikanParserModel] = [:]
var localBooks:[ZSShelfModel] = []
let helper = MonitorFileChangeHelp()
var isScanning:Bool = false
var queue:DispatchQueue = DispatchQueue(label: "com.shelf.update")
private init(){
booksCache = Cache<Data>(path: shelfBooksPath)
shelfsCache = Cache<Data>(path: "\(shelfBooksPath)/books")
createPath()
unpackBooksFile()
local()
}
func unpackBooksFile() {
if let books:[String] = booksCache.getObj(forKey: shelfBooksPath) {
self.books = books
for bookPath in books {
let fullPath = shelfModelPath(url: bookPath)
let aikan:ZSShelfModel? = shelfsCache.getObj(forKey: fullPath)
}
}
}
func saveShelfModel(shelf:ZSShelfModel) {
shelfsCache.setObj(shelf, forKey: "\(shelf.bookUrl)")
}
func getShelfModel(bookPath:String)->ZSShelfModel? {
if let shelf:ZSShelfModel = shelfsCache.getObj(forKey: "\(bookPath)") {
return shelf
}
return nil
}
func removeBook(bookPath:String) {
let bookPath = shelfModelPath(url: bookPath)
shelfsCache.removeObject(forKey: bookPath.asNSString())
}
func refresh() {
let path = "\(NSHomeDirectory())/Documents/Inbox/"
scanPath(path: path)
}
func local() {
let path = "\(NSHomeDirectory())/Documents/Inbox/"
scanPath(path: path)
helper.watcher(forPath: path) { [weak self] (type) in
self?.scanPath(path: path)
}
NotificationCenter.default.addObserver(self, selector: #selector(localChangeNoti(noti:)), name: NSNotification.Name.LocalShelfChanged, object: nil)
}
func scanPath(path:String){
if isScanning {
return
}
isScanning = true
if let items = try? FileManager.default.contentsOfDirectory(atPath: path) {
for item in items {
let filePath = path.appending("\(item)")
let txtPathExtension = ".txt"
if filePath.hasSuffix(txtPathExtension) {
let fileFullName = filePath.nsString.lastPathComponent.replacingOccurrences(of: txtPathExtension, with: "")
let bookUrl = "\(NSHomeDirectory())/Documents/Inbox/\(fileFullName)\(txtPathExtension)"
let localBookUrl = "\(NSHomeDirectory())/Documents/LocalBooks/\(fileFullName)\(txtPathExtension)"
if !FileManager.default.fileExists(atPath: localBookUrl) {
try? FileManager.default.copyItem(atPath: bookUrl, toPath: localBookUrl)
}
}
}
}
localBooks.removeAll()
let localPath = "\(NSHomeDirectory())/Documents/LocalBooks/"
guard let localItems = try? FileManager.default.contentsOfDirectory(atPath: localPath) else { return }
for item in localItems {
let filePath = path.appending("\(item)")
let txtPathExtension = ".txt"
if filePath.hasSuffix(txtPathExtension) {
let fileFullName = filePath.nsString.lastPathComponent.replacingOccurrences(of: txtPathExtension, with: "")
let localBookUrl = "/Documents/LocalBooks/\(fileFullName)\(txtPathExtension)"
let shelf = ZSShelfModel()
shelf.bookType = .local
shelf.bookName = fileFullName
shelf.bookUrl = localBookUrl
if !exist(localBookUrl) {
books.append(localBookUrl)
localBooks.append(shelf)
saveShelfModel(shelf: shelf)
} else if !localBooks.contains(shelf) {
localBooks.append(shelf)
}
}
}
isScanning = false
NotificationCenter.default.post(name: .ShelfChanged, object: nil)
}
//MARK: - local handler
@objc
private func localChangeNoti(noti:Notification) {
refresh()
}
func removeLocalBook(bookUrl:String) {
if exist(bookUrl) {
books.removeAll { (model) -> Bool in
return model == bookUrl
}
try? FileManager.default.removeItem(atPath:"\(NSHomeDirectory())\(bookUrl)")
save()
refresh()
}
}
@discardableResult
func add(_ book:ZSShelfModel) ->Bool {
if !exist(book.bookUrl) {
books.append(book.bookUrl)
saveShelfModel(shelf: book)
return true
}
return false
}
@discardableResult
func remove(_ book:ZSShelfModel) ->Bool {
let exitIndex = index(book.bookUrl)
if exitIndex >= 0 && exitIndex < books.count {
books.remove(at: exitIndex)
removeBook(bookPath: book.bookUrl)
return true
}
return false
}
@discardableResult
func remove(_ bookUrl:String) ->Bool {
var index = 0
for book in books {
if book == bookUrl {
books.remove(at: index)
break
}
index += 1
}
return true
}
@discardableResult
func modify(_ book:ZSShelfModel) ->Bool {
let exitIndex = index(book.bookUrl)
if exitIndex >= 0 && exitIndex < books.count {
books.remove(at: exitIndex)
books.insert(book.bookUrl, at: exitIndex)
return true
}
return false
}
func change(from:Int, to:Int) {
if from >= books.count || from < 0 {
return
}
if to >= books.count || to < 0 {
return
}
if from == to {
return
}
let book = books[from]
if remove(book) {
books.insert(book, at: to)
}
}
func exist(_ bookUrl:String) ->Bool {
var exist = false
for bk in self.books {
if bk == bookUrl {
exist = true
break
}
}
return exist
}
func exist(_ bookUrl:String, at:[ZSShelfModel]) ->Bool {
var exist = false
for bk in at {
if bk.bookUrl == bookUrl {
exist = true
break
}
}
return exist
}
func exist(_ book:ZSShelfModel) -> Bool {
var exist = false
for bk in self.books {
if bk == book.bookUrl {
exist = true
break
}
}
return exist
}
func addAikan(_ book:ZSAikanParserModel) {
let shelfModel = book.transformShelf()
if add(shelfModel) {
setAikan(model: book) { (result) in
}
} else if modify(shelfModel) {
setAikan(model: book) { (result) in
}
}
}
func removeAikan(_ book:ZSAikanParserModel) {
let shelfModel = book.transformShelf()
if remove(shelfModel) {
// save aikan
let aikanFilePath = aikansPath(url: book.bookUrl)
booksCache.removeObject(forKey: aikanFilePath.asNSString())
}
}
func removeAikan(bookUrl:String) {
let aikanFilePath = aikansPath(url: bookUrl)
booksCache.removeObject(forKey: aikanFilePath.asNSString())
}
func modifyAikan(_ book:ZSAikanParserModel) {
let bookPath = shelfModelPath(url: book.bookUrl)
func updateAikan(shelf:ZSShelfModel, book:ZSAikanParserModel) {
if modify(shelf) {
setAikan(model: book) { (result) in
}
}
}
if let shelf:ZSShelfModel = shelfsCache.getObj(forKey: book.bookUrl) {
let shelf = book.updateShelf(shelf: shelf)
saveShelfModel(shelf: shelf)
updateAikan(shelf: shelf, book: book)
} else {
let shelfModel = book.transformShelf()
updateAikan(shelf: shelfModel, book: book)
}
}
func getAikanModel(_ shelf:ZSShelfModel, block: @escaping (_ aikan:ZSAikanParserModel?)->Void) {
let queue = DispatchQueue(label: "com.getaikanQueue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent)
queue.async {
let aikan:ZSAikanParserModel? = self.booksCache.getObj(forKey: shelf.bookUrl)
DispatchQueue.main.async {
block(aikan)
}
}
}
func setAikan(model: ZSAikanParserModel, block: @escaping (_ aikan:Bool)->Void) {
booksCache.setObj(model, forKey: model.bookUrl)
DispatchQueue.main.async {
block(true)
}
}
func history(_ bookUrl:String, block:@escaping (_ history:ZSReadHistory?)->Void) {
let aikanFilePath = historyStorePath(url: bookUrl)
ZSShelfStorage.share.unarchive(path: aikanFilePath, block: { result in
if let history = result as? ZSReadHistory {
block(history)
} else {
block(nil)
}
})
}
func addHistory(_ history:ZSReadHistory) {
let aikanFilePath = historyStorePath(url: history.chapter.bookUrl)
ZSShelfStorage.share.archive(obj: history, path: aikanFilePath)
}
func removeHistory(_ history:ZSReadHistory) {
let aikanFilePath = historyStorePath(url: history.chapter.bookUrl)
ZSShelfStorage.share.delete(path: aikanFilePath)
}
func removeHistory(bookUrl:String) {
let aikanFilePath = historyStorePath(url: bookUrl)
ZSShelfStorage.share.delete(path: aikanFilePath)
}
private func save() {
let booksP = booksPath()
let queue = DispatchQueue(label: "com.saveshelfQueue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent)
queue.async {
self.booksCache.setObjs(self.books, forKey: booksP)
}
}
private func index(_ bookPath:String) ->Int {
var index = 0
var exitIndex = -1
for bk in self.books {
if bk == bookPath {
exitIndex = index
break
}
index += 1
}
return exitIndex
}
private func shelfModelPath(url:String) ->String {
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? ""
let booksPath = documentPath.appending("/\(shelfBooksPath)/books/")
let aikanFileName = url.md5()
let aikanFilePath = booksPath.appending(aikanFileName)
if !FileManager.default.fileExists(atPath: booksPath, isDirectory: nil) {
try? FileManager.default.createDirectory(atPath: booksPath, withIntermediateDirectories: true, attributes: nil)
}
return aikanFilePath
}
private func aikansPath(url:String) ->String {
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? ""
let booksPath = documentPath.appending("/\(shelfBooksPath)/")
let aikanFileName = url.md5()
let aikanFilePath = booksPath.appending(aikanFileName)
return aikanFilePath
}
private func booksPath() ->String {
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? ""
let booksPath = documentPath.appending("/\(shelfBooksPath)/\(shelfBooksPathKey.md5())")
return booksPath
}
private func historyStorePath(url:String) ->String {
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? ""
let booksHistoryPath = documentPath.appending("/\(shelfBooksHistoryPath)/")
let aikanFileName = url.md5()
let aikanFilePath = booksHistoryPath.appending(aikanFileName)
return aikanFilePath
}
private func createPath() {
let fileManager = FileManager.default
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? ""
let booksPath = documentPath.appending("/\(shelfBooksPath)/")
var pointer:UnsafeMutablePointer<ObjCBool>?
if !fileManager.fileExists(atPath: booksPath, isDirectory: pointer) {
try? fileManager.createDirectory(atPath: booksPath, withIntermediateDirectories: true, attributes: nil)
}
let historyPath = documentPath.appending("/\(shelfBooksHistoryPath)")
if !fileManager.fileExists(atPath: historyPath, isDirectory: pointer) {
try? fileManager.createDirectory(atPath: historyPath, withIntermediateDirectories: true, attributes: nil)
}
}
}
class ZSShelfModel: NSObject,NSCoding, HandyJSON {
var icon:String = ""
var bookName:String = ""
var author:String = ""
// 根据url查找对应的model
var bookUrl:String = ""
// 是否更新
var update:Bool = false
// 最近更新章节
var latestChapterName:String = ""
// 是否本地书籍
var bookType:ZSReaderBookStyle = .online
required override init() {
}
func encode(with coder: NSCoder) {
coder.encode(self.icon, forKey: "icon")
coder.encode(self.bookName, forKey: "bookName")
coder.encode(self.author, forKey: "author")
coder.encode(self.bookUrl, forKey: "bookUrl")
coder.encode(self.bookType.rawValue, forKey: "bookType")
coder.encode(self.update, forKey: "update")
coder.encode(self.latestChapterName, forKey: "latestChapterName")
}
required init?(coder: NSCoder) {
self.icon = coder.decodeObject(forKey: "icon") as? String ?? ""
self.bookName = coder.decodeObject(forKey: "bookName") as? String ?? ""
self.author = coder.decodeObject(forKey: "author") as? String ?? ""
self.bookUrl = coder.decodeObject(forKey: "bookUrl") as? String ?? ""
self.bookType = ZSReaderBookStyle(rawValue: coder.decodeInteger(forKey: "bookType")) ?? .online
self.update = coder.decodeBool(forKey: "update")
self.latestChapterName = coder.decodeObject(forKey: "latestChapterName") as? String ?? ""
}
}
extension Array where Element:ZSShelfModel {
func contains(_ element: Element) -> Bool {
if self.count == 0 {
return false
}
var contain:Bool = false
for item in self {
if item.bookUrl == element.bookUrl {
contain = true
break
}
}
return contain
}
}
| mit | f563ddc5adaf89f8b40969b0131a7f54 | 32.788671 | 155 | 0.582887 | 4.536122 | false | false | false | false |
sunuslee/SULUserNotificationCenter | SULUserNotificationCenter/Classes/SULUserNotificationButton.swift | 1 | 3975 | //
// SULUserNotificationButton.swift
// CrazyCooler
//
// Created by Sunus on 01/03/2017.
// Copyright © 2017 sunus. All rights reserved.
//
import Cocoa
enum SUL_BorderEdge: Int {
case top = 1
case left = 2
case bottom = 4
case right = 8
case unknown
}
extension CALayer {
func SUL_addBorder(edge: SUL_BorderEdge, color: NSColor, thickness: CGFloat) {
let border = CALayer()
switch edge {
case .top:
border.frame = CGRect.init(x: 0, y: 0, width: frame.width, height: thickness)
break
case .bottom:
border.frame = CGRect.init(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
break
case .left:
border.frame = CGRect.init(x: 0, y: 0, width: thickness, height: frame.height)
break
case .right:
border.frame = CGRect.init(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
break
default:
break
}
border.backgroundColor = color.cgColor;
self.addSublayer(border)
}
}
open class SULUserNotificationButton: NSButton {
static let buttonColor = NSColor(calibratedHue:0.5,
saturation:0,
brightness:0.94,
alpha:1).cgColor
static let buttonBorderColor = NSColor(calibratedHue:0,
saturation:0,
brightness:0.85,
alpha:1)
let actionButtonColor = NSColor(calibratedHue:0,
saturation:0,
brightness:0.44,
alpha:1)
open override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
}
public convenience init(_ frame:CGRect, title:String, target:AnyObject?, action:Selector?) {
self.init()
self.setSULButtonTitle(title: title)
self.target = target
self.action = action
self.frame = frame
self.setButtonType(.momentaryPushIn)
self.isBordered = false
self.wantsLayer = true
self.layer?.backgroundColor = SULUserNotificationButton.buttonColor
self.layer?.SUL_addBorder(edge: .left, color: SULUserNotificationButton.buttonBorderColor, thickness: 1.0)
}
func buttonAttributes() -> [String:Any] {
let pa = NSMutableParagraphStyle()
pa.alignment = .center
let attrs = [
NSFontAttributeName: NSFont.boldSystemFont(ofSize: 12),
NSForegroundColorAttributeName:actionButtonColor,
NSParagraphStyleAttributeName: pa
]
return attrs
}
func setSULButtonTitle(title:String?) {
guard let t = title else {
return
}
self.attributedTitle = NSAttributedString(string: t, attributes:self.buttonAttributes())
}
func addBorder(borders:Int) {
if (borders & SUL_BorderEdge.top.rawValue) != 0 {
self.layer?.SUL_addBorder(edge: .top, color: SULUserNotificationButton.buttonBorderColor, thickness: 1.0)
}
if (borders & SUL_BorderEdge.bottom.rawValue) != 0 {
self.layer?.SUL_addBorder(edge: .bottom, color: SULUserNotificationButton.buttonBorderColor, thickness: 1.0)
}
if (borders & SUL_BorderEdge.left.rawValue) != 0 {
self.layer?.SUL_addBorder(edge: .left, color: SULUserNotificationButton.buttonBorderColor, thickness: 1.0)
}
if (borders & SUL_BorderEdge.right.rawValue) != 0 {
self.layer?.SUL_addBorder(edge: .right, color: SULUserNotificationButton.buttonBorderColor, thickness: 1.0)
}
}
}
| mit | 4c0216845f3192e64eb0baef79121212 | 32.394958 | 120 | 0.562406 | 4.541714 | false | false | false | false |
BenziAhamed/Nevergrid | NeverGrid/Source/DestroyCells.swift | 1 | 3249 | //
// DestroyCells.swift
// MrGreen
//
// Created by Benzi on 15/08/14.
// Copyright (c) 2014 Benzi Ahamed. All rights reserved.
//
import Foundation
import SpriteKit
/// action that makes falling cells fall based on your previous location
/// raises the floating cell destroyed event
class DestroyCells : EntityAction {
var cellFilter:[CellType]
init(cellFilter:[CellType], entity:Entity, world:WorldMapper) {
self.cellFilter = cellFilter
super.init(entity: entity, world: world)
}
override var description:String { return "DestroyCells" }
override func perform() -> SKAction? {
let location = world.location.get(entity)
let prevLocation = LocationComponent(row: location.previousRow, column: location.previousColumn)
if prevLocation == location { return nil } // if we are just standing in the same position don't do anything
let gridCell = world.level.cells.get(prevLocation)!
// if the cell does not match our filter
if !cellFilter.contains(gridCell.type) { return nil }
// or if we are an enemy and the previous cell contained a collectible item
if entity != world.mainPlayer && cellContainsCollectableItem(prevLocation) { return nil }
let cellEntityForPrevLocation = world.cellCache.get(prevLocation)
// update the walls so that we can't reach this cell anymore
gridCell.walls = Direction.All
gridCell.fallen = true
// destroy the cell
world.eventBus.raise(GameEvent.CellDestroyed, data: cellEntityForPrevLocation)
// if this cell had a portal
// destroy the source and destination portals
if let source = world.portalCache.get(prevLocation) {
let sourcePortal = world.portal.get(source)
let destination = world.portalCache.get(sourcePortal.destination)!
world.eventBus.raise(GameEvent.PortalDestroyed, data: source)
world.eventBus.raise(GameEvent.PortalDestroyed, data: destination)
world.portalCache.clear(prevLocation)
world.portalCache.clear(sourcePortal.destination)
}
// if this cell had an enemy not of type monster
// destroy the enemy too, applicable only for destroyers
if entity != world.mainPlayer {
let cell = world.level.cells.get(prevLocation)!
if cell.occupiedByEnemy {
let e = cell.occupiedBy!
let enemy = world.enemy.get(e)
if enemy.enabled || enemy.enemyType != EnemyType.Monster {
// kill this enemy
cell.occupiedBy = nil
world.eventBus.raise(GameEvent.EnemyDeath, data: e)
}
}
}
return nil
}
func cellContainsCollectableItem(cellLocation:LocationComponent) -> Bool {
for collectable in world.collectable.entities() {
let location = world.location.get(collectable)
if location == cellLocation { return true }
}
return false
}
} | isc | 47085ff919de598ead472e99a78b551f | 33.574468 | 116 | 0.614035 | 4.813333 | false | false | false | false |
alessandrostone/RIABrowser | RIABrowser/viewcontroller/ClassNamesTableViewController.swift | 1 | 1699 | //
// ClassNamesTableViewController.swift
// RIABrowser
//
// Created by Yoshiyuki Tanaka on 2015/04/04.
// Copyright (c) 2015 Yoshiyuki Tanaka. All rights reserved.
//
import UIKit
class ClassNamesTableViewController :UITableViewController {
var classNames = [String]()
var selectedClassNames = ""
override func viewDidLoad() {
super.viewDidLoad()
classNames = ObjectExtractor.sharedInstance.classNames
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
if segue.identifier == "toObjectsTableViewController" {
var objectsViewController = segue.destinationViewController as! ObjectsTableViewController
objectsViewController.className = selectedClassNames
objectsViewController.objects = ObjectExtractor.sharedInstance.objects(selectedClassNames)
// selectedClassNames = ""
}
}
//MARK: IBAction
@IBAction func pressCloseButton(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
//MARK:UITableViewDelegate
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
selectedClassNames = classNames[indexPath.row]
return indexPath
}
//MARK:UITableViewDatasource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return classNames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ClassNamesTableViewCell") as! UITableViewCell
cell.textLabel?.text = classNames[indexPath.row]
return cell
}
}
| mit | 68661f54be164688b473ab8a3ee6c465 | 32.313725 | 116 | 0.760447 | 5.179878 | false | false | false | false |
nodes-ios/NStackSDK | NStackSDK/NStackSDK/Classes/Logger/Logger.swift | 1 | 2661 | //
// Logger.swift
// NStackSDK
//
// Created by Dominik Hádl on 02/12/2016.
// Copyright © 2016 Nodes ApS. All rights reserved.
//
import Foundation
public protocol LoggerType: class {
var logLevel: LogLevel { get set }
var customName: String? { get set }
var detailedOutput: Bool { get set }
func writeLogEntry(_ items: [String], level: LogLevel,
file: StaticString, line: Int, function: StaticString)
}
extension LoggerType {
func log(_ items: CustomStringConvertible...,
level: LogLevel,
file: StaticString = #file,
line: Int = #line,
function: StaticString = #function) {
writeLogEntry(items.map({ $0.description }), level: level,
file: file, line: line, function: function)
}
func logVerbose(_ items: CustomStringConvertible...,
file: StaticString = #file,
line: Int = #line,
function: StaticString = #function) {
writeLogEntry(items.map({ $0.description }), level: .verbose,
file: file, line: line, function: function)
}
func logWarning(_ items: CustomStringConvertible...,
file: StaticString = #file,
line: Int = #line,
function: StaticString = #function) {
writeLogEntry(items.map({ $0.description }), level: .warning,
file: file, line: line, function: function)
}
func logError(_ items: CustomStringConvertible...,
file: StaticString = #file,
line: Int = #line,
function: StaticString = #function) {
writeLogEntry(items.map({ $0.description }), level: .error,
file: file, line: line, function: function)
}
}
class ConsoleLogger: LoggerType {
var logLevel: LogLevel = .error
var customName: String?
var detailedOutput: Bool = false
func writeLogEntry(_ items: [String],
level: LogLevel,
file: StaticString,
line: Int,
function: StaticString) {
guard level >= logLevel, logLevel != .none else { return }
let filename = file.description.components(separatedBy: "/").last ?? "N/A"
let message = items.joined(separator: " ")
if detailedOutput {
print("[NStackSDK\(customName ?? "")] \(level.message) \(filename):\(line) – \(function) – \(message)")
} else {
print("[NStackSDK\(customName ?? "")] \(level.message) \(message)")
}
}
}
| mit | 20fac3023fa3d2d28fa8e44062c1af4d | 33.038462 | 115 | 0.548023 | 4.741071 | false | false | false | false |
thii/FontAwesome.swift | Sources/FontAwesome/FontAwesomeView.swift | 3 | 2810 | // FontAwesomeView.swift
//
// Copyright (c) 2014-present FontAwesome.swift contributors
//
// 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
/// A view for FontAwesome icons.
@IBDesignable public class FontAwesomeView: UIView {
@IBInspectable
public var iconCode: String = "" {
didSet {
self.iconView.text = String.fontAwesomeIcon(code: iconCode)
}
}
@IBInspectable
public var styleName: String = "Brands"
private var iconView = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
override public func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setupViews()
}
/// Add a UILabel subview containing FontAwesome icon
func setupViews() {
// Fits icon in the view
self.iconView.textAlignment = NSTextAlignment.center
self.iconView.text = String.fontAwesomeIcon(code: self.iconCode)
self.iconView.textColor = self.tintColor
self.addSubview(iconView)
}
override public func tintColorDidChange() {
self.iconView.textColor = self.tintColor
}
override public func layoutSubviews() {
super.layoutSubviews()
self.clipsToBounds = true
let size = bounds.size.width < bounds.size.height ? bounds.size.width : bounds.size.height
let style = FontAwesomeStyle(rawValue: styleName) ?? .solid
self.iconView.font = UIFont.fontAwesome(ofSize: size, style: style)
self.iconView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: bounds.size.width, height: bounds.size.height))
}
}
| mit | 259627520c5032014fa882105fa71ec2 | 35.973684 | 133 | 0.701423 | 4.652318 | false | false | false | false |
aslanyanhaik/Quick-Chat | QuickChat/Presenter/Conversations/ConversationsViewController.swift | 1 | 5595 | // MIT License
// Copyright (c) 2019 Haik Aslanyan
// 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 ConversationsViewController: UIViewController {
//MARK: IBOutlets
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var profileImageView: UIImageView!
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
//MARK: Private properties
private var conversations = [ObjectConversation]()
private let manager = ConversationManager()
private let userManager = UserManager()
private var currentUser: ObjectUser?
//MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
fetchProfile()
fetchConversations()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
navigationController?.setNavigationBarHidden(true, animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
navigationController?.setNavigationBarHidden(false, animated: true)
}
}
//MARK: IBActions
extension ConversationsViewController {
@IBAction func profilePressed(_ sender: Any) {
let vc: ProfileViewController = UIStoryboard.initial(storyboard: .profile)
vc.delegate = self
vc.user = currentUser
present(vc, animated: false)
}
@IBAction func composePressed(_ sender: Any) {
let vc: ContactsPreviewController = UIStoryboard.controller(storyboard: .previews)
vc.delegate = self
present(vc, animated: true, completion: nil)
}
}
//MARK: Private methods
extension ConversationsViewController {
func fetchConversations() {
manager.currentConversations {[weak self] conversations in
self?.conversations = conversations.sorted(by: {$0.timestamp > $1.timestamp})
self?.tableView.reloadData()
self?.playSoundIfNeeded()
}
}
func fetchProfile() {
userManager.currentUserData {[weak self] user in
self?.currentUser = user
if let urlString = user?.profilePicLink {
self?.profileImageView.setImage(url: URL(string: urlString))
}
}
}
func playSoundIfNeeded() {
guard let id = userManager.currentUserID() else { return }
if conversations.last?.isRead[id] == false {
AudioService().playSound()
}
}
}
//MARK: UITableView Delegate & DataSource
extension ConversationsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if conversations.isEmpty {
return 1
}
return conversations.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard !conversations.isEmpty else {
return tableView.dequeueReusableCell(withIdentifier: "EmptyCell")!
}
let cell = tableView.dequeueReusableCell(withIdentifier: ConversationCell.className) as! ConversationCell
cell.set(conversations[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if conversations.isEmpty {
composePressed(self)
return
}
let vc: MessagesViewController = UIStoryboard.initial(storyboard: .messages)
vc.conversation = conversations[indexPath.row]
manager.markAsRead(conversations[indexPath.row])
show(vc, sender: self)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if conversations.isEmpty {
return tableView.bounds.height - 50 //header view height
}
return 80
}
}
//MARK: ProfileViewController Delegate
extension ConversationsViewController: ProfileViewControllerDelegate {
func profileViewControllerDidLogOut() {
userManager.logout()
navigationController?.dismiss(animated: true)
}
}
//MARK: ContactsPreviewController Delegate
extension ConversationsViewController: ContactsPreviewControllerDelegate {
func contactsPreviewController(didSelect user: ObjectUser) {
guard let currentID = userManager.currentUserID() else { return }
let vc: MessagesViewController = UIStoryboard.initial(storyboard: .messages)
if let conversation = conversations.filter({$0.userIDs.contains(user.id)}).first {
vc.conversation = conversation
show(vc, sender: self)
return
}
let conversation = ObjectConversation()
conversation.userIDs.append(contentsOf: [currentID, user.id])
conversation.isRead = [currentID: true, user.id: true]
vc.conversation = conversation
show(vc, sender: self)
}
}
| mit | 3fbb5309004162837a04469fb1cccade | 32.909091 | 109 | 0.732797 | 4.835782 | false | false | false | false |
1457792186/JWSwift | SwiftWX/LGWeChatKit/LGChatKit/Extension/LGColorEx.swift | 1 | 2403 | //
// LGColorEx.swift
// LGChatViewController
//
// Created by gujianming on 15/10/8.
// Copyright © 2015年 jamy. All rights reserved.
//
import UIKit
extension UIColor {
convenience init?(hexString: String) {
self.init(hexString: hexString, alpha: 1.0)
}
convenience init?(hexString: String, alpha: Float) {
var hex = hexString
if hex.hasPrefix("#") {
hex = hex.substring(from: hex.characters.index(hex.startIndex, offsetBy: 1))
}
if let _ = hex.range(of: "(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .regularExpression) {
if hex.lengthOfBytes(using: String.Encoding.utf8) == 3 {
let redHex = hex.substring(to: hex.characters.index(hex.startIndex, offsetBy: 1))
let greenHex = hex.substring(with: (hex.characters.index(hex.startIndex, offsetBy: 1) ..< hex.characters.index(hex.startIndex, offsetBy: 2)))
let blueHex = hex.substring(from: hex.characters.index(hex.startIndex, offsetBy: 2))
hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex
}
let redHex = hex.substring(to: hex.characters.index(hex.startIndex, offsetBy: 2))
let greenHex = hex.substring(with: (hex.characters.index(hex.startIndex, offsetBy: 2) ..< hex.characters.index(hex.startIndex, offsetBy: 4)))
let blueHex = hex.substring(with: (hex.characters.index(hex.startIndex, offsetBy: 4) ..< hex.characters.index(hex.startIndex, offsetBy: 6)))
var redInt: CUnsignedInt = 0
var greenInt: CUnsignedInt = 0
var blueInt: CUnsignedInt = 0
Scanner(string: redHex).scanHexInt32(&redInt)
Scanner(string: greenHex).scanHexInt32(&greenInt)
Scanner(string: blueHex).scanHexInt32(&blueInt)
self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: CGFloat(alpha))
}
else
{
self.init()
return nil
}
}
convenience init?(hex: Int) {
self.init(hex: hex, alpha: 1.0)
}
convenience init?(hex: Int, alpha: Float) {
let hexString = NSString(format: "%2X", hex)
self.init(hexString: hexString as String, alpha: alpha)
}
}
| apache-2.0 | 4b5688133b537b0f90f2aad9323a292c | 37.709677 | 157 | 0.587917 | 4 | false | false | false | false |
0x0c/RDImageViewerController | RDImageViewerController/Classes/Model/ImageScrollView/ImageScrollView.swift | 1 | 10011 | //
// RDImageScrollView.swift
// Pods-RDImageViewerController
//
// Created by Akira Matsuda on 2019/04/07.
//
import UIKit
open class ImageScrollView<T: ImageContent>: UICollectionViewCell, UIScrollViewDelegate, PageViewRepresentation {
public struct ImageAlignment {
public enum HorizontalAlignment {
case left
case right
case center
}
public enum VerticalAlignment {
case top
case bottom
case center
}
public var horizontal: HorizontalAlignment = .center
public var vertical: VerticalAlignment = .center
}
open private(set) var scrollView: UIScrollView
public let zoomRect = CGSize(width: 100, height: 100)
open var alignment: ImageAlignment = ImageAlignment(horizontal: .center, vertical: .center) {
didSet {
fixImageViewPosition()
}
}
open var mode: ImageContent.LandscapeMode = .aspectFit {
didSet {
adjustContentAspect()
}
}
open var borderColor: UIColor? {
set {
if let color = newValue {
imageView.layer.borderColor = color.cgColor
}
}
get {
if let color = imageView.layer.borderColor {
return UIColor(cgColor: color)
}
return nil
}
}
open var borderWidth: CGFloat {
set {
imageView.layer.borderWidth = newValue
}
get {
imageView.layer.borderWidth
}
}
open var image: UIImage? {
set {
imageView.image = newValue
if imageView.image == nil {
indicatorView.startAnimating()
}
else {
indicatorView.stopAnimating()
}
fixImageViewPosition()
adjustContentAspect()
}
get {
imageView.image
}
}
open private(set) var imageView = UIImageView()
var indicatorView = UIActivityIndicatorView(style: .white)
var zoomGesture = UITapGestureRecognizer(target: nil, action: nil)
var content: T?
override public init(frame: CGRect) {
scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
super.init(frame: frame)
scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
scrollView.delegate = self
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
if #available(iOS 11.0, *) {
self.scrollView.contentInsetAdjustmentBehavior = .never
}
addSubview(scrollView)
imageView.center = scrollView.center
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
imageView.layer.borderColor = UIColor.black.cgColor
imageView.layer.borderWidth = 0.5
imageView.contentMode = .scaleAspectFit
scrollView.addSubview(imageView)
indicatorView.center = imageView.center
indicatorView.autoresizingMask = [
.flexibleTopMargin,
.flexibleLeftMargin,
.flexibleBottomMargin,
.flexibleRightMargin
]
indicatorView.startAnimating()
addSubview(indicatorView)
zoomGesture = UITapGestureRecognizer(target: self, action: #selector(zoomImage(gesture:)))
zoomGesture.numberOfTapsRequired = 2
zoomGesture.numberOfTouchesRequired = 1
addGestureRecognizer(zoomGesture)
}
@available(*, unavailable)
public required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func zoomImage(gesture: UIGestureRecognizer) {
let imageView = gesture.view as! ImageScrollView
if imageView.scrollView.zoomScale > imageView.scrollView.minimumZoomScale {
imageView.scrollView.setZoomScale(1.0, animated: true)
}
else if imageView.scrollView.zoomScale < imageView.scrollView.maximumZoomScale {
let position = gesture.location(in: imageView.scrollView)
imageView.scrollView.zoom(
to: .init(
x: position.x - zoomRect.width / 2,
y: position.y - zoomRect.height / 2,
width: zoomRect.width,
height: zoomRect.height
),
animated: true
)
}
}
private func fixImageViewPosition() {
switch alignment.horizontal {
case .left:
imageView.frame.origin.x = 0
case .right:
imageView.frame.origin.x = frame.width - imageView.frame.width
case .center:
imageView.center.x = scrollView.center.x
}
switch alignment.vertical {
case .top:
imageView.frame.origin.y = 0
case .bottom:
imageView.frame.origin.y = frame.height - imageView.frame.height
case .center:
imageView.center.y = scrollView.center.y
}
}
open func adjustContentAspect() {
let fitToAspect = { [unowned self] in
imageView.rd_fitToAspect(containerSize: frame.size)
fixImageViewPosition()
scrollView.contentSize = imageView.frame.size
scrollView.setZoomScale(1.0, animated: false)
}
switch mode {
case .aspectFit:
fitToAspect()
case .displayFit:
if imageView.rd_fitToDisplay(containerSize: frame.size) {
let height = frame.height
let width = frame.width
if width > height {
scrollView.setZoomScale(1.0, animated: false)
}
}
else {
fitToAspect()
}
}
scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
}
public func addGestureRecognizerPriorityHigherThanZoomGestureRecogniser(gesture: UIGestureRecognizer) {
gesture.require(toFail: zoomGesture)
addGestureRecognizer(gesture)
}
// MARK: UIScrollViewDelegate
public func viewForZooming(in _: UIScrollView) -> UIView? {
imageView
}
public func scrollViewDidZoom(_ scrollView: UIScrollView) {
if let subView = scrollView.subviews.first {
var x = subView.center.x
var y = subView.center.y
if alignment.horizontal == .center {
var offsetX: CGFloat {
if scrollView.bounds.width > scrollView.contentSize.width {
return (scrollView.bounds.width - scrollView.contentSize.width) * 0.5
}
return 0
}
x = scrollView.contentSize.width * 0.5 + offsetX
}
if alignment.vertical == .center {
var offsetY: CGFloat {
if scrollView.bounds.height > scrollView.contentSize.height {
return (scrollView.bounds.height - scrollView.contentSize.height) * 0.5
}
return 0
}
y = scrollView.contentSize.height * 0.5 + offsetY
}
subView.center = CGPoint(x: x, y: y)
}
}
// MARK: PageViewRepresentation
open func resize() {
adjustContentAspect()
}
public func resize(
pageIndex: Int,
scrollDirection: PagingView.ForwardDirection,
traitCollection: UITraitCollection,
isDoubleSpread: Bool
) {
if pageIndex % 2 == 0 {
var horizontalAlignment: ImageAlignment.HorizontalAlignment {
if isDoubleSpread == false {
return .center
}
if scrollDirection == .right {
return .right
}
return .left
}
alignment = ImageAlignment(horizontal: horizontalAlignment, vertical: .center)
}
else {
var horizontalAlignment: ImageAlignment.HorizontalAlignment {
if isDoubleSpread == false {
return .center
}
if scrollDirection == .right {
return .left
}
return .right
}
alignment = ImageAlignment(horizontal: horizontalAlignment, vertical: .center)
}
resize()
}
open func configure(
data: PagingViewLoadable,
pageIndex: Int,
scrollDirection: PagingView.ForwardDirection,
traitCollection: UITraitCollection,
isDoubleSpread: Bool
) {
image = nil
content = nil
guard let data = data as? T else {
return
}
content = data
scrollView.maximumZoomScale = data.maximumZoomScale
mode = data.landscapeMode
scrollView.setZoomScale(1.0, animated: false)
if RDImageViewerController.rd_isLandscape(), isDoubleSpread {
resize(
pageIndex: pageIndex,
scrollDirection: scrollDirection,
traitCollection: traitCollection,
isDoubleSpread: isDoubleSpread
)
}
if data.image == nil {
data.stopPreload()
data.preload { [weak self] content in
if let weakSelf = self,
let cnt1 = weakSelf.content,
let cnt2 = content as? T {
DispatchQueue.main.async {
if cnt1 == cnt2 {
weakSelf.image = cnt2.image
}
}
}
}
}
else {
image = data.image
}
}
}
| mit | cd1d751da5d90cdf3e1516e4d034a5cb | 30.882166 | 113 | 0.555289 | 5.485479 | false | false | false | false |
eastsss/SwiftyUtilities | SwiftyUtilities/ReactivePortionLoader/ReactivePortionLoader.swift | 1 | 7153 | //
// ReactivePortionLoader.swift
// SwiftyUtilities
//
// Created by Anatoliy Radchenko on 07/06/2017.
// Copyright © 2017 SwiftyUtilities. All rights reserved.
//
import Moya
import Argo
import ReactiveSwift
import Result
public protocol Portion: Decodable {
associatedtype Item: Decodable
var items: [Item] { get }
var totalCount: Int { get }
}
public protocol ReactivePortionLoaderDelegate: class {
func requestToken(forLoaderIdentifier identifier: String, offset: Int, limit: Int) -> TargetType
func handle(error: Swift.Error)
}
public class ReactivePortionLoader<P: Portion, T: NetworkTarget> where P.DecodedType == P {
public typealias BatchUpdate = (insertions: [Int], modifications: [Int], deletions: [Int])
public typealias Modification = (P.Item) -> P.Item
public typealias Predicate = (P.Item) -> Bool
public typealias DidLoadPortionCompletion = (_ offset: Int, _ limit: Int) -> Void
public let identifier: String
public weak var delegate: ReactivePortionLoaderDelegate?
public var didLoadPortion: DidLoadPortionCompletion?
// MARK: Reactive properties
public var reloadFromStart: BindingTarget<()> {
return BindingTarget(lifetime: lifetime, action: { [weak self] in
self?.loadInitialPortion()
})
}
public var isNoResultsViewHidden: Property<Bool> {
return Property(_isNoResultsViewHidden)
}
public var loading: Property<Bool> {
return Property(_loading)
}
// MARK: Signals
public let reload: Signal<(), NoError>
public let batchUpdate: Signal<BatchUpdate, NoError>
// MARK: Private reactive properties
fileprivate let _isNoResultsViewHidden: MutableProperty<Bool> = MutableProperty(true)
fileprivate let _loading: MutableProperty<Bool> = MutableProperty(false)
fileprivate let (lifetime, token) = Lifetime.make()
// MARK: Observers
fileprivate let reloadObserver: Observer<(), NoError>
fileprivate let batchUpdateObserver: Observer<BatchUpdate, NoError>
// MARK: Network request related properties
fileprivate let dataProvider: NetworkProvider<T>
fileprivate let portionSize: Int
fileprivate var currentRequestDisposable: Disposable?
// MARK: Data
fileprivate var items: [P.Item] = []
public fileprivate(set) var expectedTotalCount: Int = 0
public init(dataProvider: NetworkProvider<T> = NetworkProvider<T>(),
portionSize: Int = 20,
identifier: String? = nil) {
self.dataProvider = dataProvider
self.portionSize = portionSize
if let userDefinedIdentifier = identifier {
self.identifier = userDefinedIdentifier
} else {
self.identifier = "\(type(of: self))"
}
(reload, reloadObserver) = Signal<(), NoError>.pipe()
(batchUpdate, batchUpdateObserver) = Signal<BatchUpdate, NoError>.pipe()
}
deinit {
currentRequestDisposable?.dispose()
}
public func loadInitialPortion() {
loadItems(offset: 0, limit: portionSize)
}
public func loadNext() {
if items.isEmpty {
loadItems(offset: 0, limit: portionSize)
} else {
let loaded = items.count
guard loaded < expectedTotalCount else {
return
}
let remaining = expectedTotalCount - loaded
let limit = (remaining < portionSize) ? remaining : portionSize
loadItems(offset: loaded, limit: limit)
}
}
}
// MARK: Read items
extension ReactivePortionLoader {
public func item(at index: Int) -> P.Item? {
guard 0..<items.count ~= index else {
return nil
}
return items[index]
}
public var itemsCount: Int {
return items.count
}
public var allItems: [P.Item] {
return items
}
}
// MARK: Modify items
extension ReactivePortionLoader {
public func modifyItems(with modification: Modification, where predicate: Predicate) {
let indexes = items.indexes(where: predicate)
for index in indexes {
items[index] = modification(items[index])
}
if !indexes.isEmpty {
batchUpdateObserver.send(value: ([], indexes, []))
}
}
public func deleteItems(where predicate: Predicate) {
let indexes = items.indexes(where: predicate)
items = items.filter(predicate)
if !indexes.isEmpty {
batchUpdateObserver.send(value: ([], [], indexes))
}
}
public func deleteAll() {
deleteItems(where: { _ in true })
}
}
// MARK: Portion loading
private extension ReactivePortionLoader {
func loadItems(offset: Int, limit: Int) {
if let existingRequest = currentRequestDisposable, !existingRequest.isDisposed {
existingRequest.dispose()
}
guard let token = delegate?.requestToken(forLoaderIdentifier: identifier, offset: offset, limit: limit) as? T else {
fatalError("ReactivePortionLoader delegate should return correct instance in requestToken(forLoaderIdentifier:offset:limit)")
}
currentRequestDisposable = dataProvider
.req(token)
.mapObject(type: P.self)
.on(starting: { [weak self] in
self?._loading.value = true
self?._isNoResultsViewHidden.value = true
})
.on(value: { [weak self] portion in
guard let strongSelf = self else {
return
}
if offset == 0 {
strongSelf.items = portion.items
strongSelf.reloadObserver.send(value: ())
strongSelf._isNoResultsViewHidden.value = !portion.items.isEmpty
} else {
let newIndexes = (0..<portion.items.count).map({ $0 + strongSelf.items.count })
strongSelf.items.append(contentsOf: portion.items)
if !newIndexes.isEmpty {
strongSelf.batchUpdateObserver.send(value: (newIndexes, [], []))
}
}
strongSelf.expectedTotalCount = portion.totalCount
strongSelf._loading.value = false
strongSelf.didLoadPortion?(offset, limit)
})
.on(failed: { [weak self] error in
if offset == 0 {
self?._isNoResultsViewHidden.value = false
}
self?.delegate?.handle(error: error)
})
.on(event: { [weak self] event in
switch event {
case .interrupted, .failed(_):
self?._loading.value = false
default:
return
}
})
.start()
}
}
| mit | f62b8e97ce83d8219d8c343de1ae1e62 | 31.509091 | 137 | 0.582774 | 5.101284 | false | false | false | false |
mmuehlberger/tutsplus-whats-new-in-ios10 | TutsplusCourses/Ride.swift | 1 | 1119 | //
// Ride.swift
// TutsplusCourses
//
// Created by Markus Mühlberger on 02/12/2016.
// Copyright © 2016 Markus Mühlberger. All rights reserved.
//
import UIKit
import CoreLocation
public enum RideState {
case available
case driving
case collecting
case completed
}
public class Ride {
public let driver : Driver
public let image : UIImage
public var state : RideState
public var location : CLLocation
var availableForPickup : Bool {
return state == .available
}
init(driver: Driver, image: UIImage, location: CLLocation) {
self.driver = driver
self.image = image
self.location = location
self.state = .available
}
func requestRide(pickup: CLLocation, dropoff: CLLocation) -> Bool {
if !availableForPickup {
return false
}
state = .collecting
return true
}
}
extension Ride : Hashable {
public var hashValue: Int {
return image.hashValue
}
}
public func == (lhs: Ride, rhs: Ride) -> Bool {
return lhs.image == rhs.image
}
| bsd-2-clause | 0f152c1d70928a0b8a20150bd6be7d57 | 19.666667 | 71 | 0.61828 | 4.275862 | false | false | false | false |
lorentey/swift | test/Inputs/conditional_conformance_basic_conformances.swift | 3 | 21306 | public func takes_p1<T: P1>(_: T.Type) {}
public protocol P1 {
func normal()
func generic<T: P3>(_: T)
}
public protocol P2 {}
public protocol P3 {}
public struct IsP2: P2 {}
public struct IsP3: P3 {}
public struct Single<A> {}
extension Single: P1 where A: P2 {
public func normal() {}
public func generic<T: P3>(_: T) {}
}
// witness method for Single.normal
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlAaEP6normalyyFTW"(%T42conditional_conformance_basic_conformances6SingleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[A_P2_i8star:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[A_P2:%.*]] = bitcast i8* [[A_P2_i8star]] to i8**
// CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type**
// CHECK-NEXT: [[A_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2
// CHECK-NEXT: [[A:%.*]] = load %swift.type*, %swift.type** [[A_PTR]], align 8
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVA2A2P2RzlE6normalyyF"(%swift.type* [[A]], i8** [[A_P2]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// witness method for Single.generic
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6SingleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[A_P2_i8star:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[A_P2:%.*]] = bitcast i8* [[A_P2_i8star]] to i8**
// CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type**
// CHECK-NEXT: [[A_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2
// CHECK-NEXT: [[A:%.*]] = load %swift.type*, %swift.type** [[A_PTR]], align 8
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVA2A2P2RzlE7genericyyqd__AA2P3Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* [[A]], %swift.type* %"\CF\84_1_0", i8** [[A_P2]], i8** %"\CF\84_1_0.P3")
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public func single_generic<T: P2>(_: T.Type) {
takes_p1(Single<T>.self)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances14single_genericyyxmAA2P2RzlF"(%swift.type*, %swift.type* %T, i8** %T.P2)
// CHECK-NEXT: entry:
// CHECK: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6SingleVMa"(i64 0, %swift.type* %T)
// CHECK-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[T_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** %T.P2, i8*** [[T_P2_PTR]], align 8
// CHECK-NEXT: [[Single_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Single_TYPE]], %swift.type* [[Single_TYPE]], i8** [[Single_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public func single_concrete() {
takes_p1(Single<IsP2>.self)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances15single_concreteyyF"()
// CHECK-NEXT: entry:
// CHECK-NEXT: [[Single_TYPE:%.*]] = call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMD")
// CHECK-NEXT: [[Single_P1:%.*]] = call i8** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl"()
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Single_TYPE]], %swift.type* [[Single_TYPE]], i8** [[Single_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// Lazy witness table accessor for the concrete Single<IsP2> : P1.
// CHECK-LABEL: define linkonce_odr hidden i8** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl"()
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL", align 8
// CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// macosx-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMa"(i64 255)
// macosx-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// macosx-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// ios-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMa"(i64 255)
// ios-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// ios-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// tvos-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMa"(i64 255)
// tvos-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// tvos-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// watchos-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMa"(i64 255)
// watchos-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// watchos-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// linux-gnu-NEXT: [[T0:%.*]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledNameAbstract({ i32, i32 }* @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMD")
// linux-android-NEXT: [[T0:%.*]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledNameAbstract({ i32, i32 }* @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMD")
// windows-msvc-NEXT: [[T0:%.*]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledNameAbstract({ i32, i32 }* @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMD")
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP2VAA0F0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[Single_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: store atomic i8** [[Single_P1]], i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL" release, align 8
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Single_P1]], %cacheIsNull ]
// CHECK-NEXT: ret i8** [[T0]]
// CHECK-NEXT: }
// TYPEBYNAME-LABEL: define linkonce_odr hidden i8** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl"()
// TYPEBYNAME-NEXT: entry:
// TYPEBYNAME-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// TYPEBYNAME-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL", align 8
// TYPEBYNAME-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// TYPEBYNAME-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// TYPEBYNAME: cacheIsNull:
// TYPEBYNAME-NEXT: [[T0:%.*]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledNameAbstract({ i32, i32 }* @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMD")
// TYPEBYNAME-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// TYPEBYNAME-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// TYPEBYNAME-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP2VAA0F0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8
// TYPEBYNAME-NEXT: [[Single_P1:%.*]] = call i8** @swift_getWitnessTable
// TYPEBYNAME-NEXT: store atomic i8** [[Single_P1]], i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL" release, align 8
// TYPEBYNAME-NEXT: br label %cont
// TYPEBYNAME: cont:
// TYPEBYNAME-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Single_P1]], %cacheIsNull ]
// TYPEBYNAME-NEXT: ret i8** [[T0]]
// TYPEBYNAME-NEXT: }
public struct Double<B, C> {}
extension Double: P1 where B: P2, C: P3 {
public func normal() {}
public func generic<T: P3>(_: T) {}
}
// witness method for Double.normal
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlAaEP6normalyyFTW"(%T42conditional_conformance_basic_conformances6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[B_P2_i8star:%.*]] = load i8*, i8** [[B_P2_PTR]], align 8
// CHECK-NEXT: [[B_P2:%.*]] = bitcast i8* [[B_P2_i8star]] to i8**
// CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -2
// CHECK-NEXT: [[C_P3_i8star:%.*]] = load i8*, i8** [[C_P3_PTR]], align 8
// CHECK-NEXT: [[C_P3:%.*]] = bitcast i8* [[C_P3_i8star]] to i8**
// CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type**
// CHECK-NEXT: [[B_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2
// CHECK-NEXT: [[B:%.*]] = load %swift.type*, %swift.type** [[B_PTR]], align 8
// CHECK-NEXT: [[SELF_AS_TYPE_ARRAY_2:%.*]] = bitcast %swift.type* %Self to %swift.type**
// CHECK-NEXT: [[C_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY_2]], i64 3
// CHECK-NEXT: [[C:%.*]] = load %swift.type*, %swift.type** [[C_PTR]], align 8
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVA2A2P2RzAA2P3R_rlE6normalyyF"(%swift.type* [[B]], %swift.type* [[C]], i8** [[B_P2]], i8** [[C_P3]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// witness method for Double.generic
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlAaEP7genericyyqd__AaGRd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[B_P2_i8star:%.*]] = load i8*, i8** [[B_P2_PTR]], align 8
// CHECK-NEXT: [[B_P2:%.*]] = bitcast i8* [[B_P2_i8star]] to i8**
// CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -2
// CHECK-NEXT: [[C_P3_i8star:%.*]] = load i8*, i8** [[C_P3_PTR]], align 8
// CHECK-NEXT: [[C_P3:%.*]] = bitcast i8* [[C_P3_i8star]] to i8**
// CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type**
// CHECK-NEXT: [[B_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2
// CHECK-NEXT: [[B:%.*]] = load %swift.type*, %swift.type** [[B_PTR]], align 8
// CHECK-NEXT: [[SELF_AS_TYPE_ARRAY_2:%.*]] = bitcast %swift.type* %Self to %swift.type**
// CHECK-NEXT: [[C_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY_2]], i64 3
// CHECK-NEXT: [[C:%.*]] = load %swift.type*, %swift.type** [[C_PTR]], align 8
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVA2A2P2RzAA2P3R_rlE7genericyyqd__AaERd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* [[B]], %swift.type* [[C]], %swift.type* %"\CF\84_1_0", i8** [[B_P2]], i8** [[C_P3]], i8** %"\CF\84_1_0.P3")
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public func double_generic_generic<U: P2, V: P3>(_: U.Type, _: V.Type) {
takes_p1(Double<U, V>.self)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances015double_generic_F0yyxm_q_mtAA2P2RzAA2P3R_r0_lF"(%swift.type*, %swift.type*, %swift.type* %U, %swift.type* %V, i8** %U.P2, i8** %V.P3)
// CHECK-NEXT: entry:
// CHECK: %conditional.requirement.buffer = alloca [2 x i8**], align 8
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVMa"(i64 0, %swift.type* %U, %swift.type* %V)
// CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** %U.P2, i8*** [[B_P2_PTR]], align 8
// CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1
// CHECK-NEXT: store i8** %V.P3, i8*** [[C_P3_PTR]], align 8
// CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public func double_generic_concrete<X: P2>(_: X.Type) {
takes_p1(Double<X, IsP3>.self)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances23double_generic_concreteyyxmAA2P2RzlF"(%swift.type*, %swift.type* %X, i8** %X.P2)
// CHECK-NEXT: entry:
// CHECK: %conditional.requirement.buffer = alloca [2 x i8**], align 8
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVMa"(i64 0, %swift.type* %X, %swift.type* bitcast (i64* getelementptr inbounds (<{ i8**, i64, <{ {{.*}} }>* }>, <{ {{.*}} }>* @"$s42conditional_conformance_basic_conformances4IsP3VMf", i32 0, i32 1) to %swift.type*))
// CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** %X.P2, i8*** [[B_P2_PTR]], align 8
// CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[C_P3_PTR]], align 8
// CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public func double_concrete_concrete() {
takes_p1(Double<IsP2, IsP3>.self)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances016double_concrete_F0yyF"()
// CHECK-NEXT: entry:
// CHECK-NEXT: [[Double_TYPE:%.*]] = call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMD")
// CHECK-NEXT: [[Double_P1:%.*]] = call i8** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWl"()
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// Lazy witness table accessor for the concrete Double<IsP2, IsP3> : P1.
// CHECK-LABEL: define linkonce_odr hidden i8** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWl"()
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [2 x i8**], align 8
// CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWL", align 8
// CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// macosx-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMa"(i64 255)
// macosx-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// macosx-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// ios-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMa"(i64 255)
// ios-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// ios-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// tvos-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMa"(i64 255)
// tvos-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// tvos-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// watchos-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMa"(i64 255)
// watchos-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// watchos-NEXT: extractvalue %swift.metadata_response [[T0]], 1
// linux-gnu-NEXT: [[T0:%.*]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledNameAbstract({ i32, i32 }* @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMD")
// linux-android-NEXT: [[T0:%.*]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledNameAbstract({ i32, i32 }* @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMD")
// windows-msvc-NEXT: [[T0:%.*]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledNameAbstract({ i32, i32 }* @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMD")
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP2VAA0F0AAWP", i32 0, i32 0), i8*** [[B_P2_PTR]], align 8
// CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[C_P3_PTR]], align 8
// CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: store atomic i8** [[Double_P1]], i8*** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWL" release, align 8
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Double_P1]], %cacheIsNull ]
// CHECK-NEXT: ret i8** [[T0]]
// CHECK-NEXT: }
func dynamicCastToP1(_ value: Any) -> P1? {
return value as? P1
}
protocol P4 {}
typealias P4Typealias = P4
protocol P5 {}
struct SR7101<T> {}
extension SR7101 : P5 where T == P4Typealias {}
| apache-2.0 | 374987a9b02b1ab7a1b00371a208397f | 70.97973 | 383 | 0.670703 | 3.123589 | false | false | false | false |
felix91gr/swift | test/Generics/same_type_constraints.swift | 1 | 8762 | // RUN: %target-typecheck-verify-swift -swift-version 4
protocol Fooable {
associatedtype Foo
var foo: Foo { get }
}
protocol Barrable {
associatedtype Bar: Fooable
var bar: Bar { get }
}
struct X {}
struct Y: Fooable {
typealias Foo = X
var foo: X { return X() }
}
struct Z: Barrable {
typealias Bar = Y
var bar: Y { return Y() }
}
protocol TestSameTypeRequirement {
func foo<F1: Fooable>(_ f: F1) where F1.Foo == X
}
struct SatisfySameTypeRequirement : TestSameTypeRequirement {
func foo<F2: Fooable>(_ f: F2) where F2.Foo == X {}
}
protocol TestSameTypeAssocTypeRequirement {
associatedtype Assoc
func foo<F1: Fooable>(_ f: F1) where F1.Foo == Assoc
}
struct SatisfySameTypeAssocTypeRequirement : TestSameTypeAssocTypeRequirement {
typealias Assoc = X
func foo<F2: Fooable>(_ f: F2) where F2.Foo == X {}
}
struct SatisfySameTypeAssocTypeRequirementDependent<T>
: TestSameTypeAssocTypeRequirement
{
typealias Assoc = T
func foo<F3: Fooable>(_ f: F3) where F3.Foo == T {}
}
// Pulled in from old standard library to keep the following test
// (LazySequenceOf) valid.
public struct GeneratorOf<T> : IteratorProtocol, Sequence {
/// Construct an instance whose `next()` method calls `nextElement`.
public init(_ nextElement: @escaping () -> T?) {
self._next = nextElement
}
/// Construct an instance whose `next()` method pulls its results
/// from `base`.
public init<I : IteratorProtocol>(_ base: I) where I.Element == T {
var base = base
self._next = { base.next() }
}
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> T? {
return _next()
}
/// `GeneratorOf<T>` is also a `Sequence`, so it `generate`\ s
/// a copy of itself
public func makeIterator() -> GeneratorOf {
return self
}
let _next: () -> T?
}
// rdar://problem/19009056
public struct LazySequenceOf<S : Sequence, A> : Sequence where S.Iterator.Element == A {
public func makeIterator() -> GeneratorOf<A> {
return GeneratorOf<A>({ return nil })
}
public subscript(i : A) -> A { return i }
}
public func iterate<A>(_ f : @escaping (A) -> A) -> (_ x : A) -> LazySequenceOf<Iterate<A>, A>? {
return { x in nil }
}
public final class Iterate<A> : Sequence {
typealias IteratorProtocol = IterateGenerator<A>
public func makeIterator() -> IterateGenerator<A> {
return IterateGenerator<A>()
}
}
public final class IterateGenerator<A> : IteratorProtocol {
public func next() -> A? {
return nil
}
}
// rdar://problem/18475138
public protocol Observable : class {
associatedtype Output
func addObserver(_ obj : @escaping (Output) -> Void)
}
public protocol Bindable : class {
associatedtype Input
func foo()
}
class SideEffect<In> : Bindable {
typealias Input = In
func foo() { }
}
struct Composed<Left: Bindable, Right: Observable> where Left.Input == Right.Output {}
infix operator <- : AssignmentPrecedence
func <- <
Right
>(lhs: @escaping (Right.Output) -> Void, rhs: Right) -> Composed<SideEffect<Right>, Right>?
{
return nil
}
// rdar://problem/17855378
struct Pair<T, U> {
typealias Type_ = (T, U)
}
protocol Seq {
associatedtype Element
func zip<OtherSeq: Seq, ResultSeq: Seq> (_ otherSeq: OtherSeq) -> ResultSeq
where ResultSeq.Element == Pair<Element, OtherSeq.Element>.Type_
}
// rdar://problem/18435371
extension Dictionary {
func multiSubscript<S : Sequence>(_ seq: S) -> [Value?] where S.Iterator.Element == Key {
var result = [Value?]()
for seqElt in seq {
result.append(self[seqElt])
}
return result
}
}
// rdar://problem/19245317
protocol P {
associatedtype T: P // expected-error{{type may not reference itself as a requirement}}
}
struct S<A: P> {
init<Q: P>(_ q: Q) where Q.T == A {}
}
// rdar://problem/19371678
protocol Food { }
class Grass : Food { }
protocol Animal {
associatedtype EdibleFood:Food
func eat(_ f:EdibleFood)
}
class Cow : Animal {
func eat(_ f: Grass) { }
}
struct SpecificAnimal<F:Food> : Animal {
typealias EdibleFood=F
let _eat:(_ f:F) -> ()
init<A:Animal>(_ selfie:A) where A.EdibleFood == F {
_eat = { selfie.eat($0) }
}
func eat(_ f:F) {
_eat(f)
}
}
// rdar://problem/18803556
struct Something<T> {
var items: [T] = []
}
extension Something {
init<S : Sequence>(_ s: S) where S.Iterator.Element == T {
for item in s {
items.append(item)
}
}
}
// rdar://problem/18120419
func TTGenWrap<T, I : IteratorProtocol>(_ iterator: I) where I.Element == (T,T)
{
var iterator = iterator
_ = iterator.next()
}
func IntIntGenWrap<I : IteratorProtocol>(_ iterator: I) where I.Element == (Int,Int)
{
var iterator = iterator
_ = iterator.next()
}
func GGWrap<I1 : IteratorProtocol, I2 : IteratorProtocol>(_ i1: I1, _ i2: I2) where I1.Element == I2.Element
{
var i1 = i1
var i2 = i2
_ = i1.next()
_ = i2.next()
}
func testSameTypeTuple(_ a: Array<(Int,Int)>, s: ArraySlice<(Int,Int)>) {
GGWrap(a.makeIterator(), s.makeIterator())
TTGenWrap(a.makeIterator())
IntIntGenWrap(s.makeIterator())
}
// rdar://problem/20256475
protocol FooProtocol {
associatedtype Element
func getElement() -> Element
}
protocol Bar {
associatedtype Foo : FooProtocol
func getFoo() -> Foo
mutating func extend<C : FooProtocol>(_ elements: C)
where C.Element == Foo.Element
}
// rdar://problem/21620908
protocol P1 { }
protocol P2Base { }
protocol P2 : P2Base {
associatedtype Q : P1
func getQ() -> Q
}
struct XP1<T : P2Base> : P1 {
func wibble() { }
}
func sameTypeParameterizedConcrete<C : P2>(_ c: C) where C.Q == XP1<C> {
c.getQ().wibble()
}
// rdar://problem/21621421
protocol P3 {
associatedtype AssocP3 : P1
}
protocol P4 {
associatedtype AssocP4 : P3
}
struct X1 : P1 { }
struct X3 : P3 {
typealias AssocP3 = X1
}
func foo<C : P4>(_ c: C) where C.AssocP4 == X3 {}
struct X4 : P4 {
typealias AssocP4 = X3
}
func testFoo(_ x3: X4) {
foo(x3)
}
// rdar://problem/21625478
struct X6<T> { }
protocol P6 { }
protocol P7 {
associatedtype AssocP7
}
protocol P8 {
associatedtype AssocP8 : P7
associatedtype AssocOther
}
func testP8<C : P8>(_ c: C) where C.AssocOther == X6<C.AssocP8.AssocP7> {}
// setGenericSignature() was getting called twice here
struct Ghost<T> {}
protocol Timewarp {
associatedtype Wormhole
}
struct Teleporter<A, B> where A : Timewarp, A.Wormhole == Ghost<B> {}
struct Beam {}
struct EventHorizon : Timewarp {
typealias Wormhole = Ghost<Beam>
}
func activate<T>(_ t: T) {}
activate(Teleporter<EventHorizon, Beam>())
// rdar://problem/29288428
class C {}
protocol P9 {
associatedtype A
}
struct X7<T: P9> where T.A : C { }
extension X7 where T.A == Int { } // expected-error {{'T.A' requires that 'Int' inherit from 'C'}}
struct X8<T: C> { }
extension X8 where T == Int { } // expected-error {{'T' requires that 'Int' inherit from 'C'}}
protocol P10 {
associatedtype A
associatedtype B
associatedtype C
associatedtype D
associatedtype E
}
protocol P11: P10 where A == B { }
func intracomponent<T: P11>(_: T) // expected-note{{previous same-type constraint 'T.A' == 'T.B' implied here}}
where T.A == T.B { } // expected-warning{{redundant same-type constraint 'T.A' == 'T.B'}}
func intercomponentSameComponents<T: P10>(_: T)
where T.A == T.B, // expected-warning{{redundant same-type constraint 'T.A' == 'T.B'}}
T.B == T.A { } // expected-note{{previous same-type constraint 'T.A' == 'T.B' written here}}
// FIXME: directionality of constraint above is weird
func intercomponentMoreThanSpanningTree<T: P10>(_: T)
where T.A == T.B,
T.B == T.C,
T.D == T.E, // expected-note{{previous same-type constraint 'T.D' == 'T.E' written here}}
T.D == T.B,
T.E == T.B // expected-warning{{redundant same-type constraint 'T.B' == 'T.E'}}
{ }
func trivialRedundancy<T: P10>(_: T) where T.A == T.A { } // expected-warning{{redundant same-type constraint 'T.A' == 'T.A'}}
struct X11<T: P10> where T.A == T.B { }
func intracomponentInferred<T>(_: X11<T>) // expected-note{{previous same-type constraint 'T.A' == 'T.B' inferred from type here}}
where T.A == T.B { } // expected-warning{{redundant same-type constraint 'T.A' == 'T.B'}}
// Suppress redundant same-type constraint warnings from result types.
struct StructTakingP1<T: P1> { }
func resultTypeSuppress<T: P1>() -> StructTakingP1<T> {
return StructTakingP1()
}
| apache-2.0 | e20922d7c1c35ca5b56559d6088428d6 | 22.427807 | 130 | 0.64483 | 3.292747 | false | false | false | false |
eneko/SwiftyJIRA | iOS/Pods/JSONRequest/Sources/JSONRequest.swift | 1 | 6596 | //
// JSONRequest.swift
// JSONRequest
//
// Created by Eneko Alonso on 9/12/14.
// Copyright (c) 2014 Hathway. All rights reserved.
//
import Foundation
public typealias JSONObject = Dictionary<String, AnyObject?>
public enum JSONError: ErrorType {
case InvalidURL
case PayloadSerialization
case RequestFailed
case NonHTTPResponse
case ResponseDeserialization
case UnknownError
}
public enum JSONResult {
case Success(data: AnyObject?, response: NSHTTPURLResponse)
case Failure(error: JSONError, response: NSHTTPURLResponse?, body: String?)
}
public extension JSONResult {
public var data: AnyObject? {
switch self {
case .Success(let data, _):
return data
case .Failure:
return nil
}
}
public var arrayValue: [AnyObject] {
return data as? [AnyObject] ?? []
}
public var dictionaryValue: [String: AnyObject] {
return data as? [String: AnyObject] ?? [:]
}
public var httpResponse: NSHTTPURLResponse? {
switch self {
case .Success(_, let response):
return response
case .Failure(_, let response, _):
return response
}
}
public var error: ErrorType? {
switch self {
case .Success:
return nil
case .Failure(let error, _, _):
return error
}
}
}
public class JSONRequest {
private(set) var request: NSMutableURLRequest?
public var httpRequest: NSMutableURLRequest? {
return request
}
public init() {
request = NSMutableURLRequest()
}
// MARK: Non-public business logic (testable but not public outside the module)
func submitAsyncRequest(method: JSONRequestHttpVerb, url: String,
queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil,
complete: (result: JSONResult) -> Void) {
updateRequestUrl(method, url: url, queryParams: queryParams)
updateRequestHeaders(headers)
do {
try updateRequestPayload(payload)
} catch {
complete(result: JSONResult.Failure(error: JSONError.PayloadSerialization,
response: nil, body: nil))
return
}
let task = NSURLSession.sharedSession().dataTaskWithRequest(request!) {
(data, response, error) in
if error != nil {
let body = data == nil
? nil
: String(data: data!, encoding: NSUTF8StringEncoding)
complete(result: JSONResult.Failure(error: JSONError.RequestFailed,
response: response as? NSHTTPURLResponse,
body: body))
return
}
let result = self.parseResponse(data, response: response)
complete(result: result)
}
task.resume()
}
func submitSyncRequest(method: JSONRequestHttpVerb, url: String, queryParams: JSONObject? = nil,
payload: AnyObject? = nil, headers: JSONObject? = nil) -> JSONResult {
let semaphore = dispatch_semaphore_create(0)
var requestResult: JSONResult = JSONResult.Failure(error: JSONError.RequestFailed,
response: nil, body: nil)
submitAsyncRequest(method, url: url, queryParams: queryParams, payload: payload,
headers: headers) { result in
requestResult = result
dispatch_semaphore_signal(semaphore)
}
// Wait for the request to complete
while dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW) != 0 {
let intervalDate = NSDate(timeIntervalSinceNow: 0.01) // Secs
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: intervalDate)
}
return requestResult
}
func updateRequestUrl(method: JSONRequestHttpVerb, url: String,
queryParams: JSONObject? = nil) {
request?.URL = createURL(url, queryParams: queryParams)
request?.HTTPMethod = method.rawValue
}
func updateRequestHeaders(headers: JSONObject?) {
request?.setValue("application/json", forHTTPHeaderField: "Content-Type")
request?.setValue("application/json", forHTTPHeaderField: "Accept")
if headers != nil {
for (headerName, headerValue) in headers! {
request?.setValue(String(headerValue), forHTTPHeaderField: headerName)
}
}
}
func updateRequestPayload(payload: AnyObject?) throws {
if payload != nil {
request?.HTTPBody = try NSJSONSerialization.dataWithJSONObject(payload!, options: [])
}
}
func createURL(urlString: String, queryParams: JSONObject?) -> NSURL? {
let components = NSURLComponents(string: urlString)
if queryParams != nil {
if components?.queryItems == nil {
components?.queryItems = []
}
for (key, value) in queryParams! {
if let unwrapped = value {
let encoded = String(unwrapped)
.stringByAddingPercentEncodingWithAllowedCharacters(
.URLHostAllowedCharacterSet())
let item = NSURLQueryItem(name: key, value: encoded)
components?.queryItems?.append(item)
} else {
let item = NSURLQueryItem(name: key, value: nil)
components?.queryItems?.append(item)
}
}
}
return components?.URL
}
func parseResponse(data: NSData?, response: NSURLResponse?) -> JSONResult {
guard let httpResponse = response as? NSHTTPURLResponse else {
return JSONResult.Failure(error: JSONError.NonHTTPResponse, response: nil, body: nil)
}
guard data != nil && data!.length > 0 else {
return JSONResult.Success(data: nil, response: httpResponse)
}
guard let json = try? NSJSONSerialization.JSONObjectWithData(data!,
options: [.AllowFragments]) else {
return JSONResult.Failure(error: JSONError.ResponseDeserialization,
response: httpResponse,
body: String(data: data!, encoding: NSUTF8StringEncoding))
}
return JSONResult.Success(data: json, response: httpResponse)
}
}
| mit | dffdf11caedffc3c43a81e7e3b8eafda | 33.715789 | 100 | 0.586264 | 5.315068 | false | false | false | false |
vgatto/protobuf-swift | src/ProtocolBuffers/ProtocolBuffersTests/CodedInputStreamTests.swift | 2 | 11872 | //
// CodedInputStreamTests.swift
// ProtocolBuffers
//
// Created by Alexey Khokhlov on 03.08.14.
// Copyright (c) 2014 Alexey Khokhlov. All rights reserved.
//
import Foundation
import XCTest
import ProtocolBuffers
class CodedInputStreamTests: XCTestCase
{
func bytes(from:UInt8...) -> NSData
{
var returnData:NSMutableData = NSMutableData()
var bytesArray = [UInt8](count:Int(from.count), repeatedValue: 0)
var i:Int = 0
for index:UInt8 in from
{
bytesArray[i] = index
i++
}
returnData.appendBytes(&bytesArray, length: bytesArray.count)
return returnData
}
func bytesArray(var from:[UInt8]) -> NSData
{
var returnData:NSMutableData = NSMutableData()
returnData.appendBytes(&from, length: from.count)
return returnData
}
func testDecodeZigZag()
{
XCTAssertEqual(Int32(0), WireFormat.decodeZigZag32(0))
XCTAssertEqual(Int32(-1), WireFormat.decodeZigZag32(1))
XCTAssertEqual(Int32(1), WireFormat.decodeZigZag32(2))
XCTAssertEqual(Int32(-2), WireFormat.decodeZigZag32(3))
XCTAssertTrue(0x3FFFFFFF == WireFormat.decodeZigZag32(0x7FFFFFFE))
XCTAssertEqual(Int64(0), WireFormat.decodeZigZag64(0))
XCTAssertEqual(Int64(-1), WireFormat.decodeZigZag64(1))
XCTAssertEqual(Int64(1), WireFormat.decodeZigZag64(2))
XCTAssertEqual(Int64(-2), WireFormat.decodeZigZag64(3))
XCTAssertEqual(Int64(0x000000003FFFFFFF), WireFormat.decodeZigZag64(0x000000007FFFFFFE))
XCTAssertEqual(Int64(0x000000007FFFFFFF), WireFormat.decodeZigZag64(0x00000000FFFFFFFE))
}
func assertReadVarint(data:NSData, value:Int64)
{
var shift = WireFormat.logicalRightShift64(value:value, spaces: 31)
if (shift == 0)
{
var input1:CodedInputStream = CodedInputStream(data:data)
var result = input1.readRawVarint32()
XCTAssertTrue(Int32(value) == result, "")
}
var input2:CodedInputStream = CodedInputStream(data:data)
XCTAssertTrue(value == input2.readRawVarint64(), "")
if (shift == 0)
{
var input3:CodedInputStream = CodedInputStream(inputStream:NSInputStream(data:data))
XCTAssertTrue(Int32(value) == input3.readRawVarint32(), "")
}
var input4:CodedInputStream = CodedInputStream(inputStream:NSInputStream(data:data))
var result4 = input4.readRawVarint64()
XCTAssertTrue(value == result4, "")
// Try different block sizes.
for (var blockSize:Int32 = 1; blockSize <= 16; blockSize *= 2)
{
if (shift == 0)
{
var smallblock:SmallBlockInputStream = SmallBlockInputStream()
smallblock.setup(data: data, blocksSize: blockSize)
var inputs:CodedInputStream = CodedInputStream(inputStream:smallblock)
var result2 = inputs.readRawVarint32()
XCTAssertTrue(Int32(value) == result2, "")
}
var smallblock2:SmallBlockInputStream = SmallBlockInputStream()
smallblock2.setup(data: data, blocksSize: blockSize)
var inputs2:CodedInputStream = CodedInputStream(inputStream:smallblock2)
XCTAssertTrue(value == inputs2.readRawVarint64(), "")
}
}
func assertReadLittleEndian32(data:NSData, value:Int32)
{
var dataByte:[UInt8] = [UInt8](count: data.length/sizeof(UInt8), repeatedValue: 0)
data.getBytes(&dataByte, length: data.length)
var input:CodedInputStream = CodedInputStream(data:data)
var readRes = input.readRawLittleEndian32()
XCTAssertTrue(value == readRes, "")
for (var blockSize:Int32 = 1; blockSize <= 16; blockSize *= 2)
{
var smallblock:SmallBlockInputStream = SmallBlockInputStream()
smallblock.setup(data: data, blocksSize: blockSize)
var input2:CodedInputStream = CodedInputStream(inputStream:smallblock)
var readRes2 = input2.readRawLittleEndian32()
XCTAssertTrue(value == readRes2, "")
}
}
func assertReadLittleEndian64(data:NSData, value:Int64)
{
var dataByte:[UInt8] = [UInt8](count: data.length/sizeof(UInt8), repeatedValue: 0)
data.getBytes(&dataByte, length: data.length)
var input:CodedInputStream = CodedInputStream(data:data)
XCTAssertTrue(value == input.readRawLittleEndian64(), "")
for (var blockSize:Int32 = 1; blockSize <= 16; blockSize *= 2)
{
var smallblock:SmallBlockInputStream = SmallBlockInputStream()
smallblock.setup(data: data, blocksSize: blockSize)
var input2:CodedInputStream = CodedInputStream(inputStream:smallblock)
XCTAssertTrue(value == input2.readRawLittleEndian64(), "")
}
}
func assertReadVarintFailure(data:NSData)
{
var dataByte:[UInt8] = [UInt8](count: data.length, repeatedValue: 0)
data.getBytes(&dataByte, length:data.length)
var input:CodedInputStream = CodedInputStream(data:data)
input.readRawVarint32()
var input2:CodedInputStream = CodedInputStream(data:data)
input2.readRawVarint64()
}
func atestReadLittleEndian()
{
assertReadLittleEndian32(bytes(0x78, 0x56, 0x34, 0x12), value:Int32(0x12345678))
assertReadLittleEndian32(bytes(0xa1, 0xde, 0xbc, 0x11), value:0x11bcdea1)
assertReadLittleEndian64(bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12), value:0x123456789abcdef0)
assertReadLittleEndian64(bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x11), value:0x11bcdef012345678)
}
func testReadVarint()
{
assertReadVarint(bytes(UInt8(0x00)), value:0)
assertReadVarint(bytes(UInt8(0x01)), value:1)
assertReadVarint(bytes(UInt8(0x7f)), value:127)
var rvalue14882:Int64 = (0x22 << 0)
rvalue14882 |= (0x74 << 7)
assertReadVarint(bytes(0xa2, 0x74), value:rvalue14882)
// 2961488830
var rvalue2961488830:Int64 = (0x3e << 0)
rvalue2961488830 |= (0x77 << 7)
rvalue2961488830 |= (0x12 << 14)
rvalue2961488830 |= (0x04 << 21)
rvalue2961488830 |= (0x0b << 28)
assertReadVarint(bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b), value:rvalue2961488830)
// 64-bit
// 7256456126
var rvalue:Int64 = (0x3e << 0)
rvalue |= (0x77 << 7)
rvalue |= (0x12 << 14)
rvalue |= (0x04 << 21)
rvalue |= (0x1b << 28)
assertReadVarint(bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b), value:rvalue)
//
var rvalue41256202580718336:Int64 = (0x00 << 0)
rvalue41256202580718336 |= (0x66 << 7)
rvalue41256202580718336 |= (0x6b << 14)
rvalue41256202580718336 |= (0x1c << 21)
rvalue41256202580718336 |= (0x43 << 28)
rvalue41256202580718336 |= (0x49 << 35)
rvalue41256202580718336 |= (0x24 << 42)
rvalue41256202580718336 |= (0x49 << 49)
assertReadVarint(bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49), value:rvalue41256202580718336)
// 11964378330978735131
var rvalue11964378330978735131:Int64 = (0x1b << 0)
rvalue11964378330978735131 |= (0x28 << 7)
rvalue11964378330978735131 |= (0x79 << 14)
rvalue11964378330978735131 |= (0x42 << 21)
rvalue11964378330978735131 |= (0x3b << 28)
rvalue11964378330978735131 |= (0x56 << 35)
rvalue11964378330978735131 |= (0x00 << 42)
rvalue11964378330978735131 |= (0x05 << 49)
rvalue11964378330978735131 |= (0x26 << 56)
rvalue11964378330978735131 |= (0x01 << 63)
assertReadVarint(bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01), value:rvalue11964378330978735131)
// Failures
// assertReadVarintFailure(bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00))
// assertReadVarintFailure(bytes(0x80))
}
func testReadMaliciouslyLargeBlob()
{
var rawOutput:NSOutputStream = NSOutputStream.outputStreamToMemory()
rawOutput.open()
var output:CodedOutputStream = CodedOutputStream(output: rawOutput)
var tag:Int32 = WireFormat.WireFormatLengthDelimited.wireFormatMakeTag(1)
output.writeRawVarint32(tag)
output.writeRawVarint32(0x7FFFFFFF)
var bytes:[UInt8] = [UInt8](count: 32, repeatedValue: 0)
var datas = NSData(bytes: bytes, length: 32)
output.writeRawData(datas)
output.flush()
var data:NSData = rawOutput.propertyForKey(NSStreamDataWrittenToMemoryStreamKey) as! NSData
var input:CodedInputStream = CodedInputStream(data: data)
XCTAssertTrue(tag == input.readTag(), "")
}
func testReadWholeMessage()
{
var message = TestUtilities.allSet()
var rawBytes = message.data()
let lengthRaw = Int32(rawBytes.length)
let lengthSize = message.serializedSize()
XCTAssertTrue(lengthRaw == lengthSize, "")
var message2 = ProtobufUnittest.TestAllTypes.parseFromData(rawBytes)
TestUtilities.assertAllFieldsSet(message2)
var stream:NSInputStream = NSInputStream(data: rawBytes)
var codedStream = CodedInputStream(inputStream:stream)
var message3 = ProtobufUnittest.TestAllTypes.parseFromCodedInputStream(codedStream)
TestUtilities.assertAllFieldsSet(message3)
XCTAssertTrue(message3 == message2, "")
for (var blockSize:Int32 = 1; blockSize < 256; blockSize *= 2) {
var smallblock:SmallBlockInputStream = SmallBlockInputStream()
smallblock.setup(data: rawBytes, blocksSize: blockSize)
message2 = ProtobufUnittest.TestAllTypes.parseFromInputStream(smallblock)
TestUtilities.assertAllFieldsSet(message2)
}
}
func testSkipWholeMessage()
{
var message = TestUtilities.allSet()
var rawBytes = message.data()
var input1 = CodedInputStream(data:rawBytes)
var input2 = CodedInputStream(data:rawBytes)
var unknownFields = UnknownFieldSet.Builder()
while (true) {
var tag = input1.readTag()
var tag2 = input2.readTag()
XCTAssertTrue(tag == tag2, "")
if (tag2 == 0) {
break
}
unknownFields.mergeFieldFrom(tag, input:input1)
input2.skipField(tag2)
}
}
func testReadHugeBlob()
{
// Allocate and initialize a 1MB blob.
var blob = NSMutableData(length:1 << 20)!
for (var i:Int = 0; i < blob.length; i++) {
var pointer = UnsafeMutablePointer<UInt8>(blob.mutableBytes)
var bpointer = UnsafeMutableBufferPointer(start: pointer, count: blob.length)
bpointer[i] = UInt8(1)
}
var builder = ProtobufUnittest.TestAllTypes.Builder()
TestUtilities.setAllFields(builder)
builder.optionalBytes = blob
var message = builder.build()
var data = message.data()
var message2 = ProtobufUnittest.TestAllTypes.parseFromInputStream(NSInputStream(data:data))
XCTAssertTrue(message.optionalBytes == message2.optionalBytes, "")
var builder3 = ProtobufUnittest.TestAllTypes.builderWithPrototype(message2)
builder3.optionalBytes = TestUtilities.allSet().optionalBytes
var message3 = builder3.build()
TestUtilities.assertAllFieldsSet(message3)
}
} | apache-2.0 | e6661d400c7f739887b14bb5da07b35f | 37.548701 | 125 | 0.63157 | 4.012166 | false | true | false | false |
benlangmuir/swift | test/attr/attr_availability.swift | 2 | 81138 | // RUN: %target-typecheck-verify-swift
@available(*, unavailable)
func unavailable_func() {}
@available(*, unavailable, message: "message")
func unavailable_func_with_message() {}
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(iOS, unavailable)
@available(OSX, unavailable)
func unavailable_multiple_platforms() {}
@available // expected-error {{expected '(' in 'available' attribute}}
func noArgs() {}
@available(*) // expected-error {{expected ',' in 'available' attribute}}
func noKind() {}
@available(badPlatform, unavailable) // expected-warning {{unknown platform 'badPlatform' for attribute 'available'}}
func unavailable_bad_platform() {}
// Handle unknown platform.
@available(HAL9000, unavailable) // expected-warning {{unknown platform 'HAL9000'}}
func availabilityUnknownPlatform() {}
// <rdar://problem/17669805> Availability can't appear on a typealias
@available(*, unavailable, message: "oh no you don't")
typealias int = Int // expected-note {{'int' has been explicitly marked unavailable here}}
@available(*, unavailable, renamed: "Float")
typealias float = Float // expected-note {{'float' has been explicitly marked unavailable here}}
protocol MyNewerProtocol {}
@available(*, unavailable, renamed: "MyNewerProtocol")
protocol MyOlderProtocol {} // expected-note {{'MyOlderProtocol' has been explicitly marked unavailable here}}
extension Int: MyOlderProtocol {} // expected-error {{'MyOlderProtocol' has been renamed to 'MyNewerProtocol'}}
struct MyCollection<Element> {
@available(*, unavailable, renamed: "Element")
typealias T = Element // expected-note 2{{'T' has been explicitly marked unavailable here}}
func foo(x: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{15-16=Element}}
}
extension MyCollection {
func append(element: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{24-25=Element}}
}
@available(*, unavailable, renamed: "MyCollection")
typealias YourCollection<Element> = MyCollection<Element> // expected-note {{'YourCollection' has been explicitly marked unavailable here}}
var x : YourCollection<Int> // expected-error {{'YourCollection' has been renamed to 'MyCollection'}}{{9-23=MyCollection}}
var y : int // expected-error {{'int' is unavailable: oh no you don't}}
var z : float // expected-error {{'float' has been renamed to 'Float'}}{{9-14=Float}}
// Encoded message
@available(*, unavailable, message: "This message has a double quote \"")
func unavailableWithDoubleQuoteInMessage() {} // expected-note {{'unavailableWithDoubleQuoteInMessage()' has been explicitly marked unavailable here}}
func useWithEscapedMessage() {
unavailableWithDoubleQuoteInMessage() // expected-error {{'unavailableWithDoubleQuoteInMessage()' is unavailable: This message has a double quote \"}}
}
// More complicated parsing.
@available(OSX, message: "x", unavailable)
let _: Int
@available(OSX, introduced: 1, deprecated: 2.0, obsoleted: 3.0.0)
let _: Int
@available(OSX, introduced: 1.0.0, deprecated: 2.0, obsoleted: 3, unavailable, renamed: "x")
let _: Int
// Meaningless but accepted.
@available(OSX, message: "x")
let _: Int
// Parse errors.
@available() // expected-error{{expected platform name or '*' for 'available' attribute}}
let _: Int
@available(OSX,) // expected-error{{expected 'available' option such as 'unavailable', 'introduced', 'deprecated', 'obsoleted', 'message', or 'renamed'}}
let _: Int
@available(OSX, message) // expected-error{{expected ':' after 'message' in 'available' attribute}}
let _: Int
@available(OSX, message: ) // expected-error{{expected string literal in 'available' attribute}}
let _: Int
@available(OSX, message: x) // expected-error{{expected string literal in 'available' attribute}}
let _: Int
@available(OSX, unavailable:) // expected-error{{expected ')' in 'available' attribute}} expected-error{{expected declaration}}
let _: Int
@available(OSX, introduced) // expected-error{{expected ':' after 'introduced' in 'available' attribute}}
let _: Int
@available(OSX, introduced: ) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: x) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 1.x) // expected-error{{expected ')' in 'available' attribute}} expected-error {{expected declaration}}
let _: Int
@available(OSX, introduced: 1.0.x) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 0x1) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 1.0e4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: -1) // expected-error{{expected version number in 'available' attribute}} expected-error{{expected declaration}}
let _: Int
@available(OSX, introduced: 1.0.1e4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 1.0.0x4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(*, renamed: "bad name") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "_") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a+b") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a(") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a(:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a(:b:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, deprecated, unavailable, message: "message") // expected-error{{'available' attribute cannot be both 'unavailable' and 'deprecated'}}
struct BadUnconditionalAvailability { };
@available(*, unavailable, message="oh no you don't") // expected-error {{'=' has been replaced with ':' in attribute arguments}} {{35-36=: }}
typealias EqualFixIt1 = Int
@available(*, unavailable, message = "oh no you don't") // expected-error {{'=' has been replaced with ':' in attribute arguments}} {{36-37=:}}
typealias EqualFixIt2 = Int
// Encoding in messages
@available(*, deprecated, message: "Say \"Hi\"")
func deprecated_func_with_message() {}
// 'PANDA FACE' (U+1F43C)
@available(*, deprecated, message: "Pandas \u{1F43C} are cute")
struct DeprecatedTypeWithMessage { }
func use_deprecated_with_message() {
deprecated_func_with_message() // expected-warning{{'deprecated_func_with_message()' is deprecated: Say \"Hi\"}}
var _: DeprecatedTypeWithMessage // expected-warning{{'DeprecatedTypeWithMessage' is deprecated: Pandas \u{1F43C} are cute}}
}
@available(*, deprecated, message: "message")
func use_deprecated_func_with_message2() {
deprecated_func_with_message() // no diagnostic
}
@available(*, deprecated, renamed: "blarg")
func deprecated_func_with_renamed() {}
@available(*, deprecated, message: "blarg is your friend", renamed: "blarg")
func deprecated_func_with_message_renamed() {}
@available(*, deprecated, renamed: "wobble")
struct DeprecatedTypeWithRename { }
func use_deprecated_with_renamed() {
deprecated_func_with_renamed() // expected-warning{{'deprecated_func_with_renamed()' is deprecated: renamed to 'blarg'}}
// expected-note@-1{{use 'blarg'}}{{3-31=blarg}}
deprecated_func_with_message_renamed() //expected-warning{{'deprecated_func_with_message_renamed()' is deprecated: blarg is your friend}}
// expected-note@-1{{use 'blarg'}}{{3-39=blarg}}
var _: DeprecatedTypeWithRename // expected-warning{{'DeprecatedTypeWithRename' is deprecated: renamed to 'wobble'}}
// expected-note@-1{{use 'wobble'}}{{10-34=wobble}}
}
// Short form of @available()
@available(iOS 8.0, *)
func functionWithShortFormIOSAvailable() {}
@available(iOS 8, *)
func functionWithShortFormIOSVersionNoPointAvailable() {}
@available(iOS 8.0, OSX 10.10.3, *)
func functionWithShortFormIOSOSXAvailable() {}
@available(iOS 8.0 // expected-error {{must handle potential future platforms with '*'}} {{19-19=, *}}
func shortFormMissingParen() { // expected-error {{expected ')' in 'available' attribute}}
}
@available(iOS 8.0, // expected-error {{expected platform name}}
func shortFormMissingPlatform() {
}
@available(iOS 8.0, iDishwasherOS 22.0, *) // expected-warning {{unrecognized platform name 'iDishwasherOS'}}
func shortFormWithUnrecognizedPlatform() {
}
@available(iOS 8.0, iDishwasherOS 22.0, iRefrigeratorOS 18.0, *)
// expected-warning@-1 {{unrecognized platform name 'iDishwasherOS'}}
// expected-warning@-2 {{unrecognized platform name 'iRefrigeratorOS'}}
func shortFormWithTwoUnrecognizedPlatforms() {
}
// Make sure that even after the parser hits an unrecognized
// platform it validates the availability.
@available(iOS 8.0, iDishwasherOS 22.0, iOS 9.0, *)
// expected-warning@-1 {{unrecognized platform name 'iDishwasherOS'}}
// expected-error@-2 {{version for 'iOS' already specified}}
func shortFormWithUnrecognizedPlatformContinueValidating() {
}
@available(iOS 8.0, *
func shortFormMissingParenAfterWildcard() { // expected-error {{expected ')' in 'available' attribute}}
}
@available(*) // expected-error {{expected ',' in 'available' attribute}}
func onlyWildcardInAvailable() {}
@available(iOS 8.0, *, OSX 10.10.3)
func shortFormWithWildcardInMiddle() {}
@available(iOS 8.0, OSX 10.10.3) // expected-error {{must handle potential future platforms with '*'}} {{32-32=, *}}
func shortFormMissingWildcard() {}
@availability(OSX, introduced: 10.10) // expected-error {{'@availability' has been renamed to '@available'}} {{2-14=available}}
func someFuncUsingOldAttribute() { }
// <rdar://problem/23853709> Compiler crash on call to unavailable "print"
@available(*, unavailable, message: "Please use the 'to' label for the target stream: 'print((...), to: &...)'")
func print<T>(_: T, _: inout TextOutputStream) {} // expected-note {{}}
func TextOutputStreamTest(message: String, to: inout TextOutputStream) {
print(message, &to) // expected-error {{'print' is unavailable: Please use the 'to' label for the target stream: 'print((...), to: &...)'}}
}
struct DummyType {}
@available(*, unavailable, renamed: "&+")
func +(x: DummyType, y: DummyType) {} // expected-note {{here}}
@available(*, deprecated, renamed: "&-")
func -(x: DummyType, y: DummyType) {}
func testOperators(x: DummyType, y: DummyType) {
x + y // expected-error {{'+' has been renamed to '&+'}} {{5-6=&+}}
x - y // expected-warning {{'-' is deprecated: renamed to '&-'}} expected-note {{use '&-' instead}} {{5-6=&-}}
}
@available(*, unavailable, renamed: "DummyType.foo")
func unavailableMember() {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.bar")
func deprecatedMember() {}
@available(*, unavailable, renamed: "DummyType.Inner.foo")
func unavailableNestedMember() {} // expected-note {{here}}
@available(*, unavailable, renamed: "DummyType.Foo")
struct UnavailableType {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.Bar")
typealias DeprecatedType = Int
func testGlobalToMembers() {
unavailableMember() // expected-error {{'unavailableMember()' has been renamed to 'DummyType.foo'}} {{3-20=DummyType.foo}}
deprecatedMember() // expected-warning {{'deprecatedMember()' is deprecated: renamed to 'DummyType.bar'}} expected-note {{use 'DummyType.bar' instead}} {{3-19=DummyType.bar}}
unavailableNestedMember() // expected-error {{'unavailableNestedMember()' has been renamed to 'DummyType.Inner.foo'}} {{3-26=DummyType.Inner.foo}}
let x: UnavailableType? = nil // expected-error {{'UnavailableType' has been renamed to 'DummyType.Foo'}} {{10-25=DummyType.Foo}}
_ = x
let y: DeprecatedType? = nil // expected-warning {{'DeprecatedType' is deprecated: renamed to 'DummyType.Bar'}} expected-note {{use 'DummyType.Bar' instead}} {{10-24=DummyType.Bar}}
_ = y
}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgNames(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "moreShinyLabeledArguments(example:)")
func deprecatedArgNames(b: Int) {}
@available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)")
func unavailableMemberArgNames(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)")
func deprecatedMemberArgNames(b: Int) {}
@available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)", message: "ha")
func unavailableMemberArgNamesMsg(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)", message: "ha")
func deprecatedMemberArgNamesMsg(b: Int) {}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableNoArgs() {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableSame(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)")
func unavailableVeryLongArgNames(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)")
func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.init(other:)")
func unavailableInit(a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "Foo.Bar.init(other:)")
func unavailableNestedInit(a: Int) {} // expected-note 2 {{here}}
func testArgNames() {
unavailableArgNames(a: 0) // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-22=shinyLabeledArguments}} {{23-24=example}}
deprecatedArgNames(b: 1) // expected-warning {{'deprecatedArgNames(b:)' is deprecated: renamed to 'moreShinyLabeledArguments(example:)'}} expected-note {{use 'moreShinyLabeledArguments(example:)' instead}} {{3-21=moreShinyLabeledArguments}} {{22-23=example}}
unavailableMemberArgNames(a: 0) // expected-error {{'unavailableMemberArgNames(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)'}} {{3-28=DummyType.shinyLabeledArguments}} {{29-30=example}}
deprecatedMemberArgNames(b: 1) // expected-warning {{'deprecatedMemberArgNames(b:)' is deprecated: replaced by 'DummyType.moreShinyLabeledArguments(example:)'}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-27=DummyType.moreShinyLabeledArguments}} {{28-29=example}}
unavailableMemberArgNamesMsg(a: 0) // expected-error {{'unavailableMemberArgNamesMsg(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)': ha}} {{3-31=DummyType.shinyLabeledArguments}} {{32-33=example}}
deprecatedMemberArgNamesMsg(b: 1) // expected-warning {{'deprecatedMemberArgNamesMsg(b:)' is deprecated: ha}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-30=DummyType.moreShinyLabeledArguments}} {{31-32=example}}
unavailableNoArgs() // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}}
unavailableSame(a: 0) // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-18=shinyLabeledArguments}}
unavailableUnnamed(0) // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-21=shinyLabeledArguments}} {{22-22=example: }}
unavailableUnnamedSame(0) // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-25=shinyLabeledArguments}}
unavailableNewlyUnnamed(a: 0) // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-26=shinyLabeledArguments}} {{27-30=}}
unavailableVeryLongArgNames(a: 0) // expected-error {{'unavailableVeryLongArgNames(a:)' has been renamed to 'shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)'}} {{3-30=shinyLabeledArguments}} {{31-32=veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ}}
unavailableMultiSame(a: 0, b: 1) // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-23=shinyLabeledArguments}}
unavailableMultiUnnamed(0, 1) // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{3-26=shinyLabeledArguments}} {{27-27=example: }} {{30-30=another: }}
unavailableMultiUnnamedSame(0, 1) // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-30=shinyLabeledArguments}}
unavailableMultiNewlyUnnamed(a: 0, b: 1) // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-31=shinyLabeledArguments}} {{32-35=}} {{38-41=}}
unavailableInit(a: 0) // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{3-18=Int}} {{19-20=other}}
let fn = unavailableInit // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{12-27=Int.init}}
fn(1)
unavailableNestedInit(a: 0) // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{3-24=Foo.Bar}} {{25-26=other}}
let fn2 = unavailableNestedInit // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{13-34=Foo.Bar.init}}
fn2(1)
}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableTooFew(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableTooFewUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableTooMany(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableTooManyUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableNoArgsTooMany() {} // expected-note {{here}}
func testRenameArgMismatch() {
unavailableTooFew(a: 0) // expected-error{{'unavailableTooFew(a:)' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}}
unavailableTooFewUnnamed(0) // expected-error{{'unavailableTooFewUnnamed' has been renamed to 'shinyLabeledArguments()'}} {{3-27=shinyLabeledArguments}}
unavailableTooMany(a: 0) // expected-error{{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-21=shinyLabeledArguments}}
unavailableTooManyUnnamed(0) // expected-error{{'unavailableTooManyUnnamed' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-28=shinyLabeledArguments}}
unavailableNoArgsTooMany() // expected-error{{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-27=shinyLabeledArguments}}
}
@available(*, unavailable, renamed: "Int.foo(self:)")
func unavailableInstance(a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)")
func unavailableInstanceUnlabeled(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:other:)")
func unavailableInstanceFirst(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(other:self:)")
func unavailableInstanceSecond(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(_:self:c:)")
func unavailableInstanceSecondOfThree(a: Int, b: Int, c: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)", message: "blah")
func unavailableInstanceMessage(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "Int.foo(self:)")
func deprecatedInstance(a: Int) {}
@available(*, deprecated, renamed: "Int.foo(self:)", message: "blah")
func deprecatedInstanceMessage(a: Int) {}
@available(*, unavailable, renamed: "Foo.Bar.foo(self:)")
func unavailableNestedInstance(a: Int) {} // expected-note {{here}}
func testRenameInstance() {
unavailableInstance(a: 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=0.foo}} {{23-27=}}
unavailableInstanceUnlabeled(0) // expected-error{{'unavailableInstanceUnlabeled' has been replaced by instance method 'Int.foo()'}} {{3-31=0.foo}} {{32-33=}}
unavailableInstanceFirst(a: 0, b: 1) // expected-error{{'unavailableInstanceFirst(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-27=0.foo}} {{28-34=}} {{34-35=other}}
unavailableInstanceSecond(a: 0, b: 1) // expected-error{{'unavailableInstanceSecond(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-28=1.foo}} {{29-30=other}} {{33-39=}}
unavailableInstanceSecondOfThree(a: 0, b: 1, c: 2) // expected-error{{'unavailableInstanceSecondOfThree(a:b:c:)' has been replaced by instance method 'Int.foo(_:c:)'}} {{3-35=1.foo}} {{36-39=}} {{42-48=}}
unavailableInstance(a: 0 + 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=(0 + 0).foo}} {{23-31=}}
unavailableInstanceMessage(a: 0) // expected-error{{'unavailableInstanceMessage(a:)' has been replaced by instance method 'Int.foo()': blah}} {{3-29=0.foo}} {{30-34=}}
deprecatedInstance(a: 0) // expected-warning{{'deprecatedInstance(a:)' is deprecated: replaced by instance method 'Int.foo()'}} expected-note{{use 'Int.foo()' instead}} {{3-21=0.foo}} {{22-26=}}
deprecatedInstanceMessage(a: 0) // expected-warning{{'deprecatedInstanceMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.foo()' instead}} {{3-28=0.foo}} {{29-33=}}
unavailableNestedInstance(a: 0) // expected-error{{'unavailableNestedInstance(a:)' has been replaced by instance method 'Foo.Bar.foo()'}} {{3-28=0.foo}} {{29-33=}}
}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)")
func unavailableInstanceTooFew(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)")
func unavailableInstanceTooFewUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)")
func unavailableInstanceTooMany(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)")
func unavailableInstanceTooManyUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)")
func unavailableInstanceNoArgsTooMany() {} // expected-note {{here}}
func testRenameInstanceArgMismatch() {
unavailableInstanceTooFew(a: 0, b: 1) // expected-error{{'unavailableInstanceTooFew(a:b:)' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}}
unavailableInstanceTooFewUnnamed(0, 1) // expected-error{{'unavailableInstanceTooFewUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}}
unavailableInstanceTooMany(a: 0) // expected-error{{'unavailableInstanceTooMany(a:)' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}}
unavailableInstanceTooManyUnnamed(0) // expected-error{{'unavailableInstanceTooManyUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}}
unavailableInstanceNoArgsTooMany() // expected-error{{'unavailableInstanceNoArgsTooMany()' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}}
}
@available(*, unavailable, renamed: "getter:Int.prop(self:)")
func unavailableInstanceProperty(a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "getter:Int.prop(self:)")
func unavailableInstancePropertyUnlabeled(_ a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "getter:Int.prop()")
func unavailableClassProperty() {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:global()")
func unavailableGlobalProperty() {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:Int.prop(self:)", message: "blah")
func unavailableInstancePropertyMessage(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:Int.prop()", message: "blah")
func unavailableClassPropertyMessage() {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:global()", message: "blah")
func unavailableGlobalPropertyMessage() {} // expected-note {{here}}
@available(*, deprecated, renamed: "getter:Int.prop(self:)")
func deprecatedInstanceProperty(a: Int) {}
@available(*, deprecated, renamed: "getter:Int.prop()")
func deprecatedClassProperty() {}
@available(*, deprecated, renamed: "getter:global()")
func deprecatedGlobalProperty() {}
@available(*, deprecated, renamed: "getter:Int.prop(self:)", message: "blah")
func deprecatedInstancePropertyMessage(a: Int) {}
@available(*, deprecated, renamed: "getter:Int.prop()", message: "blah")
func deprecatedClassPropertyMessage() {}
@available(*, deprecated, renamed: "getter:global()", message: "blah")
func deprecatedGlobalPropertyMessage() {}
func testRenameGetters() {
unavailableInstanceProperty(a: 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=1.prop}} {{30-36=}}
unavailableInstancePropertyUnlabeled(1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=1.prop}} {{39-42=}}
unavailableInstanceProperty(a: 1 + 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=(1 + 1).prop}} {{30-40=}}
unavailableInstancePropertyUnlabeled(1 + 1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=(1 + 1).prop}} {{39-46=}}
unavailableClassProperty() // expected-error{{'unavailableClassProperty()' has been replaced by property 'Int.prop'}} {{3-27=Int.prop}} {{27-29=}}
unavailableGlobalProperty() // expected-error{{'unavailableGlobalProperty()' has been replaced by 'global'}} {{3-28=global}} {{28-30=}}
unavailableInstancePropertyMessage(a: 1) // expected-error{{'unavailableInstancePropertyMessage(a:)' has been replaced by property 'Int.prop': blah}} {{3-37=1.prop}} {{37-43=}}
unavailableClassPropertyMessage() // expected-error{{'unavailableClassPropertyMessage()' has been replaced by property 'Int.prop': blah}} {{3-34=Int.prop}} {{34-36=}}
unavailableGlobalPropertyMessage() // expected-error{{'unavailableGlobalPropertyMessage()' has been replaced by 'global': blah}} {{3-35=global}} {{35-37=}}
deprecatedInstanceProperty(a: 1) // expected-warning {{'deprecatedInstanceProperty(a:)' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-29=1.prop}} {{29-35=}}
deprecatedClassProperty() // expected-warning {{'deprecatedClassProperty()' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-26=Int.prop}} {{26-28=}}
deprecatedGlobalProperty() // expected-warning {{'deprecatedGlobalProperty()' is deprecated: replaced by 'global'}} expected-note{{use 'global' instead}} {{3-27=global}} {{27-29=}}
deprecatedInstancePropertyMessage(a: 1) // expected-warning {{'deprecatedInstancePropertyMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-36=1.prop}} {{36-42=}}
deprecatedClassPropertyMessage() // expected-warning {{'deprecatedClassPropertyMessage()' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-33=Int.prop}} {{33-35=}}
deprecatedGlobalPropertyMessage() // expected-warning {{'deprecatedGlobalPropertyMessage()' is deprecated: blah}} expected-note{{use 'global' instead}} {{3-34=global}} {{34-36=}}
}
@available(*, unavailable, renamed: "setter:Int.prop(self:_:)")
func unavailableSetInstanceProperty(a: Int, b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(_:self:)")
func unavailableSetInstancePropertyReverse(a: Int, b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(self:newValue:)")
func unavailableSetInstancePropertyUnlabeled(_ a: Int, _ b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(newValue:self:)")
func unavailableSetInstancePropertyUnlabeledReverse(_ a: Int, _ b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(x:)")
func unavailableSetClassProperty(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "setter:global(_:)")
func unavailableSetGlobalProperty(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(self:_:)")
func unavailableSetInstancePropertyInout(a: inout Int, b: Int) {} // expected-note {{here}}
func testRenameSetters() {
unavailableSetInstanceProperty(a: 1, b: 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=1.prop}} {{33-43= = }} {{44-45=}}
unavailableSetInstancePropertyUnlabeled(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=1.prop}} {{42-46= = }} {{47-48=}}
unavailableSetInstancePropertyReverse(a: 1, b: 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=2.prop}} {{40-44= = }} {{45-52=}}
unavailableSetInstancePropertyUnlabeledReverse(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=2.prop}} {{49-50= = }} {{51-55=}}
unavailableSetInstanceProperty(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=(1 + 1).prop}} {{33-47= = }} {{52-53=}}
unavailableSetInstancePropertyUnlabeled(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=(1 + 1).prop}} {{42-50= = }} {{55-56=}}
unavailableSetInstancePropertyReverse(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=(2 + 2).prop}} {{40-44= = }} {{49-60=}}
unavailableSetInstancePropertyUnlabeledReverse(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=(2 + 2).prop}} {{49-50= = }} {{55-63=}}
unavailableSetClassProperty(a: 1) // expected-error{{'unavailableSetClassProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=Int.prop}} {{30-34= = }} {{35-36=}}
unavailableSetGlobalProperty(1) // expected-error{{'unavailableSetGlobalProperty' has been replaced by 'global'}} {{3-31=global}} {{31-32= = }} {{33-34=}}
var x = 0
unavailableSetInstancePropertyInout(a: &x, b: 2) // expected-error{{'unavailableSetInstancePropertyInout(a:b:)' has been replaced by property 'Int.prop'}} {{3-38=x.prop}} {{38-49= = }} {{50-51=}}
}
@available(*, unavailable, renamed: "Int.foo(self:execute:)")
func trailingClosure(_ value: Int, fn: () -> Void) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:bar:execute:)")
func trailingClosureArg(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(bar:self:execute:)")
func trailingClosureArg2(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}}
func testInstanceTrailingClosure() {
// FIXME: regression in fixit due to noescape-by-default
trailingClosure(0) {} // expected-error {{'trailingClosure(_:fn:)' has been replaced by instance method 'Int.foo(execute:)'}} // FIXME: {{3-18=0.foo}} {{19-20=}}
trailingClosureArg(0, 1) {} // expected-error {{'trailingClosureArg(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} // FIXME: {{3-21=0.foo}} {{22-25=}} {{25-25=bar: }}
trailingClosureArg2(0, 1) {} // expected-error {{'trailingClosureArg2(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} // FIXME: {{3-22=1.foo}} {{23-23=bar: }} {{24-27=}}
}
@available(*, unavailable, renamed: "+")
func add(_ value: Int, _ other: Int) {} // expected-note {{here}}
infix operator ***
@available(*, unavailable, renamed: "add")
func ***(value: (), other: ()) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:_:)")
func ***(value: Int, other: Int) {} // expected-note {{here}}
prefix operator ***
@available(*, unavailable, renamed: "add")
prefix func ***(value: Int?) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)")
prefix func ***(value: Int) {} // expected-note {{here}}
postfix operator ***
@available(*, unavailable, renamed: "add")
postfix func ***(value: Int?) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)")
postfix func ***(value: Int) {} // expected-note {{here}}
func testOperators() {
add(0, 1) // expected-error {{'add' has been renamed to '+'}} {{none}}
() *** () // expected-error {{'***' has been renamed to 'add'}} {{none}}
0 *** 1 // expected-error {{'***' has been replaced by instance method 'Int.foo(_:)'}} {{none}}
***nil // expected-error {{'***' has been renamed to 'add'}} {{none}}
***0 // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}}
nil*** // expected-error {{'***' has been renamed to 'add'}} {{none}}
0*** // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}}
}
extension Int {
@available(*, unavailable, renamed: "init(other:)")
@discardableResult
static func factory(other: Int) -> Int { return other } // expected-note 2 {{here}}
@available(*, unavailable, renamed: "Int.init(other:)")
@discardableResult
static func factory2(other: Int) -> Int { return other } // expected-note 2 {{here}}
static func testFactoryMethods() {
factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{none}}
factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{5-13=Int}}
}
}
func testFactoryMethods() {
Int.factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{6-14=}}
Int.factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{3-15=Int}}
}
class Base {
@available(*, unavailable)
func bad() {} // expected-note {{here}}
@available(*, unavailable, message: "it was smelly")
func smelly() {} // expected-note {{here}}
@available(*, unavailable, renamed: "new")
func old() {} // expected-note {{here}}
@available(*, unavailable, renamed: "new", message: "it was smelly")
func oldAndSmelly() {} // expected-note {{here}}
@available(*, unavailable)
func expendable() {}
@available(*, unavailable)
var badProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, message: "it was smelly")
var smellyProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, renamed: "new")
var oldProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, renamed: "new", message: "it was smelly")
var oldAndSmellyProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable)
var expendableProp: Int { return 0 }
@available(*, unavailable, renamed: "init")
func nowAnInitializer() {} // expected-note {{here}}
@available(*, unavailable, renamed: "init()")
func nowAnInitializer2() {} // expected-note {{here}}
@available(*, unavailable, renamed: "foo")
init(nowAFunction: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "foo(_:)")
init(nowAFunction2: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgNames(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgRenamed(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableNoArgs() {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableSame(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)")
func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "init(shinyNewName:)")
init(unavailableArgNames: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(a:)")
init(_ unavailableUnnamed: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(_:)")
init(unavailableNewlyUnnamed: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(a:b:)")
init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(_:_:)")
init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:)")
func unavailableTooFew(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:b:)")
func unavailableTooMany(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:)")
func unavailableNoArgsTooMany() {} // expected-note {{here}}
@available(*, unavailable, renamed: "Base.shinyLabeledArguments()")
func unavailableHasType() {} // expected-note {{here}}
}
class Sub : Base {
override func bad() {} // expected-error {{cannot override 'bad' which has been marked unavailable}} {{none}} expected-note {{remove 'override' modifier to declare a new 'bad'}} {{3-12=}}
override func smelly() {} // expected-error {{cannot override 'smelly' which has been marked unavailable: it was smelly}} {{none}} expected-note {{remove 'override' modifier to declare a new 'smelly'}} {{3-12=}}
override func old() {} // expected-error {{'old()' has been renamed to 'new'}} {{17-20=new}} expected-note {{remove 'override' modifier to declare a new 'old'}} {{3-12=}}
override func oldAndSmelly() {} // expected-error {{'oldAndSmelly()' has been renamed to 'new': it was smelly}} {{17-29=new}} expected-note {{remove 'override' modifier to declare a new 'oldAndSmelly'}} {{3-12=}}
func expendable() {} // no-error
override var badProp: Int { return 0 } // expected-error {{cannot override 'badProp' which has been marked unavailable}} {{none}} expected-note {{remove 'override' modifier to declare a new 'badProp'}} {{3-12=}}
override var smellyProp: Int { return 0 } // expected-error {{cannot override 'smellyProp' which has been marked unavailable: it was smelly}} {{none}} expected-note {{remove 'override' modifier to declare a new 'smellyProp'}} {{3-12=}}
override var oldProp: Int { return 0 } // expected-error {{'oldProp' has been renamed to 'new'}} {{16-23=new}} expected-note {{remove 'override' modifier to declare a new 'oldProp'}} {{3-12=}}
override var oldAndSmellyProp: Int { return 0 } // expected-error {{'oldAndSmellyProp' has been renamed to 'new': it was smelly}} {{16-32=new}} expected-note {{remove 'override' modifier to declare a new 'oldAndSmellyProp'}} {{3-12=}}
var expendableProp: Int { return 0 } // no-error
override func nowAnInitializer() {} // expected-error {{'nowAnInitializer()' has been replaced by 'init'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'nowAnInitializer'}} {{3-12=}}
override func nowAnInitializer2() {} // expected-error {{'nowAnInitializer2()' has been replaced by 'init()'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'nowAnInitializer2'}} {{3-12=}}
override init(nowAFunction: Int) {} // expected-error {{'init(nowAFunction:)' has been renamed to 'foo'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override init(nowAFunction2: Int) {} // expected-error {{'init(nowAFunction2:)' has been renamed to 'foo(_:)'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override func unavailableArgNames(a: Int) {} // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-36=shinyLabeledArguments}} {{37-37=example }} expected-note {{remove 'override' modifier to declare a new 'unavailableArgNames'}} {{3-12=}}
override func unavailableArgRenamed(a param: Int) {} // expected-error {{'unavailableArgRenamed(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-38=shinyLabeledArguments}} {{39-40=example}} expected-note {{remove 'override' modifier to declare a new 'unavailableArgRenamed'}} {{3-12=}}
override func unavailableNoArgs() {} // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{17-34=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableNoArgs'}} {{3-12=}}
override func unavailableSame(a: Int) {} // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{17-32=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableSame'}} {{3-12=}}
override func unavailableUnnamed(_ a: Int) {} // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-35=shinyLabeledArguments}} {{36-37=example}} expected-note {{remove 'override' modifier to declare a new 'unavailableUnnamed'}} {{3-12=}}
override func unavailableUnnamedSame(_ a: Int) {} // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-39=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableUnnamedSame'}} {{3-12=}}
override func unavailableNewlyUnnamed(a: Int) {} // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-40=shinyLabeledArguments}} {{41-41=_ }} expected-note {{remove 'override' modifier to declare a new 'unavailableNewlyUnnamed'}} {{3-12=}}
override func unavailableMultiSame(a: Int, b: Int) {} // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{17-37=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableMultiSame'}} {{3-12=}}
override func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{17-40=shinyLabeledArguments}} {{41-42=example}} {{51-52=another}} expected-note {{remove 'override' modifier to declare a new 'unavailableMultiUnnamed'}} {{3-12=}}
override func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-44=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableMultiUnnamedSame'}} {{3-12=}}
override func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-45=shinyLabeledArguments}} {{46-46=_ }} {{54-54=_ }} expected-note {{remove 'override' modifier to declare a new 'unavailableMultiNewlyUnnamed'}} {{3-12=}}
override init(unavailableArgNames: Int) {} // expected-error {{'init(unavailableArgNames:)' has been renamed to 'init(shinyNewName:)'}} {{17-17=shinyNewName }} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override init(_ unavailableUnnamed: Int) {} // expected-error {{'init(_:)' has been renamed to 'init(a:)'}} {{17-18=a}} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override init(unavailableNewlyUnnamed: Int) {} // expected-error {{'init(unavailableNewlyUnnamed:)' has been renamed to 'init(_:)'}} {{17-17=_ }} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-error {{'init(_:_:)' has been renamed to 'init(a:b:)'}} {{17-18=a}} {{49-51=}} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-error {{'init(unavailableMultiNewlyUnnamed:b:)' has been renamed to 'init(_:_:)'}} {{17-45=_}} {{54-54=_ }} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}}
override func unavailableTooFew(a: Int, b: Int) {} // expected-error {{'unavailableTooFew(a:b:)' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'unavailableTooFew'}} {{3-12=}}
override func unavailableTooMany(a: Int) {} // expected-error {{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(x:b:)'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'unavailableTooMany'}} {{3-12=}}
override func unavailableNoArgsTooMany() {} // expected-error {{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'unavailableNoArgsTooMany'}} {{3-12=}}
override func unavailableHasType() {} // expected-error {{'unavailableHasType()' has been replaced by 'Base.shinyLabeledArguments()'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'unavailableHasType'}} {{3-12=}}
}
// U: Unnamed, L: Labeled
@available(*, unavailable, renamed: "after(fn:)")
func closure_U_L(_ x: () -> Int) {} // expected-note 3 {{here}}
@available(*, unavailable, renamed: "after(fn:)")
func closure_L_L(x: () -> Int) {} // expected-note 3 {{here}}
@available(*, unavailable, renamed: "after(_:)")
func closure_L_U(x: () -> Int) {} // expected-note 3 {{here}}
@available(*, unavailable, renamed: "after(arg:fn:)")
func closure_UU_LL(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:fn:)")
func closure_LU_LL(x: Int, _ y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:fn:)")
func closure_LL_LL(x: Int, y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:fn:)")
func closure_UU_LL_ne(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:_:)")
func closure_UU_LU(_ x: Int, _ closure: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:_:)")
func closure_LU_LU(x: Int, _ closure: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:_:)")
func closure_LL_LU(x: Int, y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:_:)")
func closure_UU_LU_ne(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}}
func testTrailingClosure() {
closure_U_L { 0 } // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}}
closure_U_L() { 0 } // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}}
closure_U_L({ 0 }) // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{15-15=fn: }} {{none}}
closure_L_L { 0 } // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}}
closure_L_L() { 0 } // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}}
closure_L_L(x: { 0 }) // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{15-16=fn}} {{none}}
closure_L_U { 0 } // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{none}}
closure_L_U() { 0 } // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{none}}
closure_L_U(x: { 0 }) // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{15-18=}} {{none}}
closure_UU_LL(0) { 0 } // expected-error {{'closure_UU_LL' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-17=arg: }} {{none}}
closure_UU_LL(0, { 0 }) // expected-error {{'closure_UU_LL' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-17=arg: }} {{20-20=fn: }} {{none}}
closure_LU_LL(x: 0) { 0 } // expected-error {{'closure_LU_LL(x:_:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LU_LL(x: 0, { 0 }) // expected-error {{'closure_LU_LL(x:_:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{23-23=fn: }} {{none}}
closure_LL_LL(x: 1) { 1 } // expected-error {{'closure_LL_LL(x:y:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LL_LL(x: 1, y: { 0 }) // expected-error {{'closure_LL_LL(x:y:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{23-24=fn}} {{none}}
closure_UU_LL_ne(1) { 1 } // expected-error {{'closure_UU_LL_ne' has been renamed to 'after(arg:fn:)'}} {{3-19=after}} {{20-20=arg: }} {{none}}
closure_UU_LL_ne(1, { 0 }) // expected-error {{'closure_UU_LL_ne' has been renamed to 'after(arg:fn:)'}} {{3-19=after}} {{20-20=arg: }} {{23-23=fn: }} {{none}}
closure_UU_LU(0) { 0 } // expected-error {{'closure_UU_LU' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-17=arg: }} {{none}}
closure_UU_LU(0, { 0 }) // expected-error {{'closure_UU_LU' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-17=arg: }} {{none}}
closure_LU_LU(x: 0) { 0 } // expected-error {{'closure_LU_LU(x:_:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LU_LU(x: 0, { 0 }) // expected-error {{'closure_LU_LU(x:_:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LL_LU(x: 1) { 1 } // expected-error {{'closure_LL_LU(x:y:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LL_LU(x: 1, y: { 0 }) // expected-error {{'closure_LL_LU(x:y:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{23-26=}} {{none}}
closure_UU_LU_ne(1) { 1 } // expected-error {{'closure_UU_LU_ne' has been renamed to 'after(arg:_:)'}} {{3-19=after}} {{20-20=arg: }} {{none}}
closure_UU_LU_ne(1, { 0 }) // expected-error {{'closure_UU_LU_ne' has been renamed to 'after(arg:_:)'}} {{3-19=after}} {{20-20=arg: }} {{none}}
}
@available(*, unavailable, renamed: "after(x:)")
func defaultUnnamed(_ a: Int = 1) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(x:y:)")
func defaultBeforeRequired(a: Int = 1, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "after(x:y:z:)")
func defaultPlusTrailingClosure(a: Int = 1, b: Int = 2, c: () -> Void) {} // expected-note 3 {{here}}
func testDefaults() {
defaultUnnamed() // expected-error {{'defaultUnnamed' has been renamed to 'after(x:)'}} {{3-17=after}} {{none}}
defaultUnnamed(1) // expected-error {{'defaultUnnamed' has been renamed to 'after(x:)'}} {{3-17=after}} {{18-18=x: }} {{none}}
defaultBeforeRequired(b: 5) // expected-error {{'defaultBeforeRequired(a:b:)' has been renamed to 'after(x:y:)'}} {{3-24=after}} {{25-26=y}} {{none}}
defaultPlusTrailingClosure {} // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{none}}
defaultPlusTrailingClosure(c: {}) // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{30-31=z}} {{none}}
defaultPlusTrailingClosure(a: 1) {} // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{30-31=x}} {{none}}
}
@available(*, unavailable, renamed: "after(x:y:)")
func variadic1(a: Int ..., b: Int = 0) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(x:y:)")
func variadic2(a: Int, _ b: Int ...) {} // expected-note {{here}}
@available(*, unavailable, renamed: "after(x:_:y:z:)")
func variadic3(_ a: Int, b: Int ..., c: String = "", d: String) {} // expected-note 2 {{here}}
func testVariadic() {
variadic1(a: 1, 2) // expected-error {{'variadic1(a:b:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{none}}
variadic1(a: 1, 2, b: 3) // expected-error {{'variadic1(a:b:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{22-23=y}} {{none}}
variadic2(a: 1, 2, 3) // expected-error {{'variadic2(a:_:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{19-19=y: }} {{none}}
variadic3(1, b: 2, 3, d: "test") // expected-error {{'variadic3(_:b:c:d:)' has been renamed to 'after(x:_:y:z:)'}} {{3-12=after}} {{13-13=x: }} {{16-19=}} {{25-26=z}} {{none}}
variadic3(1, d:"test") // expected-error {{'variadic3(_:b:c:d:)' has been renamed to 'after(x:_:y:z:)'}} {{3-12=after}} {{13-13=x: }} {{16-17=z}} {{none}}
}
enum E_32526620 {
case foo
case bar
func set() {}
}
@available(*, unavailable, renamed: "E_32526620.set(self:)")
func rdar32526620_1(a: E_32526620) {} // expected-note {{here}}
rdar32526620_1(a: .foo)
// expected-error@-1 {{'rdar32526620_1(a:)' has been replaced by instance method 'E_32526620.set()'}} {{1-15=E_32526620.foo.set}} {{16-23=}}
@available(*, unavailable, renamed: "E_32526620.set(a:self:)")
func rdar32526620_2(a: Int, b: E_32526620) {} // expected-note {{here}}
rdar32526620_2(a: 42, b: .bar)
// expected-error@-1 {{'rdar32526620_2(a:b:)' has been replaced by instance method 'E_32526620.set(a:)'}} {{1-15=E_32526620.bar.set}} {{21-30=}}
@available(*, unavailable, renamed: "E_32526620.set(a:self:c:)")
func rdar32526620_3(a: Int, b: E_32526620, c: String) {} // expected-note {{here}}
rdar32526620_3(a: 42, b: .bar, c: "question")
// expected-error@-1 {{'rdar32526620_3(a:b:c:)' has been replaced by instance method 'E_32526620.set(a:c:)'}} {{1-15=E_32526620.bar.set}} {{23-32=}}
var deprecatedGetter: Int {
@available(*, deprecated) get { return 0 }
set {}
}
var deprecatedGetterOnly: Int {
@available(*, deprecated) get { return 0 }
}
var deprecatedSetter: Int {
get { return 0 }
@available(*, deprecated) set {}
}
var deprecatedBoth: Int {
@available(*, deprecated) get { return 0 }
@available(*, deprecated) set {}
}
var deprecatedMessage: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
var deprecatedRename: Int {
@available(*, deprecated, renamed: "betterThing()") get { return 0 }
@available(*, deprecated, renamed: "setBetterThing(_:)") set {}
}
@available(*, deprecated, message: "bad variable")
var deprecatedProperty: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
_ = deprecatedGetter // expected-warning {{getter for 'deprecatedGetter' is deprecated}} {{none}}
deprecatedGetter = 0
deprecatedGetter += 1 // expected-warning {{getter for 'deprecatedGetter' is deprecated}} {{none}}
_ = deprecatedGetterOnly // expected-warning {{getter for 'deprecatedGetterOnly' is deprecated}} {{none}}
_ = deprecatedSetter
deprecatedSetter = 0 // expected-warning {{setter for 'deprecatedSetter' is deprecated}} {{none}}
deprecatedSetter += 1 // expected-warning {{setter for 'deprecatedSetter' is deprecated}} {{none}}
_ = deprecatedBoth // expected-warning {{getter for 'deprecatedBoth' is deprecated}} {{none}}
deprecatedBoth = 0 // expected-warning {{setter for 'deprecatedBoth' is deprecated}} {{none}}
deprecatedBoth += 1 // expected-warning {{getter for 'deprecatedBoth' is deprecated}} {{none}} expected-warning {{setter for 'deprecatedBoth' is deprecated}} {{none}}
_ = deprecatedMessage // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}}
deprecatedMessage = 0 // expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
deprecatedMessage += 1 // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
_ = deprecatedRename // expected-warning {{getter for 'deprecatedRename' is deprecated: renamed to 'betterThing()'}} {{none}}
deprecatedRename = 0 // expected-warning {{setter for 'deprecatedRename' is deprecated: renamed to 'setBetterThing(_:)'}} {{none}}
deprecatedRename += 1 // expected-warning {{getter for 'deprecatedRename' is deprecated: renamed to 'betterThing()'}} {{none}} expected-warning {{setter for 'deprecatedRename' is deprecated: renamed to 'setBetterThing(_:)'}} {{none}}
_ = deprecatedProperty // expected-warning {{'deprecatedProperty' is deprecated: bad variable}} {{none}}
deprecatedProperty = 0 // expected-warning {{'deprecatedProperty' is deprecated: bad variable}} {{none}}
deprecatedProperty += 1 // expected-warning {{'deprecatedProperty' is deprecated: bad variable}} {{none}}
var unavailableGetter: Int {
@available(*, unavailable) get { return 0 } // expected-note * {{here}}
set {}
}
var unavailableGetterOnly: Int {
@available(*, unavailable) get { return 0 } // expected-note * {{here}}
}
var unavailableSetter: Int {
get { return 0 }
@available(*, unavailable) set {} // expected-note * {{here}}
}
var unavailableBoth: Int {
@available(*, unavailable) get { return 0 } // expected-note * {{here}}
@available(*, unavailable) set {} // expected-note * {{here}}
}
var unavailableMessage: Int {
@available(*, unavailable, message: "bad getter") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, message: "bad setter") set {} // expected-note * {{here}}
}
var unavailableRename: Int {
@available(*, unavailable, renamed: "betterThing()") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, renamed: "setBetterThing(_:)") set {} // expected-note * {{here}}
}
@available(*, unavailable, message: "bad variable")
var unavailableProperty: Int { // expected-note * {{here}}
@available(*, unavailable, message: "bad getter") get { return 0 }
@available(*, unavailable, message: "bad setter") set {}
}
_ = unavailableGetter // expected-error {{getter for 'unavailableGetter' is unavailable}} {{none}}
unavailableGetter = 0
unavailableGetter += 1 // expected-error {{getter for 'unavailableGetter' is unavailable}} {{none}}
_ = unavailableGetterOnly // expected-error {{getter for 'unavailableGetterOnly' is unavailable}} {{none}}
_ = unavailableSetter
unavailableSetter = 0 // expected-error {{setter for 'unavailableSetter' is unavailable}} {{none}}
unavailableSetter += 1 // expected-error {{setter for 'unavailableSetter' is unavailable}} {{none}}
_ = unavailableBoth // expected-error {{getter for 'unavailableBoth' is unavailable}} {{none}}
unavailableBoth = 0 // expected-error {{setter for 'unavailableBoth' is unavailable}} {{none}}
unavailableBoth += 1 // expected-error {{getter for 'unavailableBoth' is unavailable}} {{none}} expected-error {{setter for 'unavailableBoth' is unavailable}} {{none}}
_ = unavailableMessage // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}}
unavailableMessage = 0 // expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
unavailableMessage += 1 // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
_ = unavailableRename // expected-error {{getter for 'unavailableRename' has been renamed to 'betterThing()'}} {{none}}
unavailableRename = 0 // expected-error {{setter for 'unavailableRename' has been renamed to 'setBetterThing(_:)'}} {{none}}
unavailableRename += 1 // expected-error {{getter for 'unavailableRename' has been renamed to 'betterThing()'}} {{none}} expected-error {{setter for 'unavailableRename' has been renamed to 'setBetterThing(_:)'}} {{none}}
_ = unavailableProperty // expected-error {{'unavailableProperty' is unavailable: bad variable}} {{none}}
unavailableProperty = 0 // expected-error {{'unavailableProperty' is unavailable: bad variable}} {{none}}
unavailableProperty += 1 // expected-error {{'unavailableProperty' is unavailable: bad variable}} {{none}}
struct DeprecatedAccessors {
var deprecatedMessage: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
static var staticDeprecated: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
@available(*, deprecated, message: "bad property")
var deprecatedProperty: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
subscript(_: Int) -> Int {
@available(*, deprecated, message: "bad subscript getter") get { return 0 }
@available(*, deprecated, message: "bad subscript setter") set {}
}
@available(*, deprecated, message: "bad subscript!")
subscript(alsoDeprecated _: Int) -> Int {
@available(*, deprecated, message: "bad subscript getter") get { return 0 }
@available(*, deprecated, message: "bad subscript setter") set {}
}
mutating func testAccessors(other: inout DeprecatedAccessors) {
_ = deprecatedMessage // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}}
deprecatedMessage = 0 // expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
deprecatedMessage += 1 // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
_ = other.deprecatedMessage // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}}
other.deprecatedMessage = 0 // expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
other.deprecatedMessage += 1 // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
_ = other.deprecatedProperty // expected-warning {{'deprecatedProperty' is deprecated: bad property}} {{none}}
other.deprecatedProperty = 0 // expected-warning {{'deprecatedProperty' is deprecated: bad property}} {{none}}
other.deprecatedProperty += 1 // expected-warning {{'deprecatedProperty' is deprecated: bad property}} {{none}}
_ = DeprecatedAccessors.staticDeprecated // expected-warning {{getter for 'staticDeprecated' is deprecated: bad getter}} {{none}}
DeprecatedAccessors.staticDeprecated = 0 // expected-warning {{setter for 'staticDeprecated' is deprecated: bad setter}} {{none}}
DeprecatedAccessors.staticDeprecated += 1 // expected-warning {{getter for 'staticDeprecated' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'staticDeprecated' is deprecated: bad setter}} {{none}}
_ = other[0] // expected-warning {{getter for 'subscript(_:)' is deprecated: bad subscript getter}} {{none}}
other[0] = 0 // expected-warning {{setter for 'subscript(_:)' is deprecated: bad subscript setter}} {{none}}
other[0] += 1 // expected-warning {{getter for 'subscript(_:)' is deprecated: bad subscript getter}} {{none}} expected-warning {{setter for 'subscript(_:)' is deprecated: bad subscript setter}} {{none}}
_ = other[alsoDeprecated: 0] // expected-warning {{'subscript(alsoDeprecated:)' is deprecated: bad subscript!}} {{none}}
other[alsoDeprecated: 0] = 0 // expected-warning {{'subscript(alsoDeprecated:)' is deprecated: bad subscript!}} {{none}}
other[alsoDeprecated: 0] += 1 // expected-warning {{'subscript(alsoDeprecated:)' is deprecated: bad subscript!}} {{none}}
}
}
struct UnavailableAccessors {
var unavailableMessage: Int {
@available(*, unavailable, message: "bad getter") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, message: "bad setter") set {} // expected-note * {{here}}
}
static var staticUnavailable: Int {
@available(*, unavailable, message: "bad getter") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, message: "bad setter") set {} // expected-note * {{here}}
}
@available(*, unavailable, message: "bad property")
var unavailableProperty: Int { // expected-note * {{here}}
@available(*, unavailable, message: "bad getter") get { return 0 }
@available(*, unavailable, message: "bad setter") set {}
}
subscript(_: Int) -> Int {
@available(*, unavailable, message: "bad subscript getter") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, message: "bad subscript setter") set {} // expected-note * {{here}}
}
@available(*, unavailable, message: "bad subscript!")
subscript(alsoUnavailable _: Int) -> Int { // expected-note * {{here}}
@available(*, unavailable, message: "bad subscript getter") get { return 0 }
@available(*, unavailable, message: "bad subscript setter") set {}
}
mutating func testAccessors(other: inout UnavailableAccessors) {
_ = unavailableMessage // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}}
unavailableMessage = 0 // expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
unavailableMessage += 1 // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
_ = other.unavailableMessage // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}}
other.unavailableMessage = 0 // expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
other.unavailableMessage += 1 // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
_ = other.unavailableProperty // expected-error {{'unavailableProperty' is unavailable: bad property}} {{none}}
other.unavailableProperty = 0 // expected-error {{'unavailableProperty' is unavailable: bad property}} {{none}}
other.unavailableProperty += 1 // expected-error {{'unavailableProperty' is unavailable: bad property}} {{none}}
_ = UnavailableAccessors.staticUnavailable // expected-error {{getter for 'staticUnavailable' is unavailable: bad getter}} {{none}}
UnavailableAccessors.staticUnavailable = 0 // expected-error {{setter for 'staticUnavailable' is unavailable: bad setter}} {{none}}
UnavailableAccessors.staticUnavailable += 1 // expected-error {{getter for 'staticUnavailable' is unavailable: bad getter}} {{none}} expected-error {{setter for 'staticUnavailable' is unavailable: bad setter}} {{none}}
_ = other[0] // expected-error {{getter for 'subscript(_:)' is unavailable: bad subscript getter}} {{none}}
other[0] = 0 // expected-error {{setter for 'subscript(_:)' is unavailable: bad subscript setter}} {{none}}
other[0] += 1 // expected-error {{getter for 'subscript(_:)' is unavailable: bad subscript getter}} {{none}} expected-error {{setter for 'subscript(_:)' is unavailable: bad subscript setter}} {{none}}
_ = other[alsoUnavailable: 0] // expected-error {{'subscript(alsoUnavailable:)' is unavailable: bad subscript!}} {{none}}
other[alsoUnavailable: 0] = 0 // expected-error {{'subscript(alsoUnavailable:)' is unavailable: bad subscript!}} {{none}}
other[alsoUnavailable: 0] += 1 // expected-error {{'subscript(alsoUnavailable:)' is unavailable: bad subscript!}} {{none}}
}
}
class BaseDeprecatedInit {
@available(*, deprecated) init(bad: Int) { }
}
class SubInheritedDeprecatedInit: BaseDeprecatedInit { }
_ = SubInheritedDeprecatedInit(bad: 0) // expected-warning {{'init(bad:)' is deprecated}}
// https://github.com/apple/swift/issues/51149
// Should produce no warnings.
enum Enum_51149: Int {
case a
@available(*, deprecated, message: "I must not be raised in synthesized code")
case b
case c
}
struct Struct_51149: Equatable {
@available(*, deprecated, message: "I must not be raised in synthesized code", renamed: "x")
let a: Int
}
@available(*, deprecated, message: "This is a message", message: "This is another message")
// expected-warning@-1 {{'message' argument has already been specified}}
func rdar46348825_message() {}
@available(*, deprecated, renamed: "rdar46348825_message", renamed: "unavailable_func_with_message")
// expected-warning@-1 {{'renamed' argument has already been specified}}
func rdar46348825_renamed() {}
@available(swift, introduced: 4.0, introduced: 4.0)
// expected-warning@-1 {{'introduced' argument has already been specified}}
func rdar46348825_introduced() {}
@available(swift, deprecated: 4.0, deprecated: 4.0)
// expected-warning@-1 {{'deprecated' argument has already been specified}}
func rdar46348825_deprecated() {}
@available(swift, obsoleted: 4.0, obsoleted: 4.0)
// expected-warning@-1 {{'obsoleted' argument has already been specified}}
func rdar46348825_obsoleted() {}
// Referencing unavailable types in signatures of unavailable functions should be accepted
@available(*, unavailable)
protocol UnavailableProto {
}
@available(*, unavailable)
func unavailableFunc(_ arg: UnavailableProto) -> UnavailableProto {}
@available(*, unavailable)
struct S {
var a: UnavailableProto
}
// Bad rename.
struct BadRename {
@available(*, deprecated, renamed: "init(range:step:)")
init(from: Int, to: Int, step: Int = 1) { }
init(range: Range<Int>, step: Int) { }
}
func testBadRename() {
_ = BadRename(from: 5, to: 17) // expected-warning{{'init(from:to:step:)' is deprecated: replaced by 'init(range:step:)'}}
// expected-note@-1{{use 'init(range:step:)' instead}}
}
struct AvailableGenericParam<@available(*, deprecated) T> {}
// expected-error@-1 {{'@available' attribute cannot be applied to this declaration}}
class UnavailableNoArgsSuperclassInit {
@available(*, unavailable)
init() {} // expected-note {{'init()' has been explicitly marked unavailable here}}
}
class UnavailableNoArgsSubclassInit: UnavailableNoArgsSuperclassInit {
init(marker: ()) {}
// expected-error@-1 {{'init()' is unavailable}}
// expected-note@-2 {{call to unavailable initializer 'init()' from superclass 'UnavailableNoArgsSuperclassInit' occurs implicitly at the end of this initializer}}
}
struct TypeWithTrailingClosures {
func twoTrailingClosures(a: () -> Void, b: () -> Void) {}
func threeTrailingClosures(a: () -> Void, b: () -> Void, c: () -> Void) {}
func threeUnlabeledTrailingClosures(_ a: () -> Void, _ b: () -> Void, _ c: () -> Void) {}
func variadicTrailingClosures(a: (() -> Void)..., b: Int = 0, c: Int = 0) {}
}
@available(*, deprecated, renamed: "TypeWithTrailingClosures.twoTrailingClosures(self:a:b:)")
func twoTrailingClosures(_ x: TypeWithTrailingClosures, a: () -> Void, b: () -> Void) {}
@available(*, deprecated, renamed: "TypeWithTrailingClosures.twoTrailingClosures(self:a:b:)")
func twoTrailingClosuresWithDefaults(x: TypeWithTrailingClosures, y: Int = 0, z: Int = 0, a: () -> Void, b: () -> Void) {}
@available(*, deprecated, renamed: "TypeWithTrailingClosures.threeTrailingClosures(self:a:b:c:)")
func threeTrailingClosures(_ x: TypeWithTrailingClosures, a: () -> Void, b: () -> Void, c: () -> Void) {}
@available(*, deprecated, renamed: "TypeWithTrailingClosures.threeTrailingClosures(self:a:b:c:)")
func threeTrailingClosuresDiffLabels(_: TypeWithTrailingClosures, x: () -> Void, y: () -> Void, z: () -> Void) {}
@available(*, deprecated, renamed: "TypeWithTrailingClosures.threeUnlabeledTrailingClosures(self:_:_:_:)")
func threeTrailingClosuresRemoveLabels(_ x: TypeWithTrailingClosures, a: () -> Void, b: () -> Void, c: () -> Void) {}
@available(*, deprecated, renamed: "TypeWithTrailingClosures.variadicTrailingClosures(self:a:b:c:)")
func variadicTrailingClosures(_ x: TypeWithTrailingClosures, a: (() -> Void)...) {}
func testMultipleTrailingClosures(_ x: TypeWithTrailingClosures) {
twoTrailingClosures(x) {} b: {} // expected-warning {{'twoTrailingClosures(_:a:b:)' is deprecated: replaced by instance method 'TypeWithTrailingClosures.twoTrailingClosures(a:b:)'}}
// expected-note@-1 {{use 'TypeWithTrailingClosures.twoTrailingClosures(a:b:)' instead}} {{3-22=x.twoTrailingClosures}} {{23-24=}} {{none}}
x.twoTrailingClosures() {} b: {}
twoTrailingClosuresWithDefaults(x: x) {} b: {} // expected-warning {{'twoTrailingClosuresWithDefaults(x:y:z:a:b:)' is deprecated: replaced by instance method 'TypeWithTrailingClosures.twoTrailingClosures(a:b:)'}}
// expected-note@-1 {{use 'TypeWithTrailingClosures.twoTrailingClosures(a:b:)' instead}} {{3-34=x.twoTrailingClosures}} {{35-39=}} {{none}}
x.twoTrailingClosures() {} b: {}
threeTrailingClosures(x, a: {}) {} c: {} // expected-warning {{'threeTrailingClosures(_:a:b:c:)' is deprecated: replaced by instance method 'TypeWithTrailingClosures.threeTrailingClosures(a:b:c:)'}}
// expected-note@-1 {{use 'TypeWithTrailingClosures.threeTrailingClosures(a:b:c:)' instead}} {{3-24=x.threeTrailingClosures}} {{25-28=}} {{none}}
x.threeTrailingClosures(a: {}) {} c: {}
threeTrailingClosuresDiffLabels(x, x: {}) {} z: {} // expected-warning {{'threeTrailingClosuresDiffLabels(_:x:y:z:)' is deprecated: replaced by instance method 'TypeWithTrailingClosures.threeTrailingClosures(a:b:c:)'}}
// expected-note@-1 {{use 'TypeWithTrailingClosures.threeTrailingClosures(a:b:c:)' instead}} {{3-34=x.threeTrailingClosures}} {{35-38=}} {{38-39=a}} {{48-49=c}} {{none}}
x.threeTrailingClosures(a: {}) {} c: {}
threeTrailingClosuresRemoveLabels(x, a: {}) {} c: {} // expected-warning {{'threeTrailingClosuresRemoveLabels(_:a:b:c:)' is deprecated: replaced by instance method 'TypeWithTrailingClosures.threeUnlabeledTrailingClosures(_:_:_:)'}}
// expected-note@-1 {{use 'TypeWithTrailingClosures.threeUnlabeledTrailingClosures(_:_:_:)' instead}} {{3-36=x.threeUnlabeledTrailingClosures}} {{37-40=}} {{40-43=}} {{50-51=_}} {{none}}
x.threeUnlabeledTrailingClosures({}) {} _: {}
variadicTrailingClosures(x) {} _: {} _: {} // expected-warning {{'variadicTrailingClosures(_:a:)' is deprecated: replaced by instance method 'TypeWithTrailingClosures.variadicTrailingClosures(a:b:c:)'}}
// expected-note@-1 {{use 'TypeWithTrailingClosures.variadicTrailingClosures(a:b:c:)' instead}} {{3-27=x.variadicTrailingClosures}} {{28-29=}} {{none}}
x.variadicTrailingClosures() {} _: {} _: {}
}
struct UnavailableSubscripts {
@available(*, unavailable, renamed: "subscript(new:)")
subscript(old index: Int) -> Int { 3 } // expected-note * {{'subscript(old:)' has been explicitly marked unavailable here}}
@available(*, unavailable, renamed: "subscript(new:)")
func getValue(old: Int) -> Int { 3 } // expected-note * {{'getValue(old:)' has been explicitly marked unavailable here}}
subscript(new index: Int) -> Int { 3 }
@available(*, unavailable, renamed: "getAValue(new:)")
subscript(getAValue index: Int) -> Int { 3 } // expected-note * {{'subscript(getAValue:)' has been explicitly marked unavailable here}}
func getAValue(new: Int) -> Int { 3 }
@available(*, unavailable, renamed: "subscript(arg1:arg2:arg3:)")
subscript(_ argg1: Int, _ argg2: Int, _ argg3: Int) -> Int { 3 } // expected-note * {{'subscript(_:_:_:)' has been explicitly marked unavailable here}}
@available(*, deprecated, renamed: "subscript(arg1:arg2:arg3:)")
subscript(argg1 argg1: Int, argg2 argg2: Int, argg3 argg3: Int) -> Int { 3 }
@available(*, deprecated, renamed: "subscript(arg1:arg2:arg3:)")
subscript(only1 only1: Int, only2 only2: Int) -> Int { 3 }
subscript(arg1 arg1: Int, arg2 arg2: Int, arg3 arg3: Int) -> Int { 3 }
@available(*, deprecated, renamed: "subscriptTo(_:)")
subscript(to to: Int) -> Int { 3 }
func subscriptTo(_ index: Int) -> Int { 3 }
func testUnavailableSubscripts(_ x: UnavailableSubscripts) {
_ = self[old: 3] // expected-error {{'subscript(old:)' has been renamed to 'subscript(new:)'}} {{14-17=new}}
_ = x[old: 3] // expected-error {{'subscript(old:)' has been renamed to 'subscript(new:)'}} {{11-14=new}}
_ = self.getValue(old: 3) // expected-error {{'getValue(old:)' has been renamed to 'subscript(new:)'}} {{14-22=[}} {{29-30=]}} {{23-26=new}}
_ = getValue(old: 3) // expected-error {{'getValue(old:)' has been renamed to 'subscript(new:)'}} {{9-9=self}} {{9-17=[}} {{24-25=]}} {{18-21=new}}
_ = x.getValue(old: 3) // expected-error {{'getValue(old:)' has been renamed to 'subscript(new:)'}} {{11-19=[}} {{26-27=]}} {{20-23=new}}
_ = self[getAValue: 3] // expected-error {{'subscript(getAValue:)' has been renamed to 'getAValue(new:)'}} {{13-14=.getAValue(}} {{26-27=)}} {{14-23=new}}
_ = x[getAValue: 3] // expected-error {{'subscript(getAValue:)' has been renamed to 'getAValue(new:)'}} {{10-11=.getAValue(}} {{23-24=)}} {{11-20=new}}
_ = self[argg1: 3, argg2: 3, argg3: 3] // expected-warning {{'subscript(argg1:argg2:argg3:)' is deprecated: renamed to 'subscript(arg1:arg2:arg3:)'}} // expected-note {{use 'subscript(arg1:arg2:arg3:)' instead}} {{14-19=arg1}} {{24-29=arg2}} {{34-39=arg3}}
_ = x[argg1: 3, argg2: 3, argg3: 3] // expected-warning {{'subscript(argg1:argg2:argg3:)' is deprecated: renamed to 'subscript(arg1:arg2:arg3:)'}} // expected-note {{use 'subscript(arg1:arg2:arg3:)' instead}} {{11-16=arg1}} {{21-26=arg2}} {{31-36=arg3}}
// Different number of parameters emit no fixit
_ = self[only1: 3, only2: 3] // expected-warning {{'subscript(only1:only2:)' is deprecated: renamed to 'subscript(arg1:arg2:arg3:)'}} // expected-note {{use 'subscript(arg1:arg2:arg3:)' instead}} {{none}}
_ = self[3, 3, 3] // expected-error {{'subscript(_:_:_:)' has been renamed to 'subscript(arg1:arg2:arg3:)'}} {{14-14=arg1: }} {{17-17=arg2: }} {{20-20=arg3: }}
_ = x[3, 3, 3] // expected-error {{'subscript(_:_:_:)' has been renamed to 'subscript(arg1:arg2:arg3:)'}} {{11-11=arg1: }} {{14-14=arg2: }} {{17-17=arg3: }}
_ = self[to: 3] // expected-warning {{'subscript(to:)' is deprecated: renamed to 'subscriptTo(_:)'}} // expected-note {{use 'subscriptTo(_:)' instead}} {{13-14=.subscriptTo(}} {{19-20=)}} {{14-18=}}
_ = x[to: 3] // expected-warning {{'subscript(to:)' is deprecated: renamed to 'subscriptTo(_:)'}} // expected-note {{use 'subscriptTo(_:)' instead}} {{10-11=.subscriptTo(}} {{16-17=)}} {{11-15=}}
}
}
| apache-2.0 | 47a7a4241620c0d4422c62e26e6c62ec | 64.698785 | 338 | 0.693818 | 3.877563 | false | false | false | false |
benlangmuir/swift | test/IRGen/protocol_conformance_records.swift | 10 | 7583 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -enable-library-evolution -enable-source-import -I %S/../Inputs | %FileCheck %s
// RUN: %target-swift-frontend %s -emit-ir -num-threads 8 -enable-library-evolution -enable-source-import -I %S/../Inputs | %FileCheck %s
import resilient_struct
import resilient_protocol
public protocol Associate {
associatedtype X
}
public struct Dependent<T> {}
public protocol Runcible {
func runce()
}
// CHECK-LABEL: @"$s28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE:@"\$s28protocol_conformance_records8RuncibleMp"]]
// -- type metadata
// CHECK-SAME: @"$s28protocol_conformance_records15NativeValueTypeVMn"
// -- witness table
// CHECK-SAME: @"$s28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAWP"
// -- flags
// CHECK-SAME: i32 0 },
public struct NativeValueType: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"$s28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- class metadata
// CHECK-SAME: @"$s28protocol_conformance_records15NativeClassTypeCMn"
// -- witness table
// CHECK-SAME: @"$s28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAWP"
// -- flags
// CHECK-SAME: i32 0 },
public class NativeClassType: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- nominal type descriptor
// CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVMn"
// -- witness table
// CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAWP"
// -- flags
// CHECK-SAME: i32 0 },
public struct NativeGenericType<T>: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"$sSi28protocol_conformance_records8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- type metadata
// CHECK-SAME: @"{{got.|\\01__imp__?}}$sSiMn"
// -- witness table
// CHECK-SAME: @"$sSi28protocol_conformance_records8RuncibleAAWP"
// -- reserved
// CHECK-SAME: i32 8
// CHECK-SAME: }
extension Int: Runcible {
public func runce() {}
}
// For a resilient struct, reference the NominalTypeDescriptor
// CHECK-LABEL: @"$s16resilient_struct4SizeV28protocol_conformance_records8RuncibleADMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- nominal type descriptor
// CHECK-SAME: @"{{got.|\\01__imp__?}}$s16resilient_struct4SizeVMn"
// -- witness table
// CHECK-SAME: @"$s16resilient_struct4SizeV28protocol_conformance_records8RuncibleADWP"
// -- reserved
// CHECK-SAME: i32 8
// CHECK-SAME: }
extension Size: Runcible {
public func runce() {}
}
// A non-dependent type conforming to a protocol with associated conformances
// does not require a generic witness table.
public protocol Simple {}
public protocol AssociateConformance {
associatedtype X : Simple
}
public struct Other : Simple {}
public struct Concrete : AssociateConformance {
public typealias X = Other
}
// CHECK-LABEL: @"$s28protocol_conformance_records8ConcreteVAA20AssociateConformanceAAMc" ={{ dllexport | protected | }}constant
// -- protocol descriptor
// CHECK-SAME: @"$s28protocol_conformance_records20AssociateConformanceMp"
// -- nominal type descriptor
// CHECK-SAME: @"$s28protocol_conformance_records8ConcreteVMn"
// -- witness table
// CHECK-SAME: @"$s28protocol_conformance_records8ConcreteVAA20AssociateConformanceAAWP"
// -- no flags are set, and no generic witness table follows
// CHECK-SAME: i32 0 }
public protocol Spoon { }
// Conditional conformances
// CHECK-LABEL: {{^}}@"$s28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlMc" ={{ dllexport | protected | }}constant
// -- protocol descriptor
// CHECK-SAME: @"$s28protocol_conformance_records5SpoonMp"
// -- nominal type descriptor
// CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVMn"
// -- witness table accessor
// CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA5Spoon
// -- flags
// CHECK-SAME: i32 131328
// -- conditional requirement #1
// CHECK-SAME: i32 128,
// CHECK-SAME: i32 0,
// CHECK-SAME: @"$s28protocol_conformance_records5SpoonMp"
// CHECK-SAME: }
extension NativeGenericType : Spoon where T: Spoon {
public func runce() {}
}
// Retroactive conformance
// CHECK-LABEL: @"$sSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsMc" ={{ dllexport | protected | }}constant
// -- protocol descriptor
// CHECK-SAME: @"{{got.|\\01__imp__?}}$s18resilient_protocol22OtherResilientProtocolMp"
// -- nominal type descriptor
// CHECK-SAME: @"{{got.|\\01__imp__?}}$sSiMn"
// -- witness table pattern
// CHECK-SAME: i32 0,
// -- flags
// CHECK-SAME: i32 131144,
// -- module context for retroactive conformance
// CHECK-SAME: @"$s28protocol_conformance_recordsMXM"
// CHECK-SAME: }
extension Int : OtherResilientProtocol { }
// Dependent conformance
// CHECK-LABEL: @"$s28protocol_conformance_records9DependentVyxGAA9AssociateAAMc" ={{ dllexport | protected | }}constant
// -- protocol descriptor
// CHECK-SAME: @"$s28protocol_conformance_records9AssociateMp"
// -- nominal type descriptor
// CHECK-SAME: @"$s28protocol_conformance_records9DependentVMn"
// -- witness table pattern
// CHECK-SAME: @"$s28protocol_conformance_records9DependentVyxGAA9AssociateAAWp"
// -- flags
// CHECK-SAME: i32 131072,
// -- number of words in witness table
// CHECK-SAME: i16 2,
// -- number of private words in witness table + bit for "needs instantiation"
// CHECK-SAME: i16 1
// CHECK-SAME: }
extension Dependent : Associate {
public typealias X = (T, T)
}
// CHECK-LABEL: @"$s28protocol_conformance_records9AssociateHr" = private constant
// CHECK-LABEL: @"$s28protocol_conformance_records8RuncibleHr" = private constant
// CHECK-LABEL: @"$s28protocol_conformance_records5SpoonHr" = private constant
// CHECK-LABEL: @"$s28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAHc" = private constant
// CHECK-LABEL: @"$s28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAHc" = private constant
// CHECK-LABEL: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAHc" = private constant
// CHECK-LABEL: @"$s16resilient_struct4SizeV28protocol_conformance_records8RuncibleADHc" = private constant
// CHECK-LABEL: @"$s28protocol_conformance_records8ConcreteVAA20AssociateConformanceAAHc" = private constant
// CHECK-LABEL: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlHc" = private constant
// CHECK-LABEL: @"$sSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsHc" = private constant
| apache-2.0 | 9e8e9944ca1673f35ac60b3d89f039ee | 42.085227 | 177 | 0.701833 | 4.079075 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/TabContentsScripts/FormPostHelper.swift | 2 | 3173 | // 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 WebKit
struct FormPostData {
let action: URL
let method: String
let target: String
let enctype: String
let requestBody: Data
init?(messageBody: Any) {
guard let messageBodyDict = messageBody as? [String: String],
let actionString = messageBodyDict["action"],
let method = messageBodyDict["method"],
let target = messageBodyDict["target"],
let enctype = messageBodyDict["enctype"],
let requestBodyString = messageBodyDict["requestBody"],
let action = URL(string: actionString),
let requestBody = requestBodyString.data(using: .utf8)
else {
return nil
}
self.action = action
self.method = method
self.target = target
self.enctype = enctype
self.requestBody = requestBody
}
func matchesNavigationAction(_ navigationAction: WKNavigationAction) -> Bool {
let request = navigationAction.request
let headers = request.allHTTPHeaderFields ?? [:]
if self.action == request.url,
self.method == request.httpMethod,
self.enctype == headers["Content-Type"] {
return true
}
return false
}
func urlRequestWithHeaders(_ headers: [String: String]?) -> URLRequest {
var urlRequest = URLRequest(url: action)
urlRequest.httpMethod = method
urlRequest.allHTTPHeaderFields = headers ?? [:]
urlRequest.setValue(enctype, forHTTPHeaderField: "Content-Type")
urlRequest.httpBody = requestBody
return urlRequest
}
}
class FormPostHelper: TabContentScript {
fileprivate weak var tab: Tab?
fileprivate var blankTargetFormPosts: [FormPostData] = []
required init(tab: Tab) {
self.tab = tab
}
static func name() -> String {
return "FormPostHelper"
}
func scriptMessageHandlerName() -> String? {
return "formPostHelper"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard let formPostData = FormPostData(messageBody: message.body) else {
print("Unable to parse FormPostData from script message body.")
return
}
blankTargetFormPosts.append(formPostData)
}
func urlRequestForNavigationAction(_ navigationAction: WKNavigationAction) -> URLRequest {
guard let formPostData = blankTargetFormPosts.first(where: { $0.matchesNavigationAction(navigationAction) }) else {
return navigationAction.request
}
let request = formPostData.urlRequestWithHeaders(navigationAction.request.allHTTPHeaderFields)
if let index = blankTargetFormPosts.firstIndex(where: { $0.matchesNavigationAction(navigationAction) }) {
blankTargetFormPosts.remove(at: index)
}
return request
}
}
| mpl-2.0 | 29ef33aa12eb203bb4259bf312c2ce65 | 32.4 | 132 | 0.649228 | 5.12601 | false | false | false | false |
xiaoxinghu/OrgMarker | Sources/Regex.swift | 1 | 1628 | //
// Regex.swift
// OrgMarker
//
// Created by Xiaoxing Hu on 15/03/17.
//
//
import Foundation
#if !os(Linux)
typealias RegularExpression = NSRegularExpression
typealias TextCheckingResult = NSTextCheckingResult
#else
extension TextCheckingResult {
func rangeAt(_ idx: Int) -> NSRange {
return range(at: idx)
}
}
#endif
struct RegexMatchingResult {
let range: Range<String.Index>
let captures: [Range<String.Index>?]
}
fileprivate func transform(on string: String, result: TextCheckingResult) -> RegexMatchingResult {
return RegexMatchingResult(
range: string.range(from: result.range)!,
captures: (0..<result.numberOfRanges)
.map { result.rangeAt($0) }
.map { string.range(from: $0) })
}
extension RegularExpression {
func firstMatch(
in string: String,
options: RegularExpression.MatchingOptions = [],
range: Range<String.Index>) -> RegexMatchingResult? {
guard let result = firstMatch(
in: string,
options: options,
range: string.nsRange(from: range)) else {
return nil
}
return transform(on: string, result: result)
}
func matches(
in string: String,
options: RegularExpression.MatchingOptions = [],
range: Range<String.Index>) -> [RegexMatchingResult] {
let result = matches(
in: string,
options: options,
range: string.nsRange(from: range))
return result.map { transform(on: string, result: $0) }
}
}
| mit | e05574fe13d26d61209ecdb4ebfacbd7 | 25.688525 | 98 | 0.601351 | 4.4 | false | false | false | false |
aaroncrespo/Swift-Playgrounds | Algorithms/Algorithms.playground/Sources/Shuffle.swift | 1 | 700 | import Foundation
public extension CollectionType where Index == Int {
/// Return a copy of `self` with its elements shuffled
func shuffle() -> [Generator.Element] {
var list = Array(self)
list.shuffleInPlace()
return list
}
}
public extension MutableCollectionType where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffleInPlace() {
// empty and single-element collections don't shuffle
if isEmpty || count == 1 {
return
}
for i in 0..<count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
swap(&self[i], &self[j])
}
}
} | artistic-2.0 | 82da6920c1288cb6030e9a26d78bf612 | 27.04 | 66 | 0.575714 | 4.402516 | false | false | false | false |
WickedColdfront/Slide-iOS | Slide for Reddit/BannerLinkCellView.swift | 1 | 9871 | //
// BannerLinkCellView.swift
// Slide for Reddit
//
// Created by Carlos Crane on 6/25/17.
// Copyright © 2017 Haptic Apps. All rights reserved.
//
import UIKit
class BannerLinkCellView: LinkCellView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override func doConstraints() {
let target = CurrentType.banner
if(currentType == target && target != .banner){
return //work is already done
}
if(currentType == target && target == .banner && bigConstraint != nil){
self.contentView.addConstraint(bigConstraint!)
return
}
let metrics=["horizontalMargin":75,"top":0,"bottom":0,"separationBetweenLabels":0,"size": full ? 16 : 8, "labelMinHeight":75, "thumb": (SettingValues.largerThumbnail ? 75 : 50), "bannerHeight": submissionHeight] as [String: Int]
let views=["label":title, "body": textView, "image": thumbImage, "info": b, "upvote": upvote, "downvote" : downvote, "score": score, "comments": comments, "banner": bannerImage, "buttons":buttons, "box": box] as [String : Any]
var bt = "[buttons]-8-"
var bx = "[box]-8-"
if(SettingValues.hideButtonActionbar && !full){
bt = "[buttons(0)]-4-"
bx = "[box(0)]-4-"
}
self.contentView.removeConstraints(thumbConstraint)
thumbConstraint = []
if(target == .thumb){
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-8-[image(thumb)]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-12-[label]-8-[image(thumb)]-12-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-8-[label]-10-\(bx)|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[image]-(>=5)-\(bt)|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
} else if(target == .banner){
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-[image(0)]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-12-[label]-12-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
if(SettingValues.centerLeadImage || full){
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-8-[label]-8@999-[banner]-12@999-\(bx)|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:[info]-[banner]",
options: NSLayoutFormatOptions.alignAllLastBaseline,
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[info(45)]-8-[buttons]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[info]-8-[box]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
} else {
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[banner]-8@999-[label]-12@999-\(bx)|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[info(45)]-8@999-[label]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
}
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:\(bt)|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:\(bx)|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[banner]-0-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[info]-0-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
} else if(target == .text){
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-8-[image(0)]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-12-[label]-12-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-12-[body]-12-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-size-[label]-5@1000-[body]-12@1000-\(bx)|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:\(bt)|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
}
self.contentView.addConstraints(thumbConstraint)
currentType = target
if( target == .banner && bigConstraint != nil){
self.contentView.addConstraint(bigConstraint!)
return
}
}
}
| apache-2.0 | 20135d253a32a81da269836e0a1feb91 | 63.509804 | 237 | 0.436373 | 7.024911 | false | false | false | false |
davidkuchar/codepath-03-parsechat | ParseChat/ChatViewController.swift | 1 | 1148 | //
// ChatViewController.swift
// ParseChat
//
// Created by David Kuchar on 5/20/15.
// Copyright (c) 2015 David Kuchar. All rights reserved.
//
import UIKit
class ChatViewController: UIViewController {
@IBOutlet weak var chatMessageField: UITextField!
override func viewDidLoad() {
//when you want to logout:
//dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func onSendMessage(sender: AnyObject) {
let chatMessage = chatMessageField.text
var currentUser:PFUser = PFUser.currentUser()!
var message = PFObject(className:"Message")
message["text"] = chatMessage
message["user"] = currentUser
message.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
// The object has been saved.
println("Just sent \(chatMessage)")
} else {
// There was a problem, check error.description
println("oh no! \(error)")
}
}
}
}
| mit | 4dd57140ef8810f8fb7b6949d12e5452 | 23.956522 | 63 | 0.560976 | 5.19457 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/Swiftz/Sources/Swiftz/HList.swift | 3 | 7284 | //
// HList.swift
// Swiftz
//
// Created by Maxwell Swadling on 19/06/2014.
// Copyright (c) 2014-2016 Maxwell Swadling. All rights reserved.
//
#if SWIFT_PACKAGE
import Operadics
import Swiftx
#endif
/// An HList can be thought of like a tuple, but with list-like operations on
/// the types. Unlike tuples there is no simple construction syntax as with the
/// `(,)` operator. But what HLists lack in convenience they gain in
/// flexibility.
///
/// An HList is a purely static entity. All its attributes including its
/// length, the type of each element, and compatible operations on said elements
/// exist fully at compile time. HLists, like regular lists, support folds,
/// maps, and appends, only at the type rather than term level.
public protocol HList {
associatedtype Head
associatedtype Tail
static var isNil : Bool { get }
static var length : Int { get }
}
/// The cons HList node.
public struct HCons<H, T : HList> : HList {
public typealias Head = H
public typealias Tail = T
public let head : H
public let tail : T
public init(_ h : H, _ t : T) {
head = h
tail = t
}
public static var isNil : Bool {
return false
}
public static var length : Int {
return Tail.length.advanced(by: 1)
}
}
/// The Nil HList node.
public struct HNil : HList {
public typealias Head = Never
public typealias Tail = Never
public init() {}
public static var isNil : Bool {
return true
}
public static var length : Int {
return 0
}
}
/// `HAppend` is a type-level append of two `HList`s. They are instantiated
/// with the type of the first list (XS), the type of the second list (YS) and
/// the type of the result (XYS). When constructed, `HAppend` provides a safe
/// append operation that yields the appropriate HList for the given types.
public struct HAppend<XS, YS, XYS> {
public let append : (XS, YS) -> XYS
private init(_ append : @escaping (XS, YS) -> XYS) {
self.append = append
}
/// Creates an HAppend that appends Nil to a List.
public static func makeAppend<L : HList>() -> HAppend<HNil, L, L> {
return HAppend<HNil, L, L> { (_, l) in return l }
}
/// Creates an HAppend that appends two non-HNil HLists.
public static func makeAppend<T, A, B : HList, C>(_ h : HAppend<A, B, C>) -> HAppend<HCons<T, A>, B, HCons<T, C>> {
return HAppend<HCons<T, A>, B, HCons<T, C>> { (c, l) in
return HCons(c.head, h.append(c.tail, l))
}
}
}
/// `HMap` is a type-level map of a function (F) over an `HList`. An `HMap`
/// must, at the very least, takes values of its input type (A) to values of its
/// output type (R). The function parameter (F) does not necessarily have to be
/// a function, and can be used as an index for extra information that the map
/// function may need in its computation.
public struct HMap<F, A, R> {
public let map : (F, A) -> R
public init(_ map : @escaping (F, A) -> R) {
self.map = map
}
/// Returns an `HMap` that leaves all elements in the HList unchanged.
public static func identity<T>() -> HMap<(), T, T> {
return HMap<(), T, T> { (_, x) in
return x
}
}
/// Returns an `HMap` that applies a function to the elements of an HList.
public static func apply<T, U>() -> HMap<(T) -> U, T, U> {
return HMap<(T) -> U, T, U> { (f, x) in
return f(x)
}
}
/// Returns an `HMap` that composes two functions, then applies the new
/// function to elements of an `HList`.
public static func compose<X, Y, Z>() -> HMap<(), ((X) -> Y, (Y) -> Z), (X) -> Z> {
return HMap<(), ((X) -> Y, (Y) -> Z), (X) -> Z> { (_, fs) in
return fs.1 • fs.0
}
}
/// Returns an `HMap` that creates an `HCons` node out of a tuple of the
/// head and tail of an `HList`.
public static func hcons<H, T>() -> HMap<(), (H, T), HCons<H, T>> {
return HMap<(), (H, T), HCons<H, T>> { (_, p) in
return HCons(p.0, p.1)
}
}
/// Returns an `HMap` that uses an `HAppend` operation to append two
/// `HList`s together.
public static func happend<A, B, C>() -> HMap<HAppend<A, B, C>, (A, B), C> {
return HMap<HAppend<A, B, C>, (A, B), C> { (f, p) in
return f.append(p.0, p.1)
}
}
}
/// `HFold` is a type-level right fold over the values in an `HList`. Like an
/// `HMap`, an HFold carries a context (of type G). The actual fold takes
/// values of type V and an accumulator A to values of type R.
///
/// Using an `HFold` necessitates defining the type of its starting and ending
/// data. For example, a fold that reduces
/// `HCons<(Int) -> Int, HCons<(Int) -> Int, HCons<(Int) -> Int, HNil>>>` to
/// `(Int) -> Int` through composition will define two `typealias`es:
///
/// public typealias FList = HCons<(Int) -> Int, HCons<(Int) -> Int, HCons<(Int) -> Int, HNil>>>
///
/// public typealias FBegin = HFold<(), (Int) -> Int, FList, (Int) -> Int>
/// public typealias FEnd = HFold<(), (Int) -> Int, HNil, (Int) -> Int>
///
/// The fold above doesn't depend on a context, and carries values of type
/// `(Int) -> Int`, contained in a list of type `FList`, to an `HNil` node and
/// an ending value of type `(Int) -> Int`.
public struct HFold<G, V, A, R> {
public let fold : (G, V, A) -> R
private init(_ fold : @escaping (G, V, A) -> R) {
self.fold = fold
}
/// Creates an `HFold` object that folds a function over an `HNil` node.
///
/// This operation returns the starting value of the fold.
public static func makeFold<G, V>() -> HFold<G, V, HNil, V> {
return HFold<G, V, HNil, V> { (f, v, n) in
return v
}
}
/// Creates an `HFold` object that folds a function over an `HCons` node.
public static func makeFold<H, G, V, T, R, RR>(_ p : HMap<G, (H, R), RR>, _ h : HFold<G, V, T, R>) -> HFold<G, V, HCons<H, T>, RR> {
return HFold<G, V, HCons<H, T>, RR> { (f, v, c) in
return p.map(f, (c.head, h.fold(f, v, c.tail)))
}
}
}
/// Uncomment if Swift decides to allow tuple patterns. rdar://20989362
///// HCons<HCons<...>> Matcher (Induction Step): If we've hit this overloading, we should have a cons
///// node, or at least something that matches HCons<HNil>
//public func ~=<H : HList where H.Head : Equatable, H.Tail : HList, H.Tail.Head : Equatable, H.Tail.Tail : HList>(pattern : (H.Head, H.Tail), predicate : H) -> Bool {
// if H.isNil {
// return false
// }
//
// if let p = (predicate as? HCons<H.Head, H.Tail>), let ps = (p.tail as? HCons<H.Tail.Head, H.Tail.Tail>), let pt = (pattern.1 as? HCons<H.Tail.Head, H.Tail.Tail>) {
// return (p.head == predicate.0) && ((ps.head, ps.tail) ~= pt)
// } else if let p = (predicate as? HCons<H.Head, H.Tail>), let ps = (p.tail as? HNil) {
// return (p.head == pattern.0)
// }
// return error("Pattern match on HList expected HCons<HSCons<...>> or HCons<HNil> but got neither.")
//}
//
///// HCons<HNil> or HNil Matcher
//public func ~=<H : HList where H.Head : Equatable, H.Tail : HList>(pattern : (H.Head, H.Tail), predicate : H) -> Bool {
// if H.isNil {
// return false
// }
// if let p = (predicate as? HCons<H.Head, H.Tail>) {
// return (p.head == pattern.0)
// } else if let p = (predicate as? HNil) {
// return false
// }
// return error("Pattern match on HList expected HCons<HNil> or HNil but got neither.")
//}
//
///// HNil matcher.
//public func ~=<H : HList>(pattern : (), predicate : H) -> Bool {
// return H.isNil
//}
| apache-2.0 | 9b8c73ff6bb6cab2935431c26f0791b8 | 32.557604 | 167 | 0.622906 | 2.865801 | false | false | false | false |
optimizely/swift-sdk | Tests/OptimizelyTests-Common/OptimizelyDecisionTests.swift | 1 | 6111 | //
// Copyright 2021, Optimizely, Inc. and contributors
//
// 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 XCTest
class OptimizelyDecisionTests: XCTestCase {
let variables = OptimizelyJSON(map: ["k1": "v1"])!
let user = OptimizelyUserContext(optimizely: OptimizelyClient(sdkKey: "sdkKey"),
userId: "userId")
var decision: OptimizelyDecision!
override func setUpWithError() throws {
decision = OptimizelyDecision(variationKey: "value-variationKey",
enabled: true,
variables: variables,
ruleKey: "value-ruleKey",
flagKey: "value-flagKey",
userContext: user,
reasons: [])
}
func testHasFailed() {
XCTAssertFalse(decision.hasFailed)
let d = OptimizelyDecision.errorDecision(key: "kv",
user: user,
error: .sdkNotReady)
XCTAssert(d.hasFailed)
}
func testOptimizelyDecision_equal() {
var d = OptimizelyDecision(variationKey: "value-variationKey",
enabled: true,
variables: variables,
ruleKey: "value-ruleKey",
flagKey: "value-flagKey",
userContext: user,
reasons: [])
XCTAssert(d == decision)
d = OptimizelyDecision(variationKey: "value-variationKey",
enabled: false,
variables: variables,
ruleKey: "value-ruleKey",
flagKey: "value-flagKey",
userContext: user,
reasons: [])
XCTAssert(d != decision)
d = OptimizelyDecision(variationKey: "wrong-value",
enabled: false,
variables: variables,
ruleKey: "value-ruleKey",
flagKey: "value-flagKey",
userContext: user,
reasons: [])
XCTAssert(d != decision)
d = OptimizelyDecision(variationKey: "wrong-value",
enabled: false,
variables: OptimizelyJSON(map: ["k1": "v2"])!,
ruleKey: "value-ruleKey",
flagKey: "value-flagKey",
userContext: user,
reasons: [])
XCTAssert(d != decision)
d = OptimizelyDecision(variationKey: "wrong-value",
enabled: false,
variables: variables,
ruleKey: "value-ruleKey",
flagKey: "value-flagKey",
userContext: OptimizelyUserContext(optimizely: OptimizelyClient(sdkKey: "sdkKey"),
userId: "wrong-user"),
reasons: [])
XCTAssert(d != decision)
d = OptimizelyDecision(variationKey: "wrong-value",
enabled: false,
variables: variables,
ruleKey: "value-ruleKey",
flagKey: "value-flagKey",
userContext: user,
reasons: ["reason-1"])
XCTAssert(d != decision)
}
func testOptimizelyDecision_description1() {
let expected = """
{
variationKey: "value-variationKey"
enabled: true
variables: ["k1": "v1"]
ruleKey: "value-ruleKey"
flagKey: "value-flagKey"
userContext: { userId: userId, attributes: [:] }
reasons: [ ]
}
"""
XCTAssertEqual(decision.description, expected)
}
func testOptimizelyDecision_description2() {
let variables = OptimizelyJSON(map: ["k2": true])!
let user = OptimizelyUserContext(optimizely: OptimizelyClient(sdkKey: "sdkKey"),
userId: "userId",
attributes: ["age": 18])
let decision = OptimizelyDecision(variationKey: "value-variationKey",
enabled: true,
variables: variables,
ruleKey: "value-ruleKey",
flagKey: "value-flagKey",
userContext: user,
reasons: ["reason-1", "reason-2"])
let expected = """
{
variationKey: "value-variationKey"
enabled: true
variables: ["k2": true]
ruleKey: "value-ruleKey"
flagKey: "value-flagKey"
userContext: { userId: userId, attributes: ["age": Optional(18)] }
reasons: [
- reason-1
- reason-2
]
}
"""
XCTAssertEqual(decision.description, expected)
}
}
| apache-2.0 | 4e99dac74972dd2735f67828b8de333f | 40.290541 | 113 | 0.449026 | 5.93301 | false | false | false | false |
HearthStats/hearthstats-video-osx | VideoOsx/HearthstoneRecorder.swift | 1 | 9740 | //
// HearthstoneRecorder.swift
// VideoOsx
//
// Copyright (c) 2014 Charles Gutjahr. See LICENSE file for license details.
//
import Foundation
import Cocoa
import AppKit
import AVFoundation
public class HearthstoneRecorder : NSObject, AVCaptureFileOutputDelegate, AVCaptureFileOutputRecordingDelegate {
var pid = 0;
var windowId = 0;
var windowX = 0;
var windowY = 0;
var windowInvertedY = 0;
var windowHeight = 0;
var windowWidth = 0;
var captureSession: AVCaptureSession? = nil;
var captureScreenInput: AVCaptureScreenInput? = nil;
var captureMovieFileOutput: AVCaptureMovieFileOutput? = nil;
var screenRecordingFileNameString: String? = nil;
public func findPid() -> Int {
var newPid = 0;
let runningApps = NSRunningApplication.runningApplicationsWithBundleIdentifier("unity.Blizzard Entertainment.Hearthstone");
if let runningApps = runningApps as? Array<NSRunningApplication> {
for runningApp in runningApps {
if (runningApp.bundleIdentifier == "unity.Blizzard Entertainment.Hearthstone") {
newPid = Int(runningApp.processIdentifier);
}
}
}
println("findPid() old=\(pid) new=\(newPid)")
NSLog("findPid() old=\(pid) new=\(newPid)")
pid = newPid
return pid;
}
public func getHSWindowBounds() -> String {
let windowInfoRef = CGWindowListCopyWindowInfo(CGWindowListOption(kCGWindowListExcludeDesktopElements) | CGWindowListOption(kCGWindowListOptionOnScreenOnly), CGWindowID(0))
let windowInfosCFArray = windowInfoRef.takeRetainedValue()
let windowInfosNSArray = windowInfosCFArray as NSArray
var newWindowId = 0;
for windowInfo in windowInfosNSArray {
let dictionaryRef = windowInfo as Dictionary<String, AnyObject>
let thisPid = dictionaryRef[kCGWindowOwnerPID] as Int
if (thisPid == pid) {
// This window is a Hearthstone window
// When running in full-screen mode, Hearthstone has two windows: one for the game and one that appears to be a temporary desktop or space for the game to run in.
// The game window always has a kCGWindowLayer of zero, whereas the desktop has a non-zero kCGWindowLayer.
let windowLayer = dictionaryRef[kCGWindowLayer] as Int
if (windowLayer == 0) {
// This window has a zero kCGWindowLayer so it must be the main Hearthstone window
newWindowId = dictionaryRef[kCGWindowNumber] as Int
let boundsDictionary = dictionaryRef[kCGWindowBounds] as Dictionary<String, AnyObject>
let scale = NSScreen.mainScreen()?.backingScaleFactor
// println("### Scale=\(scale!)")
// NSLog("### Scale=\(scale!)")
let titleBar = 22; // OS X titlebar is usually 22 pixels high
if ((boundsDictionary["Height"] as Int) > 100) {
windowWidth = boundsDictionary["Width"] as Int
windowHeight = (boundsDictionary["Height"] as Int) - titleBar
windowX = boundsDictionary["X"] as Int
windowY = (boundsDictionary["Y"] as Int) + titleBar
// This should probably be replaced with a check of the display that Hearthstone is on
let screenSize: NSRect = NSScreen.mainScreen()!.frame
windowInvertedY = Int(screenSize.height) - windowY - windowHeight
// println("### Window bounds x=\(windowX) y=\(windowY) (inverted \(windowInvertedY)) h=\(windowHeight) w=\(windowWidth)")
// NSLog("### Window bounds x=\(windowX) y=\(windowY) (inverted \(windowInvertedY)) h=\(windowHeight) w=\(windowWidth)")
// println("### Screen bounds h=\(screenSize.height) w=\(screenSize.width)")
// NSLog("### Screen bounds h=\(screenSize.height) w=\(screenSize.width)")
return "Found Window ID \(newWindowId) x=\(windowX) y=\(windowY) h=\(windowHeight) w=\(windowWidth) scale=\(scale)"
} else {
let smallHeight = boundsDictionary["Height"] as Int
return "Window too small, height=\(smallHeight)"
}
}
}
}
windowId = newWindowId
return "Found Nothing"
}
private func getCaptureSessionPreset(width: Int, height: Int) -> String {
if (width <= 640 || height <= 480) {
return AVCaptureSessionPreset640x480
} else if (width <= 960 || height <= 540) {
return AVCaptureSessionPreset960x540
} else if (width <= 1280 || height <= 720) {
return AVCaptureSessionPreset1280x720
} else {
return AVCaptureSessionPresetMedium
}
}
public func startRecording() {
println("Starting recording of window \(windowId) (x=\(windowX),y=\(windowY),height=\(windowHeight),width=\(windowWidth))")
NSLog("Starting recording of window \(windowId) (x=\(windowX),y=\(windowY),height=\(windowHeight),width=\(windowWidth))")
captureSession = AVCaptureSession();
let sessionPreset = getCaptureSessionPreset(windowWidth, height: windowHeight)
if ((captureSession?.canSetSessionPreset(sessionPreset)) != nil) {
captureSession?.sessionPreset = sessionPreset
}
let display = CGMainDisplayID()
captureScreenInput = AVCaptureScreenInput(displayID: display)
if ((captureSession?.canAddInput(captureScreenInput)) != nil) {
captureSession?.addInput(captureScreenInput)
}
captureMovieFileOutput = AVCaptureMovieFileOutput()
captureMovieFileOutput?.delegate = self
if ((captureSession?.canAddOutput(captureMovieFileOutput)) != nil) {
captureSession?.addOutput(captureMovieFileOutput)
}
// Set up screen size
captureSession?.beginConfiguration()
captureScreenInput?.cropRect = CGRect(x: windowX, y: windowInvertedY, width: windowWidth, height: windowHeight)
captureScreenInput?.minFrameDuration = CMTimeMake(1, 25)
captureScreenInput?.scaleFactor = 1.0
captureSession?.commitConfiguration()
captureSession?.startRunning()
let suffix = arc4random()
let screenRecordingFileName = "/private/tmp/hearthstats/HearthStatsRecording_\(suffix).mp4".stringByStandardizingPath.fileSystemRepresentation()
screenRecordingFileNameString = NSString(bytes: screenRecordingFileName, length: Int(strlen(screenRecordingFileName)), encoding: NSASCIIStringEncoding)!
println("screenRecordingFileName is \(screenRecordingFileNameString!)")
NSLog("screenRecordingFileName is \(screenRecordingFileNameString!)")
let fileUrl = NSURL.fileURLWithPath(screenRecordingFileNameString!)
captureMovieFileOutput?.startRecordingToOutputFileURL(fileUrl, recordingDelegate: self)
}
public func stopRecording() -> String {
println("Stopping recording of window \(windowId) (x=\(windowX),y=\(windowY),height=\(windowHeight),width=\(windowWidth))")
NSLog("Stopping recording of window \(windowId) (x=\(windowX),y=\(windowY),height=\(windowHeight),width=\(windowWidth))")
captureMovieFileOutput?.stopRecording()
captureSession?.stopRunning()
return screenRecordingFileNameString!
}
public func captureOutputShouldProvideSampleAccurateRecordingStart(captureOutput: AVCaptureOutput!) -> Bool {
// We don't require frame accurate start when we start a recording. If we answer YES, the capture output
// applies outputSettings immediately when the session starts previewing, resulting in higher CPU usage
// and shorter battery life.
return false
}
public func captureOutput(captureOutput: AVCaptureFileOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
// TODO
}
public func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
// TODO
}
public func captureOutput(captureOutput: AVCaptureFileOutput!, didPauseRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
// TODO
}
public func captureOutput(captureOutput: AVCaptureFileOutput!, didResumeRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
// TODO
}
public func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
// TODO
}
public func captureOutput(captureOutput: AVCaptureFileOutput!, willFinishRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
// TODO
}
} | bsd-3-clause | 176c2d7753716787a951b345fd42b589 | 42.293333 | 187 | 0.622485 | 5.565714 | false | false | false | false |
swillsea/DailyDiary | DailyDiary/EntriesVC.swift | 1 | 8289 | //
// EntriesVC.swift
// Quotidian
//
// Created by Sam on 5/9/16.
// Copyright © 2016 Sam Willsea, Pei Xiong, and Michael Merrill. All rights reserved.
//
import UIKit
import CoreData
class EntriesVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, NSFetchedResultsControllerDelegate{
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var layoutButton: UIBarButtonItem!
var viewIsListLayout = true
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var entryResultsController: NSFetchedResultsController!
var resultsArray : [NSManagedObject]!
var sectionChanges = NSMutableArray()
var itemChanges = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation:UIStatusBarAnimation.None)
self.navigationController?.setNavigationBarHidden(false, animated: true)
prepareForCollectionView()
self.collectionView.reloadData()
}
func prepareForCollectionView() {
entryResultsController = CoreDataManager.sharedInstance.fetchCoreData()
entryResultsController.delegate = self
resultsArray = entryResultsController.fetchedObjects! as! [NSManagedObject]
self.collectionView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
}
// MARK: CollectionViewLayout
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if (resultsArray != nil) { return resultsArray.count }
else { return 0 }
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var collectionViewWidth : CGFloat = 30.0
if collectionView.frame.size.width > 30 {
collectionViewWidth = self.collectionView.frame.size.width //we need to use a constant so that in viewWillAppear the status bar changing doesn't cause layout problems when reloading collectionView
}
if viewIsListLayout {
return CGSize(width: (collectionViewWidth-20), height: 75)
} else {
return CGSize(width: collectionViewWidth/2, height: collectionViewWidth/2)
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
if viewIsListLayout {
return 10
} else {
return 0
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if viewIsListLayout {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("listCell", forIndexPath: indexPath) as! ListCell
cell.entry = entryResultsController.objectAtIndexPath(indexPath) as? Entry
return cell
} else {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("gridCell", forIndexPath: indexPath) as! GridCell
cell.entry = entryResultsController.objectAtIndexPath(indexPath) as? Entry
return cell
}
}
@IBAction func onLayoutButtonPressed(sender: UIBarButtonItem) {
if (viewIsListLayout) {
self.layoutButton.image = UIImage.init(named:"list")
self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
viewIsListLayout = false
} else {
self.layoutButton.image = UIImage.init(named:"grid")
self.collectionView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0)
self.collectionView.setContentOffset(CGPoint.init(x: 0, y: -10), animated: false)
viewIsListLayout = true
}
self.collectionView.reloadData()
}
//MARK: Required to use NSFetchedResultsController with UICollectionView
func controller(controller: NSFetchedResultsController, didChangeSection
sectionInfo: NSFetchedResultsSectionInfo, atIndex
sectionIndex: Int, forChangeType
type: NSFetchedResultsChangeType) {
let change = NSMutableDictionary()
change.setObject(sectionIndex, forKey:"type")
sectionChanges.addObject(change)
}
func controller(controller: NSFetchedResultsController,
didChangeObject anObject: AnyObject,
atIndexPath indexPath: NSIndexPath?,
forChangeType type: NSFetchedResultsChangeType,
newIndexPath: NSIndexPath?) {
let change = NSMutableDictionary()
switch type {
case NSFetchedResultsChangeType.Insert:
change.setObject(newIndexPath!, forKey:"type")
break;
case NSFetchedResultsChangeType.Delete:
change.setObject(indexPath!, forKey:"type")
break;
case NSFetchedResultsChangeType.Update:
change.setObject(indexPath!, forKey:"type")
break;
case NSFetchedResultsChangeType.Move:
change.setObject([indexPath!, newIndexPath!], forKey:"type")
break;
}
itemChanges .addObject(change)
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.collectionView.performBatchUpdates({
for change in self.sectionChanges {
change.enumerateKeysAndObjectsUsingBlock({ (key, obj, stop) in
switch key {
case NSFetchedResultsChangeType.Insert:
self.collectionView.insertSections(NSIndexSet.init(indexSet: obj as! NSIndexSet))
break;
case NSFetchedResultsChangeType.Delete:
self.collectionView.deleteSections(NSIndexSet.init(indexSet: obj as! NSIndexSet))
break;
default:
break;
}
})
}
for change in self.itemChanges {
change.enumerateKeysAndObjectsUsingBlock({ (key, obj, stop) in
switch key {
case NSFetchedResultsChangeType.Insert:
self.collectionView.insertItemsAtIndexPaths([obj as! NSIndexPath])
break;
case NSFetchedResultsChangeType.Delete:
self.collectionView.deleteItemsAtIndexPaths([obj as! NSIndexPath])
break;
case NSFetchedResultsChangeType.Update:
self.collectionView.reloadItemsAtIndexPaths([obj as! NSIndexPath])
break;
case NSFetchedResultsChangeType.Move:
self.collectionView.moveItemAtIndexPath(obj.objectAtIndex(0) as! NSIndexPath, toIndexPath: obj.objectAtIndex(1) as! NSIndexPath)
break;
default:
break;
}
})
}
}) { (Bool) in
self.sectionChanges.removeAllObjects()
self.itemChanges.removeAllObjects()
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toAddNew" {
let destVC = segue.destinationViewController as! AddOrEditVC // since we're going to a navigation controller
destVC.moc = self.moc
} else if segue.identifier == "toDayView" {
let destVC = segue.destinationViewController as! DayByDayVC
destVC.resultsArray = resultsArray
let indexpath = self.collectionView.indexPathsForSelectedItems()![0]
//let entry = resultsArray[indexpath.row] as! Entry
destVC.index = indexpath.row
destVC.moc = self.moc
}
}
}
| mit | eb5d97d41cc1b340921b4a9b53e543ac | 41.285714 | 208 | 0.628982 | 6.171258 | false | false | false | false |
mattadatta/sulfur | Sulfur/ViewStateManager.swift | 1 | 16165 | /*
This file is subject to the terms and conditions defined in
file 'LICENSE.txt', which is part of this source code package.
*/
import UIKit
import UIKit.UIGestureRecognizerSubclass
// MARK: - ViewStateManager
public final class ViewStateManager {
public typealias TouchEventCallback = (ViewStateManager, UIView, TouchEvent) -> Void
public struct TouchEvent: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let down = TouchEvent(rawValue: 1 << 0)
public static let downRepeat = TouchEvent(rawValue: 1 << 1)
public static let dragInside = TouchEvent(rawValue: 1 << 2)
public static let dragOutside = TouchEvent(rawValue: 1 << 3)
public static let dragEnter = TouchEvent(rawValue: 1 << 4)
public static let dragExit = TouchEvent(rawValue: 1 << 5)
public static let upInside = TouchEvent(rawValue: 1 << 6)
public static let upOutside = TouchEvent(rawValue: 1 << 7)
public static let cancel = TouchEvent(rawValue: 1 << 8)
}
public typealias StateEventCallback = (ViewStateManager, UIView, State, State) -> Void
public struct State: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let enabled = State(rawValue: 1 << 0)
public static let selected = State(rawValue: 1 << 1)
public static let highlighted = State(rawValue: 1 << 2)
}
public typealias GestureEventCallback = (ViewStateManager, UIView, GestureEvent) -> Void
public enum GestureEvent {
case tap
case longPress
var isTap: Bool {
switch self {
case .tap:
return true
default:
return false
}
}
var isLongPress: Bool {
switch self {
case .longPress:
return true
default:
return false
}
}
}
public final class Token: Hashable {
fileprivate enum Action {
case touch(event: TouchEvent, callback: TouchEventCallback)
case gesture(event: GestureEvent, callback: GestureEventCallback)
case state(callback: StateEventCallback)
var gestureEvent: GestureEvent? {
switch self {
case .gesture(let event, _):
return event
default:
return nil
}
}
}
fileprivate weak var stateManager: ViewStateManager?
fileprivate let action: Action
fileprivate init(stateManager: ViewStateManager, touchEvent: TouchEvent, callback: @escaping TouchEventCallback) {
self.stateManager = stateManager
self.action = .touch(event: touchEvent, callback: callback)
}
fileprivate init(stateManager: ViewStateManager, gestureEvent: GestureEvent, callback: @escaping GestureEventCallback) {
self.stateManager = stateManager
self.action = .gesture(event: gestureEvent, callback: callback)
}
fileprivate init(stateManager: ViewStateManager, callback: @escaping StateEventCallback) {
self.stateManager = stateManager
self.action = .state(callback: callback)
}
deinit {
self.unsubscribe()
}
public func store() {
guard !self.isStored else { return }
self.stateManager?.storedRegistry.insert(self)
}
public func removeFromStore() {
guard self.isStored else { return }
let _ = self.stateManager?.storedRegistry.remove(self)
}
public var isStored: Bool {
return self.stateManager?.storedRegistry.contains(self) ?? false
}
public func unsubscribe() {
guard self.isSubscribed else { return }
self.stateManager?.unsubscribe(with: self)
}
public var isSubscribed: Bool {
return self.stateManager?.weakRegistry.contains(WeakReference(referent: self)) ?? false
}
public var hashValue: Int {
return ObjectIdentifier(self).hashValue
}
public static func == (lhs: Token, rhs: Token) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
}
fileprivate final class TouchGestureRecognizer: UIGestureRecognizer, UIGestureRecognizerDelegate {
weak var stateManager: ViewStateManager?
init(stateManager: ViewStateManager) {
self.stateManager = stateManager
super.init(target: stateManager, action: #selector(stateManager.handleGestureRecognizer(_:)))
self.delegate = self
}
var isTouchInside = false
var isTracking = false
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
override func canPrevent(_ preventedGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
override func canBePrevented(by preventingGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
guard let stateManager = self.stateManager, stateManager.view != nil else { return }
self.isTouchInside = true
self.isTracking = true
let touchEvent: TouchEvent = touches.count > 1 ? [.down, .downRepeat] : .down
stateManager.dispatch(touchEvent)
stateManager.state.insert(.highlighted)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
guard let stateManager = self.stateManager, let view = stateManager.view else { return }
guard let touch = touches.first else { return }
let wasTouchInside = self.isTouchInside
self.isTouchInside = view.point(inside: touch.location(in: view), with: event)
let touchEvent: TouchEvent = {
var touchEvent: TouchEvent = self.isTouchInside ? .dragInside : .dragOutside
if wasTouchInside != self.isTouchInside {
touchEvent.insert(self.isTouchInside ? .dragEnter : .dragExit)
}
return touchEvent
}()
stateManager.dispatch(touchEvent)
if self.isTouchInside {
stateManager.state.insert(.highlighted)
} else {
stateManager.state.remove(.highlighted)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesEnded(touches, with: event)
guard let stateManager = self.stateManager, let view = stateManager.view else { return }
guard let touch = touches.first else { return }
self.isTouchInside = view.point(inside: touch.location(in: view), with: event)
let touchEvent: TouchEvent = self.isTouchInside ? .upInside : .upOutside
self.isTracking = false
self.isTouchInside = false
stateManager.dispatch(touchEvent)
stateManager.state.remove(.highlighted)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesCancelled(touches, with: event)
guard let stateManager = self.stateManager, stateManager.view != nil else { return }
self.isTracking = false
self.isTouchInside = false
let touchEvent: TouchEvent = .cancel
stateManager.dispatch(touchEvent)
stateManager.state.remove(.highlighted)
}
}
fileprivate dynamic func handleGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer === self.touchGestureRecognizer {
// Do nothing
} else if gestureRecognizer == self.tapGestureRecognizer && gestureRecognizer.state == .ended {
self.dispatch(.tap)
} else if gestureRecognizer == self.longPressGestureRecognizer && gestureRecognizer.state == .began {
self.dispatch(.longPress)
}
}
public fileprivate(set) weak var view: UIView?
fileprivate var touchGestureRecognizer: TouchGestureRecognizer!
fileprivate var tapGestureRecognizer: UITapGestureRecognizer!
fileprivate var longPressGestureRecognizer: UILongPressGestureRecognizer!
public var isTracking: Bool { return self.touchGestureRecognizer.isTracking }
public init(view: UIView) {
self.view = view
self.touchGestureRecognizer = TouchGestureRecognizer(stateManager: self)
view.addGestureRecognizer(self.touchGestureRecognizer)
self.tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleGestureRecognizer(_:)))
self.longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleGestureRecognizer(_:)))
}
public var state: State = .enabled {
didSet {
guard self.state != oldValue else { return }
self.dispatchStateChange(from: oldValue, to: self.state)
}
}
public var configuration: ViewStateManagerConfiguration? {
willSet { self.configuration?.didDisassociate(with: self) }
didSet { self.configuration?.didAssociate(with: self) }
}
fileprivate var weakRegistry: Set<WeakReference<Token>> = [] {
didSet {
guard let view = self.view else { return }
view.removeGestureRecognizer(self.tapGestureRecognizer)
view.removeGestureRecognizer(self.longPressGestureRecognizer)
let gestureEvents = self.weakRegistry.flatMap({ $0.referent?.action.gestureEvent })
if !gestureEvents.filter({ $0.isTap }).isEmpty {
view.addGestureRecognizer(self.tapGestureRecognizer)
}
if !gestureEvents.filter({ $0.isLongPress }).isEmpty {
view.addGestureRecognizer(self.longPressGestureRecognizer)
}
}
}
fileprivate var storedRegistry: Set<Token> = []
public func subscribe(to touchEvent: TouchEvent, callback: @escaping TouchEventCallback) -> Token {
let token = Token(stateManager: self, touchEvent: touchEvent, callback: callback)
self.weakRegistry.insert(WeakReference(referent: token))
return token
}
public func subscribe(to gestureEvent: GestureEvent, callback: @escaping GestureEventCallback) -> Token {
let token = Token(stateManager: self, gestureEvent: gestureEvent, callback: callback)
self.weakRegistry.insert(WeakReference(referent: token))
return token
}
public func subscribeToStateEvent(callback: @escaping StateEventCallback) -> Token {
let token = Token(stateManager: self, callback: callback)
self.weakRegistry.insert(WeakReference(referent: token))
return token
}
public func unsubscribe(with token: Token) {
self.weakRegistry.remove(WeakReference(referent: token))
self.storedRegistry.remove(token)
token.stateManager = nil
}
fileprivate func dispatch(_ touchEvent: TouchEvent) {
guard let view = self.view else { return }
self.weakRegistry.forEach { weakToken in
guard let token = weakToken.referent else { return }
switch token.action {
case .touch(let event, let callback):
if !event.intersection(touchEvent).isEmpty {
callback(self, view, touchEvent)
}
default:
break
}
}
self.configuration?.viewStateManager(self, didDispatch: touchEvent)
}
fileprivate func dispatch(_ gestureEvent: GestureEvent) {
guard let view = self.view else { return }
self.weakRegistry.forEach { weakToken in
guard let token = weakToken.referent else { return }
switch token.action {
case .gesture(let event, let callback):
if event == gestureEvent {
callback(self, view, event)
}
default:
break
}
}
self.configuration?.viewStateManager(self, didDispatch: gestureEvent)
}
fileprivate func dispatchStateChange(from fromState: State, to toState: State) {
guard let view = self.view else { return }
self.weakRegistry.forEach { weakToken in
guard let token = weakToken.referent else { return }
switch token.action {
case .state(let callback):
callback(self, view, fromState, toState)
default:
break
}
}
self.configuration?.viewStateManager(self, didDispatchStateChangeFrom: fromState, to: toState)
}
}
public extension ViewStateManager {
fileprivate func includeState(_ newState: State, include: Bool) {
if include {
self.state.insert(newState)
} else {
self.state.remove(newState)
}
}
public func toggle(_ state: State) {
self.state.formSymmetricDifference(state)
}
public var isEnabled: Bool {
get { return self.state.contains(.enabled) }
set { self.includeState(.enabled, include: newValue) }
}
public var isSelected: Bool {
get { return self.state.contains(.selected) }
set { self.includeState(.selected, include: newValue) }
}
public var isHighlighted: Bool {
get { return self.state.contains(.highlighted) }
set { self.includeState(.highlighted, include: newValue) }
}
}
public protocol ViewStateManagerConfiguration: class {
var viewStateManagerFn: (() -> ViewStateManager?)? { get set }
func didAssociate(with viewStateManager: ViewStateManager)
func didDisassociate(with viewStateManager: ViewStateManager)
func viewStateManager(_ viewStateManager: ViewStateManager, didDispatch touchEvent: ViewStateManager.TouchEvent)
func viewStateManager(_ viewStateManager: ViewStateManager, didDispatch gestureEvent: ViewStateManager.GestureEvent)
func viewStateManager(_ viewStateManager: ViewStateManager, didDispatchStateChangeFrom fromState: ViewStateManager.State, to toState: ViewStateManager.State)
}
fileprivate struct ViewStateManagerConfigurationKeys {
static var stateManagerKey: UInt8 = 0
}
public extension ViewStateManagerConfiguration {
public var viewStateManager: ViewStateManager? {
return self.viewStateManagerFn?()
}
}
private let contextual_viewStateManagerKey = "Sulfur.ViewStateManager"
public extension Contextual where Self: UIView {
fileprivate var _stateManager: ViewStateManager? {
get { return self.retrieveValue(forKey: contextual_viewStateManagerKey) }
set { self.store(key: contextual_viewStateManagerKey, storage: .strongOrNil(object: newValue)) }
}
public var stateManager: ViewStateManager {
guard let stateManager = self._stateManager else {
let newManager = ViewStateManager(view: self)
self._stateManager = newManager
return newManager
}
return stateManager
}
}
public extension Contextual {
public func stateManager(for view: UIView) -> ViewStateManager {
let key = "contextual_viewStateManagerKey/\(view.hashValue)"
guard let stateManager: ViewStateManager = self.retrieveValue(forKey: key) else {
let stateManager = ViewStateManager(view: view)
self.store(key: key, storage: .strong(object: stateManager))
return stateManager
}
return stateManager
}
}
| mit | a8c6c8ff09a38f514507bca9db7634d7 | 35.325843 | 161 | 0.637303 | 5.196078 | false | false | false | false |
marty-suzuki/FluxCapacitor | Examples/Flux/FluxCapacitorSampleTests/Mock/RepositoryMock.swift | 2 | 1045 | //
// RepositoryMock.swift
// FluxCapacitorSample
//
// Created by marty-suzuki on 2017/08/22.
// Copyright © 2017年 marty-suzuki. All rights reserved.
//
import Foundation
@testable import FluxCapacitorSample
import GithubKit
extension Repository {
static func mock(name: String = "FluxCapacitor",
stargazerCount: Int = 100,
forkCount: Int = 10,
url: String = "https://github.com/marty-suzuki/FluxCapacitor") -> Repository {
let json: [String: Any] = [
"name" : name,
"stargazers" : ["totalCount" : stargazerCount],
"forks" : ["totalCount" : forkCount],
"url" : url,
"updatedAt" : "2015-02-07T18:51:47Z",
"languages": ["nodes": []]
]
do {
let data = try JSONSerialization.data(withJSONObject: json, options: [])
return try JSONDecoder().decode(Repository.self, from: data)
} catch let e {
fatalError("\(e)")
}
}
}
| mit | a11cd05a489691108f6c91d1bf93ae59 | 27.944444 | 99 | 0.550864 | 4.118577 | false | false | false | false |
DonMag/ScratchPad | Swift3/scratchy/XC8.playground/Pages/PointOnLine.xcplaygroundpage/Contents.swift | 1 | 9461 |
import Foundation
import UIKit
import PlaygroundSupport
var arrayOfPoints: [CGPoint] = [
CGPoint(x: 0.396464773760275, y: 0.840485369411425),
CGPoint(x: 0.353336097245244, y: 0.446583434796544),
CGPoint(x: 0.318692772311881, y: 0.886428433223031),
CGPoint(x: 0.0155828494083288, y: 0.584090220317272),
CGPoint(x: 0.0155828494083288, y: 0.384090220317272),
CGPoint(x: 0.159368626531805, y: 0.383715874807194),
CGPoint(x: 0.691004373382196, y: 0.1588589135927364),
CGPoint(x: 0.691004373382196, y: 0.3588589135927364),
CGPoint(x: 0.899854306161604, y: 0.163545950630365),
CGPoint(x: 0.159071502581806, y: 0.533064714021855),
CGPoint(x: 0.604144189711239, y: 0.582699021207219),
CGPoint(x: 0.269971117907016, y: 0.390478195463409),
CGPoint(x: 0.293400570118951, y: 0.742377406033981),
CGPoint(x: 0.298525606318119, y: 0.0755380785377824),
CGPoint(x: 0.404982633583334, y: 0.857377942708183),
CGPoint(x: 0.941968323291899, y: 0.662830659789996),
CGPoint(x: 0.846475779930007, y: 0.00275508142688352),
CGPoint(x: 0.462379245025485, y: 0.532596024438298),
CGPoint(x: 0.78787662089292, y: 0.265612234971371),
CGPoint(x: 0.98275226310103, y: 0.30678513061418),
CGPoint(x: 0.600855136489105, y: 0.608715653358658),
CGPoint(x: 0.212438798201187, y: 0.885895130587606),
CGPoint(x: 0.304657101745793, y: 0.15185986406857),
CGPoint(x: 0.337661902873531, y: 0.387476950965358),
CGPoint(x: 0.643609828900129, y: 0.753553275640016),
CGPoint(x: 0.603616098781568, y: 0.53162825175081),
CGPoint(x: 0.459360316334315, y: 0.652488446971034),
CGPoint(x: 0.32718116385065, y: 0.946370485960081),
CGPoint(x: 0.368039867432817, y: 0.943890339354468),
CGPoint(x: 0.00742826171906685, y: 0.516599949702389),
CGPoint(x: 0.272770952753351, y: 0.024299155634651),
CGPoint(x: 0.591954502437812, y: 0.2049635097516)
]
func pointAboveLine(point: CGPoint, p1: CGPoint, p2: CGPoint) -> Int {
// first, horizontally sort the points in the line
var first: CGPoint = CGPoint.zero
var second: CGPoint = CGPoint.zero
if p1.x > p2.x {
first = p2
second = p1
} else {
first = p1
second = p2
}
let v1 = CGPoint(x: second.x - first.x, y: second.y - first.y)
let v2 = CGPoint(x: second.x - point.x, y: second.y - point.y)
let xp = v1.x * v2.y - v1.y * v2.x
// above
if (xp > 0) {
return 1;
}
// below
else if (xp < 0) {
return -1;
}
// exactly on the line
else {
return 0;
}
}
public class SimpleLine: UIView {
var myArrayOfPoints = [CGPoint]()
public override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func draw(_ rect: CGRect) {
let x0 = 0.0
let x1 = Double(rect.maxX)
let y0 = 0.0
let y1 = Double(rect.maxY)
let desiredDistance = 100.0
let context = UIGraphicsGetCurrentContext()
context?.setLineWidth(4.0)
context?.setStrokeColor(UIColor.darkGray.cgColor)
context?.move(to: CGPoint(x: x0, y: y0))
context?.addLine(to: CGPoint(x: x1, y: y1))
context?.strokePath()
let baseLen = x1 - x0
let legLen = y1 - y0
let hypLen = sqrt(baseLen * baseLen + legLen * legLen)
let dRatio = desiredDistance / hypLen
let x2 = ((1 - desiredDistance) * x0) + (dRatio * x1)
let y2 = ((1 - desiredDistance) * y0) + (dRatio * y1)
context?.setFillColor(UIColor.red.cgColor)
context?.setLineWidth(1.0)
context?.fillEllipse(in: CGRect(x: x2 - 4, y: y2 - 4, width: 8.0, height: 8.0))
context?.strokeEllipse(in: CGRect(x: x2 - 12, y: y2 - 12, width: 24.0, height: 24.0))
context?.stroke(CGRect(x: x2 - 12, y: y2 - 12, width: 24.0, height: 24.0))
context?.setFillColor(UIColor.blue.cgColor)
context?.setLineWidth(1.0)
for pt in myArrayOfPoints {
context?.fillEllipse(in: CGRect(x: pt.x - 3, y: pt.y - 3, width: 6.0, height: 6.0))
}
if myArrayOfPoints.count > 2 {
context?.setFillColor(UIColor.orange.cgColor)
let npt = myArrayOfPoints[0] as CGPoint
context?.fillEllipse(in: CGRect(x: npt.x - 3, y: npt.y - 3, width: 6.0, height: 6.0))
context?.move(to: myArrayOfPoints[0])
for i in 1..<myArrayOfPoints.count {
context?.addLine(to: myArrayOfPoints[i])
}
context?.closePath()
context?.strokePath()
}
}
}
func angleBetween(point1: CGPoint, point2: CGPoint) -> CGFloat {
return atan2(point1.x - point2.x, point1.y - point2.y)
}
let container = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 600))
//
container.backgroundColor = UIColor.green
let playW = 500
let playH = 400
let firstLine = SimpleLine(frame: CGRect(x: 0, y: 0, width: playW, height: playH))
container.addSubview(firstLine)
let pt1 = CGPoint(x: 0.0, y: 0.0)
let pt2 = CGPoint(x: 400.0, y: 300.0)
var pt = CGPoint(x: 10.0, y: 100.0)
var n = pointAboveLine(point: pt, p1: pt1, p2: pt2)
var a: CGFloat = 0.0
print("Above / Below? \(n)")
pt = CGPoint(x: 100.0, y: 10.0)
n = pointAboveLine(point: pt, p1: pt1, p2: pt2)
print("Above / Below? \(n)")
var points6 = arrayOfPoints[1...7]
var aPoints = points6.map { CGPoint(x: Int($0.x * CGFloat(playW)), y: Int($0.y * CGFloat(playH))) }
let t = aPoints[3]
aPoints[3] = aPoints[4]
aPoints[4] = t
for pt in aPoints {
n = pointAboveLine(point: pt, p1: pt1, p2: pt2)
print("Above / Below? \(pt.x), \(pt.y) \(n)")
}
var leftMost = aPoints.reduce(CGFloat.greatestFiniteMagnitude) { min($0, $1.x) }
print(leftMost)
var rightMost = aPoints.reduce(CGFloat.leastNormalMagnitude) { max($0, $1.x) }
print(rightMost)
//var lp = aPoints.max(by: ($0.x, $1.x))
//var lp = aPoints.max {
// $0.0.x != $1.0.x {
// return $0.x < $1.x
// } else {
// return $0.y > $1.y
// }
//}
var lp = aPoints.max { $0.0.x != $0.1.x ? $0.0.x > $0.1.x : $0.0.y > $0.1.y }
var rp = aPoints.max { $0.0.x != $0.1.x ? $0.0.x < $0.1.x : $0.0.y < $0.1.y }
print(lp)
print(rp)
var lp2 = aPoints.min { $0.0.x != $0.1.x ? $0.0.x < $0.1.x : $0.0.y < $0.1.y }
var rp2 = aPoints.max { $0.0.x != $0.1.x ? $0.0.x < $0.1.x : $0.0.y < $0.1.y }
print(lp2)
print(rp2)
let vlp = lp! as CGPoint
let vrp = rp! as CGPoint
let cx = vlp.x + ((vrp.x - vlp.x) / 2)
let cy = vlp.y + ((vrp.y - vlp.y) / 2)
let centerPT = CGPoint(x: cx, y: cy)
for pt in aPoints {
a = angleBetween(point1: centerPT, point2: pt)
print("Angle?", a, pt)
}
firstLine.myArrayOfPoints = aPoints
//var aBelow = aPoints.filter {
//// pointAboveLine(point: $0, p1: , p2: )
//}
//print(aPoints)
PlaygroundPage.current.liveView = container
PlaygroundPage.current.needsIndefiniteExecution = true
//for j in 1...30 {
// print("CGPoint(x: \(drand48()), y: \(drand48())),")
//}
//function point () {
// if (arguments.length === 1) {
// // either object or array
// if (arguments[0].length !== undefined) {
// // it's an array
// return arguments[0];
// }
// return [arguments[0].x, arguments[0].y];
// } else if (arguments.length === 2) {
// // point(x, y)
// return [arguments[0], arguments[1]];
// }
//}
//
//let geometry = {
// point: point,
// pointAboveLine: pointAboveLine
//}
//
//function findSmallest (array, key) {
// if (key === undefined) {
// key = function (value) {
// return value;
// };
// }
// return array.reduce(function (a, b, i, arr) {
// if (Math.min(key(a), key(b)) === key(a)) {
// return a;
// } else {
// return b;
// }
// }, Infinity);
//}
//
//function findLargest (array, key) {
// if (key === undefined) {
// key = function (value) {
// return value;
// };
// }
// return array.reduce(function (a, b, i, arr) {
// if (Math.max(key(a), key(b)) === key(a)) {
// return a;
// } else {
// return b;
// }
// }, Infinity);
//}
//
//function createNonIntersectingPolygon(initialPoints, amountOfPoints, minimumArea, maximumArea) {
// let remainingPoints = amountOfPoints - initialPoints.length;
//
// // algorithm to generate non intersecting polygons
// // http://stackoverflow.com/a/20623817/2302759
//
// // This way of generating new points is beyond bad
// // both the minimum and maximum area constraints are not satisfied
// // and all polygons end up biased to the right, this is because that made sense for my application
// // please take the time to find a better way to do this
// let lmax = Math.sqrt(maximumArea);
// let points = initialPoints;
// for (var i = 0; i < remainingPoints; i++) {
// points.push({
// x: initialPoints[0].x + ((Math.random() - 0.5) * 2) * lmax,
// y: initialPoints[0].y + Math.random() * lmax
// });
// }
//
// // (1) find the leftmost point p
// let leftmost = findSmallest(points, (point) => point.x);
// // (2) find rightmost point q
// let rightmost = findLargest(points, (point) => point.x);
//
// // (3) Partition the points into A, the set of points below pq
// // and B, the set of points above pq
// let A = points.filter(function (point) {
// return geometry.pointAboveLine(geometry.point(point), geometry.point(leftmost), geometry.point(rightmost)) === -1;
// });
// let B = points.filter(function (point) {
// return geometry.pointAboveLine(geometry.point(point), geometry.point(leftmost), geometry.point(rightmost)) === 1;
// });
//
// // (4) sort A by increasing x-coordinates
// A = A.sort((p1, p2) => p1.x > p2.x);
//
// // (5) sort B by decreasing x-coordinates
// B = B.sort((p1, p2) => p1.x < p2.x);
//
// // (6) assemble a polygon in this order [p, ...A, q, ...B];
//
// return [leftmost, ...A, rightmost, ...B];
//}
| mit | 308359199e96df0508d11689340722af | 25.650704 | 118 | 0.641581 | 2.493017 | false | false | false | false |
GreenCom-Networks/ios-charts | ChartsRealm/Classes/Data/RealmBaseDataSet.swift | 1 | 12240 | //
// RealmBaseDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import Realm
import Realm.Dynamic
public class RealmBaseDataSet: ChartBaseDataSet
{
public func initialize()
{
fatalError("RealmBaseDataSet is an abstract class, you must inherit from it. Also please do not call super.initialize().")
}
public required init()
{
super.init()
// default color
colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
initialize()
}
public override init(label: String?)
{
super.init()
// default color
colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
self.label = label
initialize()
}
public init(results: RLMResults?, yValueField: String, xIndexField: String?, label: String?)
{
super.init()
// default color
colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
self.label = label
_results = results
_yValueField = yValueField
_xIndexField = xIndexField
_results = _results?.sortedResultsUsingProperty(_xIndexField!, ascending: true)
notifyDataSetChanged()
initialize()
}
public convenience init(results: RLMResults?, yValueField: String, label: String?)
{
self.init(results: results, yValueField: yValueField, xIndexField: nil, label: label)
}
public convenience init(results: RLMResults?, yValueField: String, xIndexField: String?)
{
self.init(results: results, yValueField: yValueField, xIndexField: xIndexField, label: "DataSet")
}
public convenience init(results: RLMResults?, yValueField: String)
{
self.init(results: results, yValueField: yValueField)
}
public init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, label: String?)
{
super.init()
// default color
colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
self.label = label
_yValueField = yValueField
_xIndexField = xIndexField
if realm != nil
{
loadResults(realm: realm!, modelName: modelName)
}
initialize()
}
public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, label: String?)
{
self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, label: label)
}
public func loadResults(realm realm: RLMRealm, modelName: String)
{
loadResults(realm: realm, modelName: modelName, predicate: nil)
}
public func loadResults(realm realm: RLMRealm, modelName: String, predicate: NSPredicate?)
{
if predicate == nil
{
_results = realm.allObjects(modelName)
}
else
{
_results = realm.objects(modelName, withPredicate: predicate)
}
if _xIndexField != nil
{
_results = _results?.sortedResultsUsingProperty(_xIndexField!, ascending: true)
}
notifyDataSetChanged()
}
// MARK: - Data functions and accessors
internal var _results: RLMResults?
internal var _yValueField: String?
internal var _xIndexField: String?
internal var _cache = [ChartDataEntry]()
internal var _cacheFirst: Int = -1
internal var _cacheLast: Int = -1
internal var _yMax = Double(0.0)
internal var _yMin = Double(0.0)
/// the last start value used for calcMinMax
internal var _lastStart: Int = 0
/// the last end value used for calcMinMax
internal var _lastEnd: Int = 0
/// Makes sure that the cache is populated for the specified range
internal func ensureCache(start start: Int, end: Int)
{
if start <= _cacheLast && end >= _cacheFirst
{
return
}
guard let results = _results else { return }
if _cacheFirst == -1 || _cacheLast == -1
{
_cache.removeAll()
_cache.reserveCapacity(end - start + 1)
for i in UInt(start) ..< UInt(end + 1)
{
_cache.append(buildEntryFromResultObject(results.objectAtIndex(i), atIndex: i))
}
_cacheFirst = start
_cacheLast = end
}
if start < _cacheFirst
{
var newEntries = [ChartDataEntry]()
newEntries.reserveCapacity(start - _cacheFirst)
for i in UInt(start) ..< UInt(_cacheFirst)
{
newEntries.append(buildEntryFromResultObject(results.objectAtIndex(i), atIndex: i))
}
_cache.insertContentsOf(newEntries, at: 0)
_cacheFirst = start
}
if end > _cacheLast
{
for i in UInt(_cacheLast + 1) ..< UInt(end + 1)
{
_cache.append(buildEntryFromResultObject(results.objectAtIndex(i), atIndex: i))
}
_cacheLast = end
}
}
internal func buildEntryFromResultObject(object: RLMObject, atIndex: UInt) -> ChartDataEntry
{
let entry = ChartDataEntry(value: object[_yValueField!] as! Double, xIndex: _xIndexField == nil ? Int(atIndex) : object[_xIndexField!] as! Int)
return entry
}
/// Makes sure that the cache is populated for the specified range
internal func clearCache()
{
_cache.removeAll()
_cacheFirst = -1
_cacheLast = -1
}
/// Use this method to tell the data set that the underlying data has changed
public override func notifyDataSetChanged()
{
calcMinMax(start: _lastStart, end: _lastEnd)
}
public override func calcMinMax(start start: Int, end: Int)
{
let yValCount = self.entryCount
if yValCount == 0
{
return
}
var endValue : Int
if end == 0 || end >= yValCount
{
endValue = yValCount - 1
}
else
{
endValue = end
}
ensureCache(start: start, end: endValue)
if _cache.count == 0
{
return
}
_lastStart = start
_lastEnd = endValue
_yMin = DBL_MAX
_yMax = -DBL_MAX
for i in start ... endValue
{
let e = _cache[i - _cacheFirst]
if (!e.value.isNaN)
{
if (e.value < _yMin)
{
_yMin = e.value
}
if (e.value > _yMax)
{
_yMax = e.value
}
}
}
if (_yMin == DBL_MAX)
{
_yMin = 0.0
_yMax = 0.0
}
}
/// - returns: the minimum y-value this DataSet holds
public override var yMin: Double { return _yMin }
/// - returns: the maximum y-value this DataSet holds
public override var yMax: Double { return _yMax }
/// - returns: the number of y-values this DataSet represents
public override var entryCount: Int { return Int(_results?.count ?? 0) }
/// - returns: the value of the Entry object at the given xIndex. Returns NaN if no value is at the given x-index.
public override func yValForXIndex(x: Int) -> Double
{
let e = self.entryForXIndex(x)
if (e !== nil && e!.xIndex == x) { return e!.value }
else { return Double.NaN }
}
/// - returns: the entry object found at the given index (not x-index!)
/// - throws: out of bounds
/// if `i` is out of bounds, it may throw an out-of-bounds exception
public override func entryForIndex(i: Int) -> ChartDataEntry?
{
if i < _lastStart || i > _lastEnd
{
ensureCache(start: i, end: i)
}
return _cache[i - _lastStart]
}
/// - returns: the first Entry object found at the given xIndex with binary search.
/// If the no Entry at the specifed x-index is found, this method returns the Entry at the closest x-index.
/// nil if no Entry object at that index.
public override func entryForXIndex(x: Int, rounding: ChartDataSetRounding) -> ChartDataEntry?
{
let index = self.entryIndex(xIndex: x, rounding: rounding)
if (index > -1)
{
return entryForIndex(index)
}
return nil
}
/// - returns: the first Entry object found at the given xIndex with binary search.
/// If the no Entry at the specifed x-index is found, this method returns the Entry at the closest x-index.
/// nil if no Entry object at that index.
public override func entryForXIndex(x: Int) -> ChartDataEntry?
{
return entryForXIndex(x, rounding: .Closest)
}
/// - returns: the array-index of the specified entry
///
/// - parameter x: x-index of the entry to search for
public override func entryIndex(xIndex x: Int, rounding: ChartDataSetRounding) -> Int
{
guard let results = _results else { return -1 }
let foundIndex = results.indexOfObjectWithPredicate(
NSPredicate(format: "%K == %d", _xIndexField!, x)
)
// TODO: Figure out a way to quickly find the closest index
return Int(foundIndex)
}
/// - returns: the array-index of the specified entry
///
/// - parameter e: the entry to search for
public override func entryIndex(entry e: ChartDataEntry) -> Int
{
for i in 0 ..< _cache.count
{
if (_cache[i] === e || _cache[i].isEqual(e))
{
return _cacheFirst + i
}
}
return -1
}
/// Not supported on Realm datasets
public override func addEntry(e: ChartDataEntry) -> Bool
{
return false
}
/// Not supported on Realm datasets
public override func addEntryOrdered(e: ChartDataEntry) -> Bool
{
return false
}
/// Not supported on Realm datasets
public override func removeEntry(entry: ChartDataEntry) -> Bool
{
return false
}
/// Checks if this DataSet contains the specified Entry.
/// - returns: true if contains the entry, false if not.
public override func contains(e: ChartDataEntry) -> Bool
{
for entry in _cache
{
if (entry.isEqual(e))
{
return true
}
}
return false
}
/// Returns the fieldname that represents the "y-values" in the realm-data.
public var yValueField: String?
{
get
{
return _yValueField
}
}
/// Returns the fieldname that represents the "x-index" in the realm-data.
public var xIndexField: String?
{
get
{
return _xIndexField
}
}
// MARK: - NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! RealmBaseDataSet
copy._results = _results
copy._yValueField = _yValueField
copy._xIndexField = _xIndexField
copy._yMax = _yMax
copy._yMin = _yMin
copy._lastStart = _lastStart
copy._lastEnd = _lastEnd
return copy
}
}
| apache-2.0 | bb49fcafeefb07c62377d2439543fcb1 | 27.399072 | 151 | 0.551961 | 4.650456 | false | false | false | false |
CPRTeam/CCIP-iOS | OPass/Class+addition/OPassAPI/legacy.swift | 1 | 1325 | //
// legacy.swift
// OPass
//
// Created by 腹黒い茶 on 2019/6/17.
// 2019 OPass.
//
import Foundation
import SwiftyJSON
internal typealias OPassCompletionCallbackLegacy = ( (_ success: Bool, _ data: Any?, _ error: Error) -> Void )?
@objc class OPassNonSuccessDataResponseLegacy: NSObject {
@objc public var Response: HTTPURLResponse?
public var Data: Data?
@objc public var Obj: NSObject
public var Json: JSON?
init(_ response: HTTPURLResponse?, _ data: Data?, _ json: JSON?) {
self.Response = response
self.Data = data
self.Json = json
self.Obj = NSObject.init()
if let json = json {
if let obj = json.object as? NSObject {
self.Obj = obj
}
}
}
}
extension OPassAPI {
@objc static func DoLogin(byEventId eventId: String, withToken token: String, onCompletion completion: OPassCompletionCallbackLegacy) {
self.DoLogin(eventId, token) { success, data, error in
completion?(success, data as Any, error)
}
}
@objc static func RedeemCode(forEvent: String, withToken: String, completion: OPassCompletionCallbackLegacy) {
self.RedeemCode(forEvent, withToken) { success, data, error in
completion?(success, data as Any, error)
}
}
}
| gpl-3.0 | 5c552037c6ca2ec1cc91da4eca7046f5 | 28.931818 | 139 | 0.632498 | 4.167722 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/TabContentsScripts/ContextMenuHelper.swift | 2 | 5773 | // 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 WebKit
protocol ContextMenuHelperDelegate: AnyObject {
func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UIGestureRecognizer)
func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didCancelGestureRecognizer: UIGestureRecognizer)
}
class ContextMenuHelper: NSObject {
var touchPoint = CGPoint()
struct Elements {
let link: URL?
let image: URL?
let title: String?
let alt: String?
}
fileprivate weak var tab: Tab?
weak var delegate: ContextMenuHelperDelegate?
fileprivate var nativeHighlightLongPressRecognizer: UILongPressGestureRecognizer?
lazy var gestureRecognizer: UILongPressGestureRecognizer = {
let g = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressGestureDetected))
g.delegate = self
return g
}()
fileprivate(set) var elements: Elements?
required init(tab: Tab) {
super.init()
self.tab = tab
}
}
@available(iOS, obsoleted: 14.0)
extension ContextMenuHelper: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
// BVC KVO events for all changes on the webview will call this.
// It is called frequently during a page load (particularly on progress changes and URL changes).
// As of iOS 12, WKContentView gesture setup is async, but it has been called by the time
// the webview is ready to load an URL. After this has happened, we can override the gesture.
func replaceGestureHandlerIfNeeded() {
DispatchQueue.main.async {
if self.gestureRecognizerWithDescriptionFragment("ContextMenuHelper") == nil {
self.replaceWebViewLongPress()
}
}
}
private func replaceWebViewLongPress() {
// WebKit installs gesture handlers async. If `replaceWebViewLongPress` is called after a wkwebview in most cases a small delay is sufficient
// See also https://bugs.webkit.org/show_bug.cgi?id=193366
nativeHighlightLongPressRecognizer = gestureRecognizerWithDescriptionFragment("action=_highlightLongPressRecognized:")
if let nativeLongPressRecognizer = gestureRecognizerWithDescriptionFragment("action=_longPressRecognized:") {
nativeLongPressRecognizer.removeTarget(nil, action: nil)
nativeLongPressRecognizer.addTarget(self, action: #selector(self.longPressGestureDetected))
}
}
private func gestureRecognizerWithDescriptionFragment(_ descriptionFragment: String) -> UILongPressGestureRecognizer? {
let result = tab?.webView?.scrollView.subviews.compactMap({ $0.gestureRecognizers }).joined().first(where: {
(($0 as? UILongPressGestureRecognizer) != nil) && $0.description.contains(descriptionFragment)
})
return result as? UILongPressGestureRecognizer
}
@objc func longPressGestureDetected(_ sender: UIGestureRecognizer) {
if sender.state == .cancelled {
delegate?.contextMenuHelper(self, didCancelGestureRecognizer: sender)
return
}
guard sender.state == .began else { return }
// To prevent the tapped link from proceeding with navigation, "cancel" the native WKWebView
// `_highlightLongPressRecognizer`. This preserves the original behavior as seen here:
// https://github.com/WebKit/webkit/blob/d591647baf54b4b300ca5501c21a68455429e182/Source/WebKit/UIProcess/ios/WKContentViewInteraction.mm#L1600-L1614
if let nativeHighlightLongPressRecognizer = self.nativeHighlightLongPressRecognizer,
nativeHighlightLongPressRecognizer.isEnabled {
nativeHighlightLongPressRecognizer.isEnabled = false
nativeHighlightLongPressRecognizer.isEnabled = true
}
if let elements = self.elements {
delegate?.contextMenuHelper(self, didLongPressElements: elements, gestureRecognizer: sender)
self.elements = nil
}
}
}
extension ContextMenuHelper: TabContentScript {
class func name() -> String {
return "ContextMenuHelper"
}
func scriptMessageHandlerName() -> String? {
return "contextMenuMessageHandler"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard let data = message.body as? [String: AnyObject] else { return }
if let x = data["touchX"] as? Double, let y = data["touchY"] as? Double {
touchPoint = CGPoint(x: x, y: y)
}
var linkURL: URL?
if let urlString = data["link"] as? String,
let escapedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .URLAllowed) {
linkURL = URL(string: escapedURLString)
}
var imageURL: URL?
if let urlString = data["image"] as? String,
let escapedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .URLAllowed) {
imageURL = URL(string: escapedURLString)
}
if linkURL != nil || imageURL != nil {
let title = data["title"] as? String
let alt = data["alt"] as? String
elements = Elements(link: linkURL, image: imageURL, title: title, alt: alt)
} else {
elements = nil
}
}
}
| mpl-2.0 | 9d7ca87d7a3cba410ba4eca195ddd340 | 40.235714 | 165 | 0.692881 | 5.276965 | false | false | false | false |
RayTW/Swift8ComicSDK | Swift8ComicSDK/Classes/Config.swift | 2 | 1458 | //
// Config.swift
// Pods
//
// Created by ray.lee on 2017/6/7.
//
//
open class Config {
open static let mComicHost : String = "http://www.comicbus.com/"
open let mAllUrl : String = mComicHost + "comic/all.html"
open let mCviewJSUrl : String = mComicHost + "js/comicview.js"
private let mSmallIconUrl : String = mComicHost + "pics/0/%@s.jpg"
private let mIconUrl : String = mComicHost + "pics/0/%@.jpg"
private let mComicDetail : String = mComicHost + "html/%@.html"
private let mQuickSearchUrl : String = mComicHost + "member/quicksearchjs.aspx?r=%.16f&t=item&o=id&k=%@"
private let mSearchUrl : String = mComicHost + "member/search.aspx?k=%@&page=%d"
open func getComicDetailUrl(_ comicId: String) -> String{
return String(format: mComicDetail, comicId)
}
open func getComicIconUrl(_ comicId: String) -> String{
return String(format: mIconUrl, comicId)
}
open func getComicSmallIconUrl(_ comicId: String) -> String{
return String(format: mSmallIconUrl, comicId)
}
open func getQuickSearchUrl(_ keyword: String) -> String{
return String(format: mQuickSearchUrl,(CGFloat(Float(arc4random()) / Float(UINT32_MAX))), StringUtility.urlEncodeUsingGB2312(keyword))
}
open func getSearchUrl(_ keyword: String, _ page : Int) -> String{
return String(format: mSearchUrl, StringUtility.urlEncodeUsingBIG5(keyword), page)
}
}
| mit | 62fccb73ae806501717475086e27379e | 37.368421 | 142 | 0.665295 | 3.471429 | false | true | false | false |
eCrowdMedia/MooApi | Sources/network/DownloadEpubMission.swift | 1 | 654 | import Foundation
public struct DownloadEpubMission {
public let bookId: String
public let bookURL: URL
public let authorization: Authorization
//TODO: 為了續傳準備 now byte & tatal byte & checksum 需要紀錄
public init(bookId: String, bookURL: URL, authorization: Authorization) {
self.bookId = bookId
self.bookURL = bookURL
self.authorization = authorization
}
}
extension DownloadEpubMission: Equatable {
public static func ==(lhs: DownloadEpubMission, rhs: DownloadEpubMission) -> Bool {
return lhs.bookId == rhs.bookId && lhs.bookURL == rhs.bookURL && lhs.authorization == rhs.authorization
}
}
| mit | 5d835c8f5af971f96cfcb6c226e0c1fb | 27.636364 | 107 | 0.728571 | 3.913043 | false | false | false | false |
andrealufino/Luminous | Sources/Luminous/Luminous+Locale.swift | 1 | 2239 | //
// Luminous+Locale.swift
// Luminous
//
// Created by Andrea Mario Lufino on 10/11/2019.
//
import Foundation
extension Luminous {
// MARK: Locale
/// Locale information.
public struct Locale {
/// The current language of the system.
public static var currentLanguage: String? {
if let languageCode = Foundation.Locale.current.languageCode {
return languageCode
}
return nil
}
/// The current Time Zone as TimeZone object.
public static var currentTimeZone: TimeZone {
return TimeZone.current
}
/// The current Time Zone identifier.
public static var currentTimeZoneName: String {
return TimeZone.current.identifier
}
/// The current country.
public static var currentCountry: String? {
if let regionCode = Foundation.Locale.current.regionCode {
return regionCode
}
return nil
}
/// The current currency.
public static var currentCurrency: String? {
if let currencyCode = Foundation.Locale.current.currencyCode {
return currencyCode
}
return nil
}
/// The current currency symbol.
public static var currentCurrencySymbol: String? {
if let currencySymbol = Foundation.Locale.current.currencySymbol {
return currencySymbol
}
return nil
}
/// Check if the system is using the metric system.
public static var usesMetricSystem: Bool {
return Foundation.Locale.current.usesMetricSystem
}
/// The decimal separator
public static var decimalSeparator: String? {
if let decimalSeparator = Foundation.Locale.current.decimalSeparator {
return decimalSeparator
}
return nil
}
}
}
| mit | a5a63e49650b3c3e3253621119bb9875 | 24.735632 | 82 | 0.514069 | 6.471098 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureForm/Sources/FeatureFormUI/Form.swift | 1 | 2478 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import FeatureFormDomain
import SwiftUI
public struct PrimaryForm: View {
@Binding private var form: FeatureFormDomain.Form
private let submitActionTitle: String
private let submitActionLoading: Bool
private let submitAction: () -> Void
public init(
form: Binding<FeatureFormDomain.Form>,
submitActionTitle: String,
submitActionLoading: Bool,
submitAction: @escaping () -> Void
) {
_form = form
self.submitActionTitle = submitActionTitle
self.submitActionLoading = submitActionLoading
self.submitAction = submitAction
}
public var body: some View {
ScrollView {
LazyVStack(spacing: Spacing.padding4) {
if let header = form.header {
VStack {
Icon.user
.frame(width: 32.pt, height: 32.pt)
Text(header.title)
.typography(.title2)
Text(header.description)
.typography(.paragraph1)
}
.multilineTextAlignment(.center)
.foregroundColor(.semantic.title)
}
ForEach($form.nodes) { question in
FormQuestionView(question: question)
}
PrimaryButton(
title: submitActionTitle,
isLoading: submitActionLoading,
action: submitAction
)
.disabled(!form.nodes.isValidForm)
}
.padding(Spacing.padding3)
.background(Color.semantic.background)
}
}
}
struct PrimaryForm_Previews: PreviewProvider {
static var previews: some View {
let jsonData = formPreviewJSON.data(using: .utf8)!
// swiftlint:disable:next force_try
let formRawData = try! JSONDecoder().decode(FeatureFormDomain.Form.self, from: jsonData)
PreviewHelper(form: formRawData)
}
struct PreviewHelper: View {
@State var form: FeatureFormDomain.Form
var body: some View {
PrimaryForm(
form: $form,
submitActionTitle: "Next",
submitActionLoading: false,
submitAction: {}
)
}
}
}
| lgpl-3.0 | 4c34c464d0b8e067333c0fe36df4ea8d | 29.207317 | 96 | 0.547033 | 5.28145 | false | false | false | false |
dobleuber/my-swift-exercises | Project26/Project26/GameViewController.swift | 1 | 1394 | //
// GameViewController.swift
// Project26
//
// Created by Wbert Castro on 8/08/17.
// Copyright © 2017 Wbert Castro. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| mit | b4b93927b8ee5084ae4b8d5c175b207e | 24.327273 | 77 | 0.580043 | 5.462745 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox | nRF Toolbox/Profiles/Cycling/Models/CyclingCharacteristic.swift | 1 | 6096 | /*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
private extension Flag {
static let wheelData: Flag = 0x01
static let crankData: Flag = 0x02
}
struct CyclingCharacteristic {
typealias WheelRevolutionAndTime = (revolution: Int, time: Double)
let wheelRevolutionsAndTime: WheelRevolutionAndTime?
let crankRevolutionsAndTime: WheelRevolutionAndTime?
static let zero = CyclingCharacteristic(wheelRevolutionsAndTime: (0, 0.0), crankRevolutionsAndTime: (0, 0.0))
init(wheelRevolutionsAndTime: (Int, Double)?, crankRevolutionsAndTime: (Int, Double)?) {
self.wheelRevolutionsAndTime = wheelRevolutionsAndTime
self.crankRevolutionsAndTime = crankRevolutionsAndTime
}
init(data: Data) throws {
let flags: UInt8 = try data.read()
wheelRevolutionsAndTime = try Flag.isAvailable(bits: flags, flag: .wheelData) ? {
(
Int(try data.read(fromOffset: 1) as UInt32),
Double(try data.read(fromOffset: 5) as UInt16)
)
}() : nil
let crankOffset: (Int, Int) = Flag.isAvailable(bits: flags, flag: .wheelData) ? (7, 9) : (1, 3)
crankRevolutionsAndTime = try Flag.isAvailable(bits: flags, flag: .crankData) ? {
(
Int(try data.read(fromOffset: crankOffset.0) as UInt16),
Double(try data.read(fromOffset: crankOffset.1) as UInt16)
)
}() : nil
}
func travelDistance(with wheelCircumference: Double) -> Measurement<UnitLength>? {
wheelRevolutionsAndTime.map { Measurement<UnitLength>(value: Double($0.revolution) * wheelCircumference, unit: .meters) }
}
func distance(_ oldCharacteristic: CyclingCharacteristic, wheelCircumference: Double) -> Measurement<UnitLength>? {
wheelRevolutionDiff(oldCharacteristic)
.flatMap { Measurement<UnitLength>(value: Double($0) * wheelCircumference, unit: .meters) }
}
func gearRatio(_ oldCharacteristic: CyclingCharacteristic) -> Double? {
guard let wheelRevolutionDiff = wheelRevolutionDiff(oldCharacteristic), let crankRevolutionDiff = crankRevolutionDiff(oldCharacteristic), crankRevolutionDiff != 0 else {
return nil
}
return Double(wheelRevolutionDiff) / Double(crankRevolutionDiff)
}
func speed(_ oldCharacteristic: CyclingCharacteristic, wheelCircumference: Double) -> Measurement<UnitSpeed>? {
guard let wheelRevolutionDiff = wheelRevolutionDiff(oldCharacteristic), let wheelEventTime = wheelRevolutionsAndTime?.time, let oldWheelEventTime = oldCharacteristic.wheelRevolutionsAndTime?.time else {
return nil
}
var wheelEventTimeDiff = wheelEventTime - oldWheelEventTime
guard wheelEventTimeDiff > 0 else {
return nil
}
wheelEventTimeDiff /= 1024
let speed = (Double(wheelRevolutionDiff) * wheelCircumference) / wheelEventTimeDiff
return Measurement<UnitSpeed>(value: speed, unit: .milesPerHour)
}
func cadence(_ oldCharacteristic: CyclingCharacteristic) -> Int? {
guard let crankRevolutionDiff = crankRevolutionDiff(oldCharacteristic), let crankEventTimeDiff = crankEventTimeDiff(oldCharacteristic), crankEventTimeDiff > 0 else {
return nil
}
return Int(Double(crankRevolutionDiff) / crankEventTimeDiff * 60.0)
}
private func wheelRevolutionDiff(_ oldCharacteristic: CyclingCharacteristic) -> Int? {
guard let oldWheelRevolution = oldCharacteristic.wheelRevolutionsAndTime?.revolution, let wheelRevolution = wheelRevolutionsAndTime?.revolution else {
return nil
}
guard oldWheelRevolution != 0 else { return 0 }
return wheelRevolution - oldWheelRevolution
}
private func crankRevolutionDiff(_ old: CyclingCharacteristic) -> Int? {
guard let crankRevolution = crankRevolutionsAndTime?.revolution, let oldCrankRevolution = old.crankRevolutionsAndTime?.revolution else {
return nil
}
return crankRevolution - oldCrankRevolution
}
private func crankEventTimeDiff(_ old: CyclingCharacteristic) -> Double? {
guard let crankEventTime = crankRevolutionsAndTime?.time, let oldCrankEventTime = old.crankRevolutionsAndTime?.time else {
return nil
}
return (crankEventTime - oldCrankEventTime) / 1024.0
}
}
| bsd-3-clause | f2618b90ec48fe8841e5dd7ffea45f6f | 44.155556 | 210 | 0.697014 | 4.653435 | false | false | false | false |
Yamievw/programmeerproject | YamievanWijnbergen-Programmeerproject/UserProfileViewController.swift | 1 | 2384 | //
// UserProfileViewController.swift
// YamievanWijnbergen-Programmeerproject
//
// Created by Yamie van Wijnbergen on 07/06/2017.
// Copyright © 2017 Yamie van Wijnbergen. All rights reserved.
//
import UIKit
import FirebaseDatabase
import FirebaseAuth
class UserProfileViewController: UIViewController {
var diver: User?
@IBOutlet weak var diverImage: UIImageView!
@IBOutlet weak var diverNameText: UITextView!
@IBOutlet weak var diverCertificateText: UITextView!
@IBOutlet weak var diverExperience: UILabel!
@IBOutlet weak var diverDives: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
updateDiver()
navigationController?.navigationBar.isHidden = false
navigationItem.title = diver?.name!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// Make sure user can go back to previous viewcontroller.
override func viewWillDisappear(_ animated: Bool) {
navigationController?.navigationBar.isHidden = true
super.viewWillDisappear(animated)
}
func updateDiver() {
diverImage.imageFromURL(url: (diver?.profileImageUrl)!)
diverNameText.text = (diver?.name)!
diverCertificateText.text = (diver?.certificate)!
diverExperience.text = (diver?.experience)!
diverDives.text = (diver?.dives)!
}
@IBAction func messageButton(_ sender: Any) {
performSegue(withIdentifier: "sendMessage", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let viewController = segue.destination as? MessageViewController {
viewController.diver = self.diver!
}
}
}
// Function to create image from url.
extension UIImageView {
func imageFromURL(url: String) {
if let url = URL(string: url) {
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if error != nil {
print ("Cant load imagesURL \(error)")
} else {
if let image = UIImage(data: data!) {
DispatchQueue.main.async {
self.image = image
}
}
}
}).resume()
}
}
}
| mit | 28e8561916c68d11dc1c142d9851285f | 28.7875 | 97 | 0.61603 | 4.747012 | false | false | false | false |
adamrothman/SwiftSocketIO | SwiftSocketIO/SocketIO.swift | 1 | 9204 | //
// SocketIO.swift
// SwiftSocketIO
//
// Created by Adam Rothman on 12/23/14.
//
//
import Foundation
import Alamofire
public class SocketIO: TransportDelegate {
public struct Options {
// var path: String = "/socket.io/"
var reconnection: Bool = false
var reconnectionAttempts: Int = 0
var reconnectionDelay: Double = 1.0
var reconnectionDelayMax: Double = 5.0
var reconnectionJitter: Double = 0.5
var timeout: Double = 20.0
var autoConnect: Bool = false
}
public typealias EventHandler = ([AnyObject]?) -> Void
let httpURL: NSURL
let wsURL: NSURL
let opts: Options
let pingDispatchSource: dispatch_source_t
let timeoutDispatchSource: dispatch_source_t
var transport: Transport!
var pingInterval: Double!
var pingTimeout: Double!
var handlers: [String: EventHandler] = [:]
// Convenience property - attempt to get the handler for the 'connect' event
var connectHandler: EventHandler? {
get { return handlers["connect"] }
}
// Convenience property - attempt to get the handler for the 'disconnect' event
var disconnectHandler: EventHandler? {
get { return handlers["disconnect"] }
}
// MARK: - Public interface
required public init(host: NSURL, options: Options = Options()) {
let httpURLComponents = NSURLComponents(URL: host, resolvingAgainstBaseURL: true)
httpURLComponents?.path = "/socket.io/"
httpURL = (httpURLComponents?.URL)!
// Recycle httpURLComponents to make the ws(s):// URL
let websocketProtocol = httpURLComponents?.scheme == "https" ? "wss" : "ws"
httpURLComponents?.scheme = websocketProtocol
wsURL = (httpURLComponents?.URL)!
opts = options
pingDispatchSource = dispatch_source_create(
DISPATCH_SOURCE_TYPE_TIMER,
0,
0,
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
)
timeoutDispatchSource = dispatch_source_create(
DISPATCH_SOURCE_TYPE_TIMER,
0,
0,
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
)
dispatch_source_set_event_handler(pingDispatchSource) {
self.transport.send(EngineIOPacket(type: .Ping))
}
dispatch_resume(pingDispatchSource)
dispatch_source_set_event_handler(timeoutDispatchSource) {
dispatch_source_cancel(self.pingDispatchSource)
dispatch_source_cancel(self.timeoutDispatchSource)
self.disconnect()
}
dispatch_resume(timeoutDispatchSource)
if opts.autoConnect {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
self.connect()
}
}
}
convenience public init?(host: String) {
if let url = NSURL(string: host) {
self.init(host: url)
} else {
// The Swift 1.1 compiler is unable to destroy partially initialized classes in all
// cases, so it disallows formation of a situation where it would have to. We have
// to initialize the instance before returning nil, for now. From this post on the
// Apple Developer Forums: https://devforums.apple.com/message/1062922#1062922
// See the section on failable initializers in the Xcode 6.1 Release Notes here:
// https://developer.apple.com/library/prerelease/ios/releasenotes/DeveloperTools/RN-Xcode/Chapters/xc6_release_notes.html#//apple_ref/doc/uid/TP40001051-CH4-DontLinkElementID_20
self.init(host: NSURL(string: "")!)
return nil
}
}
public func connect() {
let time = NSDate().timeIntervalSince1970 * 1000
let timeString = "\(Int(time))-0"
let manager = Alamofire.Manager(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration())
manager.request(
.GET,
httpURL,
parameters: [
"b64": true,
"EIO": 3,
"transport": "polling",
"t": timeString
]
).response { (request, response, data, error) in
if error == nil {
if let dataString: String = NSString(data: data as NSData, encoding: NSUTF8StringEncoding) {
NSLog("[SocketIO]\tconnect response:\n\(dataString)")
if let separatorIndex = dataString.rangeOfString(":")?.startIndex {
if separatorIndex < dataString.endIndex {
if let packetLength = dataString.substringToIndex(separatorIndex).toInt() {
let packetString = dataString.substringFromIndex(separatorIndex.successor())
if countElements(packetString) == packetLength {
if let packet = Parser.decodeSocketIOPacket(packetString) {
if let handshakeInfo: [String: AnyObject] = packet.payloadObject as? Dictionary {
let upgrades: [String] = handshakeInfo["upgrades"] as Array
if contains(upgrades, "websocket") {
let sid: String = handshakeInfo["sid"] as String
self.pingInterval = handshakeInfo["pingInterval"] as Double / 1000
self.pingTimeout = handshakeInfo["pingTimeout"] as Double / 1000
self.transport = WebsocketTransport(URL: self.wsURL, sid: sid)
self.transport.delegate = self
self.transport.open()
}
}
}
}
}
}
}
}
}
}
}
public func emit(event: String, data: AnyObject...) {
NSLog("[SocketIO]\temitting '\(event)' with \(data)")
let packet = SocketIOPacket(type: .Event)
var payloadArray: [AnyObject] = [event]
for datum in data {
payloadArray.append(datum)
}
packet.payloadObject = payloadArray
transport.send(packet)
}
public func on(event: String, handler: EventHandler) {
handlers[event] = handler
}
public func clearHandlers() {
handlers.removeAll(keepCapacity: true)
}
public func disconnect() {
disconnectHandler?(nil)
transport.close()
}
// MARK: - Heartbeat management
func startPingPong(delay: Double = 0) {
let start = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
// We have to send a ping every `pingInterval` seconds
let interval = UInt64(pingInterval * Double(NSEC_PER_SEC))
// The connection will die if we don't send a ping every `pingTimeout` seconds
// If `pingTimeout` is larger than `pingInterval`, we have some leeway here
// If the difference is smaller than 10, we'll say it's 0 just to be safe
let leeway = pingTimeout - pingInterval > 10 ? UInt64((pingTimeout - pingInterval - 10) * Double(NSEC_PER_SEC)) : UInt64(0)
dispatch_source_set_timer(pingDispatchSource, start, interval, leeway)
resetTimeout()
}
func resetTimeout() {
let start = dispatch_time(DISPATCH_TIME_NOW, Int64(pingTimeout * Double(NSEC_PER_SEC)))
dispatch_source_set_timer(timeoutDispatchSource, start, 0, 0)
}
// MARK: - TransportDelegate
func transportDidOpen(transport: Transport) {
transport.send(EngineIOPacket(type: .Ping, payload: "probe"))
}
func transport(transport: Transport, didReceiveMessage message: String) {
if let packet = Parser.decodeEngineIOPacket(message) {
switch packet.type {
case .Pong:
if packet.payload == "probe" {
startPingPong(delay: pingInterval)
transport.send(EngineIOPacket(type: .Upgrade))
} else {
resetTimeout()
}
case .Message:
if let ioPacket = packet.socketIOPacket {
switch ioPacket.type {
case .Connect:
NSLog("[SocketIO]\tconnected")
connectHandler?(nil)
case .Disconnect:
NSLog("[SocketIO]\tdisconnected")
disconnect()
case .Event:
NSLog("[SocketIO]\treceived event:\n\(ioPacket.payloadObject)")
if let eventArray: [AnyObject] = ioPacket.payloadObject as? Array {
if let eventName: String = eventArray.first as? String {
if let handler = handlers[eventName] {
if eventArray.count > 1 {
let restOfEvent = Array(eventArray[1 ... eventArray.count - 1])
handler(restOfEvent)
} else {
handler(nil)
}
} else {
NSLog("[SocketIO]\tno handler registered for \(eventName)")
}
}
}
case .Ack:
NSLog("[SocketIO]\treceived ACK")
case .Error:
NSLog("[SocketIO]\treceived ERROR")
case .BinaryEvent:
NSLog("[SocketIO]\treceived BINARY_EVENT")
case .BinaryAck:
NSLog("[SocketIO]\treceived BINARY_ACK")
}
}
// .Open .Close .Ping .Upgrade .NoOp
default:
return
}
}
}
func transport(transport: Transport, didCloseWithCode code: Int, reason: String!, wasClean: Bool) {
NSLog("\(transport) closed with code: \(code), reason: \(reason), wasClean: \(wasClean)")
}
func transport(transport: Transport, didFailWithError error: NSError!) {
NSLog("\(transport) failed with error: \(error)")
}
}
| mit | 074bd0a960ea3aaf6d23f498b600e474 | 30.520548 | 184 | 0.624946 | 4.446377 | false | false | false | false |
badoo/Chatto | Chatto/sources/ChatController/ChatMessages/New/NewChatMessageCollectionAdapterConfiguration.swift | 1 | 2965 | //
// The MIT License (MIT)
//
// Copyright (c) 2015-present Badoo Trading Limited.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public extension NewChatMessageCollectionAdapter {
struct Configuration {
public var autoloadingFractionalThreshold: CGFloat
public var coalesceUpdates: Bool
public var fastUpdates: Bool
public var isRegisteringPresentersAutomatically: Bool
public var preferredMaxMessageCount: Int?
public var preferredMaxMessageCountAdjustment: Int
public var updatesAnimationDuration: TimeInterval
public init(autoloadingFractionalThreshold: CGFloat,
coalesceUpdates: Bool,
fastUpdates: Bool,
isRegisteringPresentersAutomatically: Bool,
preferredMaxMessageCount: Int?,
preferredMaxMessageCountAdjustment: Int,
updatesAnimationDuration: TimeInterval) {
self.autoloadingFractionalThreshold = autoloadingFractionalThreshold
self.coalesceUpdates = coalesceUpdates
self.fastUpdates = fastUpdates
self.isRegisteringPresentersAutomatically = isRegisteringPresentersAutomatically
self.preferredMaxMessageCount = preferredMaxMessageCount
self.preferredMaxMessageCountAdjustment = preferredMaxMessageCountAdjustment
self.updatesAnimationDuration = updatesAnimationDuration
}
}
}
public extension NewChatMessageCollectionAdapter.Configuration {
static var `default`: Self {
return .init(
autoloadingFractionalThreshold: 0.05,
coalesceUpdates: true,
fastUpdates: true,
isRegisteringPresentersAutomatically: true,
preferredMaxMessageCount: 500,
preferredMaxMessageCountAdjustment: 400,
updatesAnimationDuration: 0.33
)
}
}
| mit | fefd4316bd576c3a3f856614f12d08c0 | 43.253731 | 92 | 0.713659 | 5.440367 | false | false | false | false |
uasys/swift | stdlib/public/core/Algorithm.swift | 3 | 5150 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Returns the lesser of two comparable values.
///
/// - Parameters:
/// - x: A value to compare.
/// - y: Another value to compare.
/// - Returns: The lesser of `x` and `y`. If `x` is equal to `y`, returns `x`.
@_inlineable
public func min<T : Comparable>(_ x: T, _ y: T) -> T {
// In case `x == y` we pick `x`.
// This preserves any pre-existing order in case `T` has identity,
// which is important for e.g. the stability of sorting algorithms.
// `(min(x, y), max(x, y))` should return `(x, y)` in case `x == y`.
return y < x ? y : x
}
/// Returns the least argument passed.
///
/// - Parameters:
/// - x: A value to compare.
/// - y: Another value to compare.
/// - z: A third value to compare.
/// - rest: Zero or more additional values.
/// - Returns: The least of all the arguments. If there are multiple equal
/// least arguments, the result is the first one.
@_inlineable
public func min<T : Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T {
var minValue = min(min(x, y), z)
// In case `value == minValue`, we pick `minValue`. See min(_:_:).
for value in rest where value < minValue {
minValue = value
}
return minValue
}
/// Returns the greater of two comparable values.
///
/// - Parameters:
/// - x: A value to compare.
/// - y: Another value to compare.
/// - Returns: The greater of `x` and `y`. If `x` is equal to `y`, returns `y`.
@_inlineable
public func max<T : Comparable>(_ x: T, _ y: T) -> T {
// In case `x == y`, we pick `y`. See min(_:_:).
return y >= x ? y : x
}
/// Returns the greatest argument passed.
///
/// - Parameters:
/// - x: A value to compare.
/// - y: Another value to compare.
/// - z: A third value to compare.
/// - rest: Zero or more additional values.
/// - Returns: The greatest of all the arguments. If there are multiple equal
/// greatest arguments, the result is the last one.
@_inlineable
public func max<T : Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T {
var maxValue = max(max(x, y), z)
// In case `value == maxValue`, we pick `value`. See min(_:_:).
for value in rest where value >= maxValue {
maxValue = value
}
return maxValue
}
/// The iterator for `EnumeratedSequence`.
///
/// An instance of `EnumeratedIterator` wraps a base iterator and yields
/// successive `Int` values, starting at zero, along with the elements of the
/// underlying base iterator. The following example enumerates the elements of
/// an array:
///
/// var iterator = ["foo", "bar"].enumerated().makeIterator()
/// iterator.next() // (0, "foo")
/// iterator.next() // (1, "bar")
/// iterator.next() // nil
///
/// To create an instance of `EnumeratedIterator`, call
/// `enumerated().makeIterator()` on a sequence or collection.
@_fixed_layout
public struct EnumeratedIterator<
Base : IteratorProtocol
> : IteratorProtocol, Sequence {
@_versioned
internal var _base: Base
@_versioned
internal var _count: Int
/// Construct from a `Base` iterator.
@_inlineable
@_versioned
internal init(_base: Base) {
self._base = _base
self._count = 0
}
/// The type of element returned by `next()`.
public typealias Element = (offset: Int, element: Base.Element)
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@_inlineable
public mutating func next() -> Element? {
guard let b = _base.next() else { return nil }
let result = (offset: _count, element: b)
_count += 1
return result
}
}
/// An enumeration of the elements of a sequence or collection.
///
/// `EnumeratedSequence` is a sequence of pairs (*n*, *x*), where *n*s are
/// consecutive `Int` values starting at zero, and *x*s are the elements of a
/// base sequence.
///
/// To create an instance of `EnumeratedSequence`, call `enumerated()` on a
/// sequence or collection. The following example enumerates the elements of
/// an array.
///
/// var s = ["foo", "bar"].enumerated()
/// for (n, x) in s {
/// print("\(n): \(x)")
/// }
/// // Prints "0: foo"
/// // Prints "1: bar"
@_fixed_layout
public struct EnumeratedSequence<Base : Sequence> : Sequence {
@_versioned
internal var _base: Base
/// Construct from a `Base` sequence.
@_inlineable
@_versioned
internal init(_base: Base) {
self._base = _base
}
/// Returns an iterator over the elements of this sequence.
@_inlineable
public func makeIterator() -> EnumeratedIterator<Base.Iterator> {
return EnumeratedIterator(_base: _base.makeIterator())
}
}
| apache-2.0 | cff14f08df25e74d5965f48e234ac767 | 31.389937 | 80 | 0.611845 | 3.753644 | false | false | false | false |
grpc/grpc-swift | Sources/Examples/RouteGuide/Client/RouteGuideClient.swift | 1 | 7798 | /*
* Copyright 2019, gRPC 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.
*/
#if compiler(>=5.6)
import ArgumentParser
import Foundation
import GRPC
import NIOCore
import NIOPosix
import RouteGuideModel
/// Loads the features from `route_guide_db.json`, assumed to be in the directory above this file.
func loadFeatures() throws -> [Routeguide_Feature] {
let url = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent() // main.swift
.deletingLastPathComponent() // Client/
.appendingPathComponent("route_guide_db.json")
let data = try Data(contentsOf: url)
return try Routeguide_Feature.array(fromJSONUTF8Data: data)
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
internal struct RouteGuideExample {
private let routeGuide: Routeguide_RouteGuideAsyncClient
private let features: [Routeguide_Feature]
init(routeGuide: Routeguide_RouteGuideAsyncClient, features: [Routeguide_Feature]) {
self.routeGuide = routeGuide
self.features = features
}
func run() async {
// Look for a valid feature.
await self.getFeature(latitude: 409_146_138, longitude: -746_188_906)
// Look for a missing feature.
await self.getFeature(latitude: 0, longitude: 0)
// Looking for features between 40, -75 and 42, -73.
await self.listFeatures(
lowLatitude: 400_000_000,
lowLongitude: -750_000_000,
highLatitude: 420_000_000,
highLongitude: -730_000_000
)
// Record a few randomly selected points from the features file.
await self.recordRoute(features: self.features, featuresToVisit: 10)
// Send and receive some notes.
await self.routeChat()
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension RouteGuideExample {
/// Get the feature at the given latitude and longitude, if one exists.
private func getFeature(latitude: Int, longitude: Int) async {
print("\n→ GetFeature: lat=\(latitude) lon=\(longitude)")
let point: Routeguide_Point = .with {
$0.latitude = numericCast(latitude)
$0.longitude = numericCast(longitude)
}
do {
let feature = try await self.routeGuide.getFeature(point)
if !feature.name.isEmpty {
print("Found feature called '\(feature.name)' at \(feature.location)")
} else {
print("Found no feature at \(feature.location)")
}
} catch {
print("RPC failed: \(error)")
}
}
/// List all features in the area bounded by the high and low latitude and longitudes.
private func listFeatures(
lowLatitude: Int,
lowLongitude: Int,
highLatitude: Int,
highLongitude: Int
) async {
print(
"\n→ ListFeatures: lowLat=\(lowLatitude) lowLon=\(lowLongitude), hiLat=\(highLatitude) hiLon=\(highLongitude)"
)
let rectangle: Routeguide_Rectangle = .with {
$0.lo = .with {
$0.latitude = numericCast(lowLatitude)
$0.longitude = numericCast(lowLongitude)
}
$0.hi = .with {
$0.latitude = numericCast(highLatitude)
$0.longitude = numericCast(highLongitude)
}
}
do {
var resultCount = 1
for try await feature in self.routeGuide.listFeatures(rectangle) {
print("Result #\(resultCount): \(feature)")
resultCount += 1
}
} catch {
print("RPC failed: \(error)")
}
}
/// Record a route for `featuresToVisit` features selected randomly from `features` and print a
/// summary of the route.
private func recordRoute(
features: [Routeguide_Feature],
featuresToVisit: Int
) async {
print("\n→ RecordRoute")
let recordRoute = self.routeGuide.makeRecordRouteCall()
do {
for i in 1 ... featuresToVisit {
if let feature = features.randomElement() {
let point = feature.location
print("Visiting point #\(i) at \(point)")
try await recordRoute.requestStream.send(point)
// Sleep for 0.2s ... 1.0s before sending the next point.
try await Task.sleep(nanoseconds: UInt64.random(in: UInt64(2e8) ... UInt64(1e9)))
}
}
recordRoute.requestStream.finish()
let summary = try await recordRoute.response
print(
"Finished trip with \(summary.pointCount) points. Passed \(summary.featureCount) features. " +
"Travelled \(summary.distance) meters. It took \(summary.elapsedTime) seconds."
)
} catch {
print("RecordRoute Failed: \(error)")
}
}
/// Record notes at given locations, printing each all other messages which have previously been
/// recorded at the same location.
private func routeChat() async {
print("\n→ RouteChat")
let notes = [
("First message", 0, 0),
("Second message", 0, 1),
("Third message", 1, 0),
("Fourth message", 1, 1),
].map { message, latitude, longitude in
Routeguide_RouteNote.with {
$0.message = message
$0.location = .with {
$0.latitude = Int32(latitude)
$0.longitude = Int32(longitude)
}
}
}
do {
try await withThrowingTaskGroup(of: Void.self) { group in
let routeChat = self.routeGuide.makeRouteChatCall()
// Add a task to send each message adding a small sleep between each.
group.addTask {
for note in notes {
print("Sending message '\(note.message)' at \(note.location)")
try await routeChat.requestStream.send(note)
// Sleep for 0.2s ... 1.0s before sending the next note.
try await Task.sleep(nanoseconds: UInt64.random(in: UInt64(2e8) ... UInt64(1e9)))
}
routeChat.requestStream.finish()
}
// Add a task to print each message received on the response stream.
group.addTask {
for try await note in routeChat.responseStream {
print("Received message '\(note.message)' at \(note.location)")
}
}
try await group.waitForAll()
}
} catch {
print("RouteChat Failed: \(error)")
}
}
}
@main
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
struct RouteGuide: AsyncParsableCommand {
@Option(help: "The port to connect to")
var port: Int = 1234
func run() async throws {
// Load the features.
let features = try loadFeatures()
let group = PlatformSupport.makeEventLoopGroup(loopCount: 1)
defer {
try? group.syncShutdownGracefully()
}
let channel = try GRPCChannelPool.with(
target: .host("localhost", port: self.port),
transportSecurity: .plaintext,
eventLoopGroup: group
)
defer {
try? channel.close().wait()
}
let routeGuide = Routeguide_RouteGuideAsyncClient(channel: channel)
let example = RouteGuideExample(routeGuide: routeGuide, features: features)
await example.run()
}
}
extension Routeguide_Point: CustomStringConvertible {
public var description: String {
return "(\(self.latitude), \(self.longitude))"
}
}
extension Routeguide_Feature: CustomStringConvertible {
public var description: String {
return "\(self.name) at \(self.location)"
}
}
#else
@main
enum NotAvailable {
static func main() {
print("This example requires Swift >= 5.6")
}
}
#endif // compiler(>=5.6)
| apache-2.0 | c02be8b1be7f92ffc9cea9b938a1b00c | 29.311284 | 116 | 0.651348 | 4.040456 | false | false | false | false |
apple/swift | test/Generics/issue-51450.swift | 2 | 643 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module %S/Inputs/issue-51450-other.swift -emit-module-path %t/other.swiftmodule -module-name other
// RUN: %target-swift-frontend -emit-silgen %s -I%t -debug-generic-signatures 2>&1 | %FileCheck %s
// https://github.com/apple/swift/issues/51450
import other
public class C : P {
public typealias T = Int
}
public func takesInt(_: Int) {}
// CHECK-LABEL: .foo@
// CHECK-NEXT: Generic signature: <T, S where T : C, S : Sequence, S.[Sequence]Element == Int>
public func foo<T : C, S : Sequence>(_: T, _ xs: S) where S.Element == T.T {
for x in xs {
takesInt(x)
}
}
| apache-2.0 | 361ebf1e07b54c990c8b3d88ab7a7290 | 29.619048 | 135 | 0.662519 | 2.936073 | false | false | false | false |
JohnUni/SensorTester | SensorTester/NetworkServer.swift | 1 | 7530 | /*
* NetworkServerTest.swift
* SensorTester
*
* Created by John Wong on 8/09/2015.
* Copyright (c) 2015-2015, John Wong <john dot innovation dot au at gmail dot com>
*
* All rights reserved.
*
* http://www.bitranslator.com
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import Foundation
class NetworkServer : NSObject
{
// "127.0.0.1" "10.0.1.1" 8090
var strHost: String = "127.0.0.1"
var nPort: Int32 = 8090
var server: AsyncTcpServerSocket = AsyncTcpServerSocket()
var m_arrayHandlers: Array<INetworkDataHandler> = Array<INetworkDataHandler>()
var m_arrayClients : Array<AsyncTcpClientSocket> = Array<AsyncTcpClientSocket>()
override init()
{
//m_arrayHandlers = Array<INetworkDataHandler>()
//m_arrayClients = Array<AsyncTcpClientSocket>()
super.init()
}
internal func start( callbackHandler: INetworkDataHandler ) -> Bool
{
let bRet: Bool = false
m_arrayHandlers.removeAll(keepCapacity: true)
m_arrayHandlers.append(callbackHandler)
let threadNetwork: NSThread = NSThread(target:self, selector:#selector(NetworkServer.threadNetworkFunc(_:)), object:nil)
threadNetwork.start()
return bRet
}
func threadNetworkFunc(sender : AnyObject)
{
// the unit is in second
var nLastStartTime: NSTimeInterval = NSDate.timeIntervalSinceReferenceDate()
let MIN_WAIT_BEFORE_ERROR_RETRY: NSTimeInterval = 2.0
let MIN_WAIT: NSTimeInterval = 0.20
while( true )
{
let nCurrentTime: NSTimeInterval = NSDate.timeIntervalSinceReferenceDate()
let nDiff: NSTimeInterval = nCurrentTime - nLastStartTime
//print("nDiff:\(nDiff) \n")
//nLastStartTime = nCurrentTime
//usleep(1000)
var bHaveTask: Bool = false
switch( server.getSocketStatus() )
{
case .ASYNC_SOCKET_STATUS_UNKNOWN, .ASYNC_SOCKET_STATUS_INIT:
if( nDiff > MIN_WAIT_BEFORE_ERROR_RETRY )
{
print( "start async listen \(strHost):\(nPort) \n", terminator: "" )
server.startAsyncListen( strHost, port: nPort )
nLastStartTime = nCurrentTime
}
case .ASYNC_SOCKET_STATUS_LISTENING:
if( nDiff > MIN_WAIT )
{
if( server.isListened() )
{
print( " async is listened now. \n", terminator: "" )
// Okay
}
else
{
print( " async waiting for listened. \n", terminator: "" )
}
nLastStartTime = nCurrentTime
}
else
{
// nothing only wait
}
case .ASYNC_SOCKET_STATUS_LISTENED:
if( server.isAcceptable() )
{
//print( " async try to accept \n" )
let clientSocket: AsyncTcpClientSocket? = server.acceptClient()
if( clientSocket != nil )
{
self.m_arrayClients.append( clientSocket! )
bHaveTask = true
}
else
{
print( " async try to accept error! \n", terminator: "" )
}
}
case .ASYNC_SOCKET_STATUS_ERROR:
server.reset()
nLastStartTime = nCurrentTime
default:
break
}
for client: AsyncTcpClientSocket in m_arrayClients
{
if( client.isReadable() )
{
let nBufferSize: Int32 = 64*1024
let (bResult, dataBuffer): (Bool, NSData?) = client.recv( nBufferSize )
if( bResult && dataBuffer != nil )
{
bHaveTask = true
for dataHandler: INetworkDataHandler in m_arrayHandlers
{
let nProcess: Bool = dataHandler.receiveData( client, data: dataBuffer! )
if( nProcess )
{
// break
}
}
}
else
{
print( " nothing to read from client, might be closed by client \n", terminator: "" )
}
}
}
for( var i: Int = m_arrayClients.count-1; i >= 0 ; i -= 1 )
{
let client: AsyncTcpClientSocket = m_arrayClients[i]
let nStatus: enumAsyncSocketStatus = client.getSocketStatus()
if( .ASYNC_SOCKET_STATUS_CONNECTED != nStatus )
{
print( " client status is not connected, removed! \n", terminator: "" )
m_arrayClients.removeAtIndex( i )
bHaveTask = true
}
}
if( !bHaveTask )
{
usleep( useconds_t(MIN_WAIT) )
}
}
}
}
| apache-2.0 | f7856e185e56985031c0154c1179efce | 37.22335 | 128 | 0.551527 | 4.918354 | false | false | false | false |
pksprojects/ElasticSwift | Sources/ElasticSwiftQueryDSL/Queries/Builders/JoiningQueryBuilders.swift | 1 | 7305 | //
// JoiningQueryBuilders.swift
// ElasticSwift
//
// Created by Prafull Kumar Soni on 4/14/18.
//
import ElasticSwiftCodableUtils
import ElasticSwiftCore
import Foundation
// MARK: - Nested Query Builder
public class NestedQueryBuilder: QueryBuilder {
private var _path: String?
private var _query: Query?
private var _scoreMode: ScoreMode?
private var _ignoreUnmapped: Bool?
private var _innerHits: InnerHit?
private var _boost: Decimal?
private var _name: String?
public init() {}
@discardableResult
public func set(path: String) -> Self {
_path = path
return self
}
@discardableResult
public func set(query: Query) -> Self {
_query = query
return self
}
@discardableResult
public func set(scoreMode: ScoreMode) -> Self {
_scoreMode = scoreMode
return self
}
@discardableResult
public func set(ignoreUnmapped: Bool) -> Self {
_ignoreUnmapped = ignoreUnmapped
return self
}
@discardableResult
public func set(innerHits: InnerHit) -> Self {
_innerHits = innerHits
return self
}
@discardableResult
public func set(boost: Decimal) -> Self {
_boost = boost
return self
}
@discardableResult
public func set(name: String) -> Self {
_name = name
return self
}
public var path: String? {
return _path
}
public var query: Query? {
return _query
}
public var scoreMode: ScoreMode? {
return _scoreMode
}
public var ignoreUnmapped: Bool? {
return _ignoreUnmapped
}
public var innerHits: InnerHit? {
return _innerHits
}
public var boost: Decimal? {
return _boost
}
public var name: String? {
return _name
}
public func build() throws -> NestedQuery {
return try NestedQuery(withBuilder: self)
}
}
// MARK: - HasChild Query Builder
public class HasChildQueryBuilder: QueryBuilder {
private var _type: String?
private var _query: Query?
private var _scoreMode: ScoreMode?
private var _minChildren: Int?
private var _maxChildren: Int?
private var _ignoreUnmapped: Bool?
private var _innerHits: InnerHit?
private var _boost: Decimal?
private var _name: String?
public init() {}
@discardableResult
public func set(type: String) -> Self {
_type = type
return self
}
@discardableResult
public func set(query: Query) -> Self {
_query = query
return self
}
@discardableResult
public func set(scoreMode: ScoreMode) -> Self {
_scoreMode = scoreMode
return self
}
@discardableResult
public func set(ignoreUnmapped: Bool) -> Self {
_ignoreUnmapped = ignoreUnmapped
return self
}
@discardableResult
public func set(innerHits: InnerHit) -> Self {
_innerHits = innerHits
return self
}
@discardableResult
public func set(minChildren: Int) -> Self {
_minChildren = minChildren
return self
}
@discardableResult
public func set(maxChildren: Int) -> Self {
_maxChildren = maxChildren
return self
}
@discardableResult
public func set(boost: Decimal) -> Self {
_boost = boost
return self
}
@discardableResult
public func set(name: String) -> Self {
_name = name
return self
}
public var type: String? {
return _type
}
public var query: Query? {
return _query
}
public var scoreMode: ScoreMode? {
return _scoreMode
}
public var minChildren: Int? {
return _minChildren
}
public var maxChildren: Int? {
return _maxChildren
}
public var ignoreUnmapped: Bool? {
return _ignoreUnmapped
}
public var innerHits: InnerHit? {
return _innerHits
}
public var boost: Decimal? {
return _boost
}
public var name: String? {
return _name
}
public func build() throws -> HasChildQuery {
return try HasChildQuery(withBuilder: self)
}
}
// MARK: - HasParent Query Builder
public class HasParentQueryBuilder: QueryBuilder {
private var _parentType: String?
private var _query: Query?
private var _score: Bool?
private var _ignoreUnmapped: Bool?
private var _innerHits: InnerHit?
private var _boost: Decimal?
private var _name: String?
public init() {}
@discardableResult
public func set(parentType: String) -> Self {
_parentType = parentType
return self
}
@discardableResult
public func set(query: Query) -> Self {
_query = query
return self
}
@discardableResult
public func set(score: Bool) -> Self {
_score = score
return self
}
@discardableResult
public func set(ignoreUnmapped: Bool) -> Self {
_ignoreUnmapped = ignoreUnmapped
return self
}
@discardableResult
public func set(innerHits: InnerHit) -> Self {
_innerHits = innerHits
return self
}
@discardableResult
public func set(boost: Decimal) -> Self {
_boost = boost
return self
}
@discardableResult
public func set(name: String) -> Self {
_name = name
return self
}
public var parentType: String? {
return _parentType
}
public var query: Query? {
return _query
}
public var score: Bool? {
return _score
}
public var ignoreUnmapped: Bool? {
return _ignoreUnmapped
}
public var innerHits: InnerHit? {
return _innerHits
}
public var boost: Decimal? {
return _boost
}
public var name: String? {
return _name
}
public func build() throws -> HasParentQuery {
return try HasParentQuery(withBuilder: self)
}
}
// MARK: - ParentId Query Builder
public class ParentIdQueryBuilder: QueryBuilder {
private var _type: String?
private var _id: String?
private var _ignoreUnmapped: Bool?
private var _boost: Decimal?
private var _name: String?
@discardableResult
public func set(type: String) -> Self {
_type = type
return self
}
@discardableResult
public func set(id: String) -> Self {
_id = id
return self
}
@discardableResult
public func set(ignoreUnmapped: Bool) -> Self {
_ignoreUnmapped = ignoreUnmapped
return self
}
@discardableResult
public func set(boost: Decimal) -> Self {
_boost = boost
return self
}
@discardableResult
public func set(name: String) -> Self {
_name = name
return self
}
public var type: String? {
return _type
}
public var id: String? {
return _id
}
public var ignoreUnmapped: Bool? {
return _ignoreUnmapped
}
public var boost: Decimal? {
return _boost
}
public var name: String? {
return _name
}
public func build() throws -> ParentIdQuery {
return try ParentIdQuery(withBuilder: self)
}
}
| mit | ab6ef2d433a0e124588a0d5e49619118 | 19.291667 | 52 | 0.596851 | 4.405911 | false | false | false | false |
tonyqiu1019/tsoc | ios/Smashtag/Twitter/Tweet.swift | 4 | 7848 | //
// Tweet.swift
// Twitter
//
// Created by CS193p Instructor.
// Copyright (c) 2015-17 Stanford University. All rights reserved.
//
import Foundation
// a simple container which just holds the data in a Tweet
// a Mention is a substring of the Tweet's text
// for example, a hashtag or other user or url that is mentioned in the Tweet
// note carefully the comments on the range property in a Mention
// Tweet instances are created by fetching from Twitter using a Twitter.Request
public struct Tweet : CustomStringConvertible
{
public let text: String
public let user: User
public let created: Date
public let identifier: String
public let media: [MediaItem]
public let hashtags: [Mention]
public let urls: [Mention]
public let userMentions: [Mention]
public var description: String { return "\(user) - \(created)\n\(text)\nhashtags: \(hashtags)\nurls: \(urls)\nuser_mentions: \(userMentions)" + "\nid: \(identifier)" }
// MARK: - Internal Implementation
init?(data: NSDictionary?)
{
guard
let user = User(data: data?.dictionary(forKeyPath: TwitterKey.user)),
let text = data?.string(forKeyPath: TwitterKey.text),
let created = twitterDateFormatter.date(from: data?.string(forKeyPath: TwitterKey.created) ?? ""),
let identifier = data?.string(forKeyPath: TwitterKey.identifier)
else {
return nil
}
self.user = user
self.text = text
self.created = created
self.identifier = identifier
self.media = Tweet.mediaItems(from: data?.array(forKeyPath: TwitterKey.media))
self.hashtags = Tweet.mentions(from: data?.array(forKeyPath: TwitterKey.Entities.hashtags), in: text, with: "#")
self.urls = Tweet.mentions(from: data?.array(forKeyPath: TwitterKey.Entities.urls), in: text, with: "http")
self.userMentions = Tweet.mentions(from: data?.array(forKeyPath: TwitterKey.Entities.userMentions), in: text, with: "@")
}
private static func mediaItems(from twitterData: NSArray?) -> [MediaItem] {
var mediaItems = [MediaItem]()
for mediaItemData in twitterData ?? [] {
if let mediaItem = MediaItem(data: mediaItemData as? NSDictionary) {
mediaItems.append(mediaItem)
}
}
return mediaItems
}
private static func mentions(from twitterData: NSArray?, in text: String, with prefix: String) -> [Mention] {
var mentions = [Mention]()
for mentionData in twitterData ?? [] {
if let mention = Mention(from: mentionData as? NSDictionary, in: text as NSString, with: prefix) {
mentions.append(mention)
}
}
return mentions
}
struct TwitterKey {
static let user = "user"
static let text = "text"
static let created = "created_at"
static let identifier = "id_str"
static let media = "entities.media"
struct Entities {
static let hashtags = "entities.hashtags"
static let urls = "entities.urls"
static let userMentions = "entities.user_mentions"
static let indices = "indices"
static let text = "text"
}
}
}
public struct Mention: CustomStringConvertible
{
public let keyword: String // will include # or @ or http prefix
public let nsrange: NSRange // index into an NS[Attributed]String made from the Tweet's text
public var description: String { return "\(keyword) (\(nsrange.location), \(nsrange.location+nsrange.length-1))" }
init?(from data: NSDictionary?, in text: NSString, with prefix: String)
{
guard
let indices = data?.array(forKeyPath: Tweet.TwitterKey.Entities.indices),
let start = (indices.firstObject as? NSNumber)?.intValue, start >= 0,
let end = (indices.lastObject as? NSNumber)?.intValue, end > start
else {
return nil
}
var prefixAloneOrPrefixedMention = prefix
if let mention = data?.string(forKeyPath: Tweet.TwitterKey.Entities.text) {
prefixAloneOrPrefixedMention = mention.prependPrefixIfAbsent(prefix)
}
let expectedRange = NSRange(location: Int(start), length: end - start)
guard
let nsrange = text.rangeOfSubstring(withPrefix: prefixAloneOrPrefixedMention, expectedRange: expectedRange)
else {
return nil
}
self.keyword = text.substring(with: nsrange)
self.nsrange = nsrange
}
}
private let twitterDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
private extension String {
func prependPrefixIfAbsent(_ prefix: String) -> String {
return hasPrefix(prefix) ? self : prefix + self
}
}
private extension NSString
{
func rangeOfSubstring(withPrefix prefix: String, expectedRange: NSRange) -> NSRange?
{
var offset = 0
var substringRange = expectedRange
while range.contains(substringRange) && substringRange.intersects(expectedRange) {
if substring(with: substringRange).hasPrefix(prefix) {
return substringRange
}
offset = offset > 0 ? -(offset+1) : -(offset-1)
substringRange.location += offset
}
// the prefix does not intersect the expectedRange
// let's search for it elsewhere and if we find it,
// pick the one closest to expectedRange
var searchRange = range
var bestMatchRange = NSRange.NotFound
var bestMatchDistance = Int.max
repeat {
substringRange = self.range(of: prefix, options: [], range: searchRange)
let distance = substringRange.distance(from: expectedRange)
if distance < bestMatchDistance {
bestMatchRange = substringRange
bestMatchDistance = distance
}
searchRange.length -= substringRange.end - searchRange.start
searchRange.start = substringRange.end
} while searchRange.length > 0
if bestMatchRange.location != NSNotFound {
bestMatchRange.length = expectedRange.length
if range.contains(bestMatchRange) {
return bestMatchRange
}
}
print("NSString.rangeOfSubstring(withPrefix:expectedRange:) couldn't find a keyword with the prefix \(prefix) near the range \(expectedRange) in \(self)")
return nil
}
var range: NSRange { return NSRange(location:0, length: length) }
}
private extension NSRange
{
func contains(_ range: NSRange) -> Bool {
return range.location >= location && range.location+range.length <= location+length
}
func intersects(_ range: NSRange) -> Bool {
if range.location == NSNotFound || location == NSNotFound {
return false
} else {
return (range.start >= start && range.start < end) || (range.end >= start && range.end < end)
}
}
func distance(from range: NSRange) -> Int {
if range.location == NSNotFound || location == NSNotFound {
return Int.max
} else if intersects(range) {
return 0
} else {
return (end < range.start) ? range.start - end : start - range.end
}
}
static let NotFound = NSRange(location: NSNotFound, length: 0)
var start: Int {
get { return location }
set { location = newValue }
}
var end: Int { return location+length }
}
| mit | 8cf8004e0fdf15a21b546774692adf91 | 35.502326 | 171 | 0.617864 | 4.690974 | false | false | false | false |
xiandan/diaobaoweibo-swift | XWeibo-swift/Classes/Library/Emotion/Model/XEmotion.swift | 1 | 5713 | //
// XEmotion.swift
// Emotion
//
// Created by Apple on 15/11/8.
// Copyright © 2015年 Apple. All rights reserved.
//
import UIKit
//MARK: - 表情模型
class XEmotion: NSObject {
//MARK: - 属性
var id: String?
//网络传输表情名称
var chs: String?
//表情图片名称
var png: String? {
didSet {
pngPath = XEmotionPackages.bundlePath + "/" + id! + "/" + png!
}
}
//表情完整路径
var pngPath: String?
//emoji表情名称
var code: String? {
didSet {
guard let co = code else {
return
}
// 扫描器
let scanner = NSScanner(string: co)
// 存储扫描结果
// UnsafeMutablePointer<UInt32>: UInt32类型的可变指针
var value: UInt32 = 0
scanner.scanHexInt(&value)
// print("扫描结果:\(value)")
let c = Character(UnicodeScalar(value))
emoji = String(c)
}
}
//显示emoji表情
var emoji: String?
//true 带删除按钮的表情模型, false空模型
var removeEmotion: Bool = false
//记录点击的次数
var times = 0
init(removeEmotion: Bool) {
self.removeEmotion = removeEmotion
super.init()
}
init(id: String, dic: [String: String]) {
self.id = id
super.init()
setValuesForKeysWithDictionary(dic)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
}
//MARK: - 表情包模型
class XEmotionPackages: NSObject {
//MARK: - 属性
private static let bundlePath = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
//文件夹名称
var id: String?
//表情包名称
var group_name_cn: String?
//表情模型
var emotions: [XEmotion]?
init(id: String) {
self.id = id
super.init()
}
//加载表情包
class func emotionPackages() -> [XEmotionPackages] {
let plistPth = bundlePath + "/emoticons.plist"
let sourceDic = NSDictionary(contentsOfFile: plistPth)!
var packages = [XEmotionPackages]()
//追加最近表情包
let recent = XEmotionPackages(id: "")
recent.group_name_cn = "最近"
recent.emotions = [XEmotion]()
//追加表情
recent.appdenEmptyEmotion()
packages.append(recent)
let packageArr = sourceDic["packages"] as! [[String: AnyObject]]
for dic in packageArr {
let id = dic["id"] as! String
let package = XEmotionPackages(id: id)
package.loadEmotiion()
packages.append(package)
}
return packages
}
//加载表情
func loadEmotiion() {
let infoPath = XEmotionPackages.bundlePath + "/" + id! + "/info.plist"
let infoDic = NSDictionary(contentsOfFile: infoPath)!
group_name_cn = infoDic["group_name_cn"] as? String
emotions = [XEmotion]()
var index = 0
if let array = infoDic["emoticons"] as? [[String: String]] {
for dic in array {
emotions?.append(XEmotion(id: id!, dic: dic))
index++
//最后一个
if index == 20 {
emotions?.append(XEmotion(removeEmotion: true))
index = 0
}
}
//追加空白按钮和删除按钮
appdenEmptyEmotion()
}
}
//MARK: - 追加空白按钮
private func appdenEmptyEmotion() {
let count = emotions!.count % 21
if count > 0 || emotions!.count == 0 {
for _ in count..<20 {
//追加空白按钮
emotions?.append(XEmotion(removeEmotion: false))
}
//追加删除按钮
emotions?.append(XEmotion(removeEmotion: true))
}
}
static let packages = XEmotionPackages.emotionPackages()
//MARK: - 添加按钮到最近表情包
class func addRecentEmotion(emotion: XEmotion) {
emotion.times++
//最近表情包
var package = packages[0].emotions
// print(package)
//删除按钮
let removeEmotion = package!.removeLast()
if emotion == removeEmotion {
return
}
//如果表情已经存在于最近表情包
let contains = package!.contains(emotion)
if !contains {
package?.append(emotion)
}
//排序
package = package?.sort({ (e1, e2) -> Bool in
return e1.times > e2.times
})
if !contains {
//移除最后一个表情
package?.removeLast()
}
//添加删除按钮
package?.append(removeEmotion)
packages[0].emotions = package
print(packages[0].emotions)
}
} | apache-2.0 | bfd4d7386514ebaab880a6143a75e03d | 19.827451 | 107 | 0.452731 | 4.880515 | false | false | false | false |
nate-parrott/aamoji | aamoji/SQLite.swift-master/SQLite Tests/DatabaseTests.swift | 19 | 13670 | import XCTest
import SQLite
class DatabaseTests: SQLiteTestCase {
override func setUp() {
super.setUp()
createUsersTable()
}
func test_init_withInMemory_returnsInMemoryConnection() {
let db = Database(.InMemory)
XCTAssertEqual("", db.description)
XCTAssertEqual(":memory:", Database.Location.InMemory.description)
}
func test_init_returnsInMemoryByDefault() {
let db = Database()
XCTAssertEqual("", db.description)
}
func test_init_withTemporary_returnsTemporaryConnection() {
let db = Database(.Temporary)
XCTAssertEqual("", db.description)
}
func test_init_withURI_returnsURIConnection() {
let db = Database(.URI("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3"))
XCTAssertEqual("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3", db.description)
}
func test_init_withString_returnsURIConnection() {
let db = Database("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3")
XCTAssertEqual("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3", db.description)
}
func test_readonly_returnsFalseOnReadWriteConnections() {
XCTAssert(!db.readonly)
}
func test_readonly_returnsTrueOnReadOnlyConnections() {
let db = Database(readonly: true)
XCTAssert(db.readonly)
}
func test_lastInsertRowid_returnsNilOnNewConnections() {
XCTAssert(db.lastInsertRowid == nil)
}
func test_lastInsertRowid_returnsLastIdAfterInserts() {
insertUser("alice")
XCTAssert(db.lastInsertRowid! == 1)
}
func test_changes_returnsZeroOnNewConnections() {
XCTAssertEqual(0, db.changes)
}
func test_changes_returnsNumberOfChanges() {
insertUser("alice")
XCTAssertEqual(1, db.changes)
insertUser("betsy")
XCTAssertEqual(1, db.changes)
}
func test_totalChanges_returnsTotalNumberOfChanges() {
XCTAssertEqual(0, db.totalChanges)
insertUser("alice")
XCTAssertEqual(1, db.totalChanges)
insertUser("betsy")
XCTAssertEqual(2, db.totalChanges)
}
func test_prepare_preparesAndReturnsStatements() {
db.prepare("SELECT * FROM users WHERE admin = 0")
db.prepare("SELECT * FROM users WHERE admin = ?", 0)
db.prepare("SELECT * FROM users WHERE admin = ?", [0])
db.prepare("SELECT * FROM users WHERE admin = $admin", ["$admin": 0])
// no-op assert-nothing-asserted
}
func test_run_preparesRunsAndReturnsStatements() {
db.run("SELECT * FROM users WHERE admin = 0")
db.run("SELECT * FROM users WHERE admin = ?", 0)
db.run("SELECT * FROM users WHERE admin = ?", [0])
db.run("SELECT * FROM users WHERE admin = $admin", ["$admin": 0])
AssertSQL("SELECT * FROM users WHERE admin = 0", 4)
}
func test_scalar_preparesRunsAndReturnsScalarValues() {
XCTAssertEqual(0, db.scalar("SELECT count(*) FROM users WHERE admin = 0") as! Int64)
XCTAssertEqual(0, db.scalar("SELECT count(*) FROM users WHERE admin = ?", 0) as! Int64)
XCTAssertEqual(0, db.scalar("SELECT count(*) FROM users WHERE admin = ?", [0]) as! Int64)
XCTAssertEqual(0, db.scalar("SELECT count(*) FROM users WHERE admin = $admin", ["$admin": 0]) as! Int64)
AssertSQL("SELECT count(*) FROM users WHERE admin = 0", 4)
}
func test_transaction_executesBeginDeferred() {
db.transaction(.Deferred) { _ in .Commit }
AssertSQL("BEGIN DEFERRED TRANSACTION")
}
func test_transaction_executesBeginImmediate() {
db.transaction(.Immediate) { _ in .Commit }
AssertSQL("BEGIN IMMEDIATE TRANSACTION")
}
func test_transaction_executesBeginExclusive() {
db.transaction(.Exclusive) { _ in .Commit }
AssertSQL("BEGIN EXCLUSIVE TRANSACTION")
}
func test_commit_commitsTransaction() {
db.transaction()
db.commit()
AssertSQL("COMMIT TRANSACTION")
}
func test_rollback_rollsTransactionBack() {
db.transaction()
db.rollback()
AssertSQL("ROLLBACK TRANSACTION")
}
func test_transaction_beginsAndCommitsTransactions() {
let stmt = db.prepare("INSERT INTO users (email, admin) VALUES (?, ?)", "[email protected]", 1)
db.transaction { _ in stmt.run().failed ? .Rollback : .Commit }
AssertSQL("BEGIN DEFERRED TRANSACTION")
AssertSQL("INSERT INTO users (email, admin) VALUES ('[email protected]', 1)")
AssertSQL("COMMIT TRANSACTION")
AssertSQL("ROLLBACK TRANSACTION", 0)
}
func test_transaction_beginsAndRollsTransactionsBack() {
let stmt = db.run("INSERT INTO users (email, admin) VALUES (?, ?)", "[email protected]", 1)
db.transaction { _ in stmt.run().failed ? .Rollback : .Commit }
AssertSQL("BEGIN DEFERRED TRANSACTION")
AssertSQL("INSERT INTO users (email, admin) VALUES ('[email protected]', 1)", 2)
AssertSQL("ROLLBACK TRANSACTION")
AssertSQL("COMMIT TRANSACTION", 0)
}
func test_transaction_withOperators_allowsForFlowControl() {
let stmt = db.prepare("INSERT INTO users (email, admin) VALUES (?, ?)")
let txn = db.transaction() &&
stmt.bind("[email protected]", 1) &&
stmt.bind("[email protected]", 1) &&
stmt.bind("[email protected]", 1) &&
db.commit()
txn || db.rollback()
XCTAssertTrue(txn.failed)
XCTAssert(txn.reason!.lowercaseString.rangeOfString("unique") != nil)
AssertSQL("INSERT INTO users (email, admin) VALUES ('[email protected]', 1)", 2)
AssertSQL("ROLLBACK TRANSACTION")
AssertSQL("COMMIT TRANSACTION", 0)
}
func test_savepoint_quotesSavepointNames() {
db.savepoint("That's all, Folks!")
AssertSQL("SAVEPOINT 'That''s all, Folks!'")
}
func test_release_quotesSavepointNames() {
let savepointName = "That's all, Folks!"
db.savepoint(savepointName)
db.release(savepointName)
AssertSQL("RELEASE SAVEPOINT 'That''s all, Folks!'")
}
func test_release_defaultsToCurrentSavepointName() {
db.savepoint("Hello, World!")
db.release()
AssertSQL("RELEASE SAVEPOINT 'Hello, World!'")
}
func test_release_maintainsTheSavepointNameStack() {
db.savepoint("1")
db.savepoint("2")
db.savepoint("3")
db.release("2")
db.release()
AssertSQL("RELEASE SAVEPOINT '2'")
AssertSQL("RELEASE SAVEPOINT '1'")
AssertSQL("RELEASE SAVEPOINT '3'", 0)
}
func test_rollback_quotesSavepointNames() {
let savepointName = "That's all, Folks!"
db.savepoint(savepointName)
db.rollback(savepointName)
AssertSQL("ROLLBACK TO SAVEPOINT 'That''s all, Folks!'")
}
func test_rollback_defaultsToCurrentSavepointName() {
db.savepoint("Hello, World!")
db.rollback()
AssertSQL("ROLLBACK TO SAVEPOINT 'Hello, World!'")
}
func test_rollback_maintainsTheSavepointNameStack() {
db.savepoint("1")
db.savepoint("2")
db.savepoint("3")
db.rollback("2")
db.rollback()
AssertSQL("ROLLBACK TO SAVEPOINT '2'")
AssertSQL("ROLLBACK TO SAVEPOINT '1'")
AssertSQL("ROLLBACK TO SAVEPOINT '3'", 0)
}
func test_savepoint_beginsAndReleasesTransactions() {
let stmt = db.prepare("INSERT INTO users (email, admin) VALUES (?, ?)", "[email protected]", 1)
db.savepoint("1") { _ in stmt.run().failed ? .Rollback : .Release }
AssertSQL("SAVEPOINT '1'")
AssertSQL("INSERT INTO users (email, admin) VALUES ('[email protected]', 1)")
AssertSQL("RELEASE SAVEPOINT '1'")
AssertSQL("ROLLBACK TO SAVEPOINT '1'", 0)
}
func test_savepoint_beginsAndRollsTransactionsBack() {
let stmt = db.run("INSERT INTO users (email, admin) VALUES (?, ?)", "[email protected]", 1)
db.savepoint("1") { _ in stmt.run().failed ? .Rollback : .Release }
AssertSQL("SAVEPOINT '1'")
AssertSQL("INSERT INTO users (email, admin) VALUES ('[email protected]', 1)", 2)
AssertSQL("ROLLBACK TO SAVEPOINT '1'", 1)
AssertSQL("RELEASE SAVEPOINT '1'", 0)
}
func test_savepoint_withOperators_allowsForFlowControl() {
let stmt = db.prepare("INSERT INTO users (email, admin) VALUES (?, ?)")
var txn = db.savepoint("1")
txn = txn && (
db.savepoint("2") &&
stmt.run("[email protected]", 1) &&
stmt.run("[email protected]", 1) &&
stmt.run("[email protected]", 1) &&
db.release()
)
txn || db.rollback()
txn = txn && (
db.savepoint("2") &&
stmt.run("[email protected]", 1) &&
stmt.run("[email protected]", 1) &&
stmt.run("[email protected]", 1) &&
db.release()
)
txn || db.rollback()
txn && db.release() || db.rollback()
AssertSQL("SAVEPOINT '1'")
AssertSQL("SAVEPOINT '2'")
AssertSQL("RELEASE SAVEPOINT '2'", 0)
AssertSQL("RELEASE SAVEPOINT '1'", 0)
AssertSQL("ROLLBACK TO SAVEPOINT '1'")
AssertSQL("INSERT INTO users (email, admin) VALUES ('[email protected]', 1)", 2)
}
func test_interrupt_interruptsLongRunningQuery() {
insertUsers(map("abcdefghijklmnopqrstuvwxyz") { String($0) })
db.create(function: "sleep") { args in
usleep(UInt32(Double(args[0] as? Double ?? Double(args[0] as? Int64 ?? 1)) * 1_000_000))
return nil
}
let stmt = db.prepare("SELECT *, sleep(?) FROM users", 0.1)
stmt.run()
XCTAssert(!stmt.failed)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(10 * NSEC_PER_MSEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), db.interrupt)
stmt.run()
XCTAssert(stmt.failed)
}
func test_userVersion_getsAndSetsUserVersion() {
XCTAssertEqual(0, db.userVersion)
db.userVersion = 1
XCTAssertEqual(1, db.userVersion)
}
func test_foreignKeys_getsAndSetsForeignKeys() {
XCTAssertEqual(false, db.foreignKeys)
db.foreignKeys = true
XCTAssertEqual(true, db.foreignKeys)
}
func test_updateHook_setsUpdateHook() {
async { done in
db.updateHook { operation, db, table, rowid in
XCTAssertEqual(.Insert, operation)
XCTAssertEqual("main", db)
XCTAssertEqual("users", table)
XCTAssertEqual(1, rowid)
done()
}
insertUser("alice")
}
}
func test_commitHook_setsCommitHook() {
async { done in
db.commitHook {
done()
return .Commit
}
db.transaction { _ in
insertUser("alice")
return .Commit
}
XCTAssertEqual(1, db.scalar("SELECT count(*) FROM users") as! Int64)
}
}
func test_rollbackHook_setsRollbackHook() {
async { done in
db.rollbackHook(done)
db.transaction { _ in
insertUser("alice")
return .Rollback
}
XCTAssertEqual(0, db.scalar("SELECT count(*) FROM users") as! Int64)
}
}
func test_commitHook_withRollback_rollsBack() {
async { done in
db.commitHook { .Rollback }
db.rollbackHook(done)
db.transaction { _ in
insertUser("alice")
return .Commit
}
XCTAssertEqual(0, db.scalar("SELECT count(*) FROM users") as! Int64)
}
}
func test_createFunction_withArrayArguments() {
db.create(function: "hello") { $0[0].map { "Hello, \($0)!" } }
XCTAssertEqual("Hello, world!", db.scalar("SELECT hello('world')") as! String)
XCTAssert(db.scalar("SELECT hello(NULL)") == nil)
}
func test_createFunction_createsQuotableFunction() {
db.create(function: "hello world") { $0[0].map { "Hello, \($0)!" } }
XCTAssertEqual("Hello, world!", db.scalar("SELECT \"hello world\"('world')") as! String)
XCTAssert(db.scalar("SELECT \"hello world\"(NULL)") == nil)
}
func test_createCollation_createsCollation() {
db.create(collation: "NODIACRITIC") { lhs, rhs in
return lhs.compare(rhs, options: .DiacriticInsensitiveSearch)
}
XCTAssertEqual(1, db.scalar("SELECT ? = ? COLLATE NODIACRITIC", "cafe", "café") as! Int64)
}
func test_createCollation_createsQuotableCollation() {
db.create(collation: "NO DIACRITIC") { lhs, rhs in
return lhs.compare(rhs, options: .DiacriticInsensitiveSearch)
}
XCTAssertEqual(1, db.scalar("SELECT ? = ? COLLATE \"NO DIACRITIC\"", "cafe", "café") as! Int64)
}
func test_lastError_withOK_returnsNil() {
XCTAssertNil(db.lastError)
}
func test_lastError_withRow_returnsNil() {
insertUsers("alice", "betty")
db.prepare("SELECT * FROM users").step()
XCTAssertNil(db.lastError)
}
func test_lastError_withDone_returnsNil() {
db.prepare("SELECT * FROM users").step()
XCTAssertNil(db.lastError)
}
func test_lastError_withError_returnsError() {
insertUsers("alice", "alice")
XCTAssertNotNil(db.lastError)
}
}
| mit | db777199e3ad4a5944cceb09b1bd8d24 | 31.388626 | 163 | 0.59621 | 4.340426 | false | true | false | false |
WhisperSystems/Signal-iOS | SignalMessaging/contacts/SystemContactsFetcher.swift | 1 | 15058 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import Contacts
import ContactsUI
import SignalServiceKit
enum Result<T, ErrorType> {
case success(T)
case error(ErrorType)
}
protocol ContactStoreAdaptee {
var authorizationStatus: ContactStoreAuthorizationStatus { get }
var supportsContactEditing: Bool { get }
func requestAccess(completionHandler: @escaping (Bool, Error?) -> Void)
func fetchContacts() -> Result<[Contact], Error>
func fetchCNContact(contactId: String) -> CNContact?
func startObservingChanges(changeHandler: @escaping () -> Void)
}
public
class ContactsFrameworkContactStoreAdaptee: NSObject, ContactStoreAdaptee {
private let contactStore = CNContactStore()
private var changeHandler: (() -> Void)?
private var initializedObserver = false
private var lastSortOrder: CNContactSortOrder?
let supportsContactEditing = true
public static let allowedContactKeys: [CNKeyDescriptor] = [
CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactThumbnailImageDataKey as CNKeyDescriptor, // TODO full image instead of thumbnail?
CNContactPhoneNumbersKey as CNKeyDescriptor,
CNContactEmailAddressesKey as CNKeyDescriptor,
CNContactPostalAddressesKey as CNKeyDescriptor,
CNContactViewController.descriptorForRequiredKeys(),
CNContactVCardSerialization.descriptorForRequiredKeys()
]
var authorizationStatus: ContactStoreAuthorizationStatus {
switch CNContactStore.authorizationStatus(for: CNEntityType.contacts) {
case .notDetermined:
return .notDetermined
case .restricted:
return .restricted
case .denied:
return .denied
case .authorized:
return .authorized
}
}
func startObservingChanges(changeHandler: @escaping () -> Void) {
// should only call once
assert(self.changeHandler == nil)
self.changeHandler = changeHandler
self.lastSortOrder = CNContactsUserDefaults.shared().sortOrder
NotificationCenter.default.addObserver(self, selector: #selector(runChangeHandler), name: .CNContactStoreDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: .OWSApplicationDidBecomeActive, object: nil)
}
@objc
func didBecomeActive() {
AppReadiness.runNowOrWhenAppDidBecomeReady {
let currentSortOrder = CNContactsUserDefaults.shared().sortOrder
guard currentSortOrder != self.lastSortOrder else {
// sort order unchanged
return
}
Logger.info("sort order changed: \(String(describing: self.lastSortOrder)) -> \(String(describing: currentSortOrder))")
self.lastSortOrder = currentSortOrder
self.runChangeHandler()
}
}
@objc
func runChangeHandler() {
guard let changeHandler = self.changeHandler else {
owsFailDebug("trying to run change handler before it was registered")
return
}
changeHandler()
}
func requestAccess(completionHandler: @escaping (Bool, Error?) -> Void) {
self.contactStore.requestAccess(for: .contacts, completionHandler: completionHandler)
}
func fetchContacts() -> Result<[Contact], Error> {
var systemContacts = [CNContact]()
do {
let contactFetchRequest = CNContactFetchRequest(keysToFetch: ContactsFrameworkContactStoreAdaptee.allowedContactKeys)
contactFetchRequest.sortOrder = .userDefault
try self.contactStore.enumerateContacts(with: contactFetchRequest) { (contact, _) -> Void in
systemContacts.append(contact)
}
} catch let error as NSError {
if error.domain == CNErrorDomain, error.code == CNError.Code.communicationError.rawValue {
// this seems occur intermittently, but not uncommonly.
Logger.warn("communication error: \(error)")
} else {
owsFailDebug("Failed to fetch contacts with error:\(error)")
}
return .error(error)
}
let contacts = systemContacts.map { Contact(systemContact: $0) }
return .success(contacts)
}
func fetchCNContact(contactId: String) -> CNContact? {
var result: CNContact?
do {
let contactFetchRequest = CNContactFetchRequest(keysToFetch: ContactsFrameworkContactStoreAdaptee.allowedContactKeys)
contactFetchRequest.sortOrder = .userDefault
contactFetchRequest.predicate = CNContact.predicateForContacts(withIdentifiers: [contactId])
try self.contactStore.enumerateContacts(with: contactFetchRequest) { (contact, _) -> Void in
guard result == nil else {
owsFailDebug("More than one contact with contact id.")
return
}
result = contact
}
} catch let error as NSError {
if error.domain == CNErrorDomain && error.code == CNError.communicationError.rawValue {
// These errors are transient and can be safely ignored.
Logger.error("Communication error: \(error)")
return nil
}
owsFailDebug("Failed to fetch contact with error:\(error)")
return nil
}
return result
}
}
@objc
public enum ContactStoreAuthorizationStatus: UInt {
case notDetermined,
restricted,
denied,
authorized
}
@objc public protocol SystemContactsFetcherDelegate: class {
func systemContactsFetcher(_ systemContactsFetcher: SystemContactsFetcher, updatedContacts contacts: [Contact], isUserRequested: Bool)
func systemContactsFetcher(_ systemContactsFetcher: SystemContactsFetcher, hasAuthorizationStatus authorizationStatus: ContactStoreAuthorizationStatus)
}
@objc
public class SystemContactsFetcher: NSObject {
private let serialQueue = DispatchQueue(label: "SystemContactsFetcherQueue")
var lastContactUpdateHash: Int?
var lastDelegateNotificationDate: Date?
let contactStoreAdapter: ContactsFrameworkContactStoreAdaptee
@objc
public weak var delegate: SystemContactsFetcherDelegate?
public var authorizationStatus: ContactStoreAuthorizationStatus {
return contactStoreAdapter.authorizationStatus
}
@objc
public var isAuthorized: Bool {
guard self.authorizationStatus != .notDetermined else {
owsFailDebug("should have called `requestOnce` before checking authorization status.")
return false
}
return self.authorizationStatus == .authorized
}
@objc
public var isDenied: Bool {
return self.authorizationStatus == .denied
}
@objc
public private(set) var systemContactsHaveBeenRequestedAtLeastOnce = false
private var hasSetupObservation = false
override init() {
self.contactStoreAdapter = ContactsFrameworkContactStoreAdaptee()
super.init()
SwiftSingletons.register(self)
}
@objc
public var supportsContactEditing: Bool {
return self.contactStoreAdapter.supportsContactEditing
}
private func setupObservationIfNecessary() {
AssertIsOnMainThread()
guard !hasSetupObservation else {
return
}
hasSetupObservation = true
self.contactStoreAdapter.startObservingChanges { [weak self] in
DispatchQueue.main.async {
self?.refreshAfterContactsChange()
}
}
}
/**
* Ensures we've requested access for system contacts. This can be used in multiple places,
* where we might need contact access, but will ensure we don't wastefully reload contacts
* if we have already fetched contacts.
*
* @param completionParam completion handler is called on main thread.
*/
@objc
public func requestOnce(completion completionParam: ((Error?) -> Void)?) {
AssertIsOnMainThread()
// Ensure completion is invoked on main thread.
let completion = { error in
DispatchMainThreadSafe({
completionParam?(error)
})
}
guard !systemContactsHaveBeenRequestedAtLeastOnce else {
completion(nil)
return
}
setupObservationIfNecessary()
switch authorizationStatus {
case .notDetermined:
if CurrentAppContext().isInBackground() {
Logger.error("do not request contacts permission when app is in background")
completion(nil)
return
}
self.contactStoreAdapter.requestAccess { (granted, error) in
if let error = error {
Logger.error("error fetching contacts: \(error)")
completion(error)
return
}
guard granted else {
// This case should have been caught by the error guard a few lines up.
owsFailDebug("declined contact access.")
completion(nil)
return
}
DispatchQueue.main.async {
self.updateContacts(completion: completion)
}
}
case .authorized:
self.updateContacts(completion: completion)
case .denied, .restricted:
Logger.debug("contacts were \(self.authorizationStatus)")
self.delegate?.systemContactsFetcher(self, hasAuthorizationStatus: authorizationStatus)
completion(nil)
}
}
@objc
public func fetchOnceIfAlreadyAuthorized() {
AssertIsOnMainThread()
guard authorizationStatus == .authorized else {
self.delegate?.systemContactsFetcher(self, hasAuthorizationStatus: authorizationStatus)
return
}
guard !systemContactsHaveBeenRequestedAtLeastOnce else {
return
}
updateContacts(completion: nil, isUserRequested: false)
}
@objc
public func userRequestedRefresh(completion: @escaping (Error?) -> Void) {
AssertIsOnMainThread()
guard authorizationStatus == .authorized else {
owsFailDebug("should have already requested contact access")
self.delegate?.systemContactsFetcher(self, hasAuthorizationStatus: authorizationStatus)
completion(nil)
return
}
updateContacts(completion: completion, isUserRequested: true)
}
@objc
public func refreshAfterContactsChange() {
AssertIsOnMainThread()
guard authorizationStatus == .authorized else {
Logger.info("ignoring contacts change; no access.")
self.delegate?.systemContactsFetcher(self, hasAuthorizationStatus: authorizationStatus)
return
}
updateContacts(completion: nil, isUserRequested: false)
}
private func updateContacts(completion completionParam: ((Error?) -> Void)?, isUserRequested: Bool = false) {
AssertIsOnMainThread()
var backgroundTask: OWSBackgroundTask? = OWSBackgroundTask(label: "\(#function)", completionBlock: { [weak self] status in
AssertIsOnMainThread()
guard status == .expired else {
return
}
guard let _ = self else {
return
}
Logger.error("background task time ran out before contacts fetch completed.")
})
// Ensure completion is invoked on main thread.
let completion: (Error?) -> Void = { error in
DispatchMainThreadSafe({
completionParam?(error)
assert(backgroundTask != nil)
backgroundTask = nil
})
}
systemContactsHaveBeenRequestedAtLeastOnce = true
setupObservationIfNecessary()
serialQueue.async {
Logger.info("fetching contacts")
var fetchedContacts: [Contact]?
switch self.contactStoreAdapter.fetchContacts() {
case .success(let result):
fetchedContacts = result
case .error(let error):
completion(error)
return
}
guard let contacts = fetchedContacts else {
owsFailDebug("contacts was unexpectedly not set.")
completion(nil)
}
Logger.info("fetched \(contacts.count) contacts.")
let contactsHash = contacts.hashValue
DispatchQueue.main.async {
var shouldNotifyDelegate = false
if self.lastContactUpdateHash != contactsHash {
Logger.info("contact hash changed. new contactsHash: \(contactsHash)")
shouldNotifyDelegate = true
} else if isUserRequested {
Logger.info("ignoring debounce due to user request")
shouldNotifyDelegate = true
} else {
// If nothing has changed, only notify delegate (to perform contact intersection) every N hours
if let lastDelegateNotificationDate = self.lastDelegateNotificationDate {
let kDebounceInterval = TimeInterval(12 * 60 * 60)
let expiresAtDate = Date(timeInterval: kDebounceInterval, since: lastDelegateNotificationDate)
if Date() > expiresAtDate {
Logger.info("debounce interval expired at: \(expiresAtDate)")
shouldNotifyDelegate = true
} else {
Logger.info("ignoring since debounce interval hasn't expired")
}
} else {
Logger.info("first contact fetch. contactsHash: \(contactsHash)")
shouldNotifyDelegate = true
}
}
guard shouldNotifyDelegate else {
Logger.info("no reason to notify delegate.")
completion(nil)
return
}
self.lastDelegateNotificationDate = Date()
self.lastContactUpdateHash = contactsHash
self.delegate?.systemContactsFetcher(self, updatedContacts: contacts, isUserRequested: isUserRequested)
completion(nil)
}
}
}
@objc
public func fetchCNContact(contactId: String) -> CNContact? {
guard authorizationStatus == .authorized else {
Logger.error("contact fetch failed; no access.")
return nil
}
return contactStoreAdapter.fetchCNContact(contactId: contactId)
}
}
| gpl-3.0 | ac6f3c0f2f420782994fbf08f93d6af6 | 34.682464 | 155 | 0.621596 | 5.749523 | false | false | false | false |
roambotics/swift | stdlib/public/Concurrency/SuspendingClock.swift | 2 | 5737 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
/// A clock that measures time that always increments but stops incrementing
/// while the system is asleep.
///
/// `SuspendingClock` can be considered as a system awake time clock. The frame
/// of reference of the `Instant` may be bound machine boot or some other
/// locally defined reference point. This means that the instants are
/// only comparable on the same machine in the same booted session.
///
/// This clock is suitable for high resolution measurements of execution.
@available(SwiftStdlib 5.7, *)
public struct SuspendingClock {
public struct Instant: Codable, Sendable {
internal var _value: Swift.Duration
internal init(_value: Swift.Duration) {
self._value = _value
}
}
public init() { }
}
@available(SwiftStdlib 5.7, *)
extension Clock where Self == SuspendingClock {
/// A clock that measures time that always increments but stops incrementing
/// while the system is asleep.
///
/// try await Task.sleep(until: .now + .seconds(3), clock: .suspending)
///
@available(SwiftStdlib 5.7, *)
public static var suspending: SuspendingClock { return SuspendingClock() }
}
@available(SwiftStdlib 5.7, *)
extension SuspendingClock: Clock {
/// The current instant accounting for machine suspension.
@available(SwiftStdlib 5.7, *)
public var now: SuspendingClock.Instant {
SuspendingClock.now
}
/// The current instant accounting for machine suspension.
@available(SwiftStdlib 5.7, *)
public static var now: SuspendingClock.Instant {
var seconds = Int64(0)
var nanoseconds = Int64(0)
_getTime(
seconds: &seconds,
nanoseconds: &nanoseconds,
clock: _ClockID.suspending.rawValue)
return SuspendingClock.Instant(_value:
.seconds(seconds) + .nanoseconds(nanoseconds))
}
/// The minimum non-zero resolution between any two calls to `now`.
@available(SwiftStdlib 5.7, *)
public var minimumResolution: Swift.Duration {
var seconds = Int64(0)
var nanoseconds = Int64(0)
_getClockRes(
seconds: &seconds,
nanoseconds: &nanoseconds,
clock: _ClockID.suspending.rawValue)
return .seconds(seconds) + .nanoseconds(nanoseconds)
}
#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY
/// Suspend task execution until a given deadline within a tolerance.
/// If no tolerance is specified then the system may adjust the deadline
/// to coalesce CPU wake-ups to more efficiently process the wake-ups in
/// a more power efficient manner.
///
/// If the task is canceled before the time ends, this function throws
/// `CancellationError`.
///
/// This function doesn't block the underlying thread.
@available(SwiftStdlib 5.7, *)
public func sleep(
until deadline: Instant, tolerance: Swift.Duration? = nil
) async throws {
let (seconds, attoseconds) = deadline._value.components
let nanoseconds = attoseconds / 1_000_000_000
try await Task._sleep(until:seconds, nanoseconds,
tolerance: tolerance,
clock: .suspending)
}
#else
@available(SwiftStdlib 5.7, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public func sleep(
until deadline: Instant, tolerance: Swift.Duration? = nil
) async throws {
fatalError("Unavailable in task-to-thread concurrency model")
}
#endif
}
@available(SwiftStdlib 5.7, *)
extension SuspendingClock.Instant: InstantProtocol {
@available(SwiftStdlib 5.7, *)
public static var now: SuspendingClock.Instant { SuspendingClock().now }
@available(SwiftStdlib 5.7, *)
public func advanced(by duration: Swift.Duration) -> SuspendingClock.Instant {
SuspendingClock.Instant(_value: _value + duration)
}
@available(SwiftStdlib 5.7, *)
public func duration(to other: SuspendingClock.Instant) -> Swift.Duration {
other._value - _value
}
@available(SwiftStdlib 5.7, *)
public func hash(into hasher: inout Hasher) {
hasher.combine(_value)
}
@available(SwiftStdlib 5.7, *)
public static func == (
_ lhs: SuspendingClock.Instant, _ rhs: SuspendingClock.Instant
) -> Bool {
return lhs._value == rhs._value
}
@available(SwiftStdlib 5.7, *)
public static func < (
_ lhs: SuspendingClock.Instant, _ rhs: SuspendingClock.Instant
) -> Bool {
return lhs._value < rhs._value
}
@available(SwiftStdlib 5.7, *)
public static func + (
_ lhs: SuspendingClock.Instant, _ rhs: Swift.Duration
) -> SuspendingClock.Instant {
lhs.advanced(by: rhs)
}
@available(SwiftStdlib 5.7, *)
public static func += (
_ lhs: inout SuspendingClock.Instant, _ rhs: Swift.Duration
) {
lhs = lhs.advanced(by: rhs)
}
@available(SwiftStdlib 5.7, *)
public static func - (
_ lhs: SuspendingClock.Instant, _ rhs: Swift.Duration
) -> SuspendingClock.Instant {
lhs.advanced(by: .zero - rhs)
}
@available(SwiftStdlib 5.7, *)
public static func -= (
_ lhs: inout SuspendingClock.Instant, _ rhs: Swift.Duration
) {
lhs = lhs.advanced(by: .zero - rhs)
}
@available(SwiftStdlib 5.7, *)
public static func - (
_ lhs: SuspendingClock.Instant, _ rhs: SuspendingClock.Instant
) -> Swift.Duration {
rhs.duration(to: lhs)
}
}
| apache-2.0 | 273ff6acc83ad364bd9ff58d3df6da67 | 30.872222 | 88 | 0.672826 | 4.014696 | false | false | false | false |
DashiDashCam/iOS-App | Dashi/Dashi/Models/CloudManager.swift | 1 | 2774 | //
// CloudManager.swift
// Dashi
//
// Created by Eric Smith on 11/7/17.
// Copyright © 2017 Senior Design. All rights reserved.
//
import Foundation
// this class exists to serve as the model between the application and the cloud video storage
class CloudManager {
private static let API_URL = "http://api.dashidashcam.com/Video"
static func pushToCloud(file: String, timestamp: String, size: Int, length: Int) {
let jsonEncoder = JSONEncoder()
let headers = [
"content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
"cache-control": "no-cache",
]
let parameters = [
[
"name": "video",
"content": try! String(contentsOfFile: file, encoding: String.Encoding.utf8),
"content-type": "video/mpeg",
],
[
"name": "metadata",
"content": [
"started": timestamp,
"size": size,
"length": length,
],
"content-type": "application/json",
],
]
let boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"
var body = ""
var error: NSError?
for param in parameters {
let paramName = param["name"]!
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"\(paramName)\""
if let filename = param["fileName"] {
let contentType = param["content-type"]!
let fileContent = param["content"]
if error != nil {
print(error)
}
body += "; filename=\"\(filename)\"\r\n"
body += "Content-Type: \(contentType)\r\n\r\n"
body += fileContent as! String
} else if let paramValue = param["value"] {
body += "\r\n\r\n\(paramValue)"
}
}
let request = NSMutableURLRequest(url: NSURL(string: API_URL)! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
// request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (_, response, error) -> Void in
if error != nil {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
}
}
| mit | 17c7bcd902e83ee2123b0c1a6ee615f1 | 33.234568 | 121 | 0.503787 | 4.756432 | false | false | false | false |
carabina/IGSwitch | IGSwitch/IGSwitch.swift | 2 | 6829 | //
// IGSwitch.swift
// IGSwitch
//
// Created by Ian Gruenig on 16/08/15.
// Copyright (c) 2015 Ian Gruenig. All rights reserved.
//
import UIKit
@IBDesignable
class IGSwitch: UIControl {
@IBInspectable var sliderColor: UIColor = UIColor.whiteColor() {
didSet {
sliderView.backgroundColor = sliderColor
}
}
@IBInspectable var textColorFront: UIColor = UIColor.darkGrayColor() {
didSet {
frontLabels[0].textColor = textColorFront
frontLabels[1].textColor = textColorFront
}
}
@IBInspectable var textColorBack: UIColor = UIColor.whiteColor() {
didSet {
backgroundLabels[0].textColor = textColorFront
backgroundLabels[1].textColor = textColorFront
}
}
@IBInspectable var cornerRadius: CGFloat = 12.0 {
didSet {
layer.cornerRadius = cornerRadius
sliderView.layer.cornerRadius = cornerRadius - 2
layoutSlider()
}
}
@IBInspectable var sliderInset: CGFloat = 2.0 {
didSet {
layoutSlider()
}
}
@IBInspectable var titleLeft: String! {
didSet {
backgroundLabels[0].text = titleLeft
frontLabels[0].text = titleLeft
}
}
@IBInspectable var titleRight: String! {
didSet {
backgroundLabels[1].text = titleRight
frontLabels[1].text = titleRight
}
}
var selectedIndex: Int = 0
var font: UIFont = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
private var backgroundLabels: [UILabel] = []
private var sliderView: UIView!
private var frontLabels: [UILabel] = []
private var sliderWidth: CGFloat { return bounds.width / 2 }
// MARK: Initializers
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK: Setup
private func setup() {
setupBackground()
setupBackgroundLabels()
setupSliderView()
setupFrontLabels()
}
private func setupBackground() {
userInteractionEnabled = true
layer.cornerRadius = cornerRadius
}
private func setupBackgroundLabels() {
for index in 0...1 {
let label = UILabel()
label.tag = index
label.font = font
label.textColor = textColorBack
label.adjustsFontSizeToFitWidth = true
label.textAlignment = .Center
addSubview(label)
backgroundLabels.append(label)
label.userInteractionEnabled = true
let recognizer = UITapGestureRecognizer(target: self, action: "handleRecognizerTap:")
label.addGestureRecognizer(recognizer)
}
}
private func setupSliderView() {
let sliderView = UIView()
sliderView.backgroundColor = sliderColor
sliderView.clipsToBounds = true
let sliderRecognizer = UIPanGestureRecognizer(target: self, action: "sliderMoved:")
sliderView.addGestureRecognizer(sliderRecognizer)
addSubview(sliderView)
self.sliderView = sliderView
}
private func setupFrontLabels() {
for _ in 0...1 {
let label = UILabel()
label.font = font
label.textColor = textColorFront
label.adjustsFontSizeToFitWidth = true
label.textAlignment = .Center
sliderView.addSubview(label)
frontLabels.append(label)
}
}
// MARK: Layout
private func layoutSlider() {
layoutSliderView(selectedIndex)
layoutBackgroundLabels()
layoutFrontLabels()
}
private func layoutSliderView(index: Int) {
sliderView.frame = CGRect(x: sliderWidth * CGFloat(index) + sliderInset, y: sliderInset, width: sliderWidth - sliderInset * 2, height: bounds.height - sliderInset * 2)
}
private func layoutBackgroundLabels() {
for index in 0...1 {
let label = backgroundLabels[index]
label.frame = CGRect(x: CGFloat(index) * sliderWidth, y: 0, width: sliderWidth, height: bounds.height)
}
}
private func layoutFrontLabels() {
let offsetX = sliderView.frame.origin.x - sliderInset
for index in 0...1 {
let label = frontLabels[index]
label.frame = CGRect(x: CGFloat(index) * sliderWidth - sliderInset - offsetX, y: -sliderInset, width: sliderWidth, height: bounds.height)
}
}
// MARK: Set Selection
func setSelectedIndex(index: Int, animated: Bool) {
assert(index >= 0 && index < 2)
updateSlider(index, animated: animated)
}
// MARK: Update Slider
private func updateSlider(index: Int, animated: Bool) {
animated ? updateSliderWithAnimation(index) : updateSliderWithoutAnimation(index)
}
private func updateSliderWithoutAnimation(index: Int) {
updateSlider(index)
updateSelectedIndex(index)
}
private func updateSlider(index: Int) {
layoutSliderView(index)
layoutFrontLabels()
}
private func updateSelectedIndex(index: Int) {
if selectedIndex != index {
selectedIndex = index
sendActionsForControlEvents(UIControlEvents.ValueChanged)
}
}
private func updateSliderWithAnimation(index: Int) {
let duration = calculateAnimationDuration(index)
UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseIn, animations: { () -> Void in
self.updateSlider(index)
}, completion: { (finished) -> Void in
self.updateSelectedIndex(index)
})
}
private func calculateAnimationDuration(index: Int) -> NSTimeInterval {
let targetX = sliderWidth * CGFloat(index) + sliderInset
let distance = targetX - sliderView.frame.origin.x
let duration = NSTimeInterval(distance / 300)
return duration
}
// MARK: UITapGestureRecognizer
func handleRecognizerTap(recognizer: UITapGestureRecognizer) {
let index = recognizer.view!.tag
updateSliderWithAnimation(index)
}
// MARK: UIPanGestureRecognizer
func sliderMoved(recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .Changed:
panGestureRecognizerChanged(recognizer)
case .Ended, .Cancelled, .Failed:
panGestureRecognizerFinished(recognizer)
default:
return
}
}
private func panGestureRecognizerChanged(recognizer: UIPanGestureRecognizer) {
let minPos = sliderInset
let maxPos = minPos + sliderView.bounds.width
let translation = recognizer.translationInView(recognizer.view!)
recognizer.view!.center.x += translation.x
recognizer.setTranslation(CGPointZero, inView: recognizer.view!)
if sliderView.frame.origin.x < minPos {
sliderView.frame.origin.x = minPos
} else if sliderView.frame.origin.x > maxPos {
sliderView.frame.origin.x = maxPos
}
layoutFrontLabels()
}
private func panGestureRecognizerFinished(recognizer: UIPanGestureRecognizer) {
let index = sliderView.center.x > sliderWidth ? 1 : 0
updateSliderWithAnimation(index)
}
} | mit | 867b246ce12e159de5c4985c089862ad | 25.889764 | 171 | 0.681652 | 4.56179 | false | false | false | false |
i-schuetz/scene_kit_pick | SceneKitPick/SceneView.swift | 1 | 2493 | //
// SceneView.swift
// SceneKitPick
//
// Created by ischuetz on 24/07/2014.
// Copyright (c) 2014 ivanschuetz. All rights reserved.
//
import SceneKit
import QuartzCore
protocol ItemSelectionDelegate {
func onItemSelected(name:String)
}
class SceneView: SCNView {
var selectionDelegate:ItemSelectionDelegate!
var selectedMaterial:SCNMaterial!
func loadSceneAtURL(url:NSURL) {
let options:Dictionary = [SCNSceneSourceCreateNormalsIfAbsentKey : true]
var error:NSError?
let maybeScene:SCNScene? = SCNScene.sceneWithURL(url, options: options, error: &error)
if let scene = maybeScene? {
self.scene = scene
} else {
println("Error loading scene: " + error!.localizedDescription)
}
}
func selectNode(node:SCNNode, materialIndex:Int) {
if self.selectedMaterial {
self.selectedMaterial.removeAllAnimations()
self.selectedMaterial = nil
}
let unsharedMaterial:SCNMaterial = node.geometry.materials[materialIndex].copy() as SCNMaterial
node.geometry.replaceMaterialAtIndex(materialIndex, withMaterial: unsharedMaterial)
self.selectedMaterial = unsharedMaterial
let highlightAnimation:CABasicAnimation = CABasicAnimation(keyPath: "contents")
highlightAnimation.toValue = NSColor.blueColor()
highlightAnimation.fromValue = NSColor.blackColor()
highlightAnimation.repeatCount = MAXFLOAT
highlightAnimation.removedOnCompletion = false
highlightAnimation.fillMode = kCAFillModeForwards
highlightAnimation.duration = 0.5
highlightAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
self.selectedMaterial.emission.intensity = 1.0
self.selectedMaterial.emission.addAnimation(highlightAnimation, forKey: "highlight")
self.selectionDelegate.onItemSelected(node.name)
}
override func mouseDown(event: NSEvent!) {
let mouseLocation = self.convertPoint(event.locationInWindow, fromView: nil)
let hits = self.hitTest(mouseLocation, options: nil)
if hits.count > 0 {
let hit:SCNHitTestResult = hits[0] as SCNHitTestResult
self.selectNode(hit.node, materialIndex: 0)
}
super.mouseDown(event)
}
}
| apache-2.0 | 2e16c91567022c7b4a8d32182501246d | 30.961538 | 108 | 0.661853 | 5.119097 | false | false | false | false |
macness/Sotodex | Pokedex/Pokemon.swift | 1 | 7073 | //
// Pokemon.swift
// Pokedex
//
// Created by Edwin Soto on 8/11/17.
// Copyright © 2017 Edwin Soto. All rights reserved.
//
import Foundation
import Alamofire
class Pokemon {
private var _name: String!
private var _pokedexId: Int!
private var _description: String!
private var _type: String!
private var _defense: String!
private var _height: String!
private var _weight: String!
private var _attack: String!
private var _nextEvolutionTxt: String!
private var _nextEvolutionName: String!
private var _nextEvolutionId: String!
private var _nextEvolutionLevel: String!
private var _pokemonURL: String!
var name: String {
return _name
}
var pokedexID:Int {
return _pokedexId
}
var description: String {
if _description == nil {
_description = ""
}
return _description
}
var type: String {
if _type == nil {
_type = ""
}
return _type
}
var defense: String {
if _defense == nil {
_defense = ""
}
return _defense
}
var height: String {
if _height == nil {
_height = ""
}
return _height
}
var weight: String {
if _weight == nil {
_weight = ""
}
return _weight
}
var attack: String {
if _attack == nil {
_attack = ""
}
return _attack
}
var nextEvolutionTxt: String {
if _nextEvolutionTxt == nil {
_nextEvolutionTxt = ""
}
return _nextEvolutionTxt
}
var nextEvolutionName: String {
if _nextEvolutionName == nil {
_nextEvolutionName = ""
}
return _nextEvolutionName
}
var nextEvolutionId: String {
if _nextEvolutionId == nil {
_nextEvolutionId = ""
}
return _nextEvolutionId
}
var nextEvolutionLevel: String {
if _nextEvolutionLevel == nil {
_nextEvolutionLevel = ""
}
return _nextEvolutionLevel
}
init(name: String, pokedexId: Int) {
self._name = name
self._pokedexId = pokedexId
self._pokemonURL = "\(URL_BASE)\(URL_POKEMON)\(self.pokedexID)/"
}
func downloadPokemonDetails(completed: @escaping DownloadComplete) {
Alamofire.request(_pokemonURL).responseJSON { (response) in
if let dict = response.result.value as? Dictionary<String, AnyObject> {
// get wieght from API
if let weight = dict["weight"] as? String {
self._weight = weight
}
// get height from API
if let height = dict["height"] as? String {
self._height = height
}
// get attack from API
if let attack = dict["attack"] as? Int {
self._attack = "\(attack)"
}
// get defense from API
if let defense = dict["defense"] as? Int {
self._defense = "\(defense)"
}
print(self._weight)
print(self._height)
print(self._defense)
print(self._attack)
// get types from API
if let types = dict["types"] as? [Dictionary<String, String>] , types.count > 0 {
if let name = types[0]["name"] as String! {
self._type = name.capitalized
}
if types.count > 1 {
for x in 1..<types.count {
if let name = types[x]["name"] {
self._type! += "/\(name.capitalized)"
}
}
}
print(self._type)
} else {
self._type = "None"
}
// get description from API
if let descArr = dict["descriptions"] as? [Dictionary <String, String>] , descArr.count > 0{
if let url = (descArr[0]["resource_uri"]) {
let descURL = "\(URL_BASE)\(url)"
Alamofire.request(descURL).responseJSON(completionHandler: { (response) in
if let descDict = response.result.value as? Dictionary<String, AnyObject> {
if let description = descDict["description"] as? String {
self._description = description
print(description)
}
}
completed()
})
}
}
// get evolutions from API
if let evolutions = dict["evolutions"] as? [Dictionary <String, AnyObject>] , evolutions.count > 0 {
if let nextEvolution = evolutions[0]["to"] as? String {
self._nextEvolutionName = nextEvolution
if let uri = evolutions[0]["resource_uri"] as? String {
let newStr = uri.replacingOccurrences(of: "/api/v1/pokemon/", with: "")
let nextEvoId = newStr.replacingOccurrences(of: "/", with: "")
self._nextEvolutionId = nextEvoId
if let lvlExist = evolutions[0]["level"] {
if let lvl = lvlExist as? Int {
self._nextEvolutionLevel = "\(lvl)"
}
} else {
self._nextEvolutionLevel = ""
}
}
}
}
}
completed()
}
}
}
| mit | 9a884dcd0fd1688a3943e07f2a22b5c7 | 29.222222 | 116 | 0.383201 | 5.932886 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/00948-swift-modulefile-readmembers.swift | 11 | 572 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
if c == D>() -> ()
var d = {
let c: String = g> String
}
}
extension String {
struct c: a {
}
get
func a: Boolean)
}(g, y: Any] = B<T
func a: T) {
}
}
protocol b {
func b<S : b =
| apache-2.0 | 5baca51db9d200086c9c030c82b5dedd | 22.833333 | 78 | 0.676573 | 3.195531 | false | false | false | false |
hborjaille/SimpleWizzard | SimpleWizzard/Classes/SimpleWizardViewController.swift | 1 | 8155 | //
// SimpleWizzardViewController.swift
// SimpleWizard
//
// Created by Higor Borjaille on 17/04/17.
// Copyright © 2017 Higor Borjaille. All rights reserved.
//
import UIKit
public protocol MoveStepDelegate {
func verifyPrev() -> Void
func verifyNext() -> Void
func verifyDone() -> Bool
}
public protocol CancelDelegate {
func cancel()
}
open class SimpleWizardViewController: UINavigationController, StepPageViewControllerDelegate {
// Wizzard instance holder
public static var wizardInstance: SimpleWizardViewController?
// Visual Components
public var nextImage: UIImage?
public var prevImage: UIImage?
public var doneImage: UIImage?
public var pageDots: UIPageControl?
public var prevButton: UIButton?
public var nextButton: UIButton?
open override var title: String? {
get {
return self.wrapController?.navigationItem.title
}
set {
self.wrapController?.navigationItem.title = newValue
}
}
open var nextViewController: UIViewController? {
get {
return self.pageViewController?.nextViewController
}
}
// Needed Delegates
var moveDelegate: MoveStepDelegate?
public var cancelDelegate: CancelDelegate?
// ViewCOntroller that will wrap every component together
public var wrapController: UIViewController?
// Page View Controller that will manage the transition
var pageViewController: StepPageViewController?
func setWizard() {
// Removes the previous instance if there is one already
if let instance = SimpleWizardViewController.wizardInstance {
instance.clearWizard()
instance.dismiss(animated: false, completion: nil)
}
// Generates and binds the new instance
SimpleWizardViewController.wizardInstance = self
}
// Function that manage the only Wizard instance
public func generate(_ childViews: [UIViewController]) {
// Initializing the WrapperViewController
wrapController = UIViewController()
wrapController?.view.backgroundColor = UIColor.white
// Initializing StepPageViewController
self.pageViewController = StepPageViewController()
self.pageViewController?.wizzard = self
// Setting Child Views
self.setChildViews(childViews)
// Setting up the Delegates
self.pageViewController?.stepDelegate = self
self.moveDelegate = self.pageViewController
// Setting up Interface
self.prevButton = UIButton()
self.prevButton?.setImage(self.prevImage, for: .normal)
self.prevButton?.addTarget(self, action: #selector(SimpleWizardViewController.prevAction(_:)), for: .touchUpInside)
self.nextButton = UIButton()
self.nextButton?.setImage(self.nextImage, for: .normal)
self.nextButton?.addTarget(self, action: #selector(SimpleWizardViewController.nextAction(_:)), for: .touchUpInside)
self.pageDots = UIPageControl()
self.pageDots?.pageIndicatorTintColor = UIColor.gray
self.pageDots?.currentPageIndicatorTintColor = UIColor.black
self.pageDots?.isUserInteractionEnabled = false
// Setting up Constraints
let stackView = UIStackView(arrangedSubviews: [prevButton!, pageDots!, nextButton!])
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.distribution = .equalSpacing
wrapController?.view.addSubview(self.pageViewController!.view)
self.pageViewController!.view.translatesAutoresizingMaskIntoConstraints = false
let pageView_H = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[pageView]-(0)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["pageView": self.pageViewController!.view])
let pageView_V = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(60)-[pageView]-(44)-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["pageView": self.pageViewController!.view, "stackView": stackView])
wrapController?.view.addConstraints(pageView_H)
wrapController?.view.addConstraints(pageView_V)
wrapController?.view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
let stackView_H = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(8)-[stackView]-(8)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["stackView": stackView])
let stackView_V = NSLayoutConstraint.constraints(withVisualFormat: "V:[stackView(44)]-(0)-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["stackView": stackView])
wrapController?.view.addConstraints(stackView_H)
wrapController?.view.addConstraints(stackView_V)
// Pushing the WrapViewController to a UINavigationController
self.pushViewController(wrapController!, animated: true)
self.wrapController?.navigationItem.setRightBarButton(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.stop, target: self, action: #selector(self.cancelWizzard(_:))), animated: true)
// Setting the Global Instance
self.setWizard()
}
override open func viewDidLoad() {
super.viewDidLoad()
//self.pushViewController(self.pageViewController!, animated: false)
/* Configure Every Component and add the Child Views
self.generate(_ childViews: [StepViewController])
*/
/* Styling
The user can personalize the buttons
*/
}
public func clearWizard() {
self.nextButton = nil
self.prevButton = nil
self.pageDots = nil
self.moveDelegate = nil
self.wrapController = nil
self.pageViewController?.wizzard = nil
self.popToRootViewController(animated: true)
SimpleWizardViewController.wizardInstance = nil
self.cancelDelegate = nil
}
@objc func cancelWizzard(_ gesture: UITapGestureRecognizer) {
self.cancelDelegate?.cancel()
}
func setChildViews(_ childViews: [UIViewController]) {
self.pageViewController?.orderedViewControllers = childViews
}
public func stepPageViewController(viewController: UIViewController, didUpdatePageCount count: Int) {
self.pageDots?.numberOfPages = count
}
public func stepPageViewController(viewController: UIViewController, didUpdatePageIndex index: Int) {
self.pageDots?.currentPage = index
}
public func next() {
if self.pageViewController?.currentViewController == self.pageViewController?.orderedViewControllers?.last {
if let val = self.moveDelegate?.verifyDone() {
if val {
self.clearWizard()
self.cancelDelegate = nil
self.dismiss(animated: true, completion: nil)
}
}
} else {
self.pageViewController?.goToNext()
}
}
public func prev() {
self.pageViewController?.goToPrev()
}
@objc func prevAction(_ sender: UIButton) {
self.moveDelegate?.verifyPrev()
}
@objc func nextAction(_ sender: UIButton) {
if self.pageViewController?.currentViewController == self.pageViewController?.orderedViewControllers?.last {
if let val = self.moveDelegate?.verifyDone() {
if val {
self.clearWizard()
self.cancelDelegate = nil
self.dismiss(animated: true, completion: nil)
}
}
} else {
self.moveDelegate?.verifyNext()
}
}
deinit {
self.pageViewController?.view.removeFromSuperview()
self.pageViewController?.removeFromParentViewController()
self.pageViewController = nil
}
}
| mit | 6528b6fad03ec2efabd87e7b584a17f1 | 36.232877 | 237 | 0.653054 | 5.454181 | false | false | false | false |
bazelbuild/tulsi | src/TulsiGenerator/RuleEntry.swift | 1 | 20440 | // Copyright 2016 The Tulsi 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 Foundation
/// Models the label and type of a single supported Bazel target.
/// See http://bazel.build/docs/build-ref.html#targets.
public class RuleInfo: Equatable, Hashable, CustomDebugStringConvertible {
public let label: BuildLabel
public let type: String
/// Set of BuildLabels referencing targets that are required by this RuleInfo. For example, test
/// hosts for XCTest targets.
public let linkedTargetLabels: Set<BuildLabel>
public var hashValue: Int {
return label.hashValue ^ type.hashValue
}
public var debugDescription: String {
return "\(Swift.type(of: self))(\(label) \(type))"
}
init(label: BuildLabel, type: String, linkedTargetLabels: Set<BuildLabel>) {
self.label = label
self.type = type
self.linkedTargetLabels = linkedTargetLabels
}
func equals(_ other: RuleInfo) -> Bool {
guard Swift.type(of: self) == Swift.type(of: other) else {
return false
}
return self.type == other.type && self.label == other.label
}
}
/// Encapsulates data about a file that may be a Bazel input or output.
public class BazelFileInfo: Equatable, Hashable, CustomDebugStringConvertible {
public enum TargetType: Int {
case sourceFile
case generatedFile
}
/// The path to this file relative to rootPath.
public let subPath: String
/// The root of this file's path (typically used to indicate the path to a generated file's root).
public let rootPath: String
/// The type of this file.
public let targetType: TargetType
/// Whether or not this file object is a directory.
public let isDirectory: Bool
public lazy var fullPath: String = { [unowned self] in
return NSString.path(withComponents: [self.rootPath, self.subPath])
}()
public lazy var uti: String? = { [unowned self] in
return self.subPath.pbPathUTI
}()
public lazy var hashValue: Int = { [unowned self] in
return self.subPath.hashValue &+
self.rootPath.hashValue &+
self.targetType.hashValue &+
self.isDirectory.hashValue
}()
init?(info: AnyObject?) {
guard let info = info as? [String: AnyObject] else {
return nil
}
guard let subPath = info["path"] as? String,
let isSourceFile = info["src"] as? Bool else {
assertionFailure("Aspect provided a file info dictionary but was missing required keys")
return nil
}
self.subPath = subPath
if let rootPath = info["root"] as? String {
// Patch up
self.rootPath = rootPath
} else {
self.rootPath = ""
}
self.targetType = isSourceFile ? .sourceFile : .generatedFile
self.isDirectory = info["is_dir"] as? Bool ?? false
}
init(rootPath: String, subPath: String, isDirectory: Bool, targetType: TargetType) {
self.rootPath = rootPath
self.subPath = subPath
self.isDirectory = isDirectory
self.targetType = targetType
}
// MARK: - CustomDebugStringConvertible
public lazy var debugDescription: String = { [unowned self] in
return "{\(self.fullPath) \(self.isDirectory ? "<DIR> " : "")\(self.targetType)}"
}()
}
public func ==(lhs: BazelFileInfo, rhs: BazelFileInfo) -> Bool {
return lhs.targetType == rhs.targetType &&
lhs.rootPath == rhs.rootPath &&
lhs.subPath == rhs.subPath &&
lhs.isDirectory == rhs.isDirectory
}
/// Models the full metadata of a single supported Bazel target.
/// See http://bazel.build/docs/build-ref.html#targets.
public final class RuleEntry: RuleInfo {
// Include paths are represented by a string and a boolean indicating whether they should be
// searched recursively or not.
public typealias IncludePath = (String, Bool)
/// Mapping of BUILD file type to Xcode Target type for non-bundled types.
static let BuildTypeToTargetType = [
"cc_binary": PBXTarget.ProductType.Application,
"cc_library": PBXTarget.ProductType.StaticLibrary,
"cc_test": PBXTarget.ProductType.Tool,
// macos_command_line_application is not a bundled type in our rules as it does not contain
// any resources, so we must explicitly list it here.
"macos_command_line_application": PBXTarget.ProductType.Tool,
"objc_library": PBXTarget.ProductType.StaticLibrary,
"swift_library": PBXTarget.ProductType.StaticLibrary,
]
/// Keys for a RuleEntry's attributes map. Definitions may be found in the Bazel Build
/// Encyclopedia (see http://bazel.build/docs/be/overview.html).
// Note: This set of must be kept in sync with the tulsi_aspects aspect.
public enum Attribute: String {
case bridging_header
// Contains defines that were specified by the user on the commandline or are built into
// Bazel itself.
case compiler_defines
case copts
case datamodels
case enable_modules
case has_swift_dependency
case has_swift_info
case launch_storyboard
case pch
case swift_language_version
case swift_toolchain
case swiftc_opts
// Contains various files that are used as part of the build process but need no special
// handling in the generated Xcode project. For example, asset_catalog, storyboard, and xibs
// attributes all end up as supporting_files.
case supporting_files
// For the {platform}_unit_test and {platform}_ui_test rules, contains a label reference to the
// ios_application target to be used as the test host when running the tests.
case test_host
}
/// Bazel attributes for this rule (e.g., "binary": <some label> on an ios_application).
public let attributes: [Attribute: AnyObject]
/// Artifacts produced by Bazel when this rule is built.
public let artifacts: [BazelFileInfo]
/// Objective-C defines to be applied to this rule by Bazel.
public let objcDefines: [String]?
/// Swift defines to be applied to this rule by Bazel.
public let swiftDefines: [String]?
/// Source files associated with this rule.
public let sourceFiles: [BazelFileInfo]
/// Non-ARC source files associated with this rule.
public let nonARCSourceFiles: [BazelFileInfo]
/// Paths to directories that will include header files.
public let includePaths: [IncludePath]?
/// Set of the labels that this rule depends on.
public let dependencies: Set<BuildLabel>
/// Set of the labels that this test rule's binary depends on.
public let testDependencies: Set<BuildLabel>
/// Set of ios_application extension labels that this rule utilizes.
public let extensions: Set<BuildLabel>
/// Set of ios_application app clip labels that this rule utilizes.
public let appClips: Set<BuildLabel>
/// .framework bundles provided by this rule.
public let frameworkImports: [BazelFileInfo]
/// List of implicit artifacts that are generated by this rule.
public let secondaryArtifacts: [BazelFileInfo]
/// The Swift language version used by this target.
public let swiftLanguageVersion: String?
/// The swift toolchain argument used by this target.
public let swiftToolchain: String?
/// List containing the transitive swiftmodules on which this rule depends.
public let swiftTransitiveModules: [BazelFileInfo]
/// List containing the transitive ObjC modulemaps on which this rule depends.
public let objCModuleMaps: [BazelFileInfo]
/// Module name to use in Xcode instead of the default.
public let moduleName: String?
/// The deployment platform target for this target.
public let deploymentTarget: DeploymentTarget?
/// Set of labels that this rule depends on but does not require.
/// TODO(b/71904309): Remove this once test_suite fetching via Aspect is stable.
// NOTE(abaire): This is a hack used for test_suite rules, where the possible expansions retrieved
// via queries are filtered by the existence of the selected labels extracted via the normal
// aspect path. Ideally the aspect would be able to directly express the relationship between the
// test_suite and the test rules themselves, but that expansion is done prior to the application
// of the aspect.
public var weakDependencies = Set<BuildLabel>()
/// Set of labels that this test_suite depends on. If this target is not a test_suite, returns
/// an empty set. This maps directly to the `tests` attribute of the test_suite.
public var testSuiteDependencies: Set<BuildLabel> {
guard type == "test_suite" else { return Set() }
// Legacy support for expansion of test_suite via a Bazel query. If a Bazel query is used,
// `dependencies` will be empty and `weakDependencies` will contain the test_suite's
// dependencies. Otherwise, `dependencies` will contain the test_suite's dependencies.
guard dependencies.isEmpty else { return dependencies }
return weakDependencies
}
/// The BUILD file that this rule was defined in.
public let buildFilePath: String?
// The CFBundleIdentifier associated with the target for this rule, if any.
public let bundleID: String?
/// The bundle name associated with the target for this rule, if any.
public let bundleName: String?
/// The product type for this rule (only for targets With AppleBundleInfo).
let productType: PBXTarget.ProductType?
/// The CFBundleIdentifier of the watchOS extension target associated with this rule, if any.
public let extensionBundleID: String?
/// The NSExtensionPointIdentifier of the extension associated with this rule, if any.
public let extensionType: String?
/// Xcode version used during the aspect run. Only set for bundled and runnable targets.
public let xcodeVersion: String?
/// Returns the set of non-versioned artifacts that are not source files.
public var normalNonSourceArtifacts: [BazelFileInfo] {
var artifacts = [BazelFileInfo]()
if let description = attributes[.launch_storyboard] as? [String: AnyObject],
let fileTarget = BazelFileInfo(info: description as AnyObject?) {
artifacts.append(fileTarget)
}
if let fileTargets = parseFileDescriptionListAttribute(.supporting_files) {
artifacts.append(contentsOf: fileTargets)
}
return artifacts
}
/// Returns the set of artifacts for which a versioned group should be created in the generated
/// Xcode project.
public var versionedNonSourceArtifacts: [BazelFileInfo] {
if let fileTargets = parseFileDescriptionListAttribute(.datamodels) {
return fileTargets
}
return []
}
/// The full set of input and output artifacts for this rule.
public var projectArtifacts: [BazelFileInfo] {
var artifacts = sourceFiles
artifacts.append(contentsOf: nonARCSourceFiles)
artifacts.append(contentsOf: frameworkImports)
artifacts.append(contentsOf: normalNonSourceArtifacts)
artifacts.append(contentsOf: versionedNonSourceArtifacts)
return artifacts
}
private(set) lazy var pbxTargetType: PBXTarget.ProductType? = { [unowned self] in
if let productType = self.productType {
return productType
}
return RuleEntry.BuildTypeToTargetType[self.type]
}()
/// Returns the value to be used as the Xcode SDKROOT for the build target generated for this
/// RuleEntry.
private(set) lazy var XcodeSDKRoot: String? = { [unowned self] in
guard type != "cc_binary" && type != "cc_test" else {
return PlatformType.macos.deviceSDK
}
if let platformType = self.deploymentTarget?.platform {
return platformType.deviceSDK
}
return PlatformType.ios.deviceSDK
}()
init(label: BuildLabel,
type: String,
attributes: [String: AnyObject],
artifacts: [BazelFileInfo] = [],
sourceFiles: [BazelFileInfo] = [],
nonARCSourceFiles: [BazelFileInfo] = [],
dependencies: Set<BuildLabel> = Set(),
testDependencies: Set<BuildLabel> = Set(),
frameworkImports: [BazelFileInfo] = [],
secondaryArtifacts: [BazelFileInfo] = [],
weakDependencies: Set<BuildLabel>? = nil,
extensions: Set<BuildLabel>? = nil,
appClips: Set<BuildLabel>? = nil,
bundleID: String? = nil,
bundleName: String? = nil,
productType: PBXTarget.ProductType? = nil,
extensionBundleID: String? = nil,
platformType: String? = nil,
osDeploymentTarget: String? = nil,
buildFilePath: String? = nil,
objcDefines: [String]? = nil,
swiftDefines: [String]? = nil,
includePaths: [IncludePath]? = nil,
swiftLanguageVersion: String? = nil,
swiftToolchain: String? = nil,
swiftTransitiveModules: [BazelFileInfo] = [],
objCModuleMaps: [BazelFileInfo] = [],
moduleName: String? = nil,
extensionType: String? = nil,
xcodeVersion: String? = nil) {
var checkedAttributes = [Attribute: AnyObject]()
for (key, value) in attributes {
guard let checkedKey = Attribute(rawValue: key) else {
print("Tulsi rule \(label.value) - Ignoring unknown attribute key \(key)")
assertionFailure("Unknown attribute key \(key)")
continue
}
checkedAttributes[checkedKey] = value
}
self.attributes = checkedAttributes
let parsedPlatformType: PlatformType?
if let platformTypeStr = platformType {
parsedPlatformType = PlatformType(rawValue: platformTypeStr)
} else {
parsedPlatformType = nil
}
self.artifacts = artifacts
self.sourceFiles = sourceFiles
self.nonARCSourceFiles = nonARCSourceFiles
self.dependencies = dependencies
self.testDependencies = testDependencies
self.frameworkImports = frameworkImports
self.secondaryArtifacts = secondaryArtifacts
if let weakDependencies = weakDependencies {
self.weakDependencies = weakDependencies
}
self.extensions = extensions ?? Set()
self.appClips = appClips ?? Set()
self.bundleID = bundleID
self.bundleName = bundleName
self.productType = productType
self.extensionBundleID = extensionBundleID
var deploymentTarget: DeploymentTarget? = nil
if let platform = parsedPlatformType,
let osVersion = osDeploymentTarget {
deploymentTarget = DeploymentTarget(platform: platform, osVersion: osVersion)
}
self.deploymentTarget = deploymentTarget
self.buildFilePath = buildFilePath
self.objcDefines = objcDefines
self.moduleName = moduleName
self.swiftDefines = swiftDefines
self.includePaths = includePaths
self.swiftLanguageVersion = swiftLanguageVersion
self.swiftToolchain = swiftToolchain
self.swiftTransitiveModules = swiftTransitiveModules
self.xcodeVersion = xcodeVersion
// Swift targets may have a generated Objective-C module map for their Swift generated header.
// Unfortunately, this breaks Xcode's indexing (it doesn't really make sense to ask SourceKit
// to index some source files in a module while at the same time giving it a compiled version
// of the same module), so we must exclude it.
//
// We must do the same thing for tests, except that it may apply to multiple modules as we
// combine sources from potentially multiple targets into one test target.
let targetsToAvoid = testDependencies + [label]
let moduleMapsToAvoid = targetsToAvoid.compactMap { (targetLabel: BuildLabel) -> String? in
return targetLabel.asFileName
}
if !moduleMapsToAvoid.isEmpty {
self.objCModuleMaps = objCModuleMaps.filter { moduleMapFileInfo in
let moduleMapPath = moduleMapFileInfo.fullPath
for mapToAvoid in moduleMapsToAvoid {
if moduleMapPath.hasSuffix("\(mapToAvoid).modulemaps/module.modulemap")
|| moduleMapPath.hasSuffix("\(mapToAvoid).swift.modulemap")
{
return false
}
}
return true
}
} else {
self.objCModuleMaps = objCModuleMaps
}
self.extensionType = extensionType
var linkedTargetLabels = Set<BuildLabel>()
if let hostLabelString = self.attributes[.test_host] as? String {
linkedTargetLabels.insert(BuildLabel(hostLabelString))
}
super.init(label: label, type: type, linkedTargetLabels: linkedTargetLabels)
}
convenience init(label: String,
type: String,
attributes: [String: AnyObject],
artifacts: [BazelFileInfo] = [],
sourceFiles: [BazelFileInfo] = [],
nonARCSourceFiles: [BazelFileInfo] = [],
dependencies: Set<BuildLabel> = Set(),
testDependencies: Set<BuildLabel> = Set(),
frameworkImports: [BazelFileInfo] = [],
secondaryArtifacts: [BazelFileInfo] = [],
weakDependencies: Set<BuildLabel>? = nil,
extensions: Set<BuildLabel>? = nil,
appClips: Set<BuildLabel>? = nil,
bundleID: String? = nil,
bundleName: String? = nil,
productType: PBXTarget.ProductType? = nil,
extensionBundleID: String? = nil,
platformType: String? = nil,
osDeploymentTarget: String? = nil,
buildFilePath: String? = nil,
objcDefines: [String]? = nil,
swiftDefines: [String]? = nil,
includePaths: [IncludePath]? = nil,
swiftLanguageVersion: String? = nil,
swiftToolchain: String? = nil,
swiftTransitiveModules: [BazelFileInfo] = [],
objCModuleMaps: [BazelFileInfo] = [],
moduleName: String? = nil,
extensionType: String? = nil,
xcodeVersion: String? = nil) {
self.init(label: BuildLabel(label),
type: type,
attributes: attributes,
artifacts: artifacts,
sourceFiles: sourceFiles,
nonARCSourceFiles: nonARCSourceFiles,
dependencies: dependencies,
testDependencies: testDependencies,
frameworkImports: frameworkImports,
secondaryArtifacts: secondaryArtifacts,
weakDependencies: weakDependencies,
extensions: extensions,
appClips: appClips,
bundleID: bundleID,
bundleName: bundleName,
productType: productType,
extensionBundleID: extensionBundleID,
platformType: platformType,
osDeploymentTarget: osDeploymentTarget,
buildFilePath: buildFilePath,
objcDefines: objcDefines,
swiftDefines: swiftDefines,
includePaths: includePaths,
swiftLanguageVersion: swiftLanguageVersion,
swiftToolchain: swiftToolchain,
swiftTransitiveModules: swiftTransitiveModules,
objCModuleMaps: objCModuleMaps,
moduleName: moduleName,
extensionType: extensionType,
xcodeVersion: xcodeVersion)
}
// MARK: Private methods
private func parseFileDescriptionListAttribute(_ attribute: RuleEntry.Attribute) -> [BazelFileInfo]? {
guard let descriptions = attributes[attribute] as? [[String: AnyObject]] else {
return nil
}
var fileTargets = [BazelFileInfo]()
for description in descriptions {
guard let target = BazelFileInfo(info: description as AnyObject?) else {
assertionFailure("Failed to resolve file description to a file target")
continue
}
fileTargets.append(target)
}
return fileTargets
}
override func equals(_ other: RuleInfo) -> Bool {
guard super.equals(other), let entry = other as? RuleEntry else {
return false
}
return deploymentTarget == entry.deploymentTarget
}
}
// MARK: - Equatable
public func ==(lhs: RuleInfo, rhs: RuleInfo) -> Bool {
return lhs.equals(rhs)
}
| apache-2.0 | fe1c3a2ba067429477171894f4c49a01 | 37.277154 | 104 | 0.682143 | 4.746865 | false | true | false | false |
tablexi/txi-ios-bootstrap | Example/Tests/Managers/EnvironmentManagerSpec.swift | 1 | 4692 | //
// EnvironmentManagerSpec.swift
// TXIBootstrap
//
// Created by Ed Lafoy on 12/11/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import TXIBootstrap
class EnvironmentManagerSpec: QuickSpec {
var bundle: Bundle { return Bundle(for: type(of: self)) }
let userDefaults = UserDefaults(suiteName: "test")!
let userDefaultsKey = "environment"
var environmentValues: [[String: AnyObject]] {
let path = self.bundle.path(forResource: "Environments", ofType: "plist")!
let values = NSArray(contentsOfFile: path) as? [[String: AnyObject]]
return values ?? []
}
var environmentManager: EnvironmentManager<TestEnvironment>!
override func spec() {
beforeEach {
self.userDefaults.setValue("", forKey: self.userDefaultsKey)
expect(self.environmentValues.count).to(beGreaterThan(0))
self.environmentManager = EnvironmentManager<TestEnvironment>(userDefaults: self.userDefaults, bundle: self.bundle)
}
it("reads environments from Environments.plist") {
expect(self.environmentManager.environments.count).to(equal(self.environmentValues.count))
}
it("populates valid environments") {
self.validateEnvironmentAtIndex(index: 0)
self.validateEnvironmentAtIndex(index: 1)
}
it("saves the selected environment in user defaults") {
let environment1 = self.environmentManager.environments[0]
let environment2 = self.environmentManager.environments[1]
self.environmentManager.currentEnvironment = environment1
expect(self.userDefaults.value(forKey: self.userDefaultsKey) as? String).to(equal(environment1.name))
self.environmentManager.currentEnvironment = environment2
expect(self.userDefaults.value(forKey: self.userDefaultsKey) as? String).to(equal(environment2.name))
}
it("shows the correct current environment if it's changed elsewhere by another instance of EnvironmentManager") {
let otherEnvironmentManager = EnvironmentManager<TestEnvironment>(userDefaults: self.userDefaults, bundle: self.bundle)
expect(otherEnvironmentManager.currentEnvironment).to(equal(self.environmentManager.currentEnvironment))
expect(otherEnvironmentManager.currentEnvironment).to(equal(self.environmentManager.environments[0]))
self.environmentManager.currentEnvironment = self.environmentManager.environments[1]
expect(otherEnvironmentManager.currentEnvironment).to(equal(self.environmentManager.currentEnvironment))
}
context("with no stored environment") {
var defaultEnvironment: TestEnvironment!
beforeEach {
self.userDefaults.setValue("", forKey: self.userDefaultsKey)
self.environmentManager = EnvironmentManager<TestEnvironment>(userDefaults: self.userDefaults, bundle: self.bundle)
defaultEnvironment = self.environmentManager.environments[0]
}
it("defaults to first environment") {
expect(self.environmentManager.currentEnvironment).to(equal(defaultEnvironment))
}
}
context("with saved environment") {
beforeEach {
self.userDefaults.setValue("Stage", forKey: self.userDefaultsKey)
self.environmentManager = EnvironmentManager<TestEnvironment>(userDefaults: self.userDefaults, bundle: self.bundle)
}
it("uses the saved environment") {
guard let stageEnvironment = self.environmentManager.environments.filter({ $0.name == "Stage" }).first else { return fail() }
expect(self.environmentManager.currentEnvironment).to(equal(stageEnvironment))
}
}
}
func validateEnvironmentAtIndex(index: Int) {
let environment = environmentManager.environments[index]
let values = environmentValues[index]
guard let name = values["Name"] as? String,
let domain = values["Domain"] as? String,
let key = values["Key"] as? String else { return fail() }
expect(environment.name).to(equal(name))
expect(environment.domain).to(equal(domain))
expect(environment.key).to(equal(key))
}
}
class TestEnvironment: Environment, CustomDebugStringConvertible {
var name: String = ""
var domain: String = ""
var key: String = ""
required init?(environment: [String: AnyObject]) {
guard let name = environment["Name"] as? String, let domain = environment["Domain"] as? String, let key = environment["Key"] as? String else { return nil }
self.name = name
self.domain = domain
self.key = key
}
var debugDescription: String { return self.name }
}
func ==(left: TestEnvironment, right: TestEnvironment) -> Bool { return left.name == right.name }
| mit | cb3f4ffc2e1827fd29017eb6b6457e62 | 38.754237 | 159 | 0.715199 | 4.488995 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.